qid
int64 1
74.6M
| question
stringlengths 45
24.2k
| date
stringlengths 10
10
| metadata
stringlengths 101
178
| response_j
stringlengths 32
23.2k
| response_k
stringlengths 21
13.2k
|
---|---|---|---|---|---|
31,778,365 |
So I am trying to read the words from a file. However, I have to use `putchar(ch)` where `ch` is an `int`. How do I convert ch to a string (char \*) so I can store it in a char \* variable and pass it to another function that takes char \* as a parameter. And I actually just want to store it but not print it.
This is what I have:
```
int main (void)
{
static const char filename[] = "file.txt";
FILE *file = fopen(filename, "r");
if ( file != NULL )
{
int ch, word = 0;
while ( (ch = fgetc(file)) != EOF )
{
if ( isspace(ch) || ispunct(ch) )
{
if ( word )
{
word = 0;
putchar('\n');
}
}
else
{
word = 1;
putchar(ch);
}
}
fclose(file);
}
return 0;
}
```
|
2015/08/03
|
['https://Stackoverflow.com/questions/31778365', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4807625/']
|
`sprintf(char_arr, "%d", an_integer);`
This makes `char_arr` equal to string representation of `an_integer`
(This doesn't print anything to console output in case you're wondering, this just 'stores' it)
An example:
```
char char_arr [100];
int num = 42;
sprintf(char_arr, "%d", num);
```
`char_arr` now is the string `"42"`. `sprintf`automatically adds the null character `\0` to `char_arr`.
If you want to append more on to the end of char\_arr, you can do this:
```
sprintf(char_arr+strlen(char_arr), "%d", another_num);
```
the '+ strlen' part is so it starts appending at the end.
more info here: <http://www.cplusplus.com/reference/cstdio/sprintf/>
|
You can use math functions to do that. Like this:
```
#include <stdio.h> // For the sprintf function
#include <stdlib.h> // for the malloc function
#include <math.h> // for the floor, log10 and abs functions
const char * inttostr(int n) {
char * result;
if (n >= 0)
result = malloc(floor(log10(n)) + 2);
else
result = malloc(floor(log10(n)) + 3);
sprintf(result, "%d", n);
return result;
}
```
|
31,778,365 |
So I am trying to read the words from a file. However, I have to use `putchar(ch)` where `ch` is an `int`. How do I convert ch to a string (char \*) so I can store it in a char \* variable and pass it to another function that takes char \* as a parameter. And I actually just want to store it but not print it.
This is what I have:
```
int main (void)
{
static const char filename[] = "file.txt";
FILE *file = fopen(filename, "r");
if ( file != NULL )
{
int ch, word = 0;
while ( (ch = fgetc(file)) != EOF )
{
if ( isspace(ch) || ispunct(ch) )
{
if ( word )
{
word = 0;
putchar('\n');
}
}
else
{
word = 1;
putchar(ch);
}
}
fclose(file);
}
return 0;
}
```
|
2015/08/03
|
['https://Stackoverflow.com/questions/31778365', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4807625/']
|
To represent a single character as a character string, I find using a simple 2-character buffer to be as easy as anything else. You can take advantage of the fact that dereferencing the string points to the first character and simply assign the character you wish to represent as a string. If you have initialized your 2-char buffer to `0` (or `'\0'`) when declared, you have insured your string is always `null-terminated`:
**Short Example**
```
#include <stdio.h>
int main (void) {
int ch;
char s[2] = {0};
FILE *file = stdin;
while ( (ch = fgetc(file)) != EOF ) {
*s = ch;
printf ("ch as char*: %s\n", s);
}
return 0;
}
```
**Use/Output**
```
$ printf "hello\n" | ./bin/i2s2
ch as char*: h
ch as char*: e
ch as char*: l
ch as char*: l
ch as char*: o
ch as char*:
```
**Note:** you can add `&& ch != '\n'` to the while condition to prevent printing the newline.
|
You can use math functions to do that. Like this:
```
#include <stdio.h> // For the sprintf function
#include <stdlib.h> // for the malloc function
#include <math.h> // for the floor, log10 and abs functions
const char * inttostr(int n) {
char * result;
if (n >= 0)
result = malloc(floor(log10(n)) + 2);
else
result = malloc(floor(log10(n)) + 3);
sprintf(result, "%d", n);
return result;
}
```
|
40,783,814 |
I am quite new to R and managed to use ggplot2 using google. ;)
I wanted to "stack-plot" relative abundances vs. time blocks (1-8).
What the plot looks like now:
[](https://i.stack.imgur.com/l69h4.png)
Now to my aim and problem:
I have data for males and females. My aim is to group m/f for each time block next to each other. so 2 stacked barplots (m and f) for each time series 1 - 8, next to each other (unfortunately cant add a second picture)
download link to data (txt file):
<https://www.wetransfer.com/downloads/559769b71aa32356457293161f5448f220161124101155/eb3b1f6c78d3145a1ad68d31a07e0c5c20161124101155/173f77>
```
family_abundance<-read.table("family_abundance.txt", header=T)
ggplot(family_abundance, aes(x=row, y=value, fill=factor(variable)))
+ geom_bar(stat="identity", )
+ scale_fill_manual(values=c("#523A00","#143952","#0B1E0B","#112D10","#163C16","#1C4B1B","#215A20","#2D782B","#389636","#7071b6","#390528","#4B0636","#5E0843","#710950","#970C6B","#BD0F86","#BD0F86","#E212A1","#F042B9","#5CC45A","#f7d899","#A26F3F","#C6986C","#32dcd0","#7071b6","#35bfd7","#faa756","#D4D125","#048c92","#bc94e3","#22776e","#f294d1","#c64b3f","#fac049","#491209","#A42913","#E54124","#7f8ba7","#2972A3","#EBFEF4","#c9aba5","#1f7366","#7A5800","#8F6600","#B88400","#D89A00","#FFBA0A","#A1C8E3","#B1ADA0","#996836","#58a56d","#f5a05f"))
+ xlab("Week")
+ ylab("Abundance")
+ facet_grid(. ~sex)
```
Now, I know there is postion=dodge and i tried. however, it breaks all stacked bars into individual ones. My idea is to somehow tell dodge only to do it for sex (m/f)? But I have no clue how to do this.
Could anybody help me?
Cheers
Sio
|
2016/11/24
|
['https://Stackoverflow.com/questions/40783814', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7204441/']
|
With your data that should be something like (pretty much the same idea as Axeman's ):
```
ggplot(family_abundance, aes(x=interaction(sex,row), y=value, group=sex,fill=factor(variable))) +
geom_bar(stat="identity")+
facet_grid(.~row, scales = 'free')+
scale_x_discrete("Week",labels=levels(family_abundance$sex))
```
|
```
ggplot(mpg, aes(interaction(year, class))) +
geom_bar(aes(fill = drv), position = "stack")
```
[](https://i.stack.imgur.com/FChvB.png)
```
ggplot(mpg, aes(as.factor(year))) +
geom_bar(aes(fill = drv), position = "stack") +
facet_grid(~class, scales = 'free')
```
[](https://i.stack.imgur.com/bGmRC.png)
(I'm not inclined to download your data.)
|
35,648,453 |
I have the following quesry, where the variables are arrays...
```
c.execute("INSERT into userData values=(%s,%s,%s,%s,%s,%s)",
t[i],k[0],k[1],k[2],user[i],total)
```
This gives a syntax error.
I have also tried this:
```
a = "INSERT INTO userData VALUES ('"+t[i]+"','"+k[0]+"','"+k[1]+"','"+k[2]+"',
'"+USER+"','"+total+"')"
c.execute(a)
conn.commit()
```
This does not update to the database, though there are no errors.
Note: `c` - cursor, `conn` - connection.
|
2016/02/26
|
['https://Stackoverflow.com/questions/35648453', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3788972/']
|
[`cursor.execute()`](http://mysql-python.sourceforge.net/MySQLdb.html#cursor-objects) expects the query parameters as a tuple. Try this:
```
cursor.execute("INSERT INTO userData VALUES (%s, %s, %s, %s, %s, %s)",
(t[i], k[0], k[1], k[2], user[i], total))
```
Don't use `+` or the like for constructing SQL queries, as this can lead to SQL-injection vulnerabilities in your code.
|
Maybe try with the following syntax:
```
INSERT INTO table(col1,col2,...)VALUES(val1,val2,...)
```
|
26,938,250 |
I am trying to map a valid json string to a POJO with code that worked about 2 weeks ago. **I have made no changes to the code in those 2 weeks.**
My json string is valid according to <http://jsonformatter.curiousconcept.com/>.
I am using Jackson to map the json to the POJO:
```
response = new ObjectMapper().readValue(validJsonString, response.class);
```
This worked before! Now I get the following error. Any insights would be appreciated. I cannot find anything relating to this error message (in the title and first line of the stacktrace).
```
org.codehaus.jackson.map.JsonMappingException: Duplicate property 'cause' for [simple type, class java.lang.Exception]
at org.codehaus.jackson.map.deser.StdDeserializerProvider._createAndCache2(StdDeserializerProvider.java:267)
at org.codehaus.jackson.map.deser.StdDeserializerProvider._createAndCacheValueDeserializer(StdDeserializerProvider.java:242)
at org.codehaus.jackson.map.deser.StdDeserializerProvider.findValueDeserializer(StdDeserializerProvider.java:111)
at org.codehaus.jackson.map.deser.BasicDeserializerFactory.createCollectionDeserializer(BasicDeserializerFactory.java:178)
at org.codehaus.jackson.map.deser.StdDeserializerProvider._createDeserializer(StdDeserializerProvider.java:330)
at org.codehaus.jackson.map.deser.StdDeserializerProvider._createAndCache2(StdDeserializerProvider.java:262)
at org.codehaus.jackson.map.deser.StdDeserializerProvider._createAndCacheValueDeserializer(StdDeserializerProvider.java:242)
at org.codehaus.jackson.map.deser.StdDeserializerProvider.findValueDeserializer(StdDeserializerProvider.java:111)
at org.codehaus.jackson.map.deser.StdDeserializer.findDeserializer(StdDeserializer.java:307)
at org.codehaus.jackson.map.deser.BeanDeserializer.resolve(BeanDeserializer.java:246)
at org.codehaus.jackson.map.deser.StdDeserializerProvider._resolveDeserializer(StdDeserializerProvider.java:346)
at org.codehaus.jackson.map.deser.StdDeserializerProvider._createAndCache2(StdDeserializerProvider.java:301)
at org.codehaus.jackson.map.deser.StdDeserializerProvider._createAndCacheValueDeserializer(StdDeserializerProvider.java:242)
at org.codehaus.jackson.map.deser.StdDeserializerProvider.findValueDeserializer(StdDeserializerProvider.java:111)
at org.codehaus.jackson.map.deser.StdDeserializerProvider.findTypedValueDeserializer(StdDeserializerProvider.java:127)
at org.codehaus.jackson.map.ObjectMapper._findRootDeserializer(ObjectMapper.java:1655)
at org.codehaus.jackson.map.ObjectMapper._readMapAndClose(ObjectMapper.java:1588)
at org.codehaus.jackson.map.ObjectMapper.readValue(ObjectMapper.java:1116)
at com.jpmorgan.wm.svc.client.coverage.WmSvcLogAnalytics.getMosaicTraceIdStatus(WmSvcLogAnalytics.java:178)
at com.jpmorgan.wm.svc.client.coverage.WmSvcLogAnalytics.getLogAnalyticsLogEventDetails(WmSvcLogAnalytics.java:118)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:60)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:37)
at java.lang.reflect.Method.invoke(Method.java:611)
at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$TypeOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:168)
at com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:70)
at com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:279)
at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:136)
at com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:86)
at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:136)
at com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:74)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1357)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1289)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1239)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1229)
at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:420)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:497)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:684)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:831)
at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:1661)
at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:944)
at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:507)
at com.ibm.ws.webcontainer.servlet.ServletWrapperImpl.handleRequest(ServletWrapperImpl.java:181)
at com.ibm.ws.webcontainer.servlet.CacheServletWrapper.handleRequest(CacheServletWrapper.java:91)
at com.ibm.ws.webcontainer.WebContainer.handleRequest(WebContainer.java:878)
at com.ibm.ws.webcontainer.WSWebContainer.handleRequest(WSWebContainer.java:1592)
at com.ibm.ws.webcontainer.channel.WCChannelLink.ready(WCChannelLink.java:191)
at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleDiscrimination(HttpInboundLink.java:453)
at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleNewRequest(HttpInboundLink.java:515)
at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.processRequest(HttpInboundLink.java:306)
at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.ready(HttpInboundLink.java:277)
at com.ibm.ws.tcp.channel.impl.NewConnectionInitialReadCallback.sendToDiscriminators(NewConnectionInitialReadCallback.java:214)
at com.ibm.ws.tcp.channel.impl.NewConnectionInitialReadCallback.complete(NewConnectionInitialReadCallback.java:113)
at com.ibm.ws.tcp.channel.impl.AioReadCompletionListener.futureCompleted(AioReadCompletionListener.java:175)
at com.ibm.io.async.AbstractAsyncFuture.invokeCallback(AbstractAsyncFuture.java:217)
at com.ibm.io.async.AsyncChannelFuture$1.run(AsyncChannelFuture.java:205)
at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:1660)
Caused by:
java.lang.IllegalArgumentException: Duplicate property 'cause' for [simple type, class java.lang.Exception]
at org.codehaus.jackson.map.deser.BeanDeserializer.addProperty(BeanDeserializer.java:187)
at org.codehaus.jackson.map.deser.BeanDeserializerFactory.buildThrowableDeserializer(BeanDeserializerFactory.java:164)
at org.codehaus.jackson.map.deser.BeanDeserializerFactory.createBeanDeserializer(BeanDeserializerFactory.java:95)
at org.codehaus.jackson.map.deser.StdDeserializerProvider._createDeserializer(StdDeserializerProvider.java:340)
at org.codehaus.jackson.map.deser.StdDeserializerProvider._createAndCache2(StdDeserializerProvider.java:262)
... 56 more
```
|
2014/11/14
|
['https://Stackoverflow.com/questions/26938250', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2879594/']
|
This does not answer the question exactly as written, but is the final solution to my problem.
I have refactored my code, which ultimately has led to some code reduction.
I no longer map the JSON to a java object. After inspecting my code, I realized I do very little processing on the java object, before it is reseralied back into JSON and sent out of a Jersey REST service to the front end.
So I am now simply directly returning the JSON string as a `string` instead of a java object to be serialized into JSON by Jersey.
That being said, I still have no idea what the actual issue is (was). I would still be open to hearing others' thoughts on the exception. For now though, I have a better solution.
|
I am guessing that something has indeed changed for you; and based on my experience it could be upgrade of JSK -- definition of `Exception` did change between JDK 1.6 and 1.7.
But as to solving the problem, make sure you are using a recent version of Jackson. From class names, it looks like you are using Jackson 1.x (and not 2.x), so your choice of versions may be limited. But at least make sure to use the latest patch version of minor version you have (for example, if you were using 1.9.4, use latest 1.9 one, 1.9.13).
It is possible this particular problem has been fixed in a later patch version.
|
26,938,250 |
I am trying to map a valid json string to a POJO with code that worked about 2 weeks ago. **I have made no changes to the code in those 2 weeks.**
My json string is valid according to <http://jsonformatter.curiousconcept.com/>.
I am using Jackson to map the json to the POJO:
```
response = new ObjectMapper().readValue(validJsonString, response.class);
```
This worked before! Now I get the following error. Any insights would be appreciated. I cannot find anything relating to this error message (in the title and first line of the stacktrace).
```
org.codehaus.jackson.map.JsonMappingException: Duplicate property 'cause' for [simple type, class java.lang.Exception]
at org.codehaus.jackson.map.deser.StdDeserializerProvider._createAndCache2(StdDeserializerProvider.java:267)
at org.codehaus.jackson.map.deser.StdDeserializerProvider._createAndCacheValueDeserializer(StdDeserializerProvider.java:242)
at org.codehaus.jackson.map.deser.StdDeserializerProvider.findValueDeserializer(StdDeserializerProvider.java:111)
at org.codehaus.jackson.map.deser.BasicDeserializerFactory.createCollectionDeserializer(BasicDeserializerFactory.java:178)
at org.codehaus.jackson.map.deser.StdDeserializerProvider._createDeserializer(StdDeserializerProvider.java:330)
at org.codehaus.jackson.map.deser.StdDeserializerProvider._createAndCache2(StdDeserializerProvider.java:262)
at org.codehaus.jackson.map.deser.StdDeserializerProvider._createAndCacheValueDeserializer(StdDeserializerProvider.java:242)
at org.codehaus.jackson.map.deser.StdDeserializerProvider.findValueDeserializer(StdDeserializerProvider.java:111)
at org.codehaus.jackson.map.deser.StdDeserializer.findDeserializer(StdDeserializer.java:307)
at org.codehaus.jackson.map.deser.BeanDeserializer.resolve(BeanDeserializer.java:246)
at org.codehaus.jackson.map.deser.StdDeserializerProvider._resolveDeserializer(StdDeserializerProvider.java:346)
at org.codehaus.jackson.map.deser.StdDeserializerProvider._createAndCache2(StdDeserializerProvider.java:301)
at org.codehaus.jackson.map.deser.StdDeserializerProvider._createAndCacheValueDeserializer(StdDeserializerProvider.java:242)
at org.codehaus.jackson.map.deser.StdDeserializerProvider.findValueDeserializer(StdDeserializerProvider.java:111)
at org.codehaus.jackson.map.deser.StdDeserializerProvider.findTypedValueDeserializer(StdDeserializerProvider.java:127)
at org.codehaus.jackson.map.ObjectMapper._findRootDeserializer(ObjectMapper.java:1655)
at org.codehaus.jackson.map.ObjectMapper._readMapAndClose(ObjectMapper.java:1588)
at org.codehaus.jackson.map.ObjectMapper.readValue(ObjectMapper.java:1116)
at com.jpmorgan.wm.svc.client.coverage.WmSvcLogAnalytics.getMosaicTraceIdStatus(WmSvcLogAnalytics.java:178)
at com.jpmorgan.wm.svc.client.coverage.WmSvcLogAnalytics.getLogAnalyticsLogEventDetails(WmSvcLogAnalytics.java:118)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:60)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:37)
at java.lang.reflect.Method.invoke(Method.java:611)
at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$TypeOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:168)
at com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:70)
at com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:279)
at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:136)
at com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:86)
at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:136)
at com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:74)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1357)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1289)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1239)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1229)
at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:420)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:497)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:684)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:831)
at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:1661)
at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:944)
at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:507)
at com.ibm.ws.webcontainer.servlet.ServletWrapperImpl.handleRequest(ServletWrapperImpl.java:181)
at com.ibm.ws.webcontainer.servlet.CacheServletWrapper.handleRequest(CacheServletWrapper.java:91)
at com.ibm.ws.webcontainer.WebContainer.handleRequest(WebContainer.java:878)
at com.ibm.ws.webcontainer.WSWebContainer.handleRequest(WSWebContainer.java:1592)
at com.ibm.ws.webcontainer.channel.WCChannelLink.ready(WCChannelLink.java:191)
at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleDiscrimination(HttpInboundLink.java:453)
at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleNewRequest(HttpInboundLink.java:515)
at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.processRequest(HttpInboundLink.java:306)
at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.ready(HttpInboundLink.java:277)
at com.ibm.ws.tcp.channel.impl.NewConnectionInitialReadCallback.sendToDiscriminators(NewConnectionInitialReadCallback.java:214)
at com.ibm.ws.tcp.channel.impl.NewConnectionInitialReadCallback.complete(NewConnectionInitialReadCallback.java:113)
at com.ibm.ws.tcp.channel.impl.AioReadCompletionListener.futureCompleted(AioReadCompletionListener.java:175)
at com.ibm.io.async.AbstractAsyncFuture.invokeCallback(AbstractAsyncFuture.java:217)
at com.ibm.io.async.AsyncChannelFuture$1.run(AsyncChannelFuture.java:205)
at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:1660)
Caused by:
java.lang.IllegalArgumentException: Duplicate property 'cause' for [simple type, class java.lang.Exception]
at org.codehaus.jackson.map.deser.BeanDeserializer.addProperty(BeanDeserializer.java:187)
at org.codehaus.jackson.map.deser.BeanDeserializerFactory.buildThrowableDeserializer(BeanDeserializerFactory.java:164)
at org.codehaus.jackson.map.deser.BeanDeserializerFactory.createBeanDeserializer(BeanDeserializerFactory.java:95)
at org.codehaus.jackson.map.deser.StdDeserializerProvider._createDeserializer(StdDeserializerProvider.java:340)
at org.codehaus.jackson.map.deser.StdDeserializerProvider._createAndCache2(StdDeserializerProvider.java:262)
... 56 more
```
|
2014/11/14
|
['https://Stackoverflow.com/questions/26938250', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2879594/']
|
Just came across this problem myself and I found out that I had duplicate names in my `JsonProperty` annotations. In my case the bean that caused the error referenced a separate class where the actual typo was present:
```
@JsonProperty("attributes") Object attributes,
@JsonProperty("attributes") BoundingBox boundingBox,
...
```
After re-checking and fixing all the constructors I got it to work.
Bottom-line: Check your constructors!
|
I am guessing that something has indeed changed for you; and based on my experience it could be upgrade of JSK -- definition of `Exception` did change between JDK 1.6 and 1.7.
But as to solving the problem, make sure you are using a recent version of Jackson. From class names, it looks like you are using Jackson 1.x (and not 2.x), so your choice of versions may be limited. But at least make sure to use the latest patch version of minor version you have (for example, if you were using 1.9.4, use latest 1.9 one, 1.9.13).
It is possible this particular problem has been fixed in a later patch version.
|
50,378,316 |
I have two tables `source_product` and `target_product` as shown here:
**source\_product**:
```
pitem_id prev_id citem_id crev_id qty check_no status
-------------------------------------------------------------------
AAA null null null null null null
AAA A Item_2 B 2 100 No
AAA A Item_3 A 1 100 No
```
**target\_product**:
```
pitem_id prev_id citem_id crev_id qty check_no status
-------------------------------------------------------------------
null null null null null null null
AAA A Item_2 B 2 100 No
AAA A Item_3 A 3 110 Yes
```
My required result is to compare the `source_product` and `target_product` tables and place the differences in a `final_product` table like this:
**Final\_product**:
```
pitem_id prev_id citem_id crev_id Validation_error validation_column Source_value target_value
-------------------------------------------------------------------------------------------------------------
AAA A null null pitemid ,prev_id not found in target null null null
AAA A Item_2 B citemid ,crev_id not found in target
AAA A Item_3 A qty mismatch qty 1 3
AAA A Item_3 A check_no mismatch cheeck_no 100 110
AAA A Item_3 A status mismatch status No Yes
```
How can I write this query? I tried using union all but am getting duplicates and improper data.
|
2018/05/16
|
['https://Stackoverflow.com/questions/50378316', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9463188/']
|
You can try to hack something like this:
```py
from pyspark.sql.functions import col, lit, posexplode, expr, split
(DF1
.select("*", posexplode(split(expr("repeat('_', num_elements - 1)"), '_')))
.select(col("vars").getItem(col("pos")),col("vals").getItem(col("pos")))
.show())
# +---------+---------+
# |vars[pos]|vals[pos]|
# +---------+---------+
# | a| 1|
# | b| 2|
# | c| 3|
# | d| 4|
# | e| 5|
# | f| 6|
# | g| 7|
# | a| 4|
# | b| 5|
# | g| 3|
# | c| 6|
# | c| 2|
# | d| 3|
# | a| 5|
# | b| 7|
# | c| 2|
# +---------+---------+
```
but it is anything but "cleaner and faster". Personally I would use `RDD`:
```py
(DF1.rdd
.flatMap(lambda row: ((val, var) for val, var in zip(row.vals, row.vars)))
.toDF(["val", "var"])
.show())
# +---+---+
# |val|var|
# +---+---+
# | 1| a|
# | 2| b|
# | 3| c|
# | 4| d|
# | 5| e|
# | 6| f|
# | 7| g|
# | 4| a|
# | 5| b|
# | 3| g|
# | 6| c|
# | 2| c|
# | 3| d|
# | 5| a|
# | 7| b|
# | 2| c|
# +---+---+
```
but `udf` will work as well.
|
***Using SQL DDL schema format is another alternative.***
I have a similar problem in Scala, where we struggled so much to create a dynamic nested structure using case classes. A few days prior, I attended Databricks courses where I learned about a different approach and I'm not sure why nobody is talking about this approch.
The easiest method to make it dynamic is to feed SQL DDL from the configuration file.
Because this method uses SQL DDL, it may be applied to both Scala spark and Pyspark.
An example of how that actually appears is presented below.
**Schema Using Structs.**
```
StructType([
StructField(“field1”, StringType(), true )
StructField(“field2”, StructType([
StructField(“field3”, DoubleType(), true )
StructField(“field4”, LongType(), true )
])
```
**Schema Using SQL DDL.**
```
DDL_Schema = " 'field1’ STRING, ‘field2’ STRUCT< 'field3’: DOUBLE, 'field4’: BIGINT>"
```
**Creating data frame using SQL DDL**
```
spark.read.schema (DDLSchema)•json(eventsJsonPath)
```
I hope that this may assist with a number of problems involving dynamic structure.
**Please refer to this page for more information.** <https://vincent.doba.fr/posts/20211004_spark_data_description_language_for_defining_spark_schema/>
Thank you
|
24,311,754 |
Please see the query below:
```
update dbusns
set thisdate = created
from
(select
MAX(created) AS CREATED, DBCUSTODY.REFERENCE
from dbusns
inner join [server].Custody.DBO.dbcustody on dbusns.urns = dbcustody.reference
where dbusns.datasetname = 'CUSTODY'
group by dbcustody.reference) As CustodyDateTable
WHERE
dbusns.urns = CustodyDateTable.reference
and dbusns.urns = '1'
```
The following query returns `01/01/2011`:
```
select
MAX(created) AS CREATED, DBCUSTODY.REFERENCE
from
dbusns
inner join
server.database.DBO.dbcustody on dbusns.urns = dbcustody.reference
where
dbusns.datasetname = 'CUSTODY' AND DBCUSTODY.REFERENCE = '1'
```
However, the following query return `31/10/2011` (after query 1 is run):
```
select
THISDATE
from
dbusns
where
datasetname = 'CUSTODY' AND URNS = '1' --QUERY 3
```
The query below returns two rows (31/10/2011 and 01/11/2011):
```
select created
from [server].Custody.DBO.dbcustody
where reference = '1'
```
Why does query 3 return 31/10/2011? It should return 01/11/2011? Is this something to do with the execution plan/linked server?
|
2014/06/19
|
['https://Stackoverflow.com/questions/24311754', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/937440/']
|
Your `UPDATE` syntax seems wrong for what you want. In this case, the best way would be to use an `INNER JOIN`:
```
UPDATE D
SET thisdate = T.created
FROM dbusns D
INNER JOIN (SELECT MAX(created) created,
C.reference
FROM dbusns
INNER JOIN [server].Custody.DBO.dbcustody C
ON dbusns.urns = dbcustody.reference
WHERE dbusns.datasetname = 'CUSTODY'
GROUP BY dbcustody.reference) T
ON D.urns = T.reference
WHERE D.urns = 1
```
|
I think your `update` syntax is right, except for one small thing. Consider this line:
```
update dbusns set thisdate = created from ( . . .
```
The `created` column -- I am guessing -- is in `dbusns`. So, it is just setting `thisdate` to the created value i the same table.
You can fix this by using a table alias:
```
update dbusns set thisdate = CustodyDateTable.created from ( . . .
```
|
9,915,900 |
We are using Fluent NH with convention based mapping. I have the following:
```
public class Foo() : Entity
{
public BarComponent PrimaryBar { get; set; }
public BarComponent SecondaryBar { get; set; }
}
public class BarComponent
{
public string Name { get; set; }
}
```
I have it to the point where it will create the foo table with a single name field. I've tried the following Override and it doesn't work.
```
public class FooOverride : IAutoMappingOverride<Foo>
{
public void Override(AutoMapping<Foo> mapping)
{
mapping.Component(x => x.PrimaryBar).ColumnPrefix("primary");
mapping.Component(x => x.SecondaryBar).ColumnPrefix("secondary");
}
}
```
Do I really need to do a full override mapping or can what I have here be made to work somehow?
|
2012/03/28
|
['https://Stackoverflow.com/questions/9915900', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12503/']
|
Just tested this and it works fine. If I have a Pick with a send and receive inside a trigger and a delay inside the action, the reply is received immediately.
Are you sure the Request on your SendReply activity appears to be set correctly?
Patrick is still right, you should implement your database activity as an AsyncCodeActivity but this would not be the reason for your reply being delayed.
|
This is working as intended. If the operations take such a long time, would you be better served by calling them asynchronously? Check out AsyncCodeActivity here:
<http://msdn.microsoft.com/en-us/library/system.activities.asynccodeactivity.aspx>
|
9,915,900 |
We are using Fluent NH with convention based mapping. I have the following:
```
public class Foo() : Entity
{
public BarComponent PrimaryBar { get; set; }
public BarComponent SecondaryBar { get; set; }
}
public class BarComponent
{
public string Name { get; set; }
}
```
I have it to the point where it will create the foo table with a single name field. I've tried the following Override and it doesn't work.
```
public class FooOverride : IAutoMappingOverride<Foo>
{
public void Override(AutoMapping<Foo> mapping)
{
mapping.Component(x => x.PrimaryBar).ColumnPrefix("primary");
mapping.Component(x => x.SecondaryBar).ColumnPrefix("secondary");
}
}
```
Do I really need to do a full override mapping or can what I have here be made to work somehow?
|
2012/03/28
|
['https://Stackoverflow.com/questions/9915900', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12503/']
|
Ok, I think I have a resolution for this. As per [Maurice's answer here](https://stackoverflow.com/a/7868111/132599), I added a Delay activity following the SendReplyToReceive and the workflow then started behaving as expected.

|
This is working as intended. If the operations take such a long time, would you be better served by calling them asynchronously? Check out AsyncCodeActivity here:
<http://msdn.microsoft.com/en-us/library/system.activities.asynccodeactivity.aspx>
|
9,915,900 |
We are using Fluent NH with convention based mapping. I have the following:
```
public class Foo() : Entity
{
public BarComponent PrimaryBar { get; set; }
public BarComponent SecondaryBar { get; set; }
}
public class BarComponent
{
public string Name { get; set; }
}
```
I have it to the point where it will create the foo table with a single name field. I've tried the following Override and it doesn't work.
```
public class FooOverride : IAutoMappingOverride<Foo>
{
public void Override(AutoMapping<Foo> mapping)
{
mapping.Component(x => x.PrimaryBar).ColumnPrefix("primary");
mapping.Component(x => x.SecondaryBar).ColumnPrefix("secondary");
}
}
```
Do I really need to do a full override mapping or can what I have here be made to work somehow?
|
2012/03/28
|
['https://Stackoverflow.com/questions/9915900', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12503/']
|
I my experience checking **PersistBeforeSend** on **SendReplyToReceive** to True fixes this problem. Putting Persist block after SendReplyToReceive also helps.
|
This is working as intended. If the operations take such a long time, would you be better served by calling them asynchronously? Check out AsyncCodeActivity here:
<http://msdn.microsoft.com/en-us/library/system.activities.asynccodeactivity.aspx>
|
9,915,900 |
We are using Fluent NH with convention based mapping. I have the following:
```
public class Foo() : Entity
{
public BarComponent PrimaryBar { get; set; }
public BarComponent SecondaryBar { get; set; }
}
public class BarComponent
{
public string Name { get; set; }
}
```
I have it to the point where it will create the foo table with a single name field. I've tried the following Override and it doesn't work.
```
public class FooOverride : IAutoMappingOverride<Foo>
{
public void Override(AutoMapping<Foo> mapping)
{
mapping.Component(x => x.PrimaryBar).ColumnPrefix("primary");
mapping.Component(x => x.SecondaryBar).ColumnPrefix("secondary");
}
}
```
Do I really need to do a full override mapping or can what I have here be made to work somehow?
|
2012/03/28
|
['https://Stackoverflow.com/questions/9915900', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12503/']
|
Ok, I think I have a resolution for this. As per [Maurice's answer here](https://stackoverflow.com/a/7868111/132599), I added a Delay activity following the SendReplyToReceive and the workflow then started behaving as expected.

|
Just tested this and it works fine. If I have a Pick with a send and receive inside a trigger and a delay inside the action, the reply is received immediately.
Are you sure the Request on your SendReply activity appears to be set correctly?
Patrick is still right, you should implement your database activity as an AsyncCodeActivity but this would not be the reason for your reply being delayed.
|
9,915,900 |
We are using Fluent NH with convention based mapping. I have the following:
```
public class Foo() : Entity
{
public BarComponent PrimaryBar { get; set; }
public BarComponent SecondaryBar { get; set; }
}
public class BarComponent
{
public string Name { get; set; }
}
```
I have it to the point where it will create the foo table with a single name field. I've tried the following Override and it doesn't work.
```
public class FooOverride : IAutoMappingOverride<Foo>
{
public void Override(AutoMapping<Foo> mapping)
{
mapping.Component(x => x.PrimaryBar).ColumnPrefix("primary");
mapping.Component(x => x.SecondaryBar).ColumnPrefix("secondary");
}
}
```
Do I really need to do a full override mapping or can what I have here be made to work somehow?
|
2012/03/28
|
['https://Stackoverflow.com/questions/9915900', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12503/']
|
Ok, I think I have a resolution for this. As per [Maurice's answer here](https://stackoverflow.com/a/7868111/132599), I added a Delay activity following the SendReplyToReceive and the workflow then started behaving as expected.

|
I my experience checking **PersistBeforeSend** on **SendReplyToReceive** to True fixes this problem. Putting Persist block after SendReplyToReceive also helps.
|
43,814,422 |
I created a simple snake game after following some simple tutorials on YouTube.
The problem is that the game does not have a pause function (e.g. when pressing P the game should pause/resume) and when the snake hits the border of the canvas the game restarts itself (but that is another problem).
Here is the complete code I have of the game: <https://pastebin.com/URaDxSvF>
The pause-related functions I've created:
```
function gamePaused{ /**i need help on this**/ }
function keyDown(e) {
if (e.keyCode == 80) pauseGame();
}
function pauseGame() {
if (!gamePaused) {
game = clearTimeout(game);
gamePaused = true;
} else if (gamePaused) {
game = setTimeout(loop, 1000 / 30);
gamePaused = false;
}
}
```
|
2017/05/05
|
['https://Stackoverflow.com/questions/43814422', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7971087/']
|
Create a Boolean variable called paused and set it to true if the player presses p, Then put an if statement around the loop that runs your game. and say if (!paused){run loop}
You can create a toggle pause function for when p is pressed.
```
function togglePause()
{
if (!paused)
{
paused = true;
} else if (paused)
{
paused= false;
}
}
```
You also need to create an event listener for when p is pressed
Like this
```
window.addEventListener('keydown', function (e) {
var key = e.keyCode;
if (key === 80)// p key
{
togglePause();
}
});
```
up the top where you have Game objects and constants put in paused = false, and in your loop function do this
```
draw();
if(!paused)
{
update();
}
```
|
Your game loop is not based on `setTimeout`, but on `requestAnimationFrame`. So setting and clearing a timer will not change anything.
Secondly, you did not bind your `keyDown` function to any event, so it will never get invoked.
### Solution:
Have a look at your `loop` function: it calls itself asynchronously, which provides the animation. You need to stop that loop to effectively introduce a pause:
```
function loop() {
if (gamePaused) return; // <--- stop looping
update();
draw();
window.requestAnimationFrame(loop, canvas);
}
```
Define the new variable upon page load, and bind your function to the `keyDown` event:
```
var gamePaused = false;
document.addEventListener('keydown', keyDown);
```
And your `pauseGame` function would look like this:
```
function pauseGame() {
gamePaused = !gamePaused; // toggle the gamePaused value (false <-> true)
if (!gamePaused) loop(); // restart loop
}
```
|
43,814,422 |
I created a simple snake game after following some simple tutorials on YouTube.
The problem is that the game does not have a pause function (e.g. when pressing P the game should pause/resume) and when the snake hits the border of the canvas the game restarts itself (but that is another problem).
Here is the complete code I have of the game: <https://pastebin.com/URaDxSvF>
The pause-related functions I've created:
```
function gamePaused{ /**i need help on this**/ }
function keyDown(e) {
if (e.keyCode == 80) pauseGame();
}
function pauseGame() {
if (!gamePaused) {
game = clearTimeout(game);
gamePaused = true;
} else if (gamePaused) {
game = setTimeout(loop, 1000 / 30);
gamePaused = false;
}
}
```
|
2017/05/05
|
['https://Stackoverflow.com/questions/43814422', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7971087/']
|
Create a Boolean variable called paused and set it to true if the player presses p, Then put an if statement around the loop that runs your game. and say if (!paused){run loop}
You can create a toggle pause function for when p is pressed.
```
function togglePause()
{
if (!paused)
{
paused = true;
} else if (paused)
{
paused= false;
}
}
```
You also need to create an event listener for when p is pressed
Like this
```
window.addEventListener('keydown', function (e) {
var key = e.keyCode;
if (key === 80)// p key
{
togglePause();
}
});
```
up the top where you have Game objects and constants put in paused = false, and in your loop function do this
```
draw();
if(!paused)
{
update();
}
```
|
Game state managment
--------------------
Games will usually have various game states. Pause, End game, Press key to start, etc... As the optimal way to run a game is via a single main loop the easiest way to manage game states is to have variable hold the current state function and just assign that variable the appropriate function to handle the current state.
**BTW** you should use `requestAnimationFrame` instead of `setTimeout` or `setinterval` and `keyCode` should not be used as it is depreciated use `keyEvent.code` (see example for details)
```
requestAnimationFrame(mainLoop); // start when code below done.
// set up keyboard IO
const keys = {
KeyP : false,
Enter : false,
listener(e){
if(keys[e.code] !== undefined){
keys[e.code] = e.type === "keydown";
e.preventDefault();
}
}
}
addEventListener("keydown",keys.listener);
addEventListener("keyup",keys.listener);
// the current game state
var currentState = startGame;
function startGame (){
// code to do a single frame of start game
// display press enter to start
if(keys.Enter){
keys.Enter = false;
currentState = game; // start the game
}
}
function pause(){
// code to do a single frame of pause
// display pause
if(keys.KeyP){
keys.KeyP = false; // turn off key
currentState = game; // resume game
}
}
function game(){
// code to do a single frame of game
if(keys.KeyP){
keys.KeyP = false; // turn off key
currentState = pause; // pause game
}
}
function mainLoop(time){
currentState(); // call the current game state
requestAnimationFrame(mainLoop);
}
```
Reference:
<https://developer.mozilla.org/es/docs/Web/API/KeyboardEvent>
|
43,814,422 |
I created a simple snake game after following some simple tutorials on YouTube.
The problem is that the game does not have a pause function (e.g. when pressing P the game should pause/resume) and when the snake hits the border of the canvas the game restarts itself (but that is another problem).
Here is the complete code I have of the game: <https://pastebin.com/URaDxSvF>
The pause-related functions I've created:
```
function gamePaused{ /**i need help on this**/ }
function keyDown(e) {
if (e.keyCode == 80) pauseGame();
}
function pauseGame() {
if (!gamePaused) {
game = clearTimeout(game);
gamePaused = true;
} else if (gamePaused) {
game = setTimeout(loop, 1000 / 30);
gamePaused = false;
}
}
```
|
2017/05/05
|
['https://Stackoverflow.com/questions/43814422', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7971087/']
|
Game state managment
--------------------
Games will usually have various game states. Pause, End game, Press key to start, etc... As the optimal way to run a game is via a single main loop the easiest way to manage game states is to have variable hold the current state function and just assign that variable the appropriate function to handle the current state.
**BTW** you should use `requestAnimationFrame` instead of `setTimeout` or `setinterval` and `keyCode` should not be used as it is depreciated use `keyEvent.code` (see example for details)
```
requestAnimationFrame(mainLoop); // start when code below done.
// set up keyboard IO
const keys = {
KeyP : false,
Enter : false,
listener(e){
if(keys[e.code] !== undefined){
keys[e.code] = e.type === "keydown";
e.preventDefault();
}
}
}
addEventListener("keydown",keys.listener);
addEventListener("keyup",keys.listener);
// the current game state
var currentState = startGame;
function startGame (){
// code to do a single frame of start game
// display press enter to start
if(keys.Enter){
keys.Enter = false;
currentState = game; // start the game
}
}
function pause(){
// code to do a single frame of pause
// display pause
if(keys.KeyP){
keys.KeyP = false; // turn off key
currentState = game; // resume game
}
}
function game(){
// code to do a single frame of game
if(keys.KeyP){
keys.KeyP = false; // turn off key
currentState = pause; // pause game
}
}
function mainLoop(time){
currentState(); // call the current game state
requestAnimationFrame(mainLoop);
}
```
Reference:
<https://developer.mozilla.org/es/docs/Web/API/KeyboardEvent>
|
Your game loop is not based on `setTimeout`, but on `requestAnimationFrame`. So setting and clearing a timer will not change anything.
Secondly, you did not bind your `keyDown` function to any event, so it will never get invoked.
### Solution:
Have a look at your `loop` function: it calls itself asynchronously, which provides the animation. You need to stop that loop to effectively introduce a pause:
```
function loop() {
if (gamePaused) return; // <--- stop looping
update();
draw();
window.requestAnimationFrame(loop, canvas);
}
```
Define the new variable upon page load, and bind your function to the `keyDown` event:
```
var gamePaused = false;
document.addEventListener('keydown', keyDown);
```
And your `pauseGame` function would look like this:
```
function pauseGame() {
gamePaused = !gamePaused; // toggle the gamePaused value (false <-> true)
if (!gamePaused) loop(); // restart loop
}
```
|
10,223,722 |
I have to design a crystal report in which I have to retrieve values from a particular field in a database. But this field has many entries that follow increase numerically i.e., 1 to 10000, then 10000 to 20000, 20000 to 30000 etc..
Now I want to group them in a way that 1 to 10000 are in one group, 10000 to 15000 in another and 15000 to 20000 in another. How do I do that? I will be grateful for a response.
|
2012/04/19
|
['https://Stackoverflow.com/questions/10223722', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1343318/']
|
Set up a Crystal formula, similar to:
```
if {myTable.myField} >= 1 and {myTable.myField} <= 10000 then 'A'
else if {myTable.myField} > 10000 and {myTable.myField} <= 15000 then 'B'
else if {myTable.myField} > 15000 and {myTable.myField} <= 20000 then 'C'
```
- and group on your new formula.
|
You might consider the `SELECT` expression:
```
SELECT {table.field}
CASE 1 TO 10000: "A"
CASE 10001 TO 15000: "B"
CASE 15001 TO 20000: "C"
DEFAULT: "ERROR"
```
|
81,507 |
By the completeness of FOL, one can show that a sentence $S$ in FOL is valid, i.e. that it holds true in every model, by exhibiting a proof of $S$. Such a proof string is a certificate of the validity of $S$.
To show that $S$ is *not valid*, one can either exhibit a counterexample model in which $S$ doesn't hold, or find a proof that such a model exists, either of which would serve as a certificate.
However, do I understand correctly that while a "certificate of validity" will always exist, that "certificates of invalidity" **do not exist** in the general case?
In other words, that there can exist $S$ which are not tautologies, and for which a counterexample model exists, but for which one cannot actually construct a counterexample, or a proof of its existence?
This is not a question about the ability of FOL to formalize arithmetic (which Godel proved is impossible), but simply whether or not, in a very foundational sense, it is possible to prove counterexamples exist to FOL sentences in general.
|
2017/09/22
|
['https://cs.stackexchange.com/questions/81507', 'https://cs.stackexchange.com', 'https://cs.stackexchange.com/users/10594/']
|
The completeness theorem states, in an equivalent form:
>
> If a formula $S$ is *not* valid, then there exists some model $\cal M$ such that $$ {\cal M}\not\models S$$
> or, equivalently
> $${\cal M}\models\neg S $$
>
>
>
This is simply the contraposative of the completeness theorem, as stated on e.g. [wikipedia](https://en.wikipedia.org/wiki/G%C3%B6del%27s_completeness_theorem#G.C3.B6del.27s_original_formulation).
This shows that there is always a "certificate of invalidity" as you ask. This is still true if you ask for $\cal M$ to be countable.
However, obviously there is no procedure to **compute** $\cal M$, by a straightforward argument involving undecidability of Robinson's arithmetic.
---
Edit: To answer the question of how one might represent such a counter-model:
Unpacking the proof of the completeness theorem shows that such a certificate can be represented by a [Herbrand structure](https://en.wikipedia.org/wiki/Herbrand_structure), which are the syntactic terms of the language, possibly augmented with constants and function symbols, and recursively enumerable interpretations for the predicate symbols.
In general however, the interpretation of a formula cannot be decided by such a recursive enumeration (but it can be semi-decided).
|
Let $\varphi(x)$ be a formula in first-order logic with free variables $x$. If $\varphi(x)$ is not valid, then $\exists x. \neg \varphi(x)$ is valid. Let $\psi$ denote the formula $\exists x. \neg \varphi(x)$. As you stated, if $\psi$ is valid, then there exists a finite proof of $\psi$.
Thus, if $\varphi(x)$ is not valid, then there exists a finite proof that it is not valid: namely, the proof of $\psi$ constitutes such a proof.
Moreover, if $\varphi(x)$ is not valid, then there exists a value of $x$ (say $x\_0$) such that $\varphi(x\_0)$ is false, and in that case there exists a finite proof that $\varphi(x\_0)$ is false (namely, the proof of validity of $\neg \varphi(x\_0)$).
So, the answer to your question is "no; a certificate of invalidity always exists".
|
68,698,392 |
Hello i want to make a YouTube downloader in python using tkinter but there's an error
the code is:
```
from tkinter import *
from tkinter import filedialog, ttk
from pytube import YouTube
from tkinter.ttk import *
window = Tk()
window.geometry("500x500+350+100")
def openpath():
download_out.config(text="من الطبيعي عدم استجابة الكمبيوتر عند التحميل")
font = ("bahnschrift SewiBold", 10, "bold")
download_name.config(text="")
download_size.config(text="")
download_loc.config(text="")
global direct
direct=filedialog.askdirectory()
path_holder.config(text = direct)
def Download():
url = link_ent.get()
Selceted= types.get()
if len(url) < 1:
link_error.config(text = "الرجاء ادخال موقع الفيديو")
if len(direct) < 1:
path_error.config(text = "الرجاء ادخال مكان تنزيل الملف")
else:
link.config(text="")
path_error.config(text="")
try:
Yt = YouTube(url)
try:
if Selceted == options[0]:
typ = Yt.streams.get_highest_resolution()
elif Selceted == options[1]:
typ = Yt.streams.get_lowest_resolution()
else:
Yt.streams.get_audio_only()
except:
path_error.config(text="حدثت معنا اخطاء")
except:
path_error.config(text="الرجاء ادخال مكان تنزيل صالح!")
window.title("Youtube Downloader")
window.resizable(False,False)
window.config(bg = "gray3")
heading = Label(window, text = "برنامج تحميل الفيديوهات", background = "gray3",foreground = "dark
orange",
font = ("bahnschrift SewiBold",20,"bold"))
heading.pack(anchor="center",pady=10)
link = Label(window,text="الرابط",background="gray3",foreground="dark orange",
font = ("bahnschrift SewiBold",10))
link.pack(anchor="ne",padx=30,pady=25)
entry_url=StringVar()
link_ent=Entry(window,width=52,textvariable = entry_url)
link_ent.place(x=90,y=83)
link_error= Label(window,background="gray3",foreground="dark orange",
font = ("Bahnschrift SewiBold",10))
link_error.place(x=300,y=110)
path = Label(window,text="موقع الملف",background="gray3",foreground="dark orange",
font = ("bahnschrift SewiBold",10))
path.pack(anchor="ne",padx=30,pady=2)
path_holder= Label(window,text="\t\t\t",background="white",foreground="black",
font = ("bahnschrift SewiBold",10))
path_holder.place(x=240,y=130)
path_style=ttk.Style()
path_style.configure("PT.TButton",background="DarkOrange1",foreground="DarkOrange1",
font = ("bahnschrift SewiBold",10))
path_btn = Button(window,width=11,text= "Selcet Path " ,style="PT.TButton",command=
openpath())
path_btn.place(x=323,y=156)
path_error= Label(window,text="Demo",background="gray3",foreground="dark orange",
font = ("Bahnschrift SewiBold",10))
path_error.place(x=280,y=150)
Download_type=Label(window,text="أنواع التنزيل",background="gray3",foreground="dark orange",
font = ("Bahnschrift SewiBold",10))
Download_type.pack(anchor="e",padx=30,pady=37)
options=["جودة عالية","جودة منخفضة","صوت فقط"]
types = ttk.Combobox(window,values=options,width=23)
types.current(0)
types.place(x=240,y=185)
ChooseType=Label(window,text="اختر النوع ",background="gray3",foreground="dark orange",
font = ("Bahnschrift SewiBold",10))
ChooseType.place(x=170,y=187)
download_style=ttk.Style()
download_style.configure("DD.TButton",background="DarkOrange1",foreground="DarkOrange1",
font = ("bahnschrift SewiBold",10))
Download_btn = Button(window,width=11,text= "تحميل " ,style="PT.TButton")
Download_btn.pack(anchor="center",pady=30)
download_out=Label(window,text="طبيغي ان تظهر رسالة اللابتوب غير مستجيب أثناء
التحميل",background="gray3",foreground="dark orange",
font = ("Bahnschrift SewiBold",10))
download_out.pack(anchor="center",pady=30)
download_name=Label(window,background="gray3",foreground="dark orange",
font = ("Bahnschrift SewiBold",10))
download_name.pack(anchor="ne",padx=30,pady=10)
download_size=Label(window,background="gray3",foreground="dark orange",
font = ("Bahnschrift SewiBold",10))
download_size.pack(anchor="ne",padx=30,pady=10)
download_loc=Label(window,background="gray3",foreground="dark orange",
font = ("Bahnschrift SewiBold",10))
download_loc.pack(anchor="ne",padx=30,pady=10)
window.mainloop()
```
and error is:
```none
Traceback (most recent call last):
File "C:\Users\baraa\PycharmProjects\pythonProject1\folder\baraa.py", line 72, in <module>
path_btn = Button(window,width=11,text= "Selcet Path " ,style="PT.TButton",command= openpath())
File "C:\Users\baraa\PycharmProjects\pythonProject1\folder\baraa.py", line 10, in openpath
download_out.config(text="من الطبيعي عدم استجابة الكمبيوتر عند التحميل")
NameError: name 'download_out' is not defined`
```
|
2021/08/08
|
['https://Stackoverflow.com/questions/68698392', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/16312753/']
|
You dont define `download_out` until line 100, however you call `openpath()` on line 73, so your calling this function before you have defined `download_out`. This function `openpath` first line is referncing `download_out` as this function is called before you define `download_out` is why you get the error saying its not defined
If you want to use `download_out` inside the function `openpath` then you need to define `download_out` before you call `openpath()`. Are you sure you mean to call `openpath` on line 100 or just pass a reference to it?
I suspect you want to change this line
```py
path_btn = Button(window,width=11,text= "Selcet Path ",style="PT.TButton",command=openpath())
```
to
```py
path_btn = Button(window,width=11,text= "Selcet Path ",style="PT.TButton",command=openpath)
```
So your passing a reference to openpath rather than the result of executing openpath
|
since download\_out was declared as global variable you should use the reserved word `global` in order to use it from within the function `openpath`
```
global download_out
download_out.config(text="من الطبيعي عدم استجابة الكمبيوتر عند التحميل")
```
|
68,698,392 |
Hello i want to make a YouTube downloader in python using tkinter but there's an error
the code is:
```
from tkinter import *
from tkinter import filedialog, ttk
from pytube import YouTube
from tkinter.ttk import *
window = Tk()
window.geometry("500x500+350+100")
def openpath():
download_out.config(text="من الطبيعي عدم استجابة الكمبيوتر عند التحميل")
font = ("bahnschrift SewiBold", 10, "bold")
download_name.config(text="")
download_size.config(text="")
download_loc.config(text="")
global direct
direct=filedialog.askdirectory()
path_holder.config(text = direct)
def Download():
url = link_ent.get()
Selceted= types.get()
if len(url) < 1:
link_error.config(text = "الرجاء ادخال موقع الفيديو")
if len(direct) < 1:
path_error.config(text = "الرجاء ادخال مكان تنزيل الملف")
else:
link.config(text="")
path_error.config(text="")
try:
Yt = YouTube(url)
try:
if Selceted == options[0]:
typ = Yt.streams.get_highest_resolution()
elif Selceted == options[1]:
typ = Yt.streams.get_lowest_resolution()
else:
Yt.streams.get_audio_only()
except:
path_error.config(text="حدثت معنا اخطاء")
except:
path_error.config(text="الرجاء ادخال مكان تنزيل صالح!")
window.title("Youtube Downloader")
window.resizable(False,False)
window.config(bg = "gray3")
heading = Label(window, text = "برنامج تحميل الفيديوهات", background = "gray3",foreground = "dark
orange",
font = ("bahnschrift SewiBold",20,"bold"))
heading.pack(anchor="center",pady=10)
link = Label(window,text="الرابط",background="gray3",foreground="dark orange",
font = ("bahnschrift SewiBold",10))
link.pack(anchor="ne",padx=30,pady=25)
entry_url=StringVar()
link_ent=Entry(window,width=52,textvariable = entry_url)
link_ent.place(x=90,y=83)
link_error= Label(window,background="gray3",foreground="dark orange",
font = ("Bahnschrift SewiBold",10))
link_error.place(x=300,y=110)
path = Label(window,text="موقع الملف",background="gray3",foreground="dark orange",
font = ("bahnschrift SewiBold",10))
path.pack(anchor="ne",padx=30,pady=2)
path_holder= Label(window,text="\t\t\t",background="white",foreground="black",
font = ("bahnschrift SewiBold",10))
path_holder.place(x=240,y=130)
path_style=ttk.Style()
path_style.configure("PT.TButton",background="DarkOrange1",foreground="DarkOrange1",
font = ("bahnschrift SewiBold",10))
path_btn = Button(window,width=11,text= "Selcet Path " ,style="PT.TButton",command=
openpath())
path_btn.place(x=323,y=156)
path_error= Label(window,text="Demo",background="gray3",foreground="dark orange",
font = ("Bahnschrift SewiBold",10))
path_error.place(x=280,y=150)
Download_type=Label(window,text="أنواع التنزيل",background="gray3",foreground="dark orange",
font = ("Bahnschrift SewiBold",10))
Download_type.pack(anchor="e",padx=30,pady=37)
options=["جودة عالية","جودة منخفضة","صوت فقط"]
types = ttk.Combobox(window,values=options,width=23)
types.current(0)
types.place(x=240,y=185)
ChooseType=Label(window,text="اختر النوع ",background="gray3",foreground="dark orange",
font = ("Bahnschrift SewiBold",10))
ChooseType.place(x=170,y=187)
download_style=ttk.Style()
download_style.configure("DD.TButton",background="DarkOrange1",foreground="DarkOrange1",
font = ("bahnschrift SewiBold",10))
Download_btn = Button(window,width=11,text= "تحميل " ,style="PT.TButton")
Download_btn.pack(anchor="center",pady=30)
download_out=Label(window,text="طبيغي ان تظهر رسالة اللابتوب غير مستجيب أثناء
التحميل",background="gray3",foreground="dark orange",
font = ("Bahnschrift SewiBold",10))
download_out.pack(anchor="center",pady=30)
download_name=Label(window,background="gray3",foreground="dark orange",
font = ("Bahnschrift SewiBold",10))
download_name.pack(anchor="ne",padx=30,pady=10)
download_size=Label(window,background="gray3",foreground="dark orange",
font = ("Bahnschrift SewiBold",10))
download_size.pack(anchor="ne",padx=30,pady=10)
download_loc=Label(window,background="gray3",foreground="dark orange",
font = ("Bahnschrift SewiBold",10))
download_loc.pack(anchor="ne",padx=30,pady=10)
window.mainloop()
```
and error is:
```none
Traceback (most recent call last):
File "C:\Users\baraa\PycharmProjects\pythonProject1\folder\baraa.py", line 72, in <module>
path_btn = Button(window,width=11,text= "Selcet Path " ,style="PT.TButton",command= openpath())
File "C:\Users\baraa\PycharmProjects\pythonProject1\folder\baraa.py", line 10, in openpath
download_out.config(text="من الطبيعي عدم استجابة الكمبيوتر عند التحميل")
NameError: name 'download_out' is not defined`
```
|
2021/08/08
|
['https://Stackoverflow.com/questions/68698392', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/16312753/']
|
Using wrong value for option `command` in a `Button`, it should be a function name to call when button click, not result of a function.
In your code, function will be called when button defined befor variable `download_out` defined.
```py
#path_btn = Button(window,width=11,text= "Selcet Path " ,style="PT.TButton",command=openpath())
path_btn = Button(window,width=11,text= "Selcet Path " ,style="PT.TButton",command=openpath)
```
|
since download\_out was declared as global variable you should use the reserved word `global` in order to use it from within the function `openpath`
```
global download_out
download_out.config(text="من الطبيعي عدم استجابة الكمبيوتر عند التحميل")
```
|
68,698,392 |
Hello i want to make a YouTube downloader in python using tkinter but there's an error
the code is:
```
from tkinter import *
from tkinter import filedialog, ttk
from pytube import YouTube
from tkinter.ttk import *
window = Tk()
window.geometry("500x500+350+100")
def openpath():
download_out.config(text="من الطبيعي عدم استجابة الكمبيوتر عند التحميل")
font = ("bahnschrift SewiBold", 10, "bold")
download_name.config(text="")
download_size.config(text="")
download_loc.config(text="")
global direct
direct=filedialog.askdirectory()
path_holder.config(text = direct)
def Download():
url = link_ent.get()
Selceted= types.get()
if len(url) < 1:
link_error.config(text = "الرجاء ادخال موقع الفيديو")
if len(direct) < 1:
path_error.config(text = "الرجاء ادخال مكان تنزيل الملف")
else:
link.config(text="")
path_error.config(text="")
try:
Yt = YouTube(url)
try:
if Selceted == options[0]:
typ = Yt.streams.get_highest_resolution()
elif Selceted == options[1]:
typ = Yt.streams.get_lowest_resolution()
else:
Yt.streams.get_audio_only()
except:
path_error.config(text="حدثت معنا اخطاء")
except:
path_error.config(text="الرجاء ادخال مكان تنزيل صالح!")
window.title("Youtube Downloader")
window.resizable(False,False)
window.config(bg = "gray3")
heading = Label(window, text = "برنامج تحميل الفيديوهات", background = "gray3",foreground = "dark
orange",
font = ("bahnschrift SewiBold",20,"bold"))
heading.pack(anchor="center",pady=10)
link = Label(window,text="الرابط",background="gray3",foreground="dark orange",
font = ("bahnschrift SewiBold",10))
link.pack(anchor="ne",padx=30,pady=25)
entry_url=StringVar()
link_ent=Entry(window,width=52,textvariable = entry_url)
link_ent.place(x=90,y=83)
link_error= Label(window,background="gray3",foreground="dark orange",
font = ("Bahnschrift SewiBold",10))
link_error.place(x=300,y=110)
path = Label(window,text="موقع الملف",background="gray3",foreground="dark orange",
font = ("bahnschrift SewiBold",10))
path.pack(anchor="ne",padx=30,pady=2)
path_holder= Label(window,text="\t\t\t",background="white",foreground="black",
font = ("bahnschrift SewiBold",10))
path_holder.place(x=240,y=130)
path_style=ttk.Style()
path_style.configure("PT.TButton",background="DarkOrange1",foreground="DarkOrange1",
font = ("bahnschrift SewiBold",10))
path_btn = Button(window,width=11,text= "Selcet Path " ,style="PT.TButton",command=
openpath())
path_btn.place(x=323,y=156)
path_error= Label(window,text="Demo",background="gray3",foreground="dark orange",
font = ("Bahnschrift SewiBold",10))
path_error.place(x=280,y=150)
Download_type=Label(window,text="أنواع التنزيل",background="gray3",foreground="dark orange",
font = ("Bahnschrift SewiBold",10))
Download_type.pack(anchor="e",padx=30,pady=37)
options=["جودة عالية","جودة منخفضة","صوت فقط"]
types = ttk.Combobox(window,values=options,width=23)
types.current(0)
types.place(x=240,y=185)
ChooseType=Label(window,text="اختر النوع ",background="gray3",foreground="dark orange",
font = ("Bahnschrift SewiBold",10))
ChooseType.place(x=170,y=187)
download_style=ttk.Style()
download_style.configure("DD.TButton",background="DarkOrange1",foreground="DarkOrange1",
font = ("bahnschrift SewiBold",10))
Download_btn = Button(window,width=11,text= "تحميل " ,style="PT.TButton")
Download_btn.pack(anchor="center",pady=30)
download_out=Label(window,text="طبيغي ان تظهر رسالة اللابتوب غير مستجيب أثناء
التحميل",background="gray3",foreground="dark orange",
font = ("Bahnschrift SewiBold",10))
download_out.pack(anchor="center",pady=30)
download_name=Label(window,background="gray3",foreground="dark orange",
font = ("Bahnschrift SewiBold",10))
download_name.pack(anchor="ne",padx=30,pady=10)
download_size=Label(window,background="gray3",foreground="dark orange",
font = ("Bahnschrift SewiBold",10))
download_size.pack(anchor="ne",padx=30,pady=10)
download_loc=Label(window,background="gray3",foreground="dark orange",
font = ("Bahnschrift SewiBold",10))
download_loc.pack(anchor="ne",padx=30,pady=10)
window.mainloop()
```
and error is:
```none
Traceback (most recent call last):
File "C:\Users\baraa\PycharmProjects\pythonProject1\folder\baraa.py", line 72, in <module>
path_btn = Button(window,width=11,text= "Selcet Path " ,style="PT.TButton",command= openpath())
File "C:\Users\baraa\PycharmProjects\pythonProject1\folder\baraa.py", line 10, in openpath
download_out.config(text="من الطبيعي عدم استجابة الكمبيوتر عند التحميل")
NameError: name 'download_out' is not defined`
```
|
2021/08/08
|
['https://Stackoverflow.com/questions/68698392', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/16312753/']
|
You dont define `download_out` until line 100, however you call `openpath()` on line 73, so your calling this function before you have defined `download_out`. This function `openpath` first line is referncing `download_out` as this function is called before you define `download_out` is why you get the error saying its not defined
If you want to use `download_out` inside the function `openpath` then you need to define `download_out` before you call `openpath()`. Are you sure you mean to call `openpath` on line 100 or just pass a reference to it?
I suspect you want to change this line
```py
path_btn = Button(window,width=11,text= "Selcet Path ",style="PT.TButton",command=openpath())
```
to
```py
path_btn = Button(window,width=11,text= "Selcet Path ",style="PT.TButton",command=openpath)
```
So your passing a reference to openpath rather than the result of executing openpath
|
Using wrong value for option `command` in a `Button`, it should be a function name to call when button click, not result of a function.
In your code, function will be called when button defined befor variable `download_out` defined.
```py
#path_btn = Button(window,width=11,text= "Selcet Path " ,style="PT.TButton",command=openpath())
path_btn = Button(window,width=11,text= "Selcet Path " ,style="PT.TButton",command=openpath)
```
|
118,996 |
This is my hangman game code for my GCSE computer science coursework. It has been submitted but I was wondering if there is anyway to improve it.
```
import random
import time
#Variables holding different words for each difficulty
EASYWORDS = open("Easy.txt","r+")
words = []
for item in EASYWORDS:
words.append(item.strip('\n'))
MEDWORDS = open("Med.txt","r+")
words = []
for item in MEDWORDS:
words.append(item.strip('\n'))
HARDWORDS = open("Hard.txt","r+")
words = []
for item in HARDWORDS:
words.append(item.strip('\n'))
INSANEWORDS = open("Insane.txt", "r+")
words = []
for item in INSANEWORDS:
words.append(item.strip('\n'))
#Where the user picks a difficulty
def difficulty():
print("easy\n")
print("medium\n")
print("hard\n")
print("insane\n")
menu=input("Welcome to Hangman, type in what difficulty you would like... ").lower()
if menu == "hard" or menu == "h":
hard()
elif menu == "medium" or menu == "m" or menu =="med":
med()
elif menu == "easy" or menu == "e":
easy()
elif menu == "insane" or menu == "i":
insane()
else:
print("Please type in either hard, medium, easy or insane!")
difficulty()
def difficulty2():
print("Easy\n")
print("Medium\n")
print("Hard\n")
print("Insane\n")
print("Quit\n")
menu=input("Welcome to Hangman, type in what difficulty you would like. Or would you like to quit the game?").lower()
if menu == "hard" or menu == "h":
hard()
elif menu == "medium" or menu == "m" or menu =="med":
med()
elif menu == "easy" or menu == "e":
easy()
elif menu == "insane" or menu == "i":
insane()
elif menu == "quit" or "q":
quit()
else:
print("Please type in either hard, medium, easy or insane!")
difficulty()
#if the user picked easy for their difficulty
def easy():
global score
print ("\nStart guessing...")
time.sleep(0.5)
word = random.choice(words).lower()
guesses = ''
fails = 0
while fails >= 0 and fails < 10:
failed = 0
for char in word:
if char in guesses:
print (char,)
else:
print ("_"),
failed += 1
if failed == 0:
print ("\nYou won, WELL DONE!")
score = score + 1
print ("your score is,", score)
print ("the word was, ", word)
difficultyEASY()
guess = input("\nGuess a letter:").lower()
while len(guess)==0:
guess = input("\nTry again you muppet:").lower()
guess = guess[0]
guesses += guess
if guess not in word:
fails += 1
print ("\nWrong")
if fails == 1:
print ("You have", + fails, "fail....WATCH OUT!" )
elif fails >= 2 and fails < 10:
print ("You have", + fails, "fails....WATCH OUT!" )
if fails == 10:
print ("You Lose\n")
print ("your score is, ", score)
print ("the word was,", word)
score = 0
difficultyEASY()
#if the user picked medium for their difficulty
def med():
global score
print ("\nStart guessing...")
time.sleep(0.5)
word = random.choice(words).lower()
guesses = ''
fails = 0
while fails >= 0 and fails < 10:
failed = 0
for char in word:
if char in guesses:
print (char,)
else:
print ("_"),
failed += 1
if failed == 0:
print ("\nYou won, WELL DONE!")
score = score + 1
print ("your score is,", score)
difficultyMED()
guess = input("\nGuess a letter:").lower()
while len(guess)==0:
guess = input("\nTry again you muppet:").lower()
guess = guess[0]
guesses += guess
if guess not in word:
fails += 1
print ("\nWrong")
if fails == 1:
print ("You have", + fails, "fail....WATCH OUT!" )
elif fails >= 2 and fails < 10:
print ("You have", + fails, "fails....WATCH OUT!" )
if fails == 10:
print ("You Lose\n")
print ("your score is, ", score)
print ("the word was,", word)
score = 0
difficultyMED()
#if the user picked hard for their difficulty
def hard():
global score
print ("\nStart guessing...")
time.sleep(0.5)
word = random.choice(words).lower()
guesses = ''
fails = 0
while fails >= 0 and fails < 10: #try to fix this
failed = 0
for char in word:
if char in guesses:
print (char,)
else:
print ("_"),
failed += 1
if failed == 0:
print ("\nYou won, WELL DONE!")
score = score + 1
print ("your score is,", score)
difficultyHARD()
guess = input("\nGuess a letter:").lower()
while len(guess)==0:
guess = input("\nTry again you muppet:").lower()
guess = guess[0]
guesses += guess
if guess not in word:
fails += 1
print ("\nWrong")
if fails == 1:
print ("You have", + fails, "fail....WATCH OUT!" )
elif fails >= 2 and fails < 10:
print ("You have", + fails, "fails....WATCH OUT!" )
if fails == 10:
print ("You Lose\n")
print ("your score is, ", score)
print ("the word was,", word)
score = 0
difficultyHARD()
#if the user picked insane for their difficulty
def insane():
global score
print ("This words may contain an apostrophe. \nStart guessing...")
time.sleep(0.5)
word = random.choice(words).lower()
guesses = ''
fails = 0
while fails >= 0 and fails < 10: #try to fix this
failed = 0
for char in word:
if char in guesses:
print (char,)
else:
print ("_"),
failed += 1
if failed == 0:
print ("\nYou won, WELL DONE!")
score = score + 1
print ("your score is,", score)
difficultyINSANE()
guess = input("\nGuess a letter:").lower()
while len(guess)==0:
guess = input("\nTry again you muppet:").lower()
guess = guess[0]
guesses += guess
if guess not in word:
fails += 1
print ("\nWrong")
if fails == 1:
print ("You have", + fails, "fail....WATCH OUT!" )
elif fails >= 2 and fails < 10:
print ("You have", + fails, "fails....WATCH OUT!" )
if fails == 10:
print ("You Lose\n")
print ("your score is, ", score)
print ("the word was,", word)
score = 0
difficultyINSANE()
def start():
Continue = input("Do you want to play hangman?").lower()
while Continue in ["y", "ye", "yes", "yeah"]:
name = input("What is your name? ")
print ("Hello, " + name, "Time to play hangman! You have ten guesses to win!")
print ("\n")
time.sleep(1)
difficulty()
else:
quit
#whether they want to try a diffirent difficulty or stay on easy
def difficultyEASY():
diff = input("Do you want to change the difficulty?. Or quit the game? ")
if diff == "yes" or difficulty =="y":
difficulty2()
elif diff == "no" or diff =="n":
easy()
#whether they want to try a diffirent difficulty or stay on medium
def difficultyMED():
diff = input("Do you want to change the difficulty?. Or quit the game? ")
if diff == "yes" or difficulty =="y":
difficulty2()
elif diff == "no" or diff =="n":
med()
#whether they want to try a diffirent difficulty or stay on hard
def difficultyHARD():
diff = input("Do you want to change the difficulty?. Or quit the game? ")
if diff == "yes" or difficulty =="y":
difficulty2()
elif diff == "no" or diff =="n":
hard()
#whether they want to try a diffirent difficulty or stay on insane
def difficultyINSANE():
diff = input("Do you want to change the difficulty?. Or quit the game? ")
if diff == "yes" or difficulty =="y":
difficulty2()
elif diff == "no" or diff =="n":
insane()
score = 0
start()
```
|
2016/02/05
|
['https://codereview.stackexchange.com/questions/118996', 'https://codereview.stackexchange.com', 'https://codereview.stackexchange.com/users/96787/']
|
Input checking
==============
The way you're currently checking input is clunky, hard to write, and hard to read. For example, you have the following chunk of code:
>
>
> ```
> menu=input("Welcome to Hangman, type in what difficulty you would like... ").lower()
>
> if menu == "hard" or menu == "h":
>
> hard()
>
> elif menu == "medium" or menu == "m" or menu =="med":
>
> med()
>
> elif menu == "easy" or menu == "e":
>
> easy()
>
> elif menu == "insane" or menu == "i":
>
> insane()
>
> else:
> print("Please type in either hard, medium, easy or insane!")
> difficulty()
>
> ```
>
>
There are quite a few things that can be improved here, so let's start with the obvious. Rather than having multiple individual conditional expressions to check the value of a variable, simply create a list of all possible values and use the `in` operator to check the variable's value, like this, for example:
```
if menu in ["medium", "med", "m"]:
med()
```
Next, I'd suggest that you add a `.strip()` call to the following line:
>
>
> ```
> menu=input("Welcome to Hangman, type in what difficulty you would like... ").lower()
>
> ```
>
>
The [`.strip()`](https://docs.python.org/3/library/string.html#string.strip) function, when no arguments are specified, will remove leading and trailing whitespace. This means that a user can enter something like `" med "` without worrying that the program might reject their input. In addition, you could also consider using [`re.sub`](https://docs.python.org/3/library/re.html#re.sub7) if you want to get rid of additional characters.
---
Building word lists
===================
You've got a lot of repetition in the following chunk of code:
>
>
> ```
> #Variables holding different words for each difficulty
> EASYWORDS = open("Easy.txt","r+")
> words = []
> for item in EASYWORDS:
> words.append(item.strip('\n'))
> MEDWORDS = open("Med.txt","r+")
> words = []
> for item in MEDWORDS:
> words.append(item.strip('\n'))
>
> HARDWORDS = open("Hard.txt","r+")
> words = []
> for item in HARDWORDS:
> words.append(item.strip('\n'))
>
> INSANEWORDS = open("Insane.txt", "r+")
> words = []
> for item in INSANEWORDS:
> words.append(item.strip('\n'))
>
> ```
>
>
The best way to do this would probably be to use generator expressions, and encapsulate it into a function, like this:
```
def build_word_list(word_file):
words = [item.strip("\n") for item in word_file]
return words
```
You can then use it like this, assuming you've already defined `build_word_list`:
```
EASYWORDS = open("Easy.txt","r+")
MEDWORDS = open("Med.txt","r+")
HARDWORDS = open("Hard.txt","r+")
INSANEWORDS = open("Insane.txt", "r+")
easy_words = build_word_list(EASYWORDS)
medium_words = build_word_list(MEDWORDS)
hard_words = build_word_list(HARDWORDS)
insane_words = build_word_list(INSANEWORDS)
```
I've also fixed a pretty large bug. You were creating only *one* word list, which meant that regardless of what difficulty you chose, you'd have words from all difficulties. Now there are separate word lists for each separate difficulty.
---
Creating a `play` function
==========================
The functions `easy`, `med`, `hard` and `insane` are all identical. There is no reason that you should be repeating yourself over and over again. To help prevent the repetition, create one simple `play` function with an argument named `word_list`. The signature for the `play` function *should* look like this:
def play(word\_list):
# Game logic goes here
You'd simply pass a word list, like `easy_words` or `insane_words` as the `word_list` argument, and then use the `word_list` argument in the function.
---
Misc. Nitpicks
==============
There are quite a few things I want to nitpick, so get ready.
* The `difficulty2` function serves no purpose. It is identical in every way to `difficulty`. Any calls to `difficulty2` in your code can just be changed to `difficulty` calls.
* Similarly to the above nitpick, your `difficultyEASY`, `difficultyMED`, etc. functions are *also* virtually identical. Simply create one function named `change_difficulty` and you're set.
* You need whitespace between your operators, and an introduction to [PEP8](https://www.python.org/dev/peps/pep-0008/), the official Python style guide.. Nobody wants to read code that looks like it was plucked straight out of a PPCG answer.
|
Word Storage
------------
1. Don't leave file handles open if you're done with them
Each time you `open()` a file, it allocates operating system and interpreter resources (*handles*). If you're done with a file, `close()` it!
2. You're actually **just making ONE huge word list** (**EDIT**: I see [@Ethan Bierlein](https://codereview.stackexchange.com/users/53251/ethan-bierlein) already pointed this out).
3. (Again, as [@Ethan Bierlein](https://codereview.stackexchange.com/users/53251/ethan-bierlein)'s answer goes to) You're repeating a LOT of similar code for your word lists.
Ethan's generator is a good idea here (just don't forget to `close()` those file-handles!
---
(Almost) Total repetition of game logic
---------------------------------------
The functions `easy`, `med`, `hard` and `insane` are 99% similar (okay I didn't calculate an actual percentage, but you know what I mean).
these can easily be accomplished with **MUCH** less code by making them more parameterised (*i.e.* taking an argument to a generated wordlist for difficulty).
---
Pythonic startup
----------------
Not that it's a huge deal for something like this, but if you want it to be more Pythonic, the last line:
>
> `main()`
>
>
>
Should be put inside an if statement to ensure the script isn't being used as a module, etc:
```
if __name__=='__main__':
main()
```
This simply ensures `main` is only called if we are the *main* script in the interpreter.
---
String concatenation
--------------------
Also, not an \* end of the world \* thing, but (for example), the following line inside your `start` function:
>
> `print ("Hello, " + name, "Time to play hangman! You have ten guesses to win!")`
>
>
>
Uses *string concatenation* inside `print`. This is generally bad practise in Python. Instead, you should be using format strings:
`print ("Hello, %s, Time to play hangman! You have ten guesses to win!" % name)`
---
Needless if statements (and more code repetition)
-------------------------------------------------
I'm not sure what the purpose of the following if/elif block is (as they **both** have *exactly* the same code in them:
>
>
> ```
> if fails == 1:
> print ("You have", + fails, "fail....WATCH OUT!" )
> elif fails >= 2 and fails < 10:
> print ("You have", + fails, "fails....WATCH OUT!" )
> if fails == 10:
> ...
>
> ```
>
>
But they appear in EACH of the (many) game play functions.
This would much better be done with one `if` (and using a format string):
```
if fails < 10:
print ("You have %d fails....WATCH OUT!" % fails )
else:
...
```
Also, note the *slight* logic difference here, the `else` is essentially all cases where `fails` is =>10, where as your code *just tests* ==10.
|
55,092,777 |
I have created this function called `createTeams()` which is creating data for the table.
```
func createTeams() {
let team1 = teams(Team1: "Chelsea", Team2: "Arsenal" , startTime: "15/06/2019", location: "London")
let team2 = teams(Team1: "Barcelona", Team2: "Manchester" , startTime: "16/06/2019", location: "London")
let team3 = teams(Team1: "Real Madrid", Team2: "FC Bayern" , startTime: "17/06/2019", location: "London")
let team4 = teams(Team1: "Chelsea", Team2: "Juvantis" , startTime: "18/06/2019", location: "London")
let team5 = teams(Team1: "LiverPool", Team2: "FC Dallas" , startTime: "19/06/2019", location: "London")
let team6 = teams(Team1: "Atlanta FC", Team2: "NewCastle Utd." , startTime: "20/06/2019", location: "London")
teamsList.append(team1)
teamsList.append(team2)
teamsList.append(team3)
teamsList.append(team4)
teamsList.append(team5)
teamsList.append(team6)
}
```
I call this function in `viewDidLoad` and it works fine.
However, I have this `print` statement in `viewDidLoad` that doesn't work.
```
override func viewDidLoad() {
super.viewDidLoad()
print("Awake");
self.createTeams()
tableView.dataSource = self
tableView.delegate = self
}
```
I Even have this button with a simple print statement that is not working either.
```
@IBAction func subscribeButtonClicked(_ sender: UIButton) {
print("Subscribe Button Clicked")
if(isSubscribed) {
print("User Subscribed to this ");
isSubscribed = false
} else {
print("User Unsubbed");
isSubscribed = true
}
}
```
---
>
> Edit: It is a watchKit Project i am developing so it was loading from
> the watch Interface and printing from there in order to print those
> statements i had to run the project on a iPhone simulator individually
>
>
>
|
2019/03/10
|
['https://Stackoverflow.com/questions/55092777', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']
|
So after doing a lot of research and following the previous steps mentioned about the console not showing it turned out that I've hid the console area or deactivated it.
To activate/show it :
1. Hover to "View" in the top menu in Xcode
2. Tap "Debug Area"
3. Choose "Activate Console"
or simply click command+shift+c
|
The problem is sometimes xcode debugger crashed due to some internal inconsistency or for other reasons. So what we write print statements cannot be shown in debugger window.
You need to do these steps:
1. Clean the xcode.
2. Force quit the xcode.
3. Clean the derieved data.
4. Restart the xcode and run it.
It will work fine.
|
362,271 |
This is kind of a meta-question *for* Meta Stack Exchange.
You may remember my question about a [Vietnamese to English translation issue](https://meta.stackexchange.com/questions/361994).
I realized it wasn't suitable for Meta Stack Exchange, and because regular users can't delete questions with answers, I decided to flag for mods to delete it.
My first flag said:
>
> I realize now that this is not^1 really about SE, so I was wondering if I could have it deleted?
>
>
>
It was then declined, and I got this message:
>
> flags should only be used to make moderators aware of content that requires their intervention
>
>
>
I tried reflagging and changing my message to this just in case the first one was misinterpreted:
>
> I already flagged this post asking for deletion, but it was declined. Maybe they misinterpreted my flag? Anyway, could this post be deleted by a mod (I can't; it has an answer) because I now realize it is not about SE?
>
>
>
It was then again declined with the same automated message:
>
> flags should only be used to make moderators aware of content that requires their intervention
>
>
>
Why were my flags declined with such message when I was clearly asking a moderator to delete my question (which I can't do, therefore meaning that it requires a mod to).
What should I do now? The question is off-topic, low scored (perhaps I could mark as community wiki?), and leaves an unneeded black mark on my answer list for a small matter - so I feel like it would be best deleted. I see Journeyman Geek's point though, so I am a little confused. What would the best course of action be?
And I'm afraid to flag a third time, just in case it is declined and I pick up a flag ban.
---
I don't think this question is a duplicate of the FAQ on [How does deleting work? What can cause a post to be deleted, and what does that actually mean? What are the criteria for deletion?](https://meta.stackexchange.com/questions/5221) because I already know how deleting works and the criteria behind it, I just want to know why my flags to delete were rejected. The proposed dup question tells you to flag for mod deletion, which I did. It doesn't provide any further info.
^1 I flagged originally without the not - oops, I was typing fast and my mind jumped over a word. For clarity purpose, I meant to add a *not*.
|
2021/03/18
|
['https://meta.stackexchange.com/questions/362271', 'https://meta.stackexchange.com', 'https://meta.stackexchange.com/users/879421/']
|
The really funny thing is that I was having a conversation about multiple flags earlier today.
>
> There's nothing that annoys a mod more than repeated flagging of a thing. I vaguely remember there's folks who literally have been flagging the same post over years.
>
>
> It's been seen, we've decided what to do. Mods do talk and leave trails of what happened – and generally have long memories
>
>
> Much like how a bounty is spending 'reputation' to get attention (as opposed to an answer as many assumes) – the goal of a flag, accepted or declined, is to get a mod to take a look.
>
>
>
The point of a flag is to get a mod to take a look, so more than one flag from a user for a question is redundant.
While I didn't handle the flag(s) in question – we don't *generally* delete questions with positively scored, well-regarded answers through the mod deletion route. It is unfair for the person or people who answered.
So it's fine. It has been seen, judged, and one or more mods have decided not to delete it.
|
>
> I realize now that this is really about SE, so I was wondering if I could have it deleted?
>
>
>
If it's about SE, it's [on-topic for Meta Stack Exchange](/help/whats-meta). That's a good reason to have it *not* deleted, so declining the flags is a logical response.
|
43,963,589 |
got a little problem. I have the following code:
```
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse("result1.xml");
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression expr = xpath.compile("//element");
String elements = (String) expr.evaluate(doc, XPathConstants.STRING);
```
What i get :
```
[email protected]
Cheryl
Blake
195115
```
What i want:
```
<person>
<email>[email protected]</email>
<firstname>Cheryl</firstname>
<lastname>Blake</lastname>
<number>195115</number>
</person>
```
So as you can see i want the full XML tree. Not just the NodeValue.
Maybe somebody knows the trick.
Thanks for any help.
|
2017/05/14
|
['https://Stackoverflow.com/questions/43963589', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']
|
The stack trace is pretty clear, it "talks" about this line:
```
<div th:utext="'Exception: ' + ${exception.message}" th:remove="tag">${exception.message}</div>
```
It seems that your server is failing to parse the Thymeleaf page,
**it can't find the exception object with a message field**.
I tried to figure out where exactly you pass the exception **into your model**, but I did not find it.
This function is not doing that:
```
private Map<String, Object> getErrorAttributes(HttpServletRequest request,
boolean includeStackTrace) {
RequestAttributes requestAttributes = new ServletRequestAttributes(request);
return this.errorAttributes.getErrorAttributes(requestAttributes,
includeStackTrace);
}
```
|
You can check for null on the `exception`:
```
<div th:if="${exception != null}"
th:utext="'Exception: ' + ${exception.message}" th:remove="tag">
</div>
```
Or you can use the shorthand:
```
<div th:utext="'Exception: ' + ${exception?.message}" th:remove="tag"></div>
```
|
37,933,403 |
I have a presentational component called Navbar.jsx that returns another presentational component based on whether the user is authenticated or not. When I run webpack, I am getting an error saying that the "if" in my if statement is an unexpected token. You'll see the if else statement in the navbar-collapse div. Here is Navbar.jsx:
```
import React, {PropTypes} from 'react';
import PreAuthNavTabs from './PreAuthNavTabs';
import PostAuthNavTabs from './PostAuthNavTabs';
const Navbar = ({ activeUser, loginUser }) => {
return (
<div>
<div className="navbar navbar-default navbar-fixed-top" role="navigation">
<div className="container">
<div className="navbar-header">
<button type="button" className="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span className="sr-only">Toggle Navigaton</span>
<span className="icon-bar"></span>
<span className="icon-bar"></span>
<span className="icon-bar"></span>
</button>
<Link to="/inventory"><img className="navbar-brand" src='../../css/hello_bacsi.png'></img></Link>
</div>
<div className="navbar-collapse collapse">
{
if (activeUser) {
return <PostAuthNavTabs activeUser={activeUser} />;
} else {
return <PreAuthNavTabs loginUser={loginUser} />;
}
}
</div>
</div>
</div>
</div>
);
};
Navbar.propTypes = {
activeUser: PropTypes.object,
loginUser: PropTypes.func
};
export default Navbar;
```
|
2016/06/20
|
['https://Stackoverflow.com/questions/37933403', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5264835/']
|
There is no silver bullet. [Different HTML parsers behave differently](https://www.crummy.com/software/BeautifulSoup/bs4/doc/#differences-between-parsers) and you should pick the one that works for your particular page. Works in this case basically means, that you can get to your desired data.
`lxml` parser is generally faster, `html5lib` is the most lenient one - this kind of difference would be relevant if you have a broken or non-well-formed HTML to parse. `html.parser` is built-in and can help to avoid extra dependencies, if this is a problem. Here is a [related table](https://www.crummy.com/software/BeautifulSoup/bs4/doc/#installing-a-parser) that highlights the differences.
|
I've learned it the hard way. It's been killing me. I just couldn't figure out why the tag I wanted included something that wasn't in that tag. Turned out the html parser wasn't working correctly with that site. After hours of headache, I suddenly tried switching to lxml parser, and lo and behold... The unwated stuff was gone as it should have been!
|
31,663,672 |
I am using a console application and I have batches of 20 URIs that I need to read from and I have found a massive speed boost by making all tasks and running them in parallel then sorting the results on completion in a different thread (allowing the next batch to be fetched).
In the calls I am currently using, each thread blocks when it gets the response stream, I also see there is a async version of the same method `GetResponseAsync`.
I understand there are benefits of freeing up the thread pool by using async [Await and Async in same line](https://stackoverflow.com/questions/31640371/await-and-async-in-same-line) instead of blocking:
**Async version**
```
return Task.Run(async () =>
{
var uri = item.Links.Alternate();
var request = (HttpWebRequest)WebRequest.Create(uri);
var response = await request.GetResponseAsync();
var stream = response.GetResponseStream();
if (stream == null) return null;
var reader = new StreamReader(stream);
return new FetchItemTaskResult(reader.ReadToEnd(), index, uri);
});
```
**Blocking version**
```
return Task<FetchItemTaskResult>.Factory.StartNew(() =>
{
var uri = item.Links.Alternate();
var request = (HttpWebRequest)WebRequest.Create(uri);
var response = request.GetResponse();
var stream = response.GetResponseStream();
if (stream == null) return null;
var reader = new StreamReader(stream);
return new FetchItemTaskResult(reader.ReadToEnd(), index, uri);
});
```
However I am seeing strange pauses on the console app with the async version where a System.Timers.Timer elapsed event stops being called for a many seconds (when it should go off every second).
The blocking one runs at around 3,500 items per second, CPU usage is at ~30% across all cores.
The async on runs at around 3,800 events per second, CPU usage is a little higher than the blocking but not by much (only 5%)... however my timer I am using seems to pause for around 10 to 15 seconds once every minute or so, in my `Main()` function:
```
private static void Main(string[] args)
{
// snip some code that runs the tasks
var timer = new System.Timers.Timer(1000);
timer.Elapsed += (source, e) =>
{
Console.WriteLine(DateTime.UtcNow);
// snip non relevant code
Console.WriteLine("Commands processed: " + commandsProcessed.Sum(s => s.Value) + " (" + logger.CommandsPerSecond() + " per second)");
};
timer.Start();
Console.ReadKey();
}
```
So would seem the timer and thread pool are some how related when using async (and only async, no pauses when blocking), or perhaps not, either way any ideas what is going on please and how to diagnose further?
|
2015/07/27
|
['https://Stackoverflow.com/questions/31663672', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/915839/']
|
You should use [CSS counters](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Counters) in this case.
**Update solution (better)**. Finally, a little more flexible approach would be resetting counter on the `body` initially instead of `section:first-child` and also on any immediate next sibling of the `h1`.
```
body,
section h1 + * {
counter-reset: section 0;
}
```
---
**Updated solution**. Turned out that my original solution is not very good as pointed in comments. Here is revised correct version which should work properly with arbitrary number of nested or sibling sections.
```css
section:first-child,
section h1 + section {
counter-reset: section 0;
}
section h1:before {
counter-increment: section;
content: counters(section, ".") " ";
}
```
```html
<section>
<h1>This should be numbered 1</h1>
<section>
<h1>This should be numbered 1.1</h1>
<p>blah</p>
</section>
<section>
<h1>This should be numbered 1.2</h1>
<p>blah</p>
</section>
<section>
<h1>This should be numbered 1.3</h1>
<section>
<h1>This should be numbered 1.3.1</h1>
<p>blah</p>
</section>
<section>
<h1>This should be numbered 1.3.2</h1>
<p>blah</p>
</section>
</section>
<section>
<h1>This should be numbered 1.4</h1>
<p>blah</p>
</section>
</section>
<section>
<h1>This should be numbered 2</h1>
<section>
<h1>This should be numbered 2.1</h1>
<p>blah</p>
</section>
<section>
<h1>This should be numbered 2.2</h1>
<p>blah</p>
</section>
</section>
```
---
**Original (buggy)**. There is tricky part in this case: counter should increment for every subsequent `section`. This can be achieved with `section + section` selector:
```css
section {
counter-reset: section;
}
section + section {
counter-increment: section;
}
section h1:before {
counter-increment: section;
content: counters(section, ".") " ";
}
```
```html
<section>
<h1>This should be numbered 1</h1>
<section>
<h1>This should be numbered 1.1</h1>
<p>blah</p>
</section>
<section>
<h1>This should be numbered 1.2</h1>
<p>blah</p>
</section>
</section>
<section>
<h1>This should be numbered 2</h1>
<section>
<h1>This should be numbered 2.1</h1>
<p>blah</p>
</section>
</section>
```
|
```
li{
text-align: center;
}
<ol type="1">
<li>this</li>
<li>is</li>
<li>a</li>
<li>List</li>
</ol>
```
thats not testet but should work
|
1,471,570 |
How can I use dynamic SQL statements in MySQL database and without using session variables?
Right now I have such a code (in MySQL stored procedure):
```
(...)
DECLARE TableName VARCHAR(32);
SET @SelectedId = NULL;
SET @s := CONCAT("SELECT Id INTO @SelectedId FROM ", TableName, " WHERE param=val LIMIT 1");
PREPARE stmt FROM @s;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
IF ISNULL(@SelectedId) THEN
(...)
```
But I'd like to use only local variables, that means I'd like to start this procedure with:
```
DECLARE TableName VARCHAR(32);
DECLARE s VARCHAR(1024);
DECLARE SelectedId INTEGER UNSIGNED;
(...)
```
and do not use @ char anywhere. Is there any way to do this?
|
2009/09/24
|
['https://Stackoverflow.com/questions/1471570', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/160760/']
|
Sorry, prepared statements in MySQL are session-global. According to <http://dev.mysql.com/doc/refman/5.1/en/sql-syntax-prepared-statements.html>, "A prepared statement is also global to the session."
And there's no other way (besides prepared statements) to execute dynamic SQL in MySQL 5.x.
So you can of course replace "@s" above, but AFAIK you're stuck with @SelectedId.
In MySQL 6.x, there is a feature planned which will add an "EXECUTE IMMEDIATE" statement which will execute dynamic SQL. See <http://forge.mysql.com/worklog/task.php?id=2793>.
|
The link above gives a page not found. See here instead :
<https://dev.mysql.com/doc/refman/5.7/en/prepare.html>
The end para clearly states :
"
A statement prepared in stored program context cannot refer to stored procedure or function parameters or local variables because they go out of scope when the program ends and would be unavailable were the statement to be executed later outside the program. As a workaround, refer instead to user-defined variables, which also have session scope;
"
|
25,414 |
As an Electrical Engineer (emphasis in RF and radar, class of '74) who has followed the space program(s) since Mercury, and a prior flight test telemetry engineer, I was wondering if anyone knows what frequency (frequencies), effective radiated power (ERP), and the modulation modes (I am assuming it's PCM) are being used to transmit the SpaceX images from the Tesla in space Roadster? Are they using the TDRSS satellites for data relay (although the data is only high definition images, no usable telemetry metrics that I know of).
I have been watching for any signs of data loss (dropouts) and so far this is still a very strong signal from the "spacecraft". I saw no drop outs as it performed its barbecue continuous yaw thermal control maneuver about its axis; I looked all over the SpaceX website, but there is very little technical information. It would appear that the only antennae are omnidirectional - no sign of a parabolic dish, or X-Y drives for positioning it.
|
2018/02/16
|
['https://space.stackexchange.com/questions/25414', 'https://space.stackexchange.com', 'https://space.stackexchange.com/users/23550/']
|
You can see the FCC launch permit here: <https://apps.fcc.gov/oetcf/els/reports/STA_Print.cfm?mode=current&application_seq=80036>
(STA is a Special Temporary Authority) "Application includes three sub-orbital first stage boosters, and an orbital second stage."
There are separate listings for "Launch vehicle 1st stage, sub-orbital", "Launch vehicle 2nd stage, orbital", "Launch vehicle S1-a, sub-orbital ", and "Launch vehicle S1-b, sub-orbital". Together, they have six 20W emitters with frequencies from 2211 to 2375 MHz and bit rates from 2.777 Mbps to 6.25Mbps.
Interestingly, they left the answer to "height above ground to tip of antenna" blank.
|
That is a lot of questions, let me try to address them one by one:
>
> I was wondering if anyone knows what frequency (frequencies),
> effective radiated power (ERP), and the modulation modes (I am
> assuming it's PCM) are being used
>
>
>
There has been little in the public domain in regards to the on-board RF equipment of the Falcon-Heavy, and it is assumed no RF equipment on the Tesla (e.g. it is using 2nd stage infrastructure).
From a [related question & answer](https://space.stackexchange.com/questions/25074/how-did-the-communication-work-between-the-spacex-tesla-and-earth/25075#25075) the frequencies of the Falcon-9 are well documented, including their Pout in dBm, purpose, and modulation, the following from [newer (Rev-2) version of the Falcon-9 user-guide](http://www.spacex.com/sites/spacex/files/falcon_9_users_guide_rev_2.0.pdf):
[](https://i.stack.imgur.com/SNpgg.png)
Whether they actually used PCM modulation is not certain. The [older Falcon-9 (Rev-1) user-guide](https://spaceflightnow.com/falcon9/001/f9guide.pdf) actually lists NTSC as a feed protocol for Stage-2 Video, Page 37, Table 5.2:
[](https://i.stack.imgur.com/SHKQ4.png)
The [newer (Rev-2) version of the Falcon-9 user-guide](http://www.spacex.com/sites/spacex/files/falcon_9_users_guide_rev_2.0.pdf) does not list this type of table, nor does in mentions NTSC at all.
>
> Are they using the TDRSS satellites for data relay (although the data
> is only high definition images, no usable telemetry metrics that I
> know of)
>
>
>
They are not, the just over 4-hour live feed came from the Stage-2 directly, until batteries ran out (8-hours sooner than expected)
>
> I have been watching for any signs of data loss (dropouts) and so far
> this is still a very strong signal from the "spacecraft". I saw no
> drop outs as it performed its barbecue continuous yaw thermal control
> maneuver about its axis; I looked all over the SpaceX website, but
> there is very little technical information.
>
>
>
Unfortunately the live-feed has ceased due to battery depleation. The only video's left on the internet are re-runs of the first 4 hours. Although you can find lots of references that the video ran out after 4 hours, none of them are authoratitive. Most of them are news outlets, with various levels of trustworthyness.
However SpaceX own website has an [article](http://www.spacex.com/news/2018/02/07/falcon-heavy-test-launch) which clearly details the following:
*"You can watch a replay of the test flight below, as well as a replay of the live view of Starman in orbit"*
One may safely assume there is no longer a live feed, when the best SpaceX themselves have; is a replay.
>
> It would appear that the only antennae are omnidirectional - no sign
> of a parabolic dish, or X-Y drives for positioning it.
>
>
>
It is not sure what type of antennas, omnidirectional or directional, are on the Falcon-Heavy. Again referencing an [older Rev-1 Falcon-9 user-guide](https://spaceflightnow.com/falcon9/001/f9guide.pdf) Page 11, does show us the design for that launch vehicle:
[](https://i.stack.imgur.com/cIzte.png)
Again, it is logical to assume that the Falcon-Heavy is similar than the Falcon-9 in this regard.
Without actual details in the public domain on the Falcon-Heavy, this answer is unfortunately based on quite some assumptions. Nevertheless, it will give you a good idea how communications could have been handled.
|
13,724,271 |
please give me correct way of movemenent. where can i get useful info?
what i want is: -
there is the form with parameters and 2 buttons: Search, Reset.
i want to implement logic - input some params and click search button - GridView as result is shown below.
examples, articles would be helpful.Thanks!
|
2012/12/05
|
['https://Stackoverflow.com/questions/13724271', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1450372/']
|
Are the devices all running the same version of the OS? Another possibility (beyond colorspaces, which someone already mentioned) is that the JPG decoding libraries may be subtly different. As JPEG is a lossy image format, it's not inconceivable that different decoders would produce resulting bitmaps that were not bit-equal. It's seems reasonable to posit that, given the heavy use of images in iOS UI, that the JPG decoder is something that would be undergoing constant tuning for maximum performance.
I'd even believe it conceivable that between the same OS version running on different models of device (i.e. different processors), the results could be not bit-equal if there were multiple versions of the JPG decoder, each heavily optimized for a specific CPU, although that would not explain the difference between 2 devices of the same model, with the same OS.
You might try to re-run the experiment with an image in a lossless format.
It also may be worth pointing out that providing your own backing memory for a CGBitmapContext, but not making special allowances for word alignment is likely to lead to poor performance. For instance, you have:
```
NSUInteger imageBytesPerRow = bytesPerPixel * imageWidth;
```
If imageBytesPerRow is not a multiple of the CPU's native word length, you're going to get sub-optimal performance.
|
I assume the "device grey" color space varies by device. Try with a device independent color space.
|
23,415,492 |
I have two tables:
**ID,YRMO,Counts**
1,Dec 2013,4
1,Jan 2014,6
1,Feb 2014,7
2,Jan,2014,6
2,Feb,2014,8
**ID,YRMO,Counts**
1,Dec 2013,10
1,Jan 2014,8
1,March 2014,12
2,Jan 2014,6
2,Feb 2014,10
I want to find the pearson corelation coefficient for each sets of ID. There are about more than 200 different IDS.
Pearson correlation is a measure of the linear correlation (dependence) between two variables X and Y, giving a value between +1 and −1 inclusive
More can be found here :<http://oreilly.com/catalog/transqlcook/chapter/ch08.html>
at calculating correlation section
|
2014/05/01
|
['https://Stackoverflow.com/questions/23415492', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3325141/']
|
To calculate Pearson Correlation Coefficient; you need to first calculate `Mean` then `standard daviation` and then `correlation coefficient` as outlined below
1. Calculate Mean
-----------------
```
insert into tab2 (tab1_id, mean)
select ID, sum([counts]) /
(select count(*) from tab1) as mean
from tab1
group by ID;
```
2. Calculate standard deviation
-------------------------------
```
update tab2
set stddev = (
select sqrt(
sum([counts] * [counts]) /
(select count(*) from tab1)
- mean * mean
) stddev
from tab1
where tab1.ID = tab2.tab1_id
group by tab1.ID);
```
3. Finally `Pearson Correlation Coefficient`
--------------------------------------------
```
select ID,
((sf.sum1 / (select count(*) from tab1)
- stats1.mean * stats2.mean
)
/ (stats1.stddev * stats2.stddev)) as PCC
from (
select r1.ID,
sum(r1.[counts] * r2.[counts]) as sum1
from tab1 r1
join tab1 r2
on r1.ID = r2.ID
group by r1.ID
) sf
join tab2 stats1
on stats1.tab1_id = sf.ID
join tab2 stats2
on stats2.tab1_id = sf.ID
```
Which on your posted data results in

See a demo fiddle here <http://sqlfiddle.com/#!3/0da20/5>
**EDIT:**
Well refined a bit. You can use the below function to get PCC but I am not getting exact same result as of your but rather getting `0.999996000000000` for `ID = 1`.
This could be a great entry point for you. You can refine the calculation further from here.
```
create function calculate_PCC(@id int)
returns decimal(16,15)
as
begin
declare @mean numeric(16,5);
declare @stddev numeric(16,5);
declare @count numeric(16,5);
declare @pcc numeric(16,12);
declare @store numeric(16,7);
select @count = CONVERT(numeric(16,5), count(case when Id=@id then 1 end)) from tab1;
select @mean = convert(numeric(16,5),sum([Counts])) / @count
from tab1 WHERE ID = @id;
select @store = (sum(counts * counts) / @count) from tab1 WHERE ID = @id;
set @stddev = sqrt(@store - (@mean * @mean));
set @pcc = ((@store - (@mean * @mean)) / (@stddev * @stddev));
return @pcc;
end
```
Call the function like
```
select db_name.dbo.calculate_PCC(1)
```
|
A Single-Pass Solution:
=======================
There are two flavors of the Pearson correlation coefficient, one for a Sample and one for an entire Population. These are simple, single-pass, and I believe, correct formulas for both:
```
-- Methods for calculating the two Pearson correlation coefficients
SELECT
-- For Population
(avg(x * y) - avg(x) * avg(y)) /
(sqrt(avg(x * x) - avg(x) * avg(x)) * sqrt(avg(y * y) - avg(y) * avg(y)))
AS correlation_coefficient_population,
-- For Sample
(count(*) * sum(x * y) - sum(x) * sum(y)) /
(sqrt(count(*) * sum(x * x) - sum(x) * sum(x)) * sqrt(count(*) * sum(y * y) - sum(y) * sum(y)))
AS correlation_coefficient_sample
FROM (
-- The following generates a table of sample data containing two columns with a luke-warm and tweakable correlation
-- y = x for 0 thru 99, y = x - 100 for 100 thru 199, etc. Execute it as a stand-alone to see for yourself
-- x and y are CAST as DECIMAL to avoid integer math, you should definitely do the same
-- Try TOP 100 or less for full correlation (y = x for all cases), TOP 200 for a PCC of 0.5, TOP 300 for one near 0.33, etc.
-- The superfluous "+ 0" is where you could apply various offsets to see that they have no effect on the results
SELECT TOP 200
CAST(ROW_NUMBER() OVER (ORDER BY [object_id]) - 1 + 0 AS DECIMAL) AS x,
CAST((ROW_NUMBER() OVER (ORDER BY [object_id]) - 1) % 100 AS DECIMAL) AS y
FROM sys.all_objects
) AS a
```
As I noted in the comments, you can try the example with TOP 100 or less for full correlation (y = x for all cases); TOP 200 yields correlations very near 0.5; TOP 300, around 0.33; etc. There is a place ("+ 0") to add an offset if you like; spoiler alert, it has no effect. Make sure you CAST your values as DECIMAL - integer math can significantly impact these calcs.
|
562,745 |
Ladies and Gentlemen,
I was hoping someone here could guide me in the right direction regarding the problem I am facing. I have literally tried all possible options in the internet forums with no luck.
I am trying to connect to a samba share running on a headless server running Fedora Server. I am trying to connect to it from Mac mini for Time Machine backup and getting the below error in the log:
>
> make\_connection\_snum: canonicalize\_connect\_path failed for service
> timemachine, path /home/timemachineuser/timemachinebackup
>
>
>
The Fedora Server is running as VM on Proxmox hypervisor. And I have allocated 750GB of storage via Proxmox for the sole purpose of using it for Time Machine backup.
Below is my setup in `/etc/samba/smb.conf`
```
[timemachine]
comment = Time Machine
create mask = 0770
directory mask = 0770
path = /home/timemachineuser/timemachinebackup
read only = No
spotlight = Yes
vfs objects = catia fruit streams_xattr
fruit:time machine = yes
fruit:aapl = yes
```
The path in the `smb.conf` is a mount point from the storage that I allocated in Proxmox.
```
/dev/sdc1 738G 73M 700G 1% /home/timemachineuser/timemachinebackup
```
If I change the path in smb.conf to any normal folder in `/home/timemachineuser` folder and then try to connect from Mac, it works absolutely fine. But when the path is a mount point, I get the above error. I have given execute permissions to entire hierarchy as suggested by many using `chmod -R a+x /home`. But no luck.
I have tried formatting `/dev/sdc1` with XFS and ext4 file formats with the same results.
Appreciate any kind of help to get this sorted. Thanks in advance.
**File Permissions of the hierarchy:**
~ ⌚ 21:05:09
$ ls -ld / /home /home/timemachineuser /home/timemachineuser/timemachinebackup
dr-xr-xr-x. 22 root root 4096 Jan 9 23:26 /
drwxr-xr-x. 4 root root 67 Jan 6 08:11 /home
drwxrwx--x. 5 timemachineuser timemachineuser 221 Jan 11 18:11 /home/timemachineuser
drwxrwxrwx. 3 timemachineuser timemachine 4096 Jan 11 17:45 /home/timemachineuser/timemachinebackup
~ ⌚ 21:05:12
$
|
2020/01/18
|
['https://unix.stackexchange.com/questions/562745', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/240469/']
|
I was working on something similar the other night. My setup is a little different in that I do not use a home directory, each LVM is mounted at its own root level directory but a few things that may help:
In the [Global] section, i enforce a minimum SMB level using:
```
[Global]
min protocol = SMB2
```
If you are running SMB 4 you could also set SMB3 as a minimum if you're end point client supports it (a couple of mine don't yet hence locking to v2 as a minimum).
Have you run smbpasswd to set the smb authentication for the connecting user?
As I mentioned earlier mine use root level dirs rather than home level (avoids ambiguity with selinux in regards to options for what i would call a normal samba shares and a home dir based share.
For these I use the follow to set up relevant selinux securities:
```
setsebool -P samba_export_all_ro=1 samba_export_all_rw=1
getsebool –a | grep samba_export ##Just to check it set properly
semanage fcontext –at samba_share_t "/timemachine1(/.*)?"
restorecon /timemachine1
```
I also chown on the timemachine directory so the owner is the user I am logging on to for the samba share.
Also double check your firewall ports are open:
```
firewall-cmd --permanent --add-service=samba
firewall-cmd --reload
```
From the mac if you open finder and do command-K you do a manual samba connection to test.
Beyond that there could be something odd in the Global section of your smb.conf, might want to post that section if you are still stuck.
|
Have you tried telling SELinux on the server that the directory may be accessed by Samba?
It might be as simple as telling SELinux that sharing of home directories is allowed:
setsebool -P samba\_enable\_home\_dirs 1
|
546,926 |
Trying to use `dpkg` and `egrep` commands to list packages whose names starts with `q`. Already tried:
```
dpkg -l | egrep -l q
dpkg -l | egrep -l ^q
dpkg -l | egrep q
dpkg -l | grep q
```
What is going wrong?
|
2019/10/15
|
['https://unix.stackexchange.com/questions/546926', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/377372/']
|
Use `--get-selections` instead of `-l` option:
```
dpkg --get-selections |grep ^q
```
Or using `awk` to change the column order:
```
dpkg -l |awk '{print $2 , $3 "\t\t" $1}' | grep ^q
```
|
The regular expressions for egrep do not match the expected output of `dpkg -l`. If you wish to keep the same output format as `dpkg -l`, which includes the sate of the package, the version and a description, then the regular expression needs to be changed to match the expected format: three characters at the start of the line (describing the state of the package on the system) and a space before the package name.
In the expression `^... [qQ]`, `^` indicates to match from the start of a line, `...` says to match any three characters followed by a space, then `q` matches packages that start with either an upper or lower case "q" (packages should only be lowercase on Ubuntu but there may be custom packages that do not follow these rules).
```bsh
$ dpkg -l | egrep '^... [qQ]'
ii qdbus 4:4.8.7+dfsg-7ubuntu1 amd64 Qt 4 D-Bus tool
ii qemu-block-extra:amd64 1:2.11+dfsg-1ubuntu7.19 amd64 extra block backend modules for qemu-system and qemu-utils
...
```
|
546,926 |
Trying to use `dpkg` and `egrep` commands to list packages whose names starts with `q`. Already tried:
```
dpkg -l | egrep -l q
dpkg -l | egrep -l ^q
dpkg -l | egrep q
dpkg -l | grep q
```
What is going wrong?
|
2019/10/15
|
['https://unix.stackexchange.com/questions/546926', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/377372/']
|
You don't really need grep (or egrep) at all here: the `dpkg -l` command accepts a pattern:
```
-l, --list package-name-pattern...
List packages matching given pattern.
```
Note that `package-name-pattern` is a glob pattern not a regular expression. So
```
dpkg -l 'q*'
```
If you want the output in more configurable format (for example, only the binay package name) then you can use `dpkg-query` instead ex.
```
dpkg-query -Wf '${binary:Package}\n' 'q*'
```
|
The regular expressions for egrep do not match the expected output of `dpkg -l`. If you wish to keep the same output format as `dpkg -l`, which includes the sate of the package, the version and a description, then the regular expression needs to be changed to match the expected format: three characters at the start of the line (describing the state of the package on the system) and a space before the package name.
In the expression `^... [qQ]`, `^` indicates to match from the start of a line, `...` says to match any three characters followed by a space, then `q` matches packages that start with either an upper or lower case "q" (packages should only be lowercase on Ubuntu but there may be custom packages that do not follow these rules).
```bsh
$ dpkg -l | egrep '^... [qQ]'
ii qdbus 4:4.8.7+dfsg-7ubuntu1 amd64 Qt 4 D-Bus tool
ii qemu-block-extra:amd64 1:2.11+dfsg-1ubuntu7.19 amd64 extra block backend modules for qemu-system and qemu-utils
...
```
|
37,849,294 |
I am using this ajax code to send data to server:
```
$.ajax({
data: postData,
type: method,
url: url,
timeout: 20000,
contentType: "application/x-www-form-urlencoded;charset=UTF-8",
error: function(jqXHR,textStatus,err){alert("Error returned from ajax call "+err);},
success: function(data,status,jqXHR){
// process response...
}
});
```
`postData` is a query string with many values while `method` is `GET` or `POST`
The problem is that, when I send a query string that contains a value like `Älypuhelimen lisävarusteet`, the result in database is `�lypuhelimen lis�varusteet`
The database connection collation is utf-8, and this works fine when I do not use ajax to post and save to database... It is definitely ajax that messes up the encoding...
I have also tried using encodeURIComponent() function on the data, and it becomes `%C4lypuhelimen%20lis%E4varusteet` if I use it... same goes for escape() function...
any help will be appreciated...
|
2016/06/16
|
['https://Stackoverflow.com/questions/37849294', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4575293/']
|
You should try jQuery Base64 encode.
JavaScript:
```
<script src="jquery.min.js"></script>
<script src="jquery.base64.min.js"></script>
<script>
enctext = $.base64.encode("yourtext");
//your ajax code goes here.
</script>
```
PHP :
```
<?php
$org_text = base64_decode($_POST['your_variable']);
?>
```
jQuery Base64 plugin.
download from here.
<https://github.com/carlo/jquery-base64>
|
Try changing the column in the database to utf16\_bin Collation
>
> Post you php database connection code.
>
>
>
|
37,849,294 |
I am using this ajax code to send data to server:
```
$.ajax({
data: postData,
type: method,
url: url,
timeout: 20000,
contentType: "application/x-www-form-urlencoded;charset=UTF-8",
error: function(jqXHR,textStatus,err){alert("Error returned from ajax call "+err);},
success: function(data,status,jqXHR){
// process response...
}
});
```
`postData` is a query string with many values while `method` is `GET` or `POST`
The problem is that, when I send a query string that contains a value like `Älypuhelimen lisävarusteet`, the result in database is `�lypuhelimen lis�varusteet`
The database connection collation is utf-8, and this works fine when I do not use ajax to post and save to database... It is definitely ajax that messes up the encoding...
I have also tried using encodeURIComponent() function on the data, and it becomes `%C4lypuhelimen%20lis%E4varusteet` if I use it... same goes for escape() function...
any help will be appreciated...
|
2016/06/16
|
['https://Stackoverflow.com/questions/37849294', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4575293/']
|
Just for information and to help others that might fall in the same situation...
The problem was with the postData itself... it was parsed such that every post variable was applied with escape()... Using encodeURIComponent() instead of escape() worked!
**Summary:**
Donot use escape() function to url-escape query components... use encodeURIComponent() instead...
|
Try changing the column in the database to utf16\_bin Collation
>
> Post you php database connection code.
>
>
>
|
8,977,967 |
I want to install latest stable version of Sphinx ([sphinxsearch.com](http://sphinxsearch.com/)) on Mac OS X Lion. What is a right way to do that?
|
2012/01/23
|
['https://Stackoverflow.com/questions/8977967', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/561626/']
|
Here is short guide, <http://pat.github.com/ts/en/installing_sphinx.html> its regarding thinking\_sphinx, ruby gem for workign with rails, but it covers also installing sphinx server.
|
What wasn't obvious from those instructions was that the main executables would be found in /usr/local/bin/searchd and /usr/local/bin/indexer... I was a bit puzzled after install when I couldn't find anything *sphinx* in /usr/local/bin.
|
8,977,967 |
I want to install latest stable version of Sphinx ([sphinxsearch.com](http://sphinxsearch.com/)) on Mac OS X Lion. What is a right way to do that?
|
2012/01/23
|
['https://Stackoverflow.com/questions/8977967', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/561626/']
|
Here is short guide, <http://pat.github.com/ts/en/installing_sphinx.html> its regarding thinking\_sphinx, ruby gem for workign with rails, but it covers also installing sphinx server.
|
I just checked and it's on brew, so you can just run if you have HomeBrew:
`brew install sphinx`.
|
8,977,967 |
I want to install latest stable version of Sphinx ([sphinxsearch.com](http://sphinxsearch.com/)) on Mac OS X Lion. What is a right way to do that?
|
2012/01/23
|
['https://Stackoverflow.com/questions/8977967', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/561626/']
|
Here is short guide, <http://pat.github.com/ts/en/installing_sphinx.html> its regarding thinking\_sphinx, ruby gem for workign with rails, but it covers also installing sphinx server.
|
You can try the easy Install.
-Open your terminal.
-Execute the following command: sudo easy\_install sphinx
Then it works.
|
8,977,967 |
I want to install latest stable version of Sphinx ([sphinxsearch.com](http://sphinxsearch.com/)) on Mac OS X Lion. What is a right way to do that?
|
2012/01/23
|
['https://Stackoverflow.com/questions/8977967', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/561626/']
|
I just checked and it's on brew, so you can just run if you have HomeBrew:
`brew install sphinx`.
|
What wasn't obvious from those instructions was that the main executables would be found in /usr/local/bin/searchd and /usr/local/bin/indexer... I was a bit puzzled after install when I couldn't find anything *sphinx* in /usr/local/bin.
|
8,977,967 |
I want to install latest stable version of Sphinx ([sphinxsearch.com](http://sphinxsearch.com/)) on Mac OS X Lion. What is a right way to do that?
|
2012/01/23
|
['https://Stackoverflow.com/questions/8977967', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/561626/']
|
What wasn't obvious from those instructions was that the main executables would be found in /usr/local/bin/searchd and /usr/local/bin/indexer... I was a bit puzzled after install when I couldn't find anything *sphinx* in /usr/local/bin.
|
You can try the easy Install.
-Open your terminal.
-Execute the following command: sudo easy\_install sphinx
Then it works.
|
8,977,967 |
I want to install latest stable version of Sphinx ([sphinxsearch.com](http://sphinxsearch.com/)) on Mac OS X Lion. What is a right way to do that?
|
2012/01/23
|
['https://Stackoverflow.com/questions/8977967', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/561626/']
|
I just checked and it's on brew, so you can just run if you have HomeBrew:
`brew install sphinx`.
|
You can try the easy Install.
-Open your terminal.
-Execute the following command: sudo easy\_install sphinx
Then it works.
|
36,443,086 |
I am trying to add ffmpeg into my android project. I am using ubuntu 14.04 OS.
I am following this link. [Link](https://software.intel.com/en-us/android/blogs/2013/12/06/building-ffmpeg-for-android-on-x86)
But I am getting error while executing this line.
```
$ANDROID_NDK/build/tools/make-standalone-toolchain.sh --toolchain=x86-4.8 --arch=x86 --system=linux-x86_64 --platform=android-14 --install-dir=/tmp/vplayer
```
I am getting this following error.
```
HOST_OS=linux
HOST_EXE=
HOST_ARCH=x86_64
HOST_TAG=linux-x86_64
HOST_NUM_CPUS=1
BUILD_NUM_CPUS=2
ERROR: Unknown option '--system'. See --help for usage.
```
Please help me how to solve this issue and add ffmpeg into my project.
|
2016/04/06
|
['https://Stackoverflow.com/questions/36443086', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3564344/']
|
**Yes**: CLion doesn't allow you to open multiple projects *from the menu* because it uses the *CMake* system, which is script based.
However, *CMake* is quite capable of encompassing multiple projects, and CLion will correctly parse your CMake file and show all relevant directories in the project explorer.
### Example
To do this, just like in Visual Studio, you need a parent "solution" and one or more child "projects".
Here is a simple CMake example in which "my\_solution" references two child projects, "my\_application" and "my\_library". Here, my three folders are arranged:
* `xxx/my_solution/CMakeLists.txt`
* `xxx/my_application/CMakeLists.txt`
* `xxx/my_library/CMakeLists.txt`
And `xxx/my_solution/CMakeLists.txt` simply reads:
```
cmake_minimum_required(VERSION 3.7)
project(my_solution)
add_subdirectory("${PROJECT_SOURCE_DIR}/../my_library" "${PROJECT_SOURCE_DIR}/my_library_output")
add_subdirectory("${PROJECT_SOURCE_DIR}/../my_application" "${PROJECT_SOURCE_DIR}/my_application_output")
```
Note that it *is* also permitted to put `my_application` and `my_library` *within* the `my_solution` directory, as in Visual Studio.
|
No. CLion either:
* opens a new window with the other project you want to work on
* **closes** your current project and opens the new one in the current window
as you can see in the [documentation](https://www.jetbrains.com/help/idea/2016.1/opening-multiple-projects.html). I think this is wanted in their design; probably to maintain CLion fast and reactive...
|
36,443,086 |
I am trying to add ffmpeg into my android project. I am using ubuntu 14.04 OS.
I am following this link. [Link](https://software.intel.com/en-us/android/blogs/2013/12/06/building-ffmpeg-for-android-on-x86)
But I am getting error while executing this line.
```
$ANDROID_NDK/build/tools/make-standalone-toolchain.sh --toolchain=x86-4.8 --arch=x86 --system=linux-x86_64 --platform=android-14 --install-dir=/tmp/vplayer
```
I am getting this following error.
```
HOST_OS=linux
HOST_EXE=
HOST_ARCH=x86_64
HOST_TAG=linux-x86_64
HOST_NUM_CPUS=1
BUILD_NUM_CPUS=2
ERROR: Unknown option '--system'. See --help for usage.
```
Please help me how to solve this issue and add ffmpeg into my project.
|
2016/04/06
|
['https://Stackoverflow.com/questions/36443086', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3564344/']
|
No. CLion either:
* opens a new window with the other project you want to work on
* **closes** your current project and opens the new one in the current window
as you can see in the [documentation](https://www.jetbrains.com/help/idea/2016.1/opening-multiple-projects.html). I think this is wanted in their design; probably to maintain CLion fast and reactive...
|
Adding some visual clues based on the answer from @c-z
This is how my project structure looking -
[](https://i.stack.imgur.com/2vF6D.png)
This is how my root level CMakeLists.txt is looking -
[](https://i.stack.imgur.com/GDQDT.png)
Finally, this is how my sub-directory level CMakeLists.txt is looking -
[](https://i.stack.imgur.com/5WqQb.png)
**NOTE:**
You may choose to remove the outer level main.cpp file (I've deleted it)
Also, you can remove the project level executable to remove it from the run configuration.
|
36,443,086 |
I am trying to add ffmpeg into my android project. I am using ubuntu 14.04 OS.
I am following this link. [Link](https://software.intel.com/en-us/android/blogs/2013/12/06/building-ffmpeg-for-android-on-x86)
But I am getting error while executing this line.
```
$ANDROID_NDK/build/tools/make-standalone-toolchain.sh --toolchain=x86-4.8 --arch=x86 --system=linux-x86_64 --platform=android-14 --install-dir=/tmp/vplayer
```
I am getting this following error.
```
HOST_OS=linux
HOST_EXE=
HOST_ARCH=x86_64
HOST_TAG=linux-x86_64
HOST_NUM_CPUS=1
BUILD_NUM_CPUS=2
ERROR: Unknown option '--system'. See --help for usage.
```
Please help me how to solve this issue and add ffmpeg into my project.
|
2016/04/06
|
['https://Stackoverflow.com/questions/36443086', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3564344/']
|
**Yes**: CLion doesn't allow you to open multiple projects *from the menu* because it uses the *CMake* system, which is script based.
However, *CMake* is quite capable of encompassing multiple projects, and CLion will correctly parse your CMake file and show all relevant directories in the project explorer.
### Example
To do this, just like in Visual Studio, you need a parent "solution" and one or more child "projects".
Here is a simple CMake example in which "my\_solution" references two child projects, "my\_application" and "my\_library". Here, my three folders are arranged:
* `xxx/my_solution/CMakeLists.txt`
* `xxx/my_application/CMakeLists.txt`
* `xxx/my_library/CMakeLists.txt`
And `xxx/my_solution/CMakeLists.txt` simply reads:
```
cmake_minimum_required(VERSION 3.7)
project(my_solution)
add_subdirectory("${PROJECT_SOURCE_DIR}/../my_library" "${PROJECT_SOURCE_DIR}/my_library_output")
add_subdirectory("${PROJECT_SOURCE_DIR}/../my_application" "${PROJECT_SOURCE_DIR}/my_application_output")
```
Note that it *is* also permitted to put `my_application` and `my_library` *within* the `my_solution` directory, as in Visual Studio.
|
Adding some visual clues based on the answer from @c-z
This is how my project structure looking -
[](https://i.stack.imgur.com/2vF6D.png)
This is how my root level CMakeLists.txt is looking -
[](https://i.stack.imgur.com/GDQDT.png)
Finally, this is how my sub-directory level CMakeLists.txt is looking -
[](https://i.stack.imgur.com/5WqQb.png)
**NOTE:**
You may choose to remove the outer level main.cpp file (I've deleted it)
Also, you can remove the project level executable to remove it from the run configuration.
|
17,804,096 |
I am calling a jquery function from .aspx page as follows
```
<body onload="JavaScript:createPanels('[{a,b,c,d,e}]')">
```
in my jquery I have function defined as
```
function createPanels(requiredButtons) {
var abc = JSON.stringify(requiredButtons)
abc.each(function (key, value) {
alert(value);
});
}
```
Now the issue is that I am not getting any alert.
Can any one point me where am I going wrong?
|
2013/07/23
|
['https://Stackoverflow.com/questions/17804096', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1243271/']
|
Thats not how `$.each` is to be used:
Try this:
```
$.each(abc, function (key, value) {
alert(value);
});
```
It will alert each character in the string.
|
"{a,b,c,d}" is not a object that's why your code is not working.
Second point is : **Use jQuery.each() for iterating a collection.**
Try to put it in this form :
```
var x= ['a','b','c','d','e'];
jQuery.each(x,function (key, value) {
console.log(value);
});
```
It will return **a,b,c,d,e** as you want.
Here is the working [demo](http://jsfiddle.net/MzxPk/)
|
17,804,096 |
I am calling a jquery function from .aspx page as follows
```
<body onload="JavaScript:createPanels('[{a,b,c,d,e}]')">
```
in my jquery I have function defined as
```
function createPanels(requiredButtons) {
var abc = JSON.stringify(requiredButtons)
abc.each(function (key, value) {
alert(value);
});
}
```
Now the issue is that I am not getting any alert.
Can any one point me where am I going wrong?
|
2013/07/23
|
['https://Stackoverflow.com/questions/17804096', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1243271/']
|
Thats not how `$.each` is to be used:
Try this:
```
$.each(abc, function (key, value) {
alert(value);
});
```
It will alert each character in the string.
|
I lurve jQuery and everything, but there's no need to invoke it to iterate an array.
```
abc.forEach( function (elem) {
console.log(elem);
});
```
should work, once you've tidied up your JSON thing
|
17,804,096 |
I am calling a jquery function from .aspx page as follows
```
<body onload="JavaScript:createPanels('[{a,b,c,d,e}]')">
```
in my jquery I have function defined as
```
function createPanels(requiredButtons) {
var abc = JSON.stringify(requiredButtons)
abc.each(function (key, value) {
alert(value);
});
}
```
Now the issue is that I am not getting any alert.
Can any one point me where am I going wrong?
|
2013/07/23
|
['https://Stackoverflow.com/questions/17804096', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1243271/']
|
Thats not how `$.each` is to be used:
Try this:
```
$.each(abc, function (key, value) {
alert(value);
});
```
It will alert each character in the string.
|
Thanks for your valuable suggessions
I solved the problem as
.aspx page
```
<body onload="JavaScript:createPanels('a,b,c,d,e')">
```
jquery
```
function createPanels(requiredButtons) {
var abc = requiredButtons.split(',');
$.each(abc, function (key, value) {
alert(value);
});
```
}
|
17,804,096 |
I am calling a jquery function from .aspx page as follows
```
<body onload="JavaScript:createPanels('[{a,b,c,d,e}]')">
```
in my jquery I have function defined as
```
function createPanels(requiredButtons) {
var abc = JSON.stringify(requiredButtons)
abc.each(function (key, value) {
alert(value);
});
}
```
Now the issue is that I am not getting any alert.
Can any one point me where am I going wrong?
|
2013/07/23
|
['https://Stackoverflow.com/questions/17804096', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1243271/']
|
Several issues there.
a. This is not JSON `[{a,b,c,d,e}]`
If you really want to do it on the body element then this is how to do it:
```
<body onload="JavaScript:createPanels('{"posts": [{"key":"value"}, {"key":"value"}]}')">
```
This is not a really good idea, so you call it in a jquery page load handler:
```
$(document).ready(function(){
//create the JSON object here
//call the function here
});
```
b. Change your script too:
```
function createPanels(requiredButtons){
var abc = JSON.parse(requiredButtons);
$(abc).each(function (key, value) {
alert(value);
});
}
```
|
"{a,b,c,d}" is not a object that's why your code is not working.
Second point is : **Use jQuery.each() for iterating a collection.**
Try to put it in this form :
```
var x= ['a','b','c','d','e'];
jQuery.each(x,function (key, value) {
console.log(value);
});
```
It will return **a,b,c,d,e** as you want.
Here is the working [demo](http://jsfiddle.net/MzxPk/)
|
17,804,096 |
I am calling a jquery function from .aspx page as follows
```
<body onload="JavaScript:createPanels('[{a,b,c,d,e}]')">
```
in my jquery I have function defined as
```
function createPanels(requiredButtons) {
var abc = JSON.stringify(requiredButtons)
abc.each(function (key, value) {
alert(value);
});
}
```
Now the issue is that I am not getting any alert.
Can any one point me where am I going wrong?
|
2013/07/23
|
['https://Stackoverflow.com/questions/17804096', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1243271/']
|
Several issues there.
a. This is not JSON `[{a,b,c,d,e}]`
If you really want to do it on the body element then this is how to do it:
```
<body onload="JavaScript:createPanels('{"posts": [{"key":"value"}, {"key":"value"}]}')">
```
This is not a really good idea, so you call it in a jquery page load handler:
```
$(document).ready(function(){
//create the JSON object here
//call the function here
});
```
b. Change your script too:
```
function createPanels(requiredButtons){
var abc = JSON.parse(requiredButtons);
$(abc).each(function (key, value) {
alert(value);
});
}
```
|
I lurve jQuery and everything, but there's no need to invoke it to iterate an array.
```
abc.forEach( function (elem) {
console.log(elem);
});
```
should work, once you've tidied up your JSON thing
|
17,804,096 |
I am calling a jquery function from .aspx page as follows
```
<body onload="JavaScript:createPanels('[{a,b,c,d,e}]')">
```
in my jquery I have function defined as
```
function createPanels(requiredButtons) {
var abc = JSON.stringify(requiredButtons)
abc.each(function (key, value) {
alert(value);
});
}
```
Now the issue is that I am not getting any alert.
Can any one point me where am I going wrong?
|
2013/07/23
|
['https://Stackoverflow.com/questions/17804096', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1243271/']
|
Several issues there.
a. This is not JSON `[{a,b,c,d,e}]`
If you really want to do it on the body element then this is how to do it:
```
<body onload="JavaScript:createPanels('{"posts": [{"key":"value"}, {"key":"value"}]}')">
```
This is not a really good idea, so you call it in a jquery page load handler:
```
$(document).ready(function(){
//create the JSON object here
//call the function here
});
```
b. Change your script too:
```
function createPanels(requiredButtons){
var abc = JSON.parse(requiredButtons);
$(abc).each(function (key, value) {
alert(value);
});
}
```
|
Thanks for your valuable suggessions
I solved the problem as
.aspx page
```
<body onload="JavaScript:createPanels('a,b,c,d,e')">
```
jquery
```
function createPanels(requiredButtons) {
var abc = requiredButtons.split(',');
$.each(abc, function (key, value) {
alert(value);
});
```
}
|
17,804,096 |
I am calling a jquery function from .aspx page as follows
```
<body onload="JavaScript:createPanels('[{a,b,c,d,e}]')">
```
in my jquery I have function defined as
```
function createPanels(requiredButtons) {
var abc = JSON.stringify(requiredButtons)
abc.each(function (key, value) {
alert(value);
});
}
```
Now the issue is that I am not getting any alert.
Can any one point me where am I going wrong?
|
2013/07/23
|
['https://Stackoverflow.com/questions/17804096', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1243271/']
|
This is not a valid JSON format. Json Format is like as below:
```
var obj = {
"flammable": "inflammable",
"duh": "no duh"
};
```
Then Use as below:
```
$.each( obj, function( key, value ) {
alert( key + ": " + value );
});
```
[Reference](http://api.jquery.com/jQuery.each/)
|
"{a,b,c,d}" is not a object that's why your code is not working.
Second point is : **Use jQuery.each() for iterating a collection.**
Try to put it in this form :
```
var x= ['a','b','c','d','e'];
jQuery.each(x,function (key, value) {
console.log(value);
});
```
It will return **a,b,c,d,e** as you want.
Here is the working [demo](http://jsfiddle.net/MzxPk/)
|
17,804,096 |
I am calling a jquery function from .aspx page as follows
```
<body onload="JavaScript:createPanels('[{a,b,c,d,e}]')">
```
in my jquery I have function defined as
```
function createPanels(requiredButtons) {
var abc = JSON.stringify(requiredButtons)
abc.each(function (key, value) {
alert(value);
});
}
```
Now the issue is that I am not getting any alert.
Can any one point me where am I going wrong?
|
2013/07/23
|
['https://Stackoverflow.com/questions/17804096', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1243271/']
|
This is not a valid JSON format. Json Format is like as below:
```
var obj = {
"flammable": "inflammable",
"duh": "no duh"
};
```
Then Use as below:
```
$.each( obj, function( key, value ) {
alert( key + ": " + value );
});
```
[Reference](http://api.jquery.com/jQuery.each/)
|
I lurve jQuery and everything, but there's no need to invoke it to iterate an array.
```
abc.forEach( function (elem) {
console.log(elem);
});
```
should work, once you've tidied up your JSON thing
|
17,804,096 |
I am calling a jquery function from .aspx page as follows
```
<body onload="JavaScript:createPanels('[{a,b,c,d,e}]')">
```
in my jquery I have function defined as
```
function createPanels(requiredButtons) {
var abc = JSON.stringify(requiredButtons)
abc.each(function (key, value) {
alert(value);
});
}
```
Now the issue is that I am not getting any alert.
Can any one point me where am I going wrong?
|
2013/07/23
|
['https://Stackoverflow.com/questions/17804096', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1243271/']
|
This is not a valid JSON format. Json Format is like as below:
```
var obj = {
"flammable": "inflammable",
"duh": "no duh"
};
```
Then Use as below:
```
$.each( obj, function( key, value ) {
alert( key + ": " + value );
});
```
[Reference](http://api.jquery.com/jQuery.each/)
|
Thanks for your valuable suggessions
I solved the problem as
.aspx page
```
<body onload="JavaScript:createPanels('a,b,c,d,e')">
```
jquery
```
function createPanels(requiredButtons) {
var abc = requiredButtons.split(',');
$.each(abc, function (key, value) {
alert(value);
});
```
}
|
23,808,057 |
While my C# program writes data continuously to an Excel spreadsheet, if the end user clicks on the upper right menu and opens the
**Excel Options** window, this causes following exception:
>
> System.Runtime.InteropServices.COMException with HRESULT: 0x800AC472
>
>
>
This interrupts the data from being written to the spreadsheet.
Ideally, the user should be allowed to do this without causing an exception.
The only solution I found to this error code was to loop and wait until the exception went away:
[Exception from HRESULT: 0x800AC472](https://stackoverflow.com/questions/1952759/exception-from-hresult-0x800ac472)
which effectively hangs the app, data is not written to Excel and the user is left in the dark about the problem.
I thought about disabling the main menu of Excel while writing to it, but cannot find a reference on how to do this.
My app supports **Excel 2000** to **2013**.
### Here is how to reproduce the issue:
* Using **Visual Studio Express 2013** for Windows Desktop, **.NET 4.5.1** on Windows 7 64-bit with **Excel 2007**, create a new Visual C# Console Application project.
* Add reference to "**Microsoft ExceL 12.0 Object Library**" (for Excel) and to "System.Windows.Forms" (for messagebox).
Here is the complete code:
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading.Tasks;
using System.Threading; // for sleep
using System.IO;
using System.Runtime.InteropServices;
using System.Reflection;
using Microsoft.Win32;
using Excel = Microsoft.Office.Interop.Excel;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int i = 3; // there is a split pane at row two
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
try
{
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.Application();
xlApp.Visible = false;
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlApp.Visible = true;
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
// next 2 lines for split pane in Excel:
xlWorkSheet.Application.ActiveWindow.SplitRow = 2;
xlWorkSheet.Application.ActiveWindow.FreezePanes = true;
xlWorkSheet.Cells[1, 1] = "Now open the";
xlWorkSheet.Cells[2, 1] = "Excel Options window";
}
catch (System.Runtime.InteropServices.COMException)
{
System.Windows.Forms.MessageBox.Show("Microsoft Excel does not seem to be installed on this computer any longer (although there are still registry entries for it). Please save to a .tem file. (1)");
return;
}
catch (Exception)
{
System.Windows.Forms.MessageBox.Show("Microsoft Excel does not seem to be installed on this computer any longer (although there are still registry entries for it). Please save to a .tem file. (2)");
return;
}
while(i < 65000)
{
i++;
try
{
xlWorkSheet.Cells[i, 1] = i.ToString();
Thread.Sleep(1000);
}
catch (System.Runtime.InteropServices.COMException)
{
System.Windows.Forms.MessageBox.Show("All right, what do I do here?");
}
catch (Exception)
{
System.Windows.Forms.MessageBox.Show("Something else happened.");
}
}
Console.ReadLine(); //Pause
}
}
}
```
* Lanch the app, Excel appears and data is written to it. Open the Excel options dialog window from the menu and up pops the error:
>
> An exception of type 'System.Runtime.InteropServices.COMException' occurred in mscorlib.dll and wasn't handled before a managed/native boundary
>
> Additional information: Exception from HRESULT: 0x800AC472
>
>
>
* Click on Continue and my message box **"All right, what do I do here?"** appears.
Please advise?
Best regards,
Bertrand
|
2014/05/22
|
['https://Stackoverflow.com/questions/23808057', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3597426/']
|
We finally went all the way to Microsoft Support with this issue. Their final response was:
>
> I am able to reproduce the issue. I researched on this further and
> found that this behaviour is expected and by design. This
> exception, 0x800AC472 – VBA\_E\_IGNORE, is thrown because Excel is busy
> and will not service any Object Model calls. Here is one of the
> discussions that talks about this.
> <http://social.msdn.microsoft.com/Forums/vstudio/en-US/9168f9f2-e5bc-4535-8d7d-4e374ab8ff09/hresult-800ac472-from-set-operations-in-excel?forum=vsto> The work around I see is to explicitly catch this exception and retry
> after sometime until your intended action is completed.
>
>
>
Since we cannot read the minds of the user who might decide to open a window or take a note without realizing the soft has stopped logging (if you mask the error), we decided to work around using:
```
xlWorkSheet.EnableSelection = Microsoft.Office.Interop.Excel.XlEnableSelection.xlNoSelection;
```
to lock the Excel window UI. We provide an obvious "unlock" button but when the user clicks it, he is sternly warned in a messagebox along with a "Do you wish to continue?"
|
```
xlApp = new Excel.Application();
xlApp.Interactive = false;
```
|
23,808,057 |
While my C# program writes data continuously to an Excel spreadsheet, if the end user clicks on the upper right menu and opens the
**Excel Options** window, this causes following exception:
>
> System.Runtime.InteropServices.COMException with HRESULT: 0x800AC472
>
>
>
This interrupts the data from being written to the spreadsheet.
Ideally, the user should be allowed to do this without causing an exception.
The only solution I found to this error code was to loop and wait until the exception went away:
[Exception from HRESULT: 0x800AC472](https://stackoverflow.com/questions/1952759/exception-from-hresult-0x800ac472)
which effectively hangs the app, data is not written to Excel and the user is left in the dark about the problem.
I thought about disabling the main menu of Excel while writing to it, but cannot find a reference on how to do this.
My app supports **Excel 2000** to **2013**.
### Here is how to reproduce the issue:
* Using **Visual Studio Express 2013** for Windows Desktop, **.NET 4.5.1** on Windows 7 64-bit with **Excel 2007**, create a new Visual C# Console Application project.
* Add reference to "**Microsoft ExceL 12.0 Object Library**" (for Excel) and to "System.Windows.Forms" (for messagebox).
Here is the complete code:
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading.Tasks;
using System.Threading; // for sleep
using System.IO;
using System.Runtime.InteropServices;
using System.Reflection;
using Microsoft.Win32;
using Excel = Microsoft.Office.Interop.Excel;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int i = 3; // there is a split pane at row two
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
try
{
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.Application();
xlApp.Visible = false;
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlApp.Visible = true;
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
// next 2 lines for split pane in Excel:
xlWorkSheet.Application.ActiveWindow.SplitRow = 2;
xlWorkSheet.Application.ActiveWindow.FreezePanes = true;
xlWorkSheet.Cells[1, 1] = "Now open the";
xlWorkSheet.Cells[2, 1] = "Excel Options window";
}
catch (System.Runtime.InteropServices.COMException)
{
System.Windows.Forms.MessageBox.Show("Microsoft Excel does not seem to be installed on this computer any longer (although there are still registry entries for it). Please save to a .tem file. (1)");
return;
}
catch (Exception)
{
System.Windows.Forms.MessageBox.Show("Microsoft Excel does not seem to be installed on this computer any longer (although there are still registry entries for it). Please save to a .tem file. (2)");
return;
}
while(i < 65000)
{
i++;
try
{
xlWorkSheet.Cells[i, 1] = i.ToString();
Thread.Sleep(1000);
}
catch (System.Runtime.InteropServices.COMException)
{
System.Windows.Forms.MessageBox.Show("All right, what do I do here?");
}
catch (Exception)
{
System.Windows.Forms.MessageBox.Show("Something else happened.");
}
}
Console.ReadLine(); //Pause
}
}
}
```
* Lanch the app, Excel appears and data is written to it. Open the Excel options dialog window from the menu and up pops the error:
>
> An exception of type 'System.Runtime.InteropServices.COMException' occurred in mscorlib.dll and wasn't handled before a managed/native boundary
>
> Additional information: Exception from HRESULT: 0x800AC472
>
>
>
* Click on Continue and my message box **"All right, what do I do here?"** appears.
Please advise?
Best regards,
Bertrand
|
2014/05/22
|
['https://Stackoverflow.com/questions/23808057', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3597426/']
|
What I have done successfully is to make a temp copy of the target excel file before opening it in code.
That way I can manipulate it independent of the source document being open or not.
|
Since Interop does cross threading, it may lead to accessing same object by multiple threads, leading to this exception, below code worked for me.
```
bool failed = false;
do
{
try
{
// Call goes here
failed = false;
}
catch (System.Runtime.InteropServices.COMException e)
{
failed = true;
}
System.Threading.Thread.Sleep(10);
} while (failed);
```
|
23,808,057 |
While my C# program writes data continuously to an Excel spreadsheet, if the end user clicks on the upper right menu and opens the
**Excel Options** window, this causes following exception:
>
> System.Runtime.InteropServices.COMException with HRESULT: 0x800AC472
>
>
>
This interrupts the data from being written to the spreadsheet.
Ideally, the user should be allowed to do this without causing an exception.
The only solution I found to this error code was to loop and wait until the exception went away:
[Exception from HRESULT: 0x800AC472](https://stackoverflow.com/questions/1952759/exception-from-hresult-0x800ac472)
which effectively hangs the app, data is not written to Excel and the user is left in the dark about the problem.
I thought about disabling the main menu of Excel while writing to it, but cannot find a reference on how to do this.
My app supports **Excel 2000** to **2013**.
### Here is how to reproduce the issue:
* Using **Visual Studio Express 2013** for Windows Desktop, **.NET 4.5.1** on Windows 7 64-bit with **Excel 2007**, create a new Visual C# Console Application project.
* Add reference to "**Microsoft ExceL 12.0 Object Library**" (for Excel) and to "System.Windows.Forms" (for messagebox).
Here is the complete code:
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading.Tasks;
using System.Threading; // for sleep
using System.IO;
using System.Runtime.InteropServices;
using System.Reflection;
using Microsoft.Win32;
using Excel = Microsoft.Office.Interop.Excel;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int i = 3; // there is a split pane at row two
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
try
{
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.Application();
xlApp.Visible = false;
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlApp.Visible = true;
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
// next 2 lines for split pane in Excel:
xlWorkSheet.Application.ActiveWindow.SplitRow = 2;
xlWorkSheet.Application.ActiveWindow.FreezePanes = true;
xlWorkSheet.Cells[1, 1] = "Now open the";
xlWorkSheet.Cells[2, 1] = "Excel Options window";
}
catch (System.Runtime.InteropServices.COMException)
{
System.Windows.Forms.MessageBox.Show("Microsoft Excel does not seem to be installed on this computer any longer (although there are still registry entries for it). Please save to a .tem file. (1)");
return;
}
catch (Exception)
{
System.Windows.Forms.MessageBox.Show("Microsoft Excel does not seem to be installed on this computer any longer (although there are still registry entries for it). Please save to a .tem file. (2)");
return;
}
while(i < 65000)
{
i++;
try
{
xlWorkSheet.Cells[i, 1] = i.ToString();
Thread.Sleep(1000);
}
catch (System.Runtime.InteropServices.COMException)
{
System.Windows.Forms.MessageBox.Show("All right, what do I do here?");
}
catch (Exception)
{
System.Windows.Forms.MessageBox.Show("Something else happened.");
}
}
Console.ReadLine(); //Pause
}
}
}
```
* Lanch the app, Excel appears and data is written to it. Open the Excel options dialog window from the menu and up pops the error:
>
> An exception of type 'System.Runtime.InteropServices.COMException' occurred in mscorlib.dll and wasn't handled before a managed/native boundary
>
> Additional information: Exception from HRESULT: 0x800AC472
>
>
>
* Click on Continue and my message box **"All right, what do I do here?"** appears.
Please advise?
Best regards,
Bertrand
|
2014/05/22
|
['https://Stackoverflow.com/questions/23808057', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3597426/']
|
What I have done successfully is to make a temp copy of the target excel file before opening it in code.
That way I can manipulate it independent of the source document being open or not.
|
One possible alternative to automating Excel, and wrestling with its' perculiarities, is to write the file out using the OpenXmlWriter writer (DocumentFormat.OpenXml.OpenXmlWriter).
It's a little tricky but does handle sheets with > 1 million rows without breaking a sweat.
[OpenXml docs on MSDN](http://msdn.microsoft.com/en-us/library/documentformat.openxml%28v=office.14%29.aspx)
|
23,808,057 |
While my C# program writes data continuously to an Excel spreadsheet, if the end user clicks on the upper right menu and opens the
**Excel Options** window, this causes following exception:
>
> System.Runtime.InteropServices.COMException with HRESULT: 0x800AC472
>
>
>
This interrupts the data from being written to the spreadsheet.
Ideally, the user should be allowed to do this without causing an exception.
The only solution I found to this error code was to loop and wait until the exception went away:
[Exception from HRESULT: 0x800AC472](https://stackoverflow.com/questions/1952759/exception-from-hresult-0x800ac472)
which effectively hangs the app, data is not written to Excel and the user is left in the dark about the problem.
I thought about disabling the main menu of Excel while writing to it, but cannot find a reference on how to do this.
My app supports **Excel 2000** to **2013**.
### Here is how to reproduce the issue:
* Using **Visual Studio Express 2013** for Windows Desktop, **.NET 4.5.1** on Windows 7 64-bit with **Excel 2007**, create a new Visual C# Console Application project.
* Add reference to "**Microsoft ExceL 12.0 Object Library**" (for Excel) and to "System.Windows.Forms" (for messagebox).
Here is the complete code:
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading.Tasks;
using System.Threading; // for sleep
using System.IO;
using System.Runtime.InteropServices;
using System.Reflection;
using Microsoft.Win32;
using Excel = Microsoft.Office.Interop.Excel;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int i = 3; // there is a split pane at row two
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
try
{
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.Application();
xlApp.Visible = false;
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlApp.Visible = true;
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
// next 2 lines for split pane in Excel:
xlWorkSheet.Application.ActiveWindow.SplitRow = 2;
xlWorkSheet.Application.ActiveWindow.FreezePanes = true;
xlWorkSheet.Cells[1, 1] = "Now open the";
xlWorkSheet.Cells[2, 1] = "Excel Options window";
}
catch (System.Runtime.InteropServices.COMException)
{
System.Windows.Forms.MessageBox.Show("Microsoft Excel does not seem to be installed on this computer any longer (although there are still registry entries for it). Please save to a .tem file. (1)");
return;
}
catch (Exception)
{
System.Windows.Forms.MessageBox.Show("Microsoft Excel does not seem to be installed on this computer any longer (although there are still registry entries for it). Please save to a .tem file. (2)");
return;
}
while(i < 65000)
{
i++;
try
{
xlWorkSheet.Cells[i, 1] = i.ToString();
Thread.Sleep(1000);
}
catch (System.Runtime.InteropServices.COMException)
{
System.Windows.Forms.MessageBox.Show("All right, what do I do here?");
}
catch (Exception)
{
System.Windows.Forms.MessageBox.Show("Something else happened.");
}
}
Console.ReadLine(); //Pause
}
}
}
```
* Lanch the app, Excel appears and data is written to it. Open the Excel options dialog window from the menu and up pops the error:
>
> An exception of type 'System.Runtime.InteropServices.COMException' occurred in mscorlib.dll and wasn't handled before a managed/native boundary
>
> Additional information: Exception from HRESULT: 0x800AC472
>
>
>
* Click on Continue and my message box **"All right, what do I do here?"** appears.
Please advise?
Best regards,
Bertrand
|
2014/05/22
|
['https://Stackoverflow.com/questions/23808057', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3597426/']
|
We finally went all the way to Microsoft Support with this issue. Their final response was:
>
> I am able to reproduce the issue. I researched on this further and
> found that this behaviour is expected and by design. This
> exception, 0x800AC472 – VBA\_E\_IGNORE, is thrown because Excel is busy
> and will not service any Object Model calls. Here is one of the
> discussions that talks about this.
> <http://social.msdn.microsoft.com/Forums/vstudio/en-US/9168f9f2-e5bc-4535-8d7d-4e374ab8ff09/hresult-800ac472-from-set-operations-in-excel?forum=vsto> The work around I see is to explicitly catch this exception and retry
> after sometime until your intended action is completed.
>
>
>
Since we cannot read the minds of the user who might decide to open a window or take a note without realizing the soft has stopped logging (if you mask the error), we decided to work around using:
```
xlWorkSheet.EnableSelection = Microsoft.Office.Interop.Excel.XlEnableSelection.xlNoSelection;
```
to lock the Excel window UI. We provide an obvious "unlock" button but when the user clicks it, he is sternly warned in a messagebox along with a "Do you wish to continue?"
|
What I have done successfully is to make a temp copy of the target excel file before opening it in code.
That way I can manipulate it independent of the source document being open or not.
|
23,808,057 |
While my C# program writes data continuously to an Excel spreadsheet, if the end user clicks on the upper right menu and opens the
**Excel Options** window, this causes following exception:
>
> System.Runtime.InteropServices.COMException with HRESULT: 0x800AC472
>
>
>
This interrupts the data from being written to the spreadsheet.
Ideally, the user should be allowed to do this without causing an exception.
The only solution I found to this error code was to loop and wait until the exception went away:
[Exception from HRESULT: 0x800AC472](https://stackoverflow.com/questions/1952759/exception-from-hresult-0x800ac472)
which effectively hangs the app, data is not written to Excel and the user is left in the dark about the problem.
I thought about disabling the main menu of Excel while writing to it, but cannot find a reference on how to do this.
My app supports **Excel 2000** to **2013**.
### Here is how to reproduce the issue:
* Using **Visual Studio Express 2013** for Windows Desktop, **.NET 4.5.1** on Windows 7 64-bit with **Excel 2007**, create a new Visual C# Console Application project.
* Add reference to "**Microsoft ExceL 12.0 Object Library**" (for Excel) and to "System.Windows.Forms" (for messagebox).
Here is the complete code:
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading.Tasks;
using System.Threading; // for sleep
using System.IO;
using System.Runtime.InteropServices;
using System.Reflection;
using Microsoft.Win32;
using Excel = Microsoft.Office.Interop.Excel;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int i = 3; // there is a split pane at row two
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
try
{
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.Application();
xlApp.Visible = false;
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlApp.Visible = true;
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
// next 2 lines for split pane in Excel:
xlWorkSheet.Application.ActiveWindow.SplitRow = 2;
xlWorkSheet.Application.ActiveWindow.FreezePanes = true;
xlWorkSheet.Cells[1, 1] = "Now open the";
xlWorkSheet.Cells[2, 1] = "Excel Options window";
}
catch (System.Runtime.InteropServices.COMException)
{
System.Windows.Forms.MessageBox.Show("Microsoft Excel does not seem to be installed on this computer any longer (although there are still registry entries for it). Please save to a .tem file. (1)");
return;
}
catch (Exception)
{
System.Windows.Forms.MessageBox.Show("Microsoft Excel does not seem to be installed on this computer any longer (although there are still registry entries for it). Please save to a .tem file. (2)");
return;
}
while(i < 65000)
{
i++;
try
{
xlWorkSheet.Cells[i, 1] = i.ToString();
Thread.Sleep(1000);
}
catch (System.Runtime.InteropServices.COMException)
{
System.Windows.Forms.MessageBox.Show("All right, what do I do here?");
}
catch (Exception)
{
System.Windows.Forms.MessageBox.Show("Something else happened.");
}
}
Console.ReadLine(); //Pause
}
}
}
```
* Lanch the app, Excel appears and data is written to it. Open the Excel options dialog window from the menu and up pops the error:
>
> An exception of type 'System.Runtime.InteropServices.COMException' occurred in mscorlib.dll and wasn't handled before a managed/native boundary
>
> Additional information: Exception from HRESULT: 0x800AC472
>
>
>
* Click on Continue and my message box **"All right, what do I do here?"** appears.
Please advise?
Best regards,
Bertrand
|
2014/05/22
|
['https://Stackoverflow.com/questions/23808057', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3597426/']
|
```
xlApp = new Excel.Application();
xlApp.Interactive = false;
```
|
Since Interop does cross threading, it may lead to accessing same object by multiple threads, leading to this exception, below code worked for me.
```
bool failed = false;
do
{
try
{
// Call goes here
failed = false;
}
catch (System.Runtime.InteropServices.COMException e)
{
failed = true;
}
System.Threading.Thread.Sleep(10);
} while (failed);
```
|
23,808,057 |
While my C# program writes data continuously to an Excel spreadsheet, if the end user clicks on the upper right menu and opens the
**Excel Options** window, this causes following exception:
>
> System.Runtime.InteropServices.COMException with HRESULT: 0x800AC472
>
>
>
This interrupts the data from being written to the spreadsheet.
Ideally, the user should be allowed to do this without causing an exception.
The only solution I found to this error code was to loop and wait until the exception went away:
[Exception from HRESULT: 0x800AC472](https://stackoverflow.com/questions/1952759/exception-from-hresult-0x800ac472)
which effectively hangs the app, data is not written to Excel and the user is left in the dark about the problem.
I thought about disabling the main menu of Excel while writing to it, but cannot find a reference on how to do this.
My app supports **Excel 2000** to **2013**.
### Here is how to reproduce the issue:
* Using **Visual Studio Express 2013** for Windows Desktop, **.NET 4.5.1** on Windows 7 64-bit with **Excel 2007**, create a new Visual C# Console Application project.
* Add reference to "**Microsoft ExceL 12.0 Object Library**" (for Excel) and to "System.Windows.Forms" (for messagebox).
Here is the complete code:
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading.Tasks;
using System.Threading; // for sleep
using System.IO;
using System.Runtime.InteropServices;
using System.Reflection;
using Microsoft.Win32;
using Excel = Microsoft.Office.Interop.Excel;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int i = 3; // there is a split pane at row two
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
try
{
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.Application();
xlApp.Visible = false;
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlApp.Visible = true;
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
// next 2 lines for split pane in Excel:
xlWorkSheet.Application.ActiveWindow.SplitRow = 2;
xlWorkSheet.Application.ActiveWindow.FreezePanes = true;
xlWorkSheet.Cells[1, 1] = "Now open the";
xlWorkSheet.Cells[2, 1] = "Excel Options window";
}
catch (System.Runtime.InteropServices.COMException)
{
System.Windows.Forms.MessageBox.Show("Microsoft Excel does not seem to be installed on this computer any longer (although there are still registry entries for it). Please save to a .tem file. (1)");
return;
}
catch (Exception)
{
System.Windows.Forms.MessageBox.Show("Microsoft Excel does not seem to be installed on this computer any longer (although there are still registry entries for it). Please save to a .tem file. (2)");
return;
}
while(i < 65000)
{
i++;
try
{
xlWorkSheet.Cells[i, 1] = i.ToString();
Thread.Sleep(1000);
}
catch (System.Runtime.InteropServices.COMException)
{
System.Windows.Forms.MessageBox.Show("All right, what do I do here?");
}
catch (Exception)
{
System.Windows.Forms.MessageBox.Show("Something else happened.");
}
}
Console.ReadLine(); //Pause
}
}
}
```
* Lanch the app, Excel appears and data is written to it. Open the Excel options dialog window from the menu and up pops the error:
>
> An exception of type 'System.Runtime.InteropServices.COMException' occurred in mscorlib.dll and wasn't handled before a managed/native boundary
>
> Additional information: Exception from HRESULT: 0x800AC472
>
>
>
* Click on Continue and my message box **"All right, what do I do here?"** appears.
Please advise?
Best regards,
Bertrand
|
2014/05/22
|
['https://Stackoverflow.com/questions/23808057', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3597426/']
|
Make Excel Interactive is a perfect solution. The only problem is if the user is doing something on Excel at the same time, like selecting range or editing a cell. And for example your code is returning from a different thread and trying to write on Excel the results of the calculations. So to avoid the issue my suggestions is:
```
private void x(string str)
{
while (this.Application.Interactive == true)
{
// If Excel is currently busy, try until go thru
SetAppInactive();
}
// now writing the data is protected from any user interaption
try
{
for (int i = 1; i < 2000; i++)
{
sh.Cells[i, 1].Value2 = str;
}
}
finally
{
// don't forget to turn it on again
this.Application.Interactive = true;
}
}
private void SetAppInactive()
{
try
{
this.Application.Interactive = false;
}
catch
{
}
}
```
|
Since Interop does cross threading, it may lead to accessing same object by multiple threads, leading to this exception, below code worked for me.
```
bool failed = false;
do
{
try
{
// Call goes here
failed = false;
}
catch (System.Runtime.InteropServices.COMException e)
{
failed = true;
}
System.Threading.Thread.Sleep(10);
} while (failed);
```
|
23,808,057 |
While my C# program writes data continuously to an Excel spreadsheet, if the end user clicks on the upper right menu and opens the
**Excel Options** window, this causes following exception:
>
> System.Runtime.InteropServices.COMException with HRESULT: 0x800AC472
>
>
>
This interrupts the data from being written to the spreadsheet.
Ideally, the user should be allowed to do this without causing an exception.
The only solution I found to this error code was to loop and wait until the exception went away:
[Exception from HRESULT: 0x800AC472](https://stackoverflow.com/questions/1952759/exception-from-hresult-0x800ac472)
which effectively hangs the app, data is not written to Excel and the user is left in the dark about the problem.
I thought about disabling the main menu of Excel while writing to it, but cannot find a reference on how to do this.
My app supports **Excel 2000** to **2013**.
### Here is how to reproduce the issue:
* Using **Visual Studio Express 2013** for Windows Desktop, **.NET 4.5.1** on Windows 7 64-bit with **Excel 2007**, create a new Visual C# Console Application project.
* Add reference to "**Microsoft ExceL 12.0 Object Library**" (for Excel) and to "System.Windows.Forms" (for messagebox).
Here is the complete code:
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading.Tasks;
using System.Threading; // for sleep
using System.IO;
using System.Runtime.InteropServices;
using System.Reflection;
using Microsoft.Win32;
using Excel = Microsoft.Office.Interop.Excel;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int i = 3; // there is a split pane at row two
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
try
{
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.Application();
xlApp.Visible = false;
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlApp.Visible = true;
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
// next 2 lines for split pane in Excel:
xlWorkSheet.Application.ActiveWindow.SplitRow = 2;
xlWorkSheet.Application.ActiveWindow.FreezePanes = true;
xlWorkSheet.Cells[1, 1] = "Now open the";
xlWorkSheet.Cells[2, 1] = "Excel Options window";
}
catch (System.Runtime.InteropServices.COMException)
{
System.Windows.Forms.MessageBox.Show("Microsoft Excel does not seem to be installed on this computer any longer (although there are still registry entries for it). Please save to a .tem file. (1)");
return;
}
catch (Exception)
{
System.Windows.Forms.MessageBox.Show("Microsoft Excel does not seem to be installed on this computer any longer (although there are still registry entries for it). Please save to a .tem file. (2)");
return;
}
while(i < 65000)
{
i++;
try
{
xlWorkSheet.Cells[i, 1] = i.ToString();
Thread.Sleep(1000);
}
catch (System.Runtime.InteropServices.COMException)
{
System.Windows.Forms.MessageBox.Show("All right, what do I do here?");
}
catch (Exception)
{
System.Windows.Forms.MessageBox.Show("Something else happened.");
}
}
Console.ReadLine(); //Pause
}
}
}
```
* Lanch the app, Excel appears and data is written to it. Open the Excel options dialog window from the menu and up pops the error:
>
> An exception of type 'System.Runtime.InteropServices.COMException' occurred in mscorlib.dll and wasn't handled before a managed/native boundary
>
> Additional information: Exception from HRESULT: 0x800AC472
>
>
>
* Click on Continue and my message box **"All right, what do I do here?"** appears.
Please advise?
Best regards,
Bertrand
|
2014/05/22
|
['https://Stackoverflow.com/questions/23808057', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3597426/']
|
Make Excel Interactive is a perfect solution. The only problem is if the user is doing something on Excel at the same time, like selecting range or editing a cell. And for example your code is returning from a different thread and trying to write on Excel the results of the calculations. So to avoid the issue my suggestions is:
```
private void x(string str)
{
while (this.Application.Interactive == true)
{
// If Excel is currently busy, try until go thru
SetAppInactive();
}
// now writing the data is protected from any user interaption
try
{
for (int i = 1; i < 2000; i++)
{
sh.Cells[i, 1].Value2 = str;
}
}
finally
{
// don't forget to turn it on again
this.Application.Interactive = true;
}
}
private void SetAppInactive()
{
try
{
this.Application.Interactive = false;
}
catch
{
}
}
```
|
One possible alternative to automating Excel, and wrestling with its' perculiarities, is to write the file out using the OpenXmlWriter writer (DocumentFormat.OpenXml.OpenXmlWriter).
It's a little tricky but does handle sheets with > 1 million rows without breaking a sweat.
[OpenXml docs on MSDN](http://msdn.microsoft.com/en-us/library/documentformat.openxml%28v=office.14%29.aspx)
|
23,808,057 |
While my C# program writes data continuously to an Excel spreadsheet, if the end user clicks on the upper right menu and opens the
**Excel Options** window, this causes following exception:
>
> System.Runtime.InteropServices.COMException with HRESULT: 0x800AC472
>
>
>
This interrupts the data from being written to the spreadsheet.
Ideally, the user should be allowed to do this without causing an exception.
The only solution I found to this error code was to loop and wait until the exception went away:
[Exception from HRESULT: 0x800AC472](https://stackoverflow.com/questions/1952759/exception-from-hresult-0x800ac472)
which effectively hangs the app, data is not written to Excel and the user is left in the dark about the problem.
I thought about disabling the main menu of Excel while writing to it, but cannot find a reference on how to do this.
My app supports **Excel 2000** to **2013**.
### Here is how to reproduce the issue:
* Using **Visual Studio Express 2013** for Windows Desktop, **.NET 4.5.1** on Windows 7 64-bit with **Excel 2007**, create a new Visual C# Console Application project.
* Add reference to "**Microsoft ExceL 12.0 Object Library**" (for Excel) and to "System.Windows.Forms" (for messagebox).
Here is the complete code:
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading.Tasks;
using System.Threading; // for sleep
using System.IO;
using System.Runtime.InteropServices;
using System.Reflection;
using Microsoft.Win32;
using Excel = Microsoft.Office.Interop.Excel;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int i = 3; // there is a split pane at row two
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
try
{
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.Application();
xlApp.Visible = false;
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlApp.Visible = true;
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
// next 2 lines for split pane in Excel:
xlWorkSheet.Application.ActiveWindow.SplitRow = 2;
xlWorkSheet.Application.ActiveWindow.FreezePanes = true;
xlWorkSheet.Cells[1, 1] = "Now open the";
xlWorkSheet.Cells[2, 1] = "Excel Options window";
}
catch (System.Runtime.InteropServices.COMException)
{
System.Windows.Forms.MessageBox.Show("Microsoft Excel does not seem to be installed on this computer any longer (although there are still registry entries for it). Please save to a .tem file. (1)");
return;
}
catch (Exception)
{
System.Windows.Forms.MessageBox.Show("Microsoft Excel does not seem to be installed on this computer any longer (although there are still registry entries for it). Please save to a .tem file. (2)");
return;
}
while(i < 65000)
{
i++;
try
{
xlWorkSheet.Cells[i, 1] = i.ToString();
Thread.Sleep(1000);
}
catch (System.Runtime.InteropServices.COMException)
{
System.Windows.Forms.MessageBox.Show("All right, what do I do here?");
}
catch (Exception)
{
System.Windows.Forms.MessageBox.Show("Something else happened.");
}
}
Console.ReadLine(); //Pause
}
}
}
```
* Lanch the app, Excel appears and data is written to it. Open the Excel options dialog window from the menu and up pops the error:
>
> An exception of type 'System.Runtime.InteropServices.COMException' occurred in mscorlib.dll and wasn't handled before a managed/native boundary
>
> Additional information: Exception from HRESULT: 0x800AC472
>
>
>
* Click on Continue and my message box **"All right, what do I do here?"** appears.
Please advise?
Best regards,
Bertrand
|
2014/05/22
|
['https://Stackoverflow.com/questions/23808057', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3597426/']
|
We finally went all the way to Microsoft Support with this issue. Their final response was:
>
> I am able to reproduce the issue. I researched on this further and
> found that this behaviour is expected and by design. This
> exception, 0x800AC472 – VBA\_E\_IGNORE, is thrown because Excel is busy
> and will not service any Object Model calls. Here is one of the
> discussions that talks about this.
> <http://social.msdn.microsoft.com/Forums/vstudio/en-US/9168f9f2-e5bc-4535-8d7d-4e374ab8ff09/hresult-800ac472-from-set-operations-in-excel?forum=vsto> The work around I see is to explicitly catch this exception and retry
> after sometime until your intended action is completed.
>
>
>
Since we cannot read the minds of the user who might decide to open a window or take a note without realizing the soft has stopped logging (if you mask the error), we decided to work around using:
```
xlWorkSheet.EnableSelection = Microsoft.Office.Interop.Excel.XlEnableSelection.xlNoSelection;
```
to lock the Excel window UI. We provide an obvious "unlock" button but when the user clicks it, he is sternly warned in a messagebox along with a "Do you wish to continue?"
|
One possible alternative to automating Excel, and wrestling with its' perculiarities, is to write the file out using the OpenXmlWriter writer (DocumentFormat.OpenXml.OpenXmlWriter).
It's a little tricky but does handle sheets with > 1 million rows without breaking a sweat.
[OpenXml docs on MSDN](http://msdn.microsoft.com/en-us/library/documentformat.openxml%28v=office.14%29.aspx)
|
23,808,057 |
While my C# program writes data continuously to an Excel spreadsheet, if the end user clicks on the upper right menu and opens the
**Excel Options** window, this causes following exception:
>
> System.Runtime.InteropServices.COMException with HRESULT: 0x800AC472
>
>
>
This interrupts the data from being written to the spreadsheet.
Ideally, the user should be allowed to do this without causing an exception.
The only solution I found to this error code was to loop and wait until the exception went away:
[Exception from HRESULT: 0x800AC472](https://stackoverflow.com/questions/1952759/exception-from-hresult-0x800ac472)
which effectively hangs the app, data is not written to Excel and the user is left in the dark about the problem.
I thought about disabling the main menu of Excel while writing to it, but cannot find a reference on how to do this.
My app supports **Excel 2000** to **2013**.
### Here is how to reproduce the issue:
* Using **Visual Studio Express 2013** for Windows Desktop, **.NET 4.5.1** on Windows 7 64-bit with **Excel 2007**, create a new Visual C# Console Application project.
* Add reference to "**Microsoft ExceL 12.0 Object Library**" (for Excel) and to "System.Windows.Forms" (for messagebox).
Here is the complete code:
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading.Tasks;
using System.Threading; // for sleep
using System.IO;
using System.Runtime.InteropServices;
using System.Reflection;
using Microsoft.Win32;
using Excel = Microsoft.Office.Interop.Excel;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int i = 3; // there is a split pane at row two
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
try
{
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.Application();
xlApp.Visible = false;
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlApp.Visible = true;
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
// next 2 lines for split pane in Excel:
xlWorkSheet.Application.ActiveWindow.SplitRow = 2;
xlWorkSheet.Application.ActiveWindow.FreezePanes = true;
xlWorkSheet.Cells[1, 1] = "Now open the";
xlWorkSheet.Cells[2, 1] = "Excel Options window";
}
catch (System.Runtime.InteropServices.COMException)
{
System.Windows.Forms.MessageBox.Show("Microsoft Excel does not seem to be installed on this computer any longer (although there are still registry entries for it). Please save to a .tem file. (1)");
return;
}
catch (Exception)
{
System.Windows.Forms.MessageBox.Show("Microsoft Excel does not seem to be installed on this computer any longer (although there are still registry entries for it). Please save to a .tem file. (2)");
return;
}
while(i < 65000)
{
i++;
try
{
xlWorkSheet.Cells[i, 1] = i.ToString();
Thread.Sleep(1000);
}
catch (System.Runtime.InteropServices.COMException)
{
System.Windows.Forms.MessageBox.Show("All right, what do I do here?");
}
catch (Exception)
{
System.Windows.Forms.MessageBox.Show("Something else happened.");
}
}
Console.ReadLine(); //Pause
}
}
}
```
* Lanch the app, Excel appears and data is written to it. Open the Excel options dialog window from the menu and up pops the error:
>
> An exception of type 'System.Runtime.InteropServices.COMException' occurred in mscorlib.dll and wasn't handled before a managed/native boundary
>
> Additional information: Exception from HRESULT: 0x800AC472
>
>
>
* Click on Continue and my message box **"All right, what do I do here?"** appears.
Please advise?
Best regards,
Bertrand
|
2014/05/22
|
['https://Stackoverflow.com/questions/23808057', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3597426/']
|
```
xlApp = new Excel.Application();
xlApp.Interactive = false;
```
|
One possible alternative to automating Excel, and wrestling with its' perculiarities, is to write the file out using the OpenXmlWriter writer (DocumentFormat.OpenXml.OpenXmlWriter).
It's a little tricky but does handle sheets with > 1 million rows without breaking a sweat.
[OpenXml docs on MSDN](http://msdn.microsoft.com/en-us/library/documentformat.openxml%28v=office.14%29.aspx)
|
23,808,057 |
While my C# program writes data continuously to an Excel spreadsheet, if the end user clicks on the upper right menu and opens the
**Excel Options** window, this causes following exception:
>
> System.Runtime.InteropServices.COMException with HRESULT: 0x800AC472
>
>
>
This interrupts the data from being written to the spreadsheet.
Ideally, the user should be allowed to do this without causing an exception.
The only solution I found to this error code was to loop and wait until the exception went away:
[Exception from HRESULT: 0x800AC472](https://stackoverflow.com/questions/1952759/exception-from-hresult-0x800ac472)
which effectively hangs the app, data is not written to Excel and the user is left in the dark about the problem.
I thought about disabling the main menu of Excel while writing to it, but cannot find a reference on how to do this.
My app supports **Excel 2000** to **2013**.
### Here is how to reproduce the issue:
* Using **Visual Studio Express 2013** for Windows Desktop, **.NET 4.5.1** on Windows 7 64-bit with **Excel 2007**, create a new Visual C# Console Application project.
* Add reference to "**Microsoft ExceL 12.0 Object Library**" (for Excel) and to "System.Windows.Forms" (for messagebox).
Here is the complete code:
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading.Tasks;
using System.Threading; // for sleep
using System.IO;
using System.Runtime.InteropServices;
using System.Reflection;
using Microsoft.Win32;
using Excel = Microsoft.Office.Interop.Excel;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int i = 3; // there is a split pane at row two
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
try
{
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.Application();
xlApp.Visible = false;
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlApp.Visible = true;
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
// next 2 lines for split pane in Excel:
xlWorkSheet.Application.ActiveWindow.SplitRow = 2;
xlWorkSheet.Application.ActiveWindow.FreezePanes = true;
xlWorkSheet.Cells[1, 1] = "Now open the";
xlWorkSheet.Cells[2, 1] = "Excel Options window";
}
catch (System.Runtime.InteropServices.COMException)
{
System.Windows.Forms.MessageBox.Show("Microsoft Excel does not seem to be installed on this computer any longer (although there are still registry entries for it). Please save to a .tem file. (1)");
return;
}
catch (Exception)
{
System.Windows.Forms.MessageBox.Show("Microsoft Excel does not seem to be installed on this computer any longer (although there are still registry entries for it). Please save to a .tem file. (2)");
return;
}
while(i < 65000)
{
i++;
try
{
xlWorkSheet.Cells[i, 1] = i.ToString();
Thread.Sleep(1000);
}
catch (System.Runtime.InteropServices.COMException)
{
System.Windows.Forms.MessageBox.Show("All right, what do I do here?");
}
catch (Exception)
{
System.Windows.Forms.MessageBox.Show("Something else happened.");
}
}
Console.ReadLine(); //Pause
}
}
}
```
* Lanch the app, Excel appears and data is written to it. Open the Excel options dialog window from the menu and up pops the error:
>
> An exception of type 'System.Runtime.InteropServices.COMException' occurred in mscorlib.dll and wasn't handled before a managed/native boundary
>
> Additional information: Exception from HRESULT: 0x800AC472
>
>
>
* Click on Continue and my message box **"All right, what do I do here?"** appears.
Please advise?
Best regards,
Bertrand
|
2014/05/22
|
['https://Stackoverflow.com/questions/23808057', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3597426/']
|
Make Excel Interactive is a perfect solution. The only problem is if the user is doing something on Excel at the same time, like selecting range or editing a cell. And for example your code is returning from a different thread and trying to write on Excel the results of the calculations. So to avoid the issue my suggestions is:
```
private void x(string str)
{
while (this.Application.Interactive == true)
{
// If Excel is currently busy, try until go thru
SetAppInactive();
}
// now writing the data is protected from any user interaption
try
{
for (int i = 1; i < 2000; i++)
{
sh.Cells[i, 1].Value2 = str;
}
}
finally
{
// don't forget to turn it on again
this.Application.Interactive = true;
}
}
private void SetAppInactive()
{
try
{
this.Application.Interactive = false;
}
catch
{
}
}
```
|
What I have done successfully is to make a temp copy of the target excel file before opening it in code.
That way I can manipulate it independent of the source document being open or not.
|
50,389,264 |
I am learning how to code and working on a Hack Reactor puzzle (see below). *I don't understand why the else part of my function block does not work. Can anyone point me in the right direction?*
>
> Write a function called `getElementsThatEqual10AtProperty`.
>
>
> Given an object and a key, `getElementsThatEqual10AtProperty` returns
> an array containing all the elements of the array located at the given
> key that are equal to ten.
>
>
> Notes:
>
>
> * If the array is empty, it should return an empty array.
> * If the array contains no elements are equal to 10, it should return an empty array.
> * If the property at the given key is not an array, it should return an empty array.
> * If there is no property at the key, it should return an empty array.
>
>
>
Example:
```
var obj = { key: [1000, 10, 50, 10] };
var output = getElementsThatEqual10AtProperty(obj, 'key');
console.log(output); // > --> [10, 10]
```
**My Solution:**
```
var obj = {
key: '[1000, 10, 50, 10]'
};
function getElementsThatEqual10AtProperty(obj, key) {
if (typeof Array.isArray(obj[key])) {
for (let key in obj) {
tenArray = obj.key = obj[key].filter( element => element === 10);
}
} else {
tenArray = obj.key = [];
}
return tenArray;
}
console.log(getElementsThatEqual10AtProperty(obj, 'key'))
```
Final Solution
```
var obj = {
key: [1000, 10, 50, 10]
};
function getElementsThatEqual10AtProperty(obj, key) {
if (Array.isArray(obj[key])) {
tenArray = obj[key].filter( element => element === 10);
} else {
tenArray = [];
}
return tenArray;
}
console.log(getElementsThatEqual10AtProperty(obj, 'key'))
```
|
2018/05/17
|
['https://Stackoverflow.com/questions/50389264', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8193814/']
|
Use only isArray to check for array, no need of `typeof` here.
```js
var obj = {
key: '[1000, 10, 50, 10]'
};
console.log(Array.isArray(obj.key)) // false
console.log(typeof Array.isArray(obj.key)) // 'boolean'
console.log(Boolean(typeof Array.isArray(obj.key))) // true
```
Array at 'key' value should be declared without single-quotes, else it will be treated as string.
```js
var obj = {
key: [1000, 10, 50, 10]
};
console.log(Array.isArray(obj.key)) // true
```
There is no need for a `for ..in` here as the key is already known. Also no need to modify obj.key I guess.
```
if (Array.isArray(obj[key])) {
tenArray = obj[key].filter( element => element === 10);
}
```
|
Obj[key] is not declared as an array in your code but as a string. You can also do much simpler to meet your requirements :
```js
var obj = {
key: [1000, 10, 50, 10]
};
function getElementsThatEqual10AtProperty(obj, key) {
if (obj[key] && obj[key] instanceof Array) {
return obj[key].filter( element => element === 10);
}
return [];
}
console.log(getElementsThatEqual10AtProperty(obj, 'key'));
```
|
50,389,264 |
I am learning how to code and working on a Hack Reactor puzzle (see below). *I don't understand why the else part of my function block does not work. Can anyone point me in the right direction?*
>
> Write a function called `getElementsThatEqual10AtProperty`.
>
>
> Given an object and a key, `getElementsThatEqual10AtProperty` returns
> an array containing all the elements of the array located at the given
> key that are equal to ten.
>
>
> Notes:
>
>
> * If the array is empty, it should return an empty array.
> * If the array contains no elements are equal to 10, it should return an empty array.
> * If the property at the given key is not an array, it should return an empty array.
> * If there is no property at the key, it should return an empty array.
>
>
>
Example:
```
var obj = { key: [1000, 10, 50, 10] };
var output = getElementsThatEqual10AtProperty(obj, 'key');
console.log(output); // > --> [10, 10]
```
**My Solution:**
```
var obj = {
key: '[1000, 10, 50, 10]'
};
function getElementsThatEqual10AtProperty(obj, key) {
if (typeof Array.isArray(obj[key])) {
for (let key in obj) {
tenArray = obj.key = obj[key].filter( element => element === 10);
}
} else {
tenArray = obj.key = [];
}
return tenArray;
}
console.log(getElementsThatEqual10AtProperty(obj, 'key'))
```
Final Solution
```
var obj = {
key: [1000, 10, 50, 10]
};
function getElementsThatEqual10AtProperty(obj, key) {
if (Array.isArray(obj[key])) {
tenArray = obj[key].filter( element => element === 10);
} else {
tenArray = [];
}
return tenArray;
}
console.log(getElementsThatEqual10AtProperty(obj, 'key'))
```
|
2018/05/17
|
['https://Stackoverflow.com/questions/50389264', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8193814/']
|
Use only isArray to check for array, no need of `typeof` here.
```js
var obj = {
key: '[1000, 10, 50, 10]'
};
console.log(Array.isArray(obj.key)) // false
console.log(typeof Array.isArray(obj.key)) // 'boolean'
console.log(Boolean(typeof Array.isArray(obj.key))) // true
```
Array at 'key' value should be declared without single-quotes, else it will be treated as string.
```js
var obj = {
key: [1000, 10, 50, 10]
};
console.log(Array.isArray(obj.key)) // true
```
There is no need for a `for ..in` here as the key is already known. Also no need to modify obj.key I guess.
```
if (Array.isArray(obj[key])) {
tenArray = obj[key].filter( element => element === 10);
}
```
|
Your problem is that you set `obj.key` instead of `obj[key]` in the `else` part of your function.
|
50,389,264 |
I am learning how to code and working on a Hack Reactor puzzle (see below). *I don't understand why the else part of my function block does not work. Can anyone point me in the right direction?*
>
> Write a function called `getElementsThatEqual10AtProperty`.
>
>
> Given an object and a key, `getElementsThatEqual10AtProperty` returns
> an array containing all the elements of the array located at the given
> key that are equal to ten.
>
>
> Notes:
>
>
> * If the array is empty, it should return an empty array.
> * If the array contains no elements are equal to 10, it should return an empty array.
> * If the property at the given key is not an array, it should return an empty array.
> * If there is no property at the key, it should return an empty array.
>
>
>
Example:
```
var obj = { key: [1000, 10, 50, 10] };
var output = getElementsThatEqual10AtProperty(obj, 'key');
console.log(output); // > --> [10, 10]
```
**My Solution:**
```
var obj = {
key: '[1000, 10, 50, 10]'
};
function getElementsThatEqual10AtProperty(obj, key) {
if (typeof Array.isArray(obj[key])) {
for (let key in obj) {
tenArray = obj.key = obj[key].filter( element => element === 10);
}
} else {
tenArray = obj.key = [];
}
return tenArray;
}
console.log(getElementsThatEqual10AtProperty(obj, 'key'))
```
Final Solution
```
var obj = {
key: [1000, 10, 50, 10]
};
function getElementsThatEqual10AtProperty(obj, key) {
if (Array.isArray(obj[key])) {
tenArray = obj[key].filter( element => element === 10);
} else {
tenArray = [];
}
return tenArray;
}
console.log(getElementsThatEqual10AtProperty(obj, 'key'))
```
|
2018/05/17
|
['https://Stackoverflow.com/questions/50389264', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8193814/']
|
Use only isArray to check for array, no need of `typeof` here.
```js
var obj = {
key: '[1000, 10, 50, 10]'
};
console.log(Array.isArray(obj.key)) // false
console.log(typeof Array.isArray(obj.key)) // 'boolean'
console.log(Boolean(typeof Array.isArray(obj.key))) // true
```
Array at 'key' value should be declared without single-quotes, else it will be treated as string.
```js
var obj = {
key: [1000, 10, 50, 10]
};
console.log(Array.isArray(obj.key)) // true
```
There is no need for a `for ..in` here as the key is already known. Also no need to modify obj.key I guess.
```
if (Array.isArray(obj[key])) {
tenArray = obj[key].filter( element => element === 10);
}
```
|
Filter the array:
```
var obj = {
key: [1000, 10, 50, 10]
}
function getElementsThatEqual10AtProperty(obj, key) {
var tens = []
if (Array.isArray(obj[key])) {
tens = obj[key].filter(function(el) {
return (10 === el)
})
}
return tens
}
var tensArray = getElementsThatEqual10AtProperty(obj, 'key')
console.log(tensArray)
```
|
50,389,264 |
I am learning how to code and working on a Hack Reactor puzzle (see below). *I don't understand why the else part of my function block does not work. Can anyone point me in the right direction?*
>
> Write a function called `getElementsThatEqual10AtProperty`.
>
>
> Given an object and a key, `getElementsThatEqual10AtProperty` returns
> an array containing all the elements of the array located at the given
> key that are equal to ten.
>
>
> Notes:
>
>
> * If the array is empty, it should return an empty array.
> * If the array contains no elements are equal to 10, it should return an empty array.
> * If the property at the given key is not an array, it should return an empty array.
> * If there is no property at the key, it should return an empty array.
>
>
>
Example:
```
var obj = { key: [1000, 10, 50, 10] };
var output = getElementsThatEqual10AtProperty(obj, 'key');
console.log(output); // > --> [10, 10]
```
**My Solution:**
```
var obj = {
key: '[1000, 10, 50, 10]'
};
function getElementsThatEqual10AtProperty(obj, key) {
if (typeof Array.isArray(obj[key])) {
for (let key in obj) {
tenArray = obj.key = obj[key].filter( element => element === 10);
}
} else {
tenArray = obj.key = [];
}
return tenArray;
}
console.log(getElementsThatEqual10AtProperty(obj, 'key'))
```
Final Solution
```
var obj = {
key: [1000, 10, 50, 10]
};
function getElementsThatEqual10AtProperty(obj, key) {
if (Array.isArray(obj[key])) {
tenArray = obj[key].filter( element => element === 10);
} else {
tenArray = [];
}
return tenArray;
}
console.log(getElementsThatEqual10AtProperty(obj, 'key'))
```
|
2018/05/17
|
['https://Stackoverflow.com/questions/50389264', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8193814/']
|
Obj[key] is not declared as an array in your code but as a string. You can also do much simpler to meet your requirements :
```js
var obj = {
key: [1000, 10, 50, 10]
};
function getElementsThatEqual10AtProperty(obj, key) {
if (obj[key] && obj[key] instanceof Array) {
return obj[key].filter( element => element === 10);
}
return [];
}
console.log(getElementsThatEqual10AtProperty(obj, 'key'));
```
|
Your problem is that you set `obj.key` instead of `obj[key]` in the `else` part of your function.
|
50,389,264 |
I am learning how to code and working on a Hack Reactor puzzle (see below). *I don't understand why the else part of my function block does not work. Can anyone point me in the right direction?*
>
> Write a function called `getElementsThatEqual10AtProperty`.
>
>
> Given an object and a key, `getElementsThatEqual10AtProperty` returns
> an array containing all the elements of the array located at the given
> key that are equal to ten.
>
>
> Notes:
>
>
> * If the array is empty, it should return an empty array.
> * If the array contains no elements are equal to 10, it should return an empty array.
> * If the property at the given key is not an array, it should return an empty array.
> * If there is no property at the key, it should return an empty array.
>
>
>
Example:
```
var obj = { key: [1000, 10, 50, 10] };
var output = getElementsThatEqual10AtProperty(obj, 'key');
console.log(output); // > --> [10, 10]
```
**My Solution:**
```
var obj = {
key: '[1000, 10, 50, 10]'
};
function getElementsThatEqual10AtProperty(obj, key) {
if (typeof Array.isArray(obj[key])) {
for (let key in obj) {
tenArray = obj.key = obj[key].filter( element => element === 10);
}
} else {
tenArray = obj.key = [];
}
return tenArray;
}
console.log(getElementsThatEqual10AtProperty(obj, 'key'))
```
Final Solution
```
var obj = {
key: [1000, 10, 50, 10]
};
function getElementsThatEqual10AtProperty(obj, key) {
if (Array.isArray(obj[key])) {
tenArray = obj[key].filter( element => element === 10);
} else {
tenArray = [];
}
return tenArray;
}
console.log(getElementsThatEqual10AtProperty(obj, 'key'))
```
|
2018/05/17
|
['https://Stackoverflow.com/questions/50389264', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8193814/']
|
Filter the array:
```
var obj = {
key: [1000, 10, 50, 10]
}
function getElementsThatEqual10AtProperty(obj, key) {
var tens = []
if (Array.isArray(obj[key])) {
tens = obj[key].filter(function(el) {
return (10 === el)
})
}
return tens
}
var tensArray = getElementsThatEqual10AtProperty(obj, 'key')
console.log(tensArray)
```
|
Your problem is that you set `obj.key` instead of `obj[key]` in the `else` part of your function.
|
16,853,778 |
I Have a simple unordered list containing over 12 li's.
```
<ul>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
</ul>
```
I want to target the first four li's to change their background, and the last four li's to create a different background. Is there any way to do this only with CSS? I know how to use pseudo classes for targeting the first, or the last li, or every forth element, but what I want is to target all first-four, and last-four elements.
|
2013/05/31
|
['https://Stackoverflow.com/questions/16853778', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2335523/']
|
Use
```
ul li:nth-child(-n+4)
```
for the first four, and
```
ul li:nth-last-child(-n+4)
```
for the last four.
|
Using `nth-child` is the best practice.
```
li:nth-child(-n+4) {
background-color:gren;
}
```
But you **won't get full browser compatibility.** especially in lower versions of **IE**
If you are using static html, you can create a class and and apply to the first four `li`
eg:
```
.special{
background-color:gren;
}
<ul>
<li class="special"><a href="#">Link</a></li>
<li class="special"><a href="#">Link</a></li>
<li class="special"><a href="#">Link</a></li>
<li class="special"><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
</ul>
```
|
16,853,778 |
I Have a simple unordered list containing over 12 li's.
```
<ul>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
</ul>
```
I want to target the first four li's to change their background, and the last four li's to create a different background. Is there any way to do this only with CSS? I know how to use pseudo classes for targeting the first, or the last li, or every forth element, but what I want is to target all first-four, and last-four elements.
|
2013/05/31
|
['https://Stackoverflow.com/questions/16853778', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2335523/']
|
Use
```
ul li:nth-child(-n+4)
```
for the first four, and
```
ul li:nth-last-child(-n+4)
```
for the last four.
|
You can user **nth-child** and **nth-last-of-type**.
So the CSS code will be :
```
ul li:nth-child(-n+4) {
background: red;
}
ul li:nth-last-of-type(-n+4) {
background: blue;
}
```
|
16,853,778 |
I Have a simple unordered list containing over 12 li's.
```
<ul>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
</ul>
```
I want to target the first four li's to change their background, and the last four li's to create a different background. Is there any way to do this only with CSS? I know how to use pseudo classes for targeting the first, or the last li, or every forth element, but what I want is to target all first-four, and last-four elements.
|
2013/05/31
|
['https://Stackoverflow.com/questions/16853778', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2335523/']
|
Using `nth-child` is the best practice.
```
li:nth-child(-n+4) {
background-color:gren;
}
```
But you **won't get full browser compatibility.** especially in lower versions of **IE**
If you are using static html, you can create a class and and apply to the first four `li`
eg:
```
.special{
background-color:gren;
}
<ul>
<li class="special"><a href="#">Link</a></li>
<li class="special"><a href="#">Link</a></li>
<li class="special"><a href="#">Link</a></li>
<li class="special"><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
</ul>
```
|
You can user **nth-child** and **nth-last-of-type**.
So the CSS code will be :
```
ul li:nth-child(-n+4) {
background: red;
}
ul li:nth-last-of-type(-n+4) {
background: blue;
}
```
|
640,409 |
Someone asked me to provide my public id\_rsa key to make be able to connect to their server via ssh. I did so and it's working fine. I want to do that from my another laptop as well without having to bother them. If I just copy a public and a private keys from my first laptop to the second one, will it allow me to connect to the server? Note I already have a private and public rsa keys on my **second** laptop that are, of course, different from the ones from the first laptop.
What's the best way to do so - copy the keys?
|
2014/10/29
|
['https://serverfault.com/questions/640409', 'https://serverfault.com', 'https://serverfault.com/users/250802/']
|
Followed advice from Microsoft support and created claim description items which included the attributes I wanted to include, these were then present in the metadata file. Applying an Issuance Transform allowed me to map values to these attributes.
|
This is normal. The metadata file contains the "claim descriptions" as you say, plus the endpoints of your ADFS farm, the public key of your token signing and token decrypting certificates; general information about your deployment. All of this, but not your relying party configuration (this would be a security issue in my opinion).
You must exchange metadata files with your application vendor. Then you must agree with your vendor on:
* The identifier of your trust
* The type of claims that you send
* The allowed values of these claims
* Whether you want to encrypt the token between your systems
|
4,314,060 |
I'm looking for an explanation / API doc / examples of how to use (and train?) Tesseract in C++, nothing useful on the google Tesseract page, and yet to find something over the web.
Anyone useful sources, experiences would be more than welcome, as I have no idea how to begin with it.
**P.S:**
1. I'm open for suggestions on other
libraries.
2. Only **FREE** libraries
|
2010/11/30
|
['https://Stackoverflow.com/questions/4314060', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/427306/']
|
I have some experience with Tesseract...
a simple google of 'training tesseract' reveals this page:
<http://code.google.com/p/tesseract-ocr/wiki/TrainingTesseract>
where you must choose which version of tesseract you wish to train..
While 3 is the latest version, it's brand new and thus people are still ironing out any issues - im still using version 2.4. Anyways, you'll see there are about 9 steps in training tesseract for a particular 'language' (or what should have been called 'fonts' or 'character-sets'). You could also just use the existing 'eng' language - but it depends on your application. For example, in my application I would have to do the document analysis and take a particular region and want to OCR a 13-character string of numbers - and I needed high accuracy - and I didn't want it reading '5' as 'S' and '0' as 'O' etc, so it was logical to create a particular 'language' of my particular font-set consisting only of the characters 0..9, whereas you might not care if you get extra 'noise
|
Tesseract Ocr is an open source library for detecting Optical Character. You just need to include the library files if you are using visual studio. If you are using qt creator then you have to build the library to work on the QT. You need to use CMakelist or Cmake Gui to build the library.
You can visit the link
[Opencv Ocr build for Qt 5.4 mingw](http://www.life2coding.com/opencv-ocr-tutoiral-build-tesseract-ocr-library-3-02-02-with-qt-5-4-mingw-on-windows/)
|
30,867,462 |
I have been given a web application written in Classic ASP to port from Windows 2003 Server (SQL Server 2000 and IIS 6) to Windows 2008 Server (SQL Server 2008 and IIS 7.5).
The site uses a `GLOBAL.ASA` file to define global variables, one of which is the connection string (`cnn`) to connect to SQL Server.
Below is the (old) connection string from `GLOBAL.ASA`:
```
Sub Application_OnStart
Dim cnnDem, cnnString
Set cnnDem = Server.CreateObject("ADODB.Connection")
cnnDem.CommandTimeout = 60
cnnDem.Mode = admodeshareexclusive
cnnString = "Provider=SQLOLEDB; Data Source=192.xxx.x.xx; User Id=xxxx; Password=xxxxx; default catalog=xxxxxxx;"
Application("conString")=cnnString
Call cnnDem.Open(cnnString)
Application("cnn") = cnnDem
End Sub
```
The `.ASP` pages then use the `cnn` value like this:
```
strSQL = "Select * From tblUtilities order by companyname"
Set rs = Server.CreateObject("ADODB.Recordset")
rs.Open strSQL, Application("cnn"), adOpenKeyset
```
However I could not get the connection string to connect – I whittled it down to a “Failed to Login” error message (no matter what Login ID I tried).
I edited the `GLOBAL.ASA` file as follows and it works.
```
Sub Application_OnStart
Dim cnnDem, cnnString
Set cnnDem = Server.CreateObject("ADODB.Connection")
cnnDem.CommandTimeout = 60
cnnString = "Provider=SQLNCLI10.1;User Id=xxxx; Password=xxxxx;Initial Catalog=xxxxxxx;Data Source=xxxxxx\SQLEXPRESS;"
Application("conString")=cnnString
Application("cnn")=cnnString
Call cnnDem.Open(cnnString)
End Sub
```
The main difference is that `cnn` now contains the connection string, where as previously `cnn` was an object referring to `ADOBD.Connection`.
The question I have is what impact (if any) will this have on the application. I have done some basic (local) testing and everything looks ok at the moment. But I am wondering if there might be multi-user issues (or something of that nature) that might arise when this site is deployed again.
|
2015/06/16
|
['https://Stackoverflow.com/questions/30867462', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5015237/']
|
One of the best and easiest way to connect to create a Database Connection String is to crease a new ASP file in the root directory or elsewhere and include the Connection string into it:
//Global.asp //
```
<%
Dim connectionString
connectionString = "PROVIDER=SQLOLEDB;DATA SOURCE=YourSQLServer;UID=sa;PWD=*******;DATABASE=YourDataBase"
%>
```
Then create an include statement in each file that you would like to call this connection.
```
<!-- #include virtual="global.asp" -->
```
Then, where you need to setup your connection call, simply use your code to connect to the Database:
```
<%
Set adoCon = Server.CreateObject("ADODB.Connection")
adoCon.Open = ConnectionString
Set rsReports = Server.CreateObject("ADODB.Recordset")
strSQL = "Select * From Customers"
rsReports.Open strSQL, adoCon
%>
```
|
I keep the Connection String in Global.asa but create the connection in a separate function loaded as needed. An Application connection object may not be aware of temporary network issues that may close that connection, and then future attempts to use the connection will not be successful.
Hope this makes sense.
|
9,480,338 |
I have taken 2 text boxes and 1 text area
User will be to search the content through search box
and provides by which word it should be replaced.
Scenerio 1 :
I want to replace "Good" with word "bad"
But this code does not replace the text area content.
It rather appends with the new replaced string
what's the solution ??
```
<body>
<form id="form1" name="form1" method="post" action="">
<p>
<label for="search">Search :</label>
<input type="text" name="search" id="search" />
</p>
<p>
<label for="replace">Replace</label>
<input type="text" name="replace" id="replace" />
</p>
<p><Br />
<input type="submit" name="submit" id="submit" value="Submit" />
<label for="textarea"></label>
</p>
<p><br />
<textarea name="textarea" id="textarea" cols="45" rows="5" >
"Good morning how are you today are you feeling Good.";
<?php
if(isset($_POST["submit"]))
{
$search = $_POST["search"];
$replace = $_POST["replace"];
$textarea = $_POST["textarea"];
$newtext = str_replace($search,$replace,$textarea);
echo $newtext;
}
?>
</textarea>
</p>
</form>
</body>
</html>
```
|
2012/02/28
|
['https://Stackoverflow.com/questions/9480338', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1361058/']
|
What about [the Intl Twig extension](https://github.com/fabpot/Twig-extensions/blob/master/lib/Twig/Extensions/Extension/Intl.php)?
Usage in a twig template:
```
{{ my_date | localizeddate('full', 'none', locale) }}
```
|
I didn't want to install a whole extensions just for this stuff and need to do a few things automatically: It's also possible to write a helperclass (or expand an existing helper) in Bundle/Twig/Extensions for example like this:
```
public function foo(\Datetime $datetime, $lang = 'de_DE', $pattern = 'd. MMMM Y')
{
$formatter = new \IntlDateFormatter($lang, \IntlDateFormatter::LONG, \IntlDateFormatter::LONG);
$formatter->setPattern($pattern);
return $formatter->format($datetime);
}
```
twig-Template:
```
{{ yourDateTimeObject|foo('en_US', 'd. MMMM Y') }}
```
The result is "12. February 2014" (or "12. Februar 2014" in de\_DE and so on)
|
9,480,338 |
I have taken 2 text boxes and 1 text area
User will be to search the content through search box
and provides by which word it should be replaced.
Scenerio 1 :
I want to replace "Good" with word "bad"
But this code does not replace the text area content.
It rather appends with the new replaced string
what's the solution ??
```
<body>
<form id="form1" name="form1" method="post" action="">
<p>
<label for="search">Search :</label>
<input type="text" name="search" id="search" />
</p>
<p>
<label for="replace">Replace</label>
<input type="text" name="replace" id="replace" />
</p>
<p><Br />
<input type="submit" name="submit" id="submit" value="Submit" />
<label for="textarea"></label>
</p>
<p><br />
<textarea name="textarea" id="textarea" cols="45" rows="5" >
"Good morning how are you today are you feeling Good.";
<?php
if(isset($_POST["submit"]))
{
$search = $_POST["search"];
$replace = $_POST["replace"];
$textarea = $_POST["textarea"];
$newtext = str_replace($search,$replace,$textarea);
echo $newtext;
}
?>
</textarea>
</p>
</form>
</body>
</html>
```
|
2012/02/28
|
['https://Stackoverflow.com/questions/9480338', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1361058/']
|
What about [the Intl Twig extension](https://github.com/fabpot/Twig-extensions/blob/master/lib/Twig/Extensions/Extension/Intl.php)?
Usage in a twig template:
```
{{ my_date | localizeddate('full', 'none', locale) }}
```
|
I really only wanted the day & month names to be translated according to the locale and wrote this twig extension. It accepts the normal `DateTime->format()` parameters and converts day & months names using `strftime()` if needed.
```
<?php
namespace AppBundle\Twig\Extension;
use Twig_Extension;
use Twig_SimpleFilter;
use DateTimeZone;
use DateTime;
class LocalizedDateExtension extends Twig_Extension
{
protected static $conversionMap = [
'D' => 'a',
'l' => 'A',
'M' => 'b',
'F' => 'B',
];
public function getFilters()
{
return [
new Twig_SimpleFilter('localizeddate', [$this, 'localizeDate']),
];
}
protected static function createLocalizableTodo(&$formatString)
{
$newFormatString = '';
$todo = [];
$formatLength = mb_strlen($formatString);
for ($i = 0; $i < $formatLength; $i++) {
$char = $formatString[$i];
if ('\'' === $char) {
$newFormatString = $formatString[++$i]; //advance and add new character
}
if (array_key_exists($char, static::$conversionMap)) {
$newFormatString.= '\!\L\O\C\A\L\I\Z\E\D\\'; //prefix char
$todo[$char] = static::$conversionMap[$char];
}
$newFormatString.= $char;
}
$formatString = $newFormatString;
return $todo;
}
public function localizeDate(DateTime $dateTime, $format, $timezone = null, $locale = null)
{
if (null !== $timezone && $dateTime->getTimezone()->getName() !== $timezone) {
$dateTime = clone $dateTime;
$dateTime->setTimezone(new DateTimeZone($timezone));
}
$todo = static::createLocalizableTodo($format);
$output = $dateTime->format($format);
//no localizeable parameters?
if (0 === count($todo)) {
return $output;
}
if ($locale !== null) {
$currentLocale = setlocale(LC_TIME, '0');
setlocale(LC_TIME, $locale);
}
if ($timezone !== null) {
$currentTimezone = date_default_timezone_get();
date_default_timezone_set($timezone);
}
//replace special parameters
foreach ($todo as $placeholder => $parameter) {
$output = str_replace('!LOCALIZED'.$placeholder, strftime('%'.$parameter, $dateTime->getTimestamp()), $output);
}
unset($parameter);
if (isset($currentLocale)) {
setlocale(LC_TIME, $currentLocale);
}
if (isset($currentTimezone)) {
date_default_timezone_set($currentTimezone);
}
return $output;
}
}
```
|
9,480,338 |
I have taken 2 text boxes and 1 text area
User will be to search the content through search box
and provides by which word it should be replaced.
Scenerio 1 :
I want to replace "Good" with word "bad"
But this code does not replace the text area content.
It rather appends with the new replaced string
what's the solution ??
```
<body>
<form id="form1" name="form1" method="post" action="">
<p>
<label for="search">Search :</label>
<input type="text" name="search" id="search" />
</p>
<p>
<label for="replace">Replace</label>
<input type="text" name="replace" id="replace" />
</p>
<p><Br />
<input type="submit" name="submit" id="submit" value="Submit" />
<label for="textarea"></label>
</p>
<p><br />
<textarea name="textarea" id="textarea" cols="45" rows="5" >
"Good morning how are you today are you feeling Good.";
<?php
if(isset($_POST["submit"]))
{
$search = $_POST["search"];
$replace = $_POST["replace"];
$textarea = $_POST["textarea"];
$newtext = str_replace($search,$replace,$textarea);
echo $newtext;
}
?>
</textarea>
</p>
</form>
</body>
</html>
```
|
2012/02/28
|
['https://Stackoverflow.com/questions/9480338', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1361058/']
|
I didn't want to install a whole extensions just for this stuff and need to do a few things automatically: It's also possible to write a helperclass (or expand an existing helper) in Bundle/Twig/Extensions for example like this:
```
public function foo(\Datetime $datetime, $lang = 'de_DE', $pattern = 'd. MMMM Y')
{
$formatter = new \IntlDateFormatter($lang, \IntlDateFormatter::LONG, \IntlDateFormatter::LONG);
$formatter->setPattern($pattern);
return $formatter->format($datetime);
}
```
twig-Template:
```
{{ yourDateTimeObject|foo('en_US', 'd. MMMM Y') }}
```
The result is "12. February 2014" (or "12. Februar 2014" in de\_DE and so on)
|
I really only wanted the day & month names to be translated according to the locale and wrote this twig extension. It accepts the normal `DateTime->format()` parameters and converts day & months names using `strftime()` if needed.
```
<?php
namespace AppBundle\Twig\Extension;
use Twig_Extension;
use Twig_SimpleFilter;
use DateTimeZone;
use DateTime;
class LocalizedDateExtension extends Twig_Extension
{
protected static $conversionMap = [
'D' => 'a',
'l' => 'A',
'M' => 'b',
'F' => 'B',
];
public function getFilters()
{
return [
new Twig_SimpleFilter('localizeddate', [$this, 'localizeDate']),
];
}
protected static function createLocalizableTodo(&$formatString)
{
$newFormatString = '';
$todo = [];
$formatLength = mb_strlen($formatString);
for ($i = 0; $i < $formatLength; $i++) {
$char = $formatString[$i];
if ('\'' === $char) {
$newFormatString = $formatString[++$i]; //advance and add new character
}
if (array_key_exists($char, static::$conversionMap)) {
$newFormatString.= '\!\L\O\C\A\L\I\Z\E\D\\'; //prefix char
$todo[$char] = static::$conversionMap[$char];
}
$newFormatString.= $char;
}
$formatString = $newFormatString;
return $todo;
}
public function localizeDate(DateTime $dateTime, $format, $timezone = null, $locale = null)
{
if (null !== $timezone && $dateTime->getTimezone()->getName() !== $timezone) {
$dateTime = clone $dateTime;
$dateTime->setTimezone(new DateTimeZone($timezone));
}
$todo = static::createLocalizableTodo($format);
$output = $dateTime->format($format);
//no localizeable parameters?
if (0 === count($todo)) {
return $output;
}
if ($locale !== null) {
$currentLocale = setlocale(LC_TIME, '0');
setlocale(LC_TIME, $locale);
}
if ($timezone !== null) {
$currentTimezone = date_default_timezone_get();
date_default_timezone_set($timezone);
}
//replace special parameters
foreach ($todo as $placeholder => $parameter) {
$output = str_replace('!LOCALIZED'.$placeholder, strftime('%'.$parameter, $dateTime->getTimestamp()), $output);
}
unset($parameter);
if (isset($currentLocale)) {
setlocale(LC_TIME, $currentLocale);
}
if (isset($currentTimezone)) {
date_default_timezone_set($currentTimezone);
}
return $output;
}
}
```
|
59,814,742 |
I'm trying to create an alias to help debug my docker containers.
I discovered bash [accepts a `--init-file`](https://serverfault.com/a/586272/28684) option which ought to let us run some commands before passing over to interactive mode.
So I thought I could do
```
docker-bash() {
docker run --rm -it "$1" bash --init-file <(echo "ls; pwd")
}
```
But those commands don't appear to be running:
```
% docker-bash c7460dfcab50
root@9c6f64a9db8c:/#
```
Is it an escaping issue or.. what's going on?
```
bash --init-file <(echo "ls; pwd")
```
Alone in a terminal on my host machine works as expected (runs the command starts a new bash instance).
|
2020/01/19
|
['https://Stackoverflow.com/questions/59814742', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/65387/']
|
In points:
* The `<(...)` is a bash extension [process subtitution](https://www.gnu.org/software/bash/manual/html_node/Process-Substitution.html).
* From the manual above: `Process substitution is supported on systems that support named pipes (FIFOs) or the /dev/fd method of naming open files.`.
* The process substitution works like this:
+ bash creates a fifo in `/tmp` or creates a new file descriptor in `/dev/fd`.
+ The filename, either the `/tmp/.something` or `/dev/fd/<number>` is substituted for `<(...)` when command is executed.
+ So for example `echo <(echo 1)` outputs `/dev/fd/63`.
* Docker works by creating a new environment that is separated from the host. That means that:
+ Processes inside docker do not inherit file descriptors from the host process:
- So `/dev/fd/*` files are not inherited.
+ Processes inside docker are accessing isolated filesystem tree.
- So processes can't access `/tmp/*` files from the host.
* So summarizing `docker run -ti --rm alpine cat <(echo 1)` will not work, because the filename substituted by `<(...)` is not available from docker environment.
An easy workaround would be to just:
```
docker run -ti --rm alpine sh -c 'ls; pwd; exec sh'
```
Or use a temporary file:
```
echo "ls; pwd" > /tmp/tempfile
docker run -v /tmp/tempfile:/tmp/tempfile bash bash --init-file /tmp/tempfile
```
|
For my use-case I wanted to set an `alias` which won't persist if we re-exec the shell. However, aliases can be written to `~/.bashrc` which will be reloaded on the subsequent exec. Ergo,
```
docker-bash() {
docker run --rm -it "$1" bash -c $'set -o xtrace; echo "alias ll=\'ls -lAhtrF --color=always\'" >> ~/.bashrc; exec "$0"'
}
```
Works. `--rm` should clean up any files we create anyway if I understand properly how docker works.
Or perhaps this is a nicer way to write it:
```
docker-bash() {
read -r -d '' BASHRC << EOM
alias ll='ls -lAhtrF --color=always'
EOM
docker run --rm -it "$1" bash -c "echo \"$BASHRC\" >> ~/.bashrc; exec \"\$0\""
}
```
|
12,585,447 |
The npm documentation says this:
>
> * If you’re installing something that you want to use in your program, using
> require('whatever'), then install it locally, at the root of your project.
> * If you’re installing something that you want to use in your shell, on the command line or
> something, install it globally, so that its binaries end up in your PATH environment variable.
>
>
>
I am currently writing --- or, at least, trying to write --- a genuine command line program in node that's intended to be used from the shell. Therefore, according to the above, my dependencies should be installed as global modules.
How do I actually *use* a global module installed with npm in node? Calling `require()` doesn't work, of course, because the npm global module directory (`/usr/local/lib/node_modules`) isn't on the path by default. I can make it working by explicitly adding it to the path at the top of my program, but that's a really lousy solution because it's not portable --- it requires knowledge of where the npm's global module directory is on any given system.
Just to make life even more aggravating, I have some global modules installed via dpkg. These have been put in `/usr/lib/nodejs`, and they just work. This confuses me, because if global modules aren't supposed to be used for ordinary applications I would expect neither to be on the path; or else I would expect them both to be on the path and requiring global modules to just work everywhere. Having one but not the other seems very odd. What's going on here?
**Update:** I should point out that this program is just a script, with `#!/usr/bin/env nodejs` at the top; it's not a formal node module, which is way overkill for something quite this trivial. As the Debian modules are all requireable from such a script, it seems sensible to me that npm's global modules should be requireable too, but I have a feeling that this is a Debianism...
|
2012/09/25
|
['https://Stackoverflow.com/questions/12585447', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/404568/']
|
>
> Therefore, according to the above, my dependencies should be installed as global modules.
>
>
>
Not quite.
It meant that *your module* could be installed as a global so its [binaries](https://npmjs.org/doc/json.html#bin) would be available from the shell:
```sh
npm install -g your-module
your-module-binary --option etc.
```
Its dependencies, on the other hand, should be installed following the 1st point, residing in a `node_modules` directory within your project (generally specified in a [`package.json`](https://npmjs.org/doc/json.html#dependencies) so `npm` can manage them).
But, global modules aren't (normally) available for `require`. They don't follow [Loading from `node_modules` folders](http://nodejs.org/api/modules.html#modules_loading_from_node_modules_folders), which `npm` follows for local modules, and their path isn't typically listed in the `NODE_PATH` variable for [Loading from global folders](http://nodejs.org/api/modules.html#modules_loading_from_the_global_folders).
|
So the instructions you have pertain to npm modules, but you are doing local development. Here are some guidelines.
In terms of your source code, you only need 2 types of `require` statements
```
var dep = require('somedep')
```
Use this for any core modules (like `fs`) and third party modules your library needs that you are including via npm (listing them in your package.json as dependencies). Here you specify an unqualified package name and node finds the module according to its search algorithm.
```
var mymod = require('./lib/mymod')
```
Use this for requiring the other modules in your project itself by path relative to the current javascript file.
That's all you have to do to handle your javascript dependencies.
OK, now how do you install your dependencies?
For local development (within your project's source tree), just cd into the project directory and run `npm install`, which will read your `package.json` file and install the modules you need in the `node_modules` subdirectory and all will be well for local development.
If you were to actually publish this as an npm module, other users (and you can be both the developer and one of the "other users"), could install it with `npm -g` if they wanted to access your project's binary utilities on their `PATH` which would need to include `/usr/lib/nodejs/lib/node_modules`, but in that case, the `npm -g` will handle installing both your code and your project's dependencies all at once.
Here's where you are getting confused.
>
> Therefore, according to the above, my dependencies should be installed as global modules.
>
>
>
You don't need to explicitly install dependencies as globals, only the top-level module you are interested in, which in this case is your project itself. npm will handle the dependencies automatically, which is its primary purpose in life. Your project's dependencies won't be installed globally per say, but rather in the `node_modules` subdirectory of your project, which WILL be installed globally.
Here's the directories and what lives there:
* `~/yourproject`: local development for your source code
* `~/yourproject/node_modules`: npm modules used by your project during development. Created/populated by running `npm install` in `~/yourproject`
* `/usr/lib/nodejs/lib/node_modules`: npm modules (which could eventually include yourproject if you publish it to the npm registry) that are installed globally
* `/usr/lib/nodejs/lib/node_modules/yourproject/node_modules`: your project's dependencies will get installed here when you do `npm install -g yourproject`
You may also find [my blog post on managing interpreters and the PATH](http://peterlyons.com/problog/2012/09/managing-per-project-interpreters-and-the-path) relevant.
|
12,585,447 |
The npm documentation says this:
>
> * If you’re installing something that you want to use in your program, using
> require('whatever'), then install it locally, at the root of your project.
> * If you’re installing something that you want to use in your shell, on the command line or
> something, install it globally, so that its binaries end up in your PATH environment variable.
>
>
>
I am currently writing --- or, at least, trying to write --- a genuine command line program in node that's intended to be used from the shell. Therefore, according to the above, my dependencies should be installed as global modules.
How do I actually *use* a global module installed with npm in node? Calling `require()` doesn't work, of course, because the npm global module directory (`/usr/local/lib/node_modules`) isn't on the path by default. I can make it working by explicitly adding it to the path at the top of my program, but that's a really lousy solution because it's not portable --- it requires knowledge of where the npm's global module directory is on any given system.
Just to make life even more aggravating, I have some global modules installed via dpkg. These have been put in `/usr/lib/nodejs`, and they just work. This confuses me, because if global modules aren't supposed to be used for ordinary applications I would expect neither to be on the path; or else I would expect them both to be on the path and requiring global modules to just work everywhere. Having one but not the other seems very odd. What's going on here?
**Update:** I should point out that this program is just a script, with `#!/usr/bin/env nodejs` at the top; it's not a formal node module, which is way overkill for something quite this trivial. As the Debian modules are all requireable from such a script, it seems sensible to me that npm's global modules should be requireable too, but I have a feeling that this is a Debianism...
|
2012/09/25
|
['https://Stackoverflow.com/questions/12585447', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/404568/']
|
So the instructions you have pertain to npm modules, but you are doing local development. Here are some guidelines.
In terms of your source code, you only need 2 types of `require` statements
```
var dep = require('somedep')
```
Use this for any core modules (like `fs`) and third party modules your library needs that you are including via npm (listing them in your package.json as dependencies). Here you specify an unqualified package name and node finds the module according to its search algorithm.
```
var mymod = require('./lib/mymod')
```
Use this for requiring the other modules in your project itself by path relative to the current javascript file.
That's all you have to do to handle your javascript dependencies.
OK, now how do you install your dependencies?
For local development (within your project's source tree), just cd into the project directory and run `npm install`, which will read your `package.json` file and install the modules you need in the `node_modules` subdirectory and all will be well for local development.
If you were to actually publish this as an npm module, other users (and you can be both the developer and one of the "other users"), could install it with `npm -g` if they wanted to access your project's binary utilities on their `PATH` which would need to include `/usr/lib/nodejs/lib/node_modules`, but in that case, the `npm -g` will handle installing both your code and your project's dependencies all at once.
Here's where you are getting confused.
>
> Therefore, according to the above, my dependencies should be installed as global modules.
>
>
>
You don't need to explicitly install dependencies as globals, only the top-level module you are interested in, which in this case is your project itself. npm will handle the dependencies automatically, which is its primary purpose in life. Your project's dependencies won't be installed globally per say, but rather in the `node_modules` subdirectory of your project, which WILL be installed globally.
Here's the directories and what lives there:
* `~/yourproject`: local development for your source code
* `~/yourproject/node_modules`: npm modules used by your project during development. Created/populated by running `npm install` in `~/yourproject`
* `/usr/lib/nodejs/lib/node_modules`: npm modules (which could eventually include yourproject if you publish it to the npm registry) that are installed globally
* `/usr/lib/nodejs/lib/node_modules/yourproject/node_modules`: your project's dependencies will get installed here when you do `npm install -g yourproject`
You may also find [my blog post on managing interpreters and the PATH](http://peterlyons.com/problog/2012/09/managing-per-project-interpreters-and-the-path) relevant.
|
Additionally, Node.js will search in the following list of GLOBAL\_FOLDERS:
1: $HOME/.node\_modules
2: $HOME/.node\_libraries
3: $PREFIX/lib/node
|
12,585,447 |
The npm documentation says this:
>
> * If you’re installing something that you want to use in your program, using
> require('whatever'), then install it locally, at the root of your project.
> * If you’re installing something that you want to use in your shell, on the command line or
> something, install it globally, so that its binaries end up in your PATH environment variable.
>
>
>
I am currently writing --- or, at least, trying to write --- a genuine command line program in node that's intended to be used from the shell. Therefore, according to the above, my dependencies should be installed as global modules.
How do I actually *use* a global module installed with npm in node? Calling `require()` doesn't work, of course, because the npm global module directory (`/usr/local/lib/node_modules`) isn't on the path by default. I can make it working by explicitly adding it to the path at the top of my program, but that's a really lousy solution because it's not portable --- it requires knowledge of where the npm's global module directory is on any given system.
Just to make life even more aggravating, I have some global modules installed via dpkg. These have been put in `/usr/lib/nodejs`, and they just work. This confuses me, because if global modules aren't supposed to be used for ordinary applications I would expect neither to be on the path; or else I would expect them both to be on the path and requiring global modules to just work everywhere. Having one but not the other seems very odd. What's going on here?
**Update:** I should point out that this program is just a script, with `#!/usr/bin/env nodejs` at the top; it's not a formal node module, which is way overkill for something quite this trivial. As the Debian modules are all requireable from such a script, it seems sensible to me that npm's global modules should be requireable too, but I have a feeling that this is a Debianism...
|
2012/09/25
|
['https://Stackoverflow.com/questions/12585447', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/404568/']
|
>
> Therefore, according to the above, my dependencies should be installed as global modules.
>
>
>
Not quite.
It meant that *your module* could be installed as a global so its [binaries](https://npmjs.org/doc/json.html#bin) would be available from the shell:
```sh
npm install -g your-module
your-module-binary --option etc.
```
Its dependencies, on the other hand, should be installed following the 1st point, residing in a `node_modules` directory within your project (generally specified in a [`package.json`](https://npmjs.org/doc/json.html#dependencies) so `npm` can manage them).
But, global modules aren't (normally) available for `require`. They don't follow [Loading from `node_modules` folders](http://nodejs.org/api/modules.html#modules_loading_from_node_modules_folders), which `npm` follows for local modules, and their path isn't typically listed in the `NODE_PATH` variable for [Loading from global folders](http://nodejs.org/api/modules.html#modules_loading_from_the_global_folders).
|
Additionally, Node.js will search in the following list of GLOBAL\_FOLDERS:
1: $HOME/.node\_modules
2: $HOME/.node\_libraries
3: $PREFIX/lib/node
|
54,962,657 |
I'm using an header bar from the `clarity.design` examples, I tinkered with it trying to make the search input occupy 100% of the center of the header bar, but I'm unable to do it.
The code:
```html
<clr-header class="header-6">
<div class="branding">
<a [routerLink]="['/']" routerLinkActive="router-link-active" class="nav-link">
<span class="title">Project Clarity</span>
</a>
</div>
<form class="search" (ngSubmit)="onSearchSubmit(f)" #f="ngForm">
<label for="search_input"></label>
<input id="search_input" name="search_input" type="text" placeholder=" Search for keywords or paste link..." ngModel required>
</form>
<div class="header-actions">
<div class="header-nav" [clr-nav-level]="1">
<a class="nav-link nav-text">
My menu
</a>
</div>
<clr-dropdown>
<button class="nav-icon" clrDropdownTrigger>
<clr-icon shape="user"></clr-icon>
<clr-icon shape="caret down"></clr-icon>
</button>
<clr-dropdown-menu *clrIfOpen clrPosition="bottom-right">
<a clrDropdownItem>Preferences</a>
<a clrDropdownItem>Log out</a>
</clr-dropdown-menu>
</clr-dropdown>
</div>
</clr-header>
```
This is how it looks like, I want the header to use all the remaining width.
[](https://i.stack.imgur.com/aXW1t.png)
Thanks.
|
2019/03/02
|
['https://Stackoverflow.com/questions/54962657', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4962126/']
|
Your code is okay. You could dismiss temporary results and chain method calls
```
var numbers = new StringBuilder();
string[] coordinatesVal = coordinateTxt
.Trim()
.Split(new string[] { ",0" }, StringSplitOptions.None);
for (int i = 0; i < coordinatesVal.Length - 1; i++) {
numbers
.Append(coordinatesVal[i].Trim().Replace(',', ' '))
.Append(", ");
}
numbers.Length -= 2;
```
Note that the last statement assumes that there is at least one coordinate pair available. If the coordinates can be empty, you would have to enclose the loop and this last statement in `if (coordinatesVal.Length > 0 ) { ... }`. This is still more efficient than having an `if` inside the loop.
|
Your solution is fine. Maybe you could write it a bit more elegant like this:
```
string[] coordinatesVal = coordinateTxt.Trim().Split(new string[] { ",0" },
StringSplitOptions.RemoveEmptyEntries);
string result = string.Empty;
foreach (string line in coordinatesVal)
{
string[] numbers = line.Trim().Split(',');
result += numbers[0] + " " + numbers[1] + ", ";
}
result = result.Remove(result.Count()-2, 2);
```
Note the `StringSplitOptions.RemoveEmptyEntries` parameter of `Split` method so you don't have to deal with empty lines into *foreach* block.
|
54,962,657 |
I'm using an header bar from the `clarity.design` examples, I tinkered with it trying to make the search input occupy 100% of the center of the header bar, but I'm unable to do it.
The code:
```html
<clr-header class="header-6">
<div class="branding">
<a [routerLink]="['/']" routerLinkActive="router-link-active" class="nav-link">
<span class="title">Project Clarity</span>
</a>
</div>
<form class="search" (ngSubmit)="onSearchSubmit(f)" #f="ngForm">
<label for="search_input"></label>
<input id="search_input" name="search_input" type="text" placeholder=" Search for keywords or paste link..." ngModel required>
</form>
<div class="header-actions">
<div class="header-nav" [clr-nav-level]="1">
<a class="nav-link nav-text">
My menu
</a>
</div>
<clr-dropdown>
<button class="nav-icon" clrDropdownTrigger>
<clr-icon shape="user"></clr-icon>
<clr-icon shape="caret down"></clr-icon>
</button>
<clr-dropdown-menu *clrIfOpen clrPosition="bottom-right">
<a clrDropdownItem>Preferences</a>
<a clrDropdownItem>Log out</a>
</clr-dropdown-menu>
</clr-dropdown>
</div>
</clr-header>
```
This is how it looks like, I want the header to use all the remaining width.
[](https://i.stack.imgur.com/aXW1t.png)
Thanks.
|
2019/03/02
|
['https://Stackoverflow.com/questions/54962657', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4962126/']
|
Your code is okay. You could dismiss temporary results and chain method calls
```
var numbers = new StringBuilder();
string[] coordinatesVal = coordinateTxt
.Trim()
.Split(new string[] { ",0" }, StringSplitOptions.None);
for (int i = 0; i < coordinatesVal.Length - 1; i++) {
numbers
.Append(coordinatesVal[i].Trim().Replace(',', ' '))
.Append(", ");
}
numbers.Length -= 2;
```
Note that the last statement assumes that there is at least one coordinate pair available. If the coordinates can be empty, you would have to enclose the loop and this last statement in `if (coordinatesVal.Length > 0 ) { ... }`. This is still more efficient than having an `if` inside the loop.
|
Or you can do extremely short one-liner. Harder to debug, but in simple cases does the work.
```
string result =
string.Join(", ",
coordinateTxt.Trim().Split(new string[] { ",0" }, StringSplitOptions.RemoveEmptyEntries).
Select(i => i.Replace(",", " ")));
```
|
54,962,657 |
I'm using an header bar from the `clarity.design` examples, I tinkered with it trying to make the search input occupy 100% of the center of the header bar, but I'm unable to do it.
The code:
```html
<clr-header class="header-6">
<div class="branding">
<a [routerLink]="['/']" routerLinkActive="router-link-active" class="nav-link">
<span class="title">Project Clarity</span>
</a>
</div>
<form class="search" (ngSubmit)="onSearchSubmit(f)" #f="ngForm">
<label for="search_input"></label>
<input id="search_input" name="search_input" type="text" placeholder=" Search for keywords or paste link..." ngModel required>
</form>
<div class="header-actions">
<div class="header-nav" [clr-nav-level]="1">
<a class="nav-link nav-text">
My menu
</a>
</div>
<clr-dropdown>
<button class="nav-icon" clrDropdownTrigger>
<clr-icon shape="user"></clr-icon>
<clr-icon shape="caret down"></clr-icon>
</button>
<clr-dropdown-menu *clrIfOpen clrPosition="bottom-right">
<a clrDropdownItem>Preferences</a>
<a clrDropdownItem>Log out</a>
</clr-dropdown-menu>
</clr-dropdown>
</div>
</clr-header>
```
This is how it looks like, I want the header to use all the remaining width.
[](https://i.stack.imgur.com/aXW1t.png)
Thanks.
|
2019/03/02
|
['https://Stackoverflow.com/questions/54962657', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4962126/']
|
Your code is okay. You could dismiss temporary results and chain method calls
```
var numbers = new StringBuilder();
string[] coordinatesVal = coordinateTxt
.Trim()
.Split(new string[] { ",0" }, StringSplitOptions.None);
for (int i = 0; i < coordinatesVal.Length - 1; i++) {
numbers
.Append(coordinatesVal[i].Trim().Replace(',', ' '))
.Append(", ");
}
numbers.Length -= 2;
```
Note that the last statement assumes that there is at least one coordinate pair available. If the coordinates can be empty, you would have to enclose the loop and this last statement in `if (coordinatesVal.Length > 0 ) { ... }`. This is still more efficient than having an `if` inside the loop.
|
heres another way without *defining your own loops* and replace methods, or using LINQ.
```
string coordinateTxt = @" -82.9494547,36.2913021,0
-83.0784938,36.2347521,0
-82.9537782,36.079235,0";
string[] coordinatesVal = coordinateTxt.Replace(",", "*").Trim().Split(new string[] { "*0", Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
string result = string.Join(",", coordinatesVal).Replace("*", " ");
Console.WriteLine(result);
```
or even
```
string coordinateTxt = @" -82.9494540,36.2913021,0
-83.0784938,36.2347521,0
-82.9537782,36.079235,0";
string result = coordinateTxt.Replace(Environment.NewLine, "").Replace($",", " ").Replace(" 0", ", ").Trim(new char[]{ ',',' ' });
Console.WriteLine(result);
```
|
54,962,657 |
I'm using an header bar from the `clarity.design` examples, I tinkered with it trying to make the search input occupy 100% of the center of the header bar, but I'm unable to do it.
The code:
```html
<clr-header class="header-6">
<div class="branding">
<a [routerLink]="['/']" routerLinkActive="router-link-active" class="nav-link">
<span class="title">Project Clarity</span>
</a>
</div>
<form class="search" (ngSubmit)="onSearchSubmit(f)" #f="ngForm">
<label for="search_input"></label>
<input id="search_input" name="search_input" type="text" placeholder=" Search for keywords or paste link..." ngModel required>
</form>
<div class="header-actions">
<div class="header-nav" [clr-nav-level]="1">
<a class="nav-link nav-text">
My menu
</a>
</div>
<clr-dropdown>
<button class="nav-icon" clrDropdownTrigger>
<clr-icon shape="user"></clr-icon>
<clr-icon shape="caret down"></clr-icon>
</button>
<clr-dropdown-menu *clrIfOpen clrPosition="bottom-right">
<a clrDropdownItem>Preferences</a>
<a clrDropdownItem>Log out</a>
</clr-dropdown-menu>
</clr-dropdown>
</div>
</clr-header>
```
This is how it looks like, I want the header to use all the remaining width.
[](https://i.stack.imgur.com/aXW1t.png)
Thanks.
|
2019/03/02
|
['https://Stackoverflow.com/questions/54962657', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4962126/']
|
Your code is okay. You could dismiss temporary results and chain method calls
```
var numbers = new StringBuilder();
string[] coordinatesVal = coordinateTxt
.Trim()
.Split(new string[] { ",0" }, StringSplitOptions.None);
for (int i = 0; i < coordinatesVal.Length - 1; i++) {
numbers
.Append(coordinatesVal[i].Trim().Replace(',', ' '))
.Append(", ");
}
numbers.Length -= 2;
```
Note that the last statement assumes that there is at least one coordinate pair available. If the coordinates can be empty, you would have to enclose the loop and this last statement in `if (coordinatesVal.Length > 0 ) { ... }`. This is still more efficient than having an `if` inside the loop.
|
You ask about efficiency, but you don't specify whether you mean code efficiency (execution speed) or programmer efficiency (how much time you have to spend on it).
One key part of professional programming is to judge which one of these is more important in any given situation.
The other answers do a good job of covering programmer efficiency, so I'm taking a stab at code efficiency. I'm doing this at home for fun, but for professional work I would need a good reason before putting in the effort to even spend time comparing the speeds of the methods given in the other answers, let alone try to improve on them.
Having said that, waiting around for the program to finish doing the conversion of millions of coordinate pairs would give me such a reason.
One of the speed pitfalls of C# string handling is the way `String.Replace()` and `String.Trim()` return a whole new copy of the string. This involves allocating memory, copying the characters, and eventually cleaning up the garbage generated. Do that a few million times, and it starts to add up. With that in mind, I attempted to avoid as many allocations and copies as possible.
```
enum CurrentField
{
FirstNum,
SecondNum,
UnwantedZero
};
static string ConvertStateMachine(string input)
{
// Pre-allocate enough space in the string builder.
var numbers = new StringBuilder(input.Length);
var state = CurrentField.FirstNum;
int i = 0;
while (i < input.Length)
{
char c = input[i++];
switch (state)
{
// Copying the first number to the output, next will be another number
case CurrentField.FirstNum:
if (c == ',')
{
// Separate the two numbers by space instead of comma, then move on
numbers.Append(' ');
state = CurrentField.SecondNum;
}
else if (!(c == ' ' || c == '\n'))
{
// Ignore whitespace, output anything else
numbers.Append(c);
}
break;
// Copying the second number to the output, next will be the ,0\n that we don't need
case CurrentField.SecondNum:
if (c == ',')
{
numbers.Append(", ");
state = CurrentField.UnwantedZero;
}
else if (!(c == ' ' || c == '\n'))
{
// Ignore whitespace, output anything else
numbers.Append(c);
}
break;
case CurrentField.UnwantedZero:
// Output nothing, just track when the line is finished and we start all over again.
if (c == '\n')
{
state = CurrentField.FirstNum;
}
break;
}
}
return numbers.ToString();
}
```
This uses a state machine to treat incoming characters differently depending on whether they are part of the first number, second number, or the rest of the line, and output characters accordingly. Each character is only copied once into the output, then I believe once more when the output is converted to a string at the end. This second conversion could probably be avoided by using a `char[]` for the output.
The bottleneck in this code seems to be the number of calls to `StringBuilder.Append()`. If more speed were required, I would first attempt to keep track of how many characters were to be copied directly into the output, then use `.Append(string value, int startIndex, int count)` to send an entire number across in one call.
I put a few example solutions into a test harness, and ran them on a string containing 300,000 coordinate-pair lines, averaged over 50 runs. The results on my PC were:
```
String Split, Replace each line (see Olivier's answer, though I pre-allocated the space in the StringBuilder):
6542 ms / 13493147 ticks, 130.84ms / 269862.9 ticks per conversion
Replace & Trim entire string (see Heriberto's second version):
3352 ms / 6914604 ticks, 67.04 ms / 138292.1 ticks per conversion
- Note: Original test was done with 900000 coord pairs, but this entire-string version suffered an out of memory exception so I had to rein it in a bit.
Split and Join (see Łukasz's answer):
8780 ms / 18110672 ticks, 175.6 ms / 362213.4 ticks per conversion
Character state machine (see above):
1685 ms / 3475506 ticks, 33.7 ms / 69510.12 ticks per conversion
```
So, the question of which version is most efficient comes down to: what are your requirements?
|
54,962,657 |
I'm using an header bar from the `clarity.design` examples, I tinkered with it trying to make the search input occupy 100% of the center of the header bar, but I'm unable to do it.
The code:
```html
<clr-header class="header-6">
<div class="branding">
<a [routerLink]="['/']" routerLinkActive="router-link-active" class="nav-link">
<span class="title">Project Clarity</span>
</a>
</div>
<form class="search" (ngSubmit)="onSearchSubmit(f)" #f="ngForm">
<label for="search_input"></label>
<input id="search_input" name="search_input" type="text" placeholder=" Search for keywords or paste link..." ngModel required>
</form>
<div class="header-actions">
<div class="header-nav" [clr-nav-level]="1">
<a class="nav-link nav-text">
My menu
</a>
</div>
<clr-dropdown>
<button class="nav-icon" clrDropdownTrigger>
<clr-icon shape="user"></clr-icon>
<clr-icon shape="caret down"></clr-icon>
</button>
<clr-dropdown-menu *clrIfOpen clrPosition="bottom-right">
<a clrDropdownItem>Preferences</a>
<a clrDropdownItem>Log out</a>
</clr-dropdown-menu>
</clr-dropdown>
</div>
</clr-header>
```
This is how it looks like, I want the header to use all the remaining width.
[](https://i.stack.imgur.com/aXW1t.png)
Thanks.
|
2019/03/02
|
['https://Stackoverflow.com/questions/54962657', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4962126/']
|
You ask about efficiency, but you don't specify whether you mean code efficiency (execution speed) or programmer efficiency (how much time you have to spend on it).
One key part of professional programming is to judge which one of these is more important in any given situation.
The other answers do a good job of covering programmer efficiency, so I'm taking a stab at code efficiency. I'm doing this at home for fun, but for professional work I would need a good reason before putting in the effort to even spend time comparing the speeds of the methods given in the other answers, let alone try to improve on them.
Having said that, waiting around for the program to finish doing the conversion of millions of coordinate pairs would give me such a reason.
One of the speed pitfalls of C# string handling is the way `String.Replace()` and `String.Trim()` return a whole new copy of the string. This involves allocating memory, copying the characters, and eventually cleaning up the garbage generated. Do that a few million times, and it starts to add up. With that in mind, I attempted to avoid as many allocations and copies as possible.
```
enum CurrentField
{
FirstNum,
SecondNum,
UnwantedZero
};
static string ConvertStateMachine(string input)
{
// Pre-allocate enough space in the string builder.
var numbers = new StringBuilder(input.Length);
var state = CurrentField.FirstNum;
int i = 0;
while (i < input.Length)
{
char c = input[i++];
switch (state)
{
// Copying the first number to the output, next will be another number
case CurrentField.FirstNum:
if (c == ',')
{
// Separate the two numbers by space instead of comma, then move on
numbers.Append(' ');
state = CurrentField.SecondNum;
}
else if (!(c == ' ' || c == '\n'))
{
// Ignore whitespace, output anything else
numbers.Append(c);
}
break;
// Copying the second number to the output, next will be the ,0\n that we don't need
case CurrentField.SecondNum:
if (c == ',')
{
numbers.Append(", ");
state = CurrentField.UnwantedZero;
}
else if (!(c == ' ' || c == '\n'))
{
// Ignore whitespace, output anything else
numbers.Append(c);
}
break;
case CurrentField.UnwantedZero:
// Output nothing, just track when the line is finished and we start all over again.
if (c == '\n')
{
state = CurrentField.FirstNum;
}
break;
}
}
return numbers.ToString();
}
```
This uses a state machine to treat incoming characters differently depending on whether they are part of the first number, second number, or the rest of the line, and output characters accordingly. Each character is only copied once into the output, then I believe once more when the output is converted to a string at the end. This second conversion could probably be avoided by using a `char[]` for the output.
The bottleneck in this code seems to be the number of calls to `StringBuilder.Append()`. If more speed were required, I would first attempt to keep track of how many characters were to be copied directly into the output, then use `.Append(string value, int startIndex, int count)` to send an entire number across in one call.
I put a few example solutions into a test harness, and ran them on a string containing 300,000 coordinate-pair lines, averaged over 50 runs. The results on my PC were:
```
String Split, Replace each line (see Olivier's answer, though I pre-allocated the space in the StringBuilder):
6542 ms / 13493147 ticks, 130.84ms / 269862.9 ticks per conversion
Replace & Trim entire string (see Heriberto's second version):
3352 ms / 6914604 ticks, 67.04 ms / 138292.1 ticks per conversion
- Note: Original test was done with 900000 coord pairs, but this entire-string version suffered an out of memory exception so I had to rein it in a bit.
Split and Join (see Łukasz's answer):
8780 ms / 18110672 ticks, 175.6 ms / 362213.4 ticks per conversion
Character state machine (see above):
1685 ms / 3475506 ticks, 33.7 ms / 69510.12 ticks per conversion
```
So, the question of which version is most efficient comes down to: what are your requirements?
|
Your solution is fine. Maybe you could write it a bit more elegant like this:
```
string[] coordinatesVal = coordinateTxt.Trim().Split(new string[] { ",0" },
StringSplitOptions.RemoveEmptyEntries);
string result = string.Empty;
foreach (string line in coordinatesVal)
{
string[] numbers = line.Trim().Split(',');
result += numbers[0] + " " + numbers[1] + ", ";
}
result = result.Remove(result.Count()-2, 2);
```
Note the `StringSplitOptions.RemoveEmptyEntries` parameter of `Split` method so you don't have to deal with empty lines into *foreach* block.
|
54,962,657 |
I'm using an header bar from the `clarity.design` examples, I tinkered with it trying to make the search input occupy 100% of the center of the header bar, but I'm unable to do it.
The code:
```html
<clr-header class="header-6">
<div class="branding">
<a [routerLink]="['/']" routerLinkActive="router-link-active" class="nav-link">
<span class="title">Project Clarity</span>
</a>
</div>
<form class="search" (ngSubmit)="onSearchSubmit(f)" #f="ngForm">
<label for="search_input"></label>
<input id="search_input" name="search_input" type="text" placeholder=" Search for keywords or paste link..." ngModel required>
</form>
<div class="header-actions">
<div class="header-nav" [clr-nav-level]="1">
<a class="nav-link nav-text">
My menu
</a>
</div>
<clr-dropdown>
<button class="nav-icon" clrDropdownTrigger>
<clr-icon shape="user"></clr-icon>
<clr-icon shape="caret down"></clr-icon>
</button>
<clr-dropdown-menu *clrIfOpen clrPosition="bottom-right">
<a clrDropdownItem>Preferences</a>
<a clrDropdownItem>Log out</a>
</clr-dropdown-menu>
</clr-dropdown>
</div>
</clr-header>
```
This is how it looks like, I want the header to use all the remaining width.
[](https://i.stack.imgur.com/aXW1t.png)
Thanks.
|
2019/03/02
|
['https://Stackoverflow.com/questions/54962657', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4962126/']
|
You ask about efficiency, but you don't specify whether you mean code efficiency (execution speed) or programmer efficiency (how much time you have to spend on it).
One key part of professional programming is to judge which one of these is more important in any given situation.
The other answers do a good job of covering programmer efficiency, so I'm taking a stab at code efficiency. I'm doing this at home for fun, but for professional work I would need a good reason before putting in the effort to even spend time comparing the speeds of the methods given in the other answers, let alone try to improve on them.
Having said that, waiting around for the program to finish doing the conversion of millions of coordinate pairs would give me such a reason.
One of the speed pitfalls of C# string handling is the way `String.Replace()` and `String.Trim()` return a whole new copy of the string. This involves allocating memory, copying the characters, and eventually cleaning up the garbage generated. Do that a few million times, and it starts to add up. With that in mind, I attempted to avoid as many allocations and copies as possible.
```
enum CurrentField
{
FirstNum,
SecondNum,
UnwantedZero
};
static string ConvertStateMachine(string input)
{
// Pre-allocate enough space in the string builder.
var numbers = new StringBuilder(input.Length);
var state = CurrentField.FirstNum;
int i = 0;
while (i < input.Length)
{
char c = input[i++];
switch (state)
{
// Copying the first number to the output, next will be another number
case CurrentField.FirstNum:
if (c == ',')
{
// Separate the two numbers by space instead of comma, then move on
numbers.Append(' ');
state = CurrentField.SecondNum;
}
else if (!(c == ' ' || c == '\n'))
{
// Ignore whitespace, output anything else
numbers.Append(c);
}
break;
// Copying the second number to the output, next will be the ,0\n that we don't need
case CurrentField.SecondNum:
if (c == ',')
{
numbers.Append(", ");
state = CurrentField.UnwantedZero;
}
else if (!(c == ' ' || c == '\n'))
{
// Ignore whitespace, output anything else
numbers.Append(c);
}
break;
case CurrentField.UnwantedZero:
// Output nothing, just track when the line is finished and we start all over again.
if (c == '\n')
{
state = CurrentField.FirstNum;
}
break;
}
}
return numbers.ToString();
}
```
This uses a state machine to treat incoming characters differently depending on whether they are part of the first number, second number, or the rest of the line, and output characters accordingly. Each character is only copied once into the output, then I believe once more when the output is converted to a string at the end. This second conversion could probably be avoided by using a `char[]` for the output.
The bottleneck in this code seems to be the number of calls to `StringBuilder.Append()`. If more speed were required, I would first attempt to keep track of how many characters were to be copied directly into the output, then use `.Append(string value, int startIndex, int count)` to send an entire number across in one call.
I put a few example solutions into a test harness, and ran them on a string containing 300,000 coordinate-pair lines, averaged over 50 runs. The results on my PC were:
```
String Split, Replace each line (see Olivier's answer, though I pre-allocated the space in the StringBuilder):
6542 ms / 13493147 ticks, 130.84ms / 269862.9 ticks per conversion
Replace & Trim entire string (see Heriberto's second version):
3352 ms / 6914604 ticks, 67.04 ms / 138292.1 ticks per conversion
- Note: Original test was done with 900000 coord pairs, but this entire-string version suffered an out of memory exception so I had to rein it in a bit.
Split and Join (see Łukasz's answer):
8780 ms / 18110672 ticks, 175.6 ms / 362213.4 ticks per conversion
Character state machine (see above):
1685 ms / 3475506 ticks, 33.7 ms / 69510.12 ticks per conversion
```
So, the question of which version is most efficient comes down to: what are your requirements?
|
Or you can do extremely short one-liner. Harder to debug, but in simple cases does the work.
```
string result =
string.Join(", ",
coordinateTxt.Trim().Split(new string[] { ",0" }, StringSplitOptions.RemoveEmptyEntries).
Select(i => i.Replace(",", " ")));
```
|
54,962,657 |
I'm using an header bar from the `clarity.design` examples, I tinkered with it trying to make the search input occupy 100% of the center of the header bar, but I'm unable to do it.
The code:
```html
<clr-header class="header-6">
<div class="branding">
<a [routerLink]="['/']" routerLinkActive="router-link-active" class="nav-link">
<span class="title">Project Clarity</span>
</a>
</div>
<form class="search" (ngSubmit)="onSearchSubmit(f)" #f="ngForm">
<label for="search_input"></label>
<input id="search_input" name="search_input" type="text" placeholder=" Search for keywords or paste link..." ngModel required>
</form>
<div class="header-actions">
<div class="header-nav" [clr-nav-level]="1">
<a class="nav-link nav-text">
My menu
</a>
</div>
<clr-dropdown>
<button class="nav-icon" clrDropdownTrigger>
<clr-icon shape="user"></clr-icon>
<clr-icon shape="caret down"></clr-icon>
</button>
<clr-dropdown-menu *clrIfOpen clrPosition="bottom-right">
<a clrDropdownItem>Preferences</a>
<a clrDropdownItem>Log out</a>
</clr-dropdown-menu>
</clr-dropdown>
</div>
</clr-header>
```
This is how it looks like, I want the header to use all the remaining width.
[](https://i.stack.imgur.com/aXW1t.png)
Thanks.
|
2019/03/02
|
['https://Stackoverflow.com/questions/54962657', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4962126/']
|
You ask about efficiency, but you don't specify whether you mean code efficiency (execution speed) or programmer efficiency (how much time you have to spend on it).
One key part of professional programming is to judge which one of these is more important in any given situation.
The other answers do a good job of covering programmer efficiency, so I'm taking a stab at code efficiency. I'm doing this at home for fun, but for professional work I would need a good reason before putting in the effort to even spend time comparing the speeds of the methods given in the other answers, let alone try to improve on them.
Having said that, waiting around for the program to finish doing the conversion of millions of coordinate pairs would give me such a reason.
One of the speed pitfalls of C# string handling is the way `String.Replace()` and `String.Trim()` return a whole new copy of the string. This involves allocating memory, copying the characters, and eventually cleaning up the garbage generated. Do that a few million times, and it starts to add up. With that in mind, I attempted to avoid as many allocations and copies as possible.
```
enum CurrentField
{
FirstNum,
SecondNum,
UnwantedZero
};
static string ConvertStateMachine(string input)
{
// Pre-allocate enough space in the string builder.
var numbers = new StringBuilder(input.Length);
var state = CurrentField.FirstNum;
int i = 0;
while (i < input.Length)
{
char c = input[i++];
switch (state)
{
// Copying the first number to the output, next will be another number
case CurrentField.FirstNum:
if (c == ',')
{
// Separate the two numbers by space instead of comma, then move on
numbers.Append(' ');
state = CurrentField.SecondNum;
}
else if (!(c == ' ' || c == '\n'))
{
// Ignore whitespace, output anything else
numbers.Append(c);
}
break;
// Copying the second number to the output, next will be the ,0\n that we don't need
case CurrentField.SecondNum:
if (c == ',')
{
numbers.Append(", ");
state = CurrentField.UnwantedZero;
}
else if (!(c == ' ' || c == '\n'))
{
// Ignore whitespace, output anything else
numbers.Append(c);
}
break;
case CurrentField.UnwantedZero:
// Output nothing, just track when the line is finished and we start all over again.
if (c == '\n')
{
state = CurrentField.FirstNum;
}
break;
}
}
return numbers.ToString();
}
```
This uses a state machine to treat incoming characters differently depending on whether they are part of the first number, second number, or the rest of the line, and output characters accordingly. Each character is only copied once into the output, then I believe once more when the output is converted to a string at the end. This second conversion could probably be avoided by using a `char[]` for the output.
The bottleneck in this code seems to be the number of calls to `StringBuilder.Append()`. If more speed were required, I would first attempt to keep track of how many characters were to be copied directly into the output, then use `.Append(string value, int startIndex, int count)` to send an entire number across in one call.
I put a few example solutions into a test harness, and ran them on a string containing 300,000 coordinate-pair lines, averaged over 50 runs. The results on my PC were:
```
String Split, Replace each line (see Olivier's answer, though I pre-allocated the space in the StringBuilder):
6542 ms / 13493147 ticks, 130.84ms / 269862.9 ticks per conversion
Replace & Trim entire string (see Heriberto's second version):
3352 ms / 6914604 ticks, 67.04 ms / 138292.1 ticks per conversion
- Note: Original test was done with 900000 coord pairs, but this entire-string version suffered an out of memory exception so I had to rein it in a bit.
Split and Join (see Łukasz's answer):
8780 ms / 18110672 ticks, 175.6 ms / 362213.4 ticks per conversion
Character state machine (see above):
1685 ms / 3475506 ticks, 33.7 ms / 69510.12 ticks per conversion
```
So, the question of which version is most efficient comes down to: what are your requirements?
|
heres another way without *defining your own loops* and replace methods, or using LINQ.
```
string coordinateTxt = @" -82.9494547,36.2913021,0
-83.0784938,36.2347521,0
-82.9537782,36.079235,0";
string[] coordinatesVal = coordinateTxt.Replace(",", "*").Trim().Split(new string[] { "*0", Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
string result = string.Join(",", coordinatesVal).Replace("*", " ");
Console.WriteLine(result);
```
or even
```
string coordinateTxt = @" -82.9494540,36.2913021,0
-83.0784938,36.2347521,0
-82.9537782,36.079235,0";
string result = coordinateTxt.Replace(Environment.NewLine, "").Replace($",", " ").Replace(" 0", ", ").Trim(new char[]{ ',',' ' });
Console.WriteLine(result);
```
|
46,467,481 |
I have tensorflow program that work with TFRecord and i want to read the data with tf.contrib.data.TFRecordDataset but when i try to parse the example i get an exception: "TypeError: Failed to convert object of type to Tensor"
When trying with only
The code is:
```
def _parse_function(example_proto):
features = {"var_len_feature": tf.VarLenFeature(tf.float32),
"FixedLenFeature": tf.FixedLenFeature([10], tf.int64),
"label": tf.FixedLenFeature((), tf.int32default_value=0)}
parsed_features = tf.parse_single_example(example_proto, features)
return parsed_features["image"], parsed_features["label"]
filenames = ["/var/data/file1.tfrecord", "/var/data/file2.tfrecord"]
dataset = tf.contrib.data.TFRecordDataset(filenames)
dataset = dataset.map(_parse_function)
```
|
2017/09/28
|
['https://Stackoverflow.com/questions/46467481', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1211587/']
|
TensorFlow added support for this in v1.5
<https://github.com/tensorflow/tensorflow/releases/tag/v1.5.0>
"tf.data now supports tf.SparseTensor components in dataset elements."
|
The Tutorial in the Tensor Flow programming [guide](https://www.tensorflow.org/programmers_guide/datasets#parsing_tfexample_protocol_buffer_messages) have a different indenting.
```
# Transforms a scalar string `example_proto` into a pair of a scalar string and
# a scalar integer, representing an image and its label, respectively.
def _parse_function(example_proto):
features = {"image": tf.FixedLenFeature((), tf.string, default_value=""),
"label": tf.FixedLenFeature((), tf.int32, default_value=0)}
parsed_features = tf.parse_single_example(example_proto, features)
return parsed_features["image"], parsed_features["label"]
# Creates a dataset that reads all of the examples from two files, and extracts
# the image and label features.
filenames = ["/var/data/file1.tfrecord", "/var/data/file2.tfrecord"]
dataset = tf.contrib.data.TFRecordDataset(filenames)
dataset = dataset.map(_parse_function)
```
The wrong indenting can result in a TypeError, processing an unwanted control flow by the pyton interpreter.
|
46,467,481 |
I have tensorflow program that work with TFRecord and i want to read the data with tf.contrib.data.TFRecordDataset but when i try to parse the example i get an exception: "TypeError: Failed to convert object of type to Tensor"
When trying with only
The code is:
```
def _parse_function(example_proto):
features = {"var_len_feature": tf.VarLenFeature(tf.float32),
"FixedLenFeature": tf.FixedLenFeature([10], tf.int64),
"label": tf.FixedLenFeature((), tf.int32default_value=0)}
parsed_features = tf.parse_single_example(example_proto, features)
return parsed_features["image"], parsed_features["label"]
filenames = ["/var/data/file1.tfrecord", "/var/data/file2.tfrecord"]
dataset = tf.contrib.data.TFRecordDataset(filenames)
dataset = dataset.map(_parse_function)
```
|
2017/09/28
|
['https://Stackoverflow.com/questions/46467481', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1211587/']
|
TensorFlow added support for this in v1.5
<https://github.com/tensorflow/tensorflow/releases/tag/v1.5.0>
"tf.data now supports tf.SparseTensor components in dataset elements."
|
tf.VarLenFeature creates SparseTensor. And most of the times the SparseTensors are associated with the mini batch. Can you try it like below?
dataset = tf.contrib.data.TFRecordDataset(filenames)
dataset = dataset.batch(batch\_size=32)
dataset = dataset.map(\_parse\_function)
|
551,536 |
How to prove that the new number produced by the Cantor's diagonalization process applied to $\Bbb Q$ is not a rational number ?
Suppose, someone claims that there is a flaw in the Cantor's diagonalization process by applying it to the set of rational numbers. I want to prove that the claim is false by showing that the new number produced by this process is not rational. How to prove this ? Hope I have made my question clear.
|
2013/11/04
|
['https://math.stackexchange.com/questions/551536', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/103623/']
|
This has very little to do with rational numbers themselves. You apply the diagonal argument to construct a number that is not on the list. Now the *only* reason that you must have produced an irrational number is that all the rational numbers are on the list, so it cannot be any of them. There is nothing intrinsic the construction that favours irrational numbers: if just one rational number were missing from the list, it might be that you have constructed just that number.
*Added*. Actually, now that I think about that, it is not true: in order for given some rational number to be the result of the diagonal procedure, there are a great many (other) rational numbers that must be *absent* from the list. Assuming decimal notation and for simplicity a rational number without terminating decimal representation, there are for every digit position $9$ rational numbers that differ from it only in that digit position. Of those, *only one* can be on the list, and only if it occurs at the exactly right position. So an infinite number of those "neigbours" need to be absent from the list. And even if one assumes binary notation (with only one neighbour per digit position), there must be one neighbour absent for every non-neighbour that is on the list (because the position of the former is taken), still making for a requirement of infinitely many rational numbers from the list. All this is related to the fact that modifying a rational number in a single position will not make it irrational. Curious!
|
I might have an approach that shows a counter example - where the flipped diagonal number produced is also rational. See: [Should a Cantor diagonal argument on a list of all rationals always produce an irrational number?](https://math.stackexchange.com/questions/677649/should-a-cantor-diagonal-argument-on-a-list-of-all-rationals-always-produce-an-i)
|
551,536 |
How to prove that the new number produced by the Cantor's diagonalization process applied to $\Bbb Q$ is not a rational number ?
Suppose, someone claims that there is a flaw in the Cantor's diagonalization process by applying it to the set of rational numbers. I want to prove that the claim is false by showing that the new number produced by this process is not rational. How to prove this ? Hope I have made my question clear.
|
2013/11/04
|
['https://math.stackexchange.com/questions/551536', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/103623/']
|
This has very little to do with rational numbers themselves. You apply the diagonal argument to construct a number that is not on the list. Now the *only* reason that you must have produced an irrational number is that all the rational numbers are on the list, so it cannot be any of them. There is nothing intrinsic the construction that favours irrational numbers: if just one rational number were missing from the list, it might be that you have constructed just that number.
*Added*. Actually, now that I think about that, it is not true: in order for given some rational number to be the result of the diagonal procedure, there are a great many (other) rational numbers that must be *absent* from the list. Assuming decimal notation and for simplicity a rational number without terminating decimal representation, there are for every digit position $9$ rational numbers that differ from it only in that digit position. Of those, *only one* can be on the list, and only if it occurs at the exactly right position. So an infinite number of those "neigbours" need to be absent from the list. And even if one assumes binary notation (with only one neighbour per digit position), there must be one neighbour absent for every non-neighbour that is on the list (because the position of the former is taken), still making for a requirement of infinitely many rational numbers from the list. All this is related to the fact that modifying a rational number in a single position will not make it irrational. Curious!
|
Despite replying to an old post, I would like to supplement things that that I missed out after reading all replies.
Fact:
1. $\pi$ is irrational
Cantor's technique for finding a contradiction has 1 property
1. The generated new number must be different
Cantor's contradiction makes sense because the new number is
1. Real number
2. Resulted from the aforementioned technique, which means its different from all enumerated real numbers
The contradiction will makes sense to $\mathbb{Q}$ if the new number is
1. Rational number
2. Resulted from the aforementioned technique, which means its different from all enumerated rationals
Here's the key. The very technique can give this number--$\pi$,
1. Rational number (***No***, it isn't)
2. Resulted from the method (Yes, it is different from all since its irrational)
This is how you conclude why is the generated number not necessarily rational, because the method gives a lot of freedom in picking the number
|
551,536 |
How to prove that the new number produced by the Cantor's diagonalization process applied to $\Bbb Q$ is not a rational number ?
Suppose, someone claims that there is a flaw in the Cantor's diagonalization process by applying it to the set of rational numbers. I want to prove that the claim is false by showing that the new number produced by this process is not rational. How to prove this ? Hope I have made my question clear.
|
2013/11/04
|
['https://math.stackexchange.com/questions/551536', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/103623/']
|
I might have an approach that shows a counter example - where the flipped diagonal number produced is also rational. See: [Should a Cantor diagonal argument on a list of all rationals always produce an irrational number?](https://math.stackexchange.com/questions/677649/should-a-cantor-diagonal-argument-on-a-list-of-all-rationals-always-produce-an-i)
|
Despite replying to an old post, I would like to supplement things that that I missed out after reading all replies.
Fact:
1. $\pi$ is irrational
Cantor's technique for finding a contradiction has 1 property
1. The generated new number must be different
Cantor's contradiction makes sense because the new number is
1. Real number
2. Resulted from the aforementioned technique, which means its different from all enumerated real numbers
The contradiction will makes sense to $\mathbb{Q}$ if the new number is
1. Rational number
2. Resulted from the aforementioned technique, which means its different from all enumerated rationals
Here's the key. The very technique can give this number--$\pi$,
1. Rational number (***No***, it isn't)
2. Resulted from the method (Yes, it is different from all since its irrational)
This is how you conclude why is the generated number not necessarily rational, because the method gives a lot of freedom in picking the number
|
47,005,284 |
I've used the column command to split some of my output into 3 different columns. Problem is with the final column, the filetype output is being split into a 4th and 5th column because of the spaces.
Can somebody tell me how to change my code so that output stays under the Filetype column?
```
list_files()
{
if [ "$(ls -A ~/.junkdir)" ]
then
filesdir=/home/student/.junkdir/*
echo "Listing files in Junk Directory"
output="FILENAME SIZE(BYTES) TYPE \n\n---------------- ---------------- ------------------- "
for listed_file in $filesdir
do
file_name=$(basename "file $listed_file" | cut -d ' ' -f1)
file_size=$(du --bytes $listed_file | awk '{print $1}')
file_type=$(file $listed_file | cut -d ' ' -f2-)
output="$output\n${file_name} ${file_size} ${file_type}\n"
done
echo -ne $output | column -t
else
echo 'Junk directory is empty'
fi
}
```
The output at the moment..
```
Listing files in Junk Directory
FILENAME SIZE(BYTES) TYPE
---------------- ---------------- -------------------
files.txt 216 ASCII text
forLoop 401 Bourne-Again shell script,
ASCII text executable
```
|
2017/10/29
|
['https://Stackoverflow.com/questions/47005284', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8791139/']
|
The proper way to do this would be to pass the clipping function `tf.clip_by_value` as the `constraint` argument to the `tf.Variable` constructor:
```
Mj=tf.get_variable('Mj_',
dtype=tf.float32,
shape=[500,4],
initializer=tf.random_uniform_initializer(maxval=1, minval=0),
constraint=lambda t: tf.clip_by_value(t, 0, 1))
```
From the docs of `tf.Variable`:
>
> constraint: An optional projection function to be applied to the
> variable after being updated by an Optimizer (e.g. used to implement
> norm constraints or value constraints for layer weights). The function
> must take as input the unprojected Tensor representing the value of
> the variable and return the Tensor for the projected value (which must
> have the same shape). Constraints are not safe to use when doing
> asynchronous distributed training.
>
>
>
Or you might want to consider simply adding a nonlinearity [`tf.sigmoid`](https://www.tensorflow.org/api_docs/python/tf/sigmoid) on top of your variable.
```
Mj=tf.get_variable('Mj_',dtype=tf.float32, shape=[500,4])
Mj_out=tf.sigmoid(Mj)
```
This will transform your variable to range between 0 and 1. Read more about activation functions [here](https://www.tensorflow.org/api_guides/python/nn#Activation_Functions).
|
I think the function you're looking for is `tf.clip_by_value`.
Link to [Docs](https://www.tensorflow.org/api_docs/python/tf/clip_by_value).
|
19,486,762 |
I know this question has been asked before, but I was just wondering why it isn't working in my particular case.
I am trying to send an invitation from multipeer connectivity from one view controller and receive it on another. My code for sending it is:
```
[self invitePeer:selectedPeerID toSession:self.mySession withContext:nil timeout:timeInterval ];
```
and method is just blank:
```
- (void)invitePeer:(MCPeerID *)peerID toSession:(MCSession *)session withContext:(NSData *)context timeout:(NSTimeInterval)timeout
{
}
```
My code for receiving and invitation is:
```
- (void)advertiser:(MCNearbyServiceAdvertiser *)advertiser didReceiveInvitationFromPeer:(MCPeerID *)peerID withContext:(NSData *)context invitationHandler:(void(^)(BOOL accept, MCSession *session))invitationHandler
{
// http://down.vcnc.co.kr/WWDC_2013/Video/708.pdf -- wwdc tutorial, this part is towards the end (p119)
self.arrayInvitationHandler = [NSArray arrayWithObject:[invitationHandler copy]];
// ask the user
UIAlertView *alertView = [[UIAlertView alloc]
initWithTitle:peerID.displayName
message:@"Would like to create a session with you"
delegate:self
cancelButtonTitle:@"Decline" otherButtonTitles:@"Accept", nil];
[alertView show];
}
- (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
// retrieve the invitationHandler and check whether the user accepted or declined the invitation...
BOOL accept = (buttonIndex != alertView.cancelButtonIndex) ? YES : NO;
// respond
if(accept) {
void (^invitationHandler)(BOOL, MCSession *) = [self.arrayInvitationHandler objectAtIndex:0];
invitationHandler(accept, self.mySession);
}
else
{
NSLog(@"Session disallowed");
}
}
```
I have all the delegate methods correctly set up as well as the same service types and that. But when i try to initiate the session, the tableviewcell which i click on just remains highlighted...
I'm thinking I have to put something in the invitePeer toSession method but I'm not sure...
I copied this directly from Apple's wwdc talk on Multipeer Connectivity referenced in my code... As you can see it is my own implementation of the code and I am not using an advertiser assistant or the mcbrowserviewcontroller.
Does anyone have any suggestions as to how I can get this to work??
|
2013/10/21
|
['https://Stackoverflow.com/questions/19486762', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2218728/']
|
This should be expected, as per the [JavaDoc:](http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#sleep%28long%29)
>
> Causes the currently executing thread to sleep (temporarily cease
> execution) for the specified number of milliseconds, subject to the
> precision and accuracy of system timers and schedulers. The thread
> does not lose ownership of any monitors.
>
>
>
What you could do, could be to sleep less, say, 400ms and then check to see if the time has changed.
Alternatively, you could use a [`Timer`](http://docs.oracle.com/javase/7/docs/api/java/util/Timer.html) and fire events once every second and update your time.
Edit: As per your comment, you could do something like so:
```
long initTime = System.getTimeinMillis();
while(true)
{
Thread.sleep(200);
if((System.getTimeInMillis() - initTime) >= 1000)
{
initTime = System.getTimeInMillis();
//Update your timer.
}
}
```
|
Idea is to go to sleep, wake up(possibly prematurely) and check time again to go to sleep.
Under heavy system load, your timer thread does not get scheduled and thread may not wake up from sleep resulting your clock going off time.
But its always about showing correct time, whenever possible.
General suggestion: maximize sleep to keep wake ups minimum(each wakeup involves one context switch).
Here is something I wrote for myself:
```
/**
* Put the calling thread to sleep.
* Note, this thread does not throw interrupted exception,
* and will not return until the thread has slept for provided time.
*
* @param milliSecond milliSecond time to sleep in millisecond
*/
public static void sleepForcefully(int milliSecond) {
final long endingTime = System.currentTimeMillis() + milliSecond;
long remainingTime = milliSecond;
while (remainingTime > 0) {
try {
Thread.sleep(remainingTime);
} catch (InterruptedException ignore) {
}
remainingTime = endingTime - System.currentTimeMillis();
}
}
```
This type of logic is used all over timers, pingers, etc in JDK and other places.
|
36,536,657 |
I have a simple script on my site that adds a css class to the navigation bar after the user has started to scroll, and removes it when they are back at the top of the page.
However, this is causing a significant amount of jank (fps lag), and it 100% is not worth the performance hit.
Is there a way to optimise this or to make it work without causing jank?
```
$(window).scroll(function() {
var scroll = $(window).scrollTop();
var navbar = $('#navbar');
if (scroll >= 40) {
navbar.addClass("navbar-border");
} else {
navbar.removeClass("navbar-border");
}
});
```
If not, I'll remove it.
Thanks!
|
2016/04/10
|
['https://Stackoverflow.com/questions/36536657', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2484643/']
|
You code is accessing the DOM potentially 100 times per second, which is the reason for your performance issue, to improve performance you can throttle the scroll event so that it executes your code less by using a Timeout that first unbinds the Scroll event then binds it after a delay(threshold), increasing the threshold will cause the code to execute less often.
```
var navbar = $('#navbar-border');
var threshold = 100; // in milliseconds
function borderControl() {
console.log("run");
var scroll = $(window).scrollTop();
if (scroll >= 40) {
navbar.addClass("navbar-border");
} else {
navbar.removeClass("navbar-border");
}
}
function setScrollTimer() {
unbindScroll();
scrollTimer = window.setTimeout(function() {
bindScroll()
}, threshold);
}
function unbindScroll() {
$(window).unbind("scroll");
}
function bindScroll() {
$(window).scroll(function(e) {
setScrollTimer();
borderControl();
});
}
bindScroll();
```
<https://jsfiddle.net/sjmcpherson/Lugrukwm/>
|
You could cache the results of processing to process less often by storing results in global variables or at least variables that persist outside the scroll callback.
There is so little in the callback to begin with that we don't have much room for improvement.
```
var navbar = $('#navbar');
var navborder = false;
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (!navborder && scroll >= 40) {
navborder = true;
navbar.addClass("navbar-border");
} else if(navborder && scroll < 40) {
navborder = false;
navbar.removeClass("navbar-border");
}
});
```
<http://codepen.io/t3hpwninat0r/pen/yOvaGN>
Alternatively you could disable the scroll position checking, and then set a timer to re-enable it after a short delay
```
var scrollTimer = 0;
$(window).scroll(function() {
clearTimeout(scrollTimer);
scrollTimer = setTimeout(function() {
var scroll = $(window).scrollTop();
var navbar = $('#navbar');
if (scroll >= 40) {
navbar.addClass("navbar-border");
} else {
navbar.removeClass("navbar-border");
}
}, 100);
});
```
<http://codepen.io/t3hpwninat0r/pen/BKYLMb>
If the user keeps scrolling, the timer keeps restarting, and the function will only run when the 100ms timer is complete. This example adds only 4 lines to your code without any other changes.
I took (read: plagiarised) the code from this answer: <https://stackoverflow.com/a/14092859/1160540>
|
46,545,841 |
I have a list of file names produced by a third party. They all look like this: `'D:\\a\\b\\c/d/e/f/g.cpp'`.
I would like to normalize these to have a uniform path separator. However the command:
```
os.path.normpath('D:\\a\\b\\c/d/e/f/g.cpp')
```
does nothing to the string under Linux (Python3).
Under Windows I get the expected result, i.e. all slashes converted to `\\`.
How can I make it work under Linux, without resorting to regex? Is it a bug?
|
2017/10/03
|
['https://Stackoverflow.com/questions/46545841', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2077783/']
|
On Windows, `os.path` redirects to `ntpath` module which is aware of `\`, drives, ...
On Linux, you have to import & use `ntpath` explicitly because you're not using the native separators.
The code below works on both platforms:
```
>>> import ntpath
>>> ntpath.normpath(r'D:\a\b\c/d/e/f/g.cpp')
'D:\\a\\b\\c\\d\\e\\f\\g.cpp'
>>>
```
(note the usage of `r` prefix when pasting the paths, avoids doubling the backslashes)
|
I find this to be the best option just write your own function
```
import os
def norm_path(path_in, sep=None):
if sep==None:
sep = os.sep
tmp_list = '\\'.join([k for k in path_in.split('/') if len(k)>0])
final_list = [k for k in tmp_list.split('\\') if len(k)>0]
return sep.join(final_list)
```
or if you don't want to use any packages then just
```
def norm_path(path_in, sep='/'):
tmp_list = '\\'.join([k for k in path_in.split('/') if len(k)>0])
final_list = [k for k in tmp_list.split('\\') if len(k)>0]
return sep.join(final_list)
```
|
22,706,628 |
I am not able to figure out the error :NoClassDefFoundError . I am trying to create a simple Google map. Is there any problem with the Google play services library?
error:-
```
03-28 03:17:45.489: E/AndroidRuntime(2338): FATAL EXCEPTION: main
03-28 03:17:45.489: E/AndroidRuntime(2338): Process: com.example.gpsdemo, PID: 2338
03-28 03:17:45.489: E/AndroidRuntime(2338): java.lang.NoClassDefFoundError: com.google.android.gms.R$styleable
03-28 03:17:45.489: E/AndroidRuntime(2338): at com.google.android.gms.maps.GoogleMapOptions.createFromAttributes(Unknown Source)
03-28 03:17:45.489: E/AndroidRuntime(2338): at com.google.android.gms.maps.MapFragment.onInflate(Unknown Source)
03-28 03:17:45.489: E/AndroidRuntime(2338): at android.app.Activity.onCreateView(Activity.java:4785)
03-28 03:17:45.489: E/AndroidRuntime(2338): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:689)
03-28 03:17:45.489: E/AndroidRuntime(2338): at android.view.LayoutInflater.inflate(LayoutInflater.java:469)
03-28 03:17:45.489: E/AndroidRuntime(2338): at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
03-28 03:17:45.489: E/AndroidRuntime(2338): at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
03-28 03:17:45.489: E/AndroidRuntime(2338): at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:290)
03-28 03:17:45.489: E/AndroidRuntime(2338): at android.app.Activity.setContentView(Activity.java:1929)
03-28 03:17:45.489: E/AndroidRuntime(2338): at com.example.gpsdemo.MainActivity.onCreate(MainActivity.java:12)
03-28 03:17:45.489: E/AndroidRuntime(2338): at android.app.Activity.performCreate(Activity.java:5231)
03-28 03:17:45.489: E/AndroidRuntime(2338): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
03-28 03:17:45.489: E/AndroidRuntime(2338): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
03-28 03:17:45.489: E/AndroidRuntime(2338): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
03-28 03:17:45.489: E/AndroidRuntime(2338): at android.app.ActivityThread.access$800(ActivityThread.java:135)
03-28 03:17:45.489: E/AndroidRuntime(2338): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
03-28 03:17:45.489: E/AndroidRuntime(2338): at android.os.Handler.dispatchMessage(Handler.java:102)
03-28 03:17:45.489: E/AndroidRuntime(2338): at android.os.Looper.loop(Looper.java:136)
03-28 03:17:45.489: E/AndroidRuntime(2338): at android.app.ActivityThread.main(ActivityThread.java:5017)
03-28 03:17:45.489: E/AndroidRuntime(2338): at java.lang.reflect.Method.invokeNative(Native Method)
03-28 03:17:45.489: E/AndroidRuntime(2338): at java.lang.reflect.Method.invoke(Method.java:515)
03-28 03:17:45.489: E/AndroidRuntime(2338): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
03-28 03:17:45.489: E/AndroidRuntime(2338): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
03-28 03:17:45.489: E/AndroidRuntime(2338): at dalvik.system.NativeStart.main(Native Method)
```
MainActivity.java
```
package com.example.gpsdemo;
import android.app.Activity;
import android.os.Bundle;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
```
actvity\_main.xml:
```
<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="com.google.android.gms.maps.MapFragment"/>
```
Error after changes:-
```
03-28 03:45:52.759: E/AndroidRuntime(2625): FATAL EXCEPTION: main
03-28 03:45:52.759: E/AndroidRuntime(2625): Process: com.example.gpsdemo, PID: 2625
03-28 03:45:52.759: E/AndroidRuntime(2625): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.gpsdemo/com.example.gpsdemo.MainActivity}: android.view.InflateException: Binary XML file line #2: Error inflating class fragment
03-28 03:45:52.759: E/AndroidRuntime(2625): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
03-28 03:45:52.759: E/AndroidRuntime(2625): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
03-28 03:45:52.759: E/AndroidRuntime(2625): at android.app.ActivityThread.access$800(ActivityThread.java:135)
03-28 03:45:52.759: E/AndroidRuntime(2625): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
03-28 03:45:52.759: E/AndroidRuntime(2625): at android.os.Handler.dispatchMessage(Handler.java:102)
03-28 03:45:52.759: E/AndroidRuntime(2625): at android.os.Looper.loop(Looper.java:136)
03-28 03:45:52.759: E/AndroidRuntime(2625): at android.app.ActivityThread.main(ActivityThread.java:5017)
03-28 03:45:52.759: E/AndroidRuntime(2625): at java.lang.reflect.Method.invokeNative(Native Method)
03-28 03:45:52.759: E/AndroidRuntime(2625): at java.lang.reflect.Method.invoke(Method.java:515)
03-28 03:45:52.759: E/AndroidRuntime(2625): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
03-28 03:45:52.759: E/AndroidRuntime(2625): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
03-28 03:45:52.759: E/AndroidRuntime(2625): at dalvik.system.NativeStart.main(Native Method)
03-28 03:45:52.759: E/AndroidRuntime(2625): Caused by: android.view.InflateException: Binary XML file line #2: Error inflating class fragment
03-28 03:45:52.759: E/AndroidRuntime(2625): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:713)
03-28 03:45:52.759: E/AndroidRuntime(2625): at android.view.LayoutInflater.inflate(LayoutInflater.java:469)
03-28 03:45:52.759: E/AndroidRuntime(2625): at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
03-28 03:45:52.759: E/AndroidRuntime(2625): at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
03-28 03:45:52.759: E/AndroidRuntime(2625): at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:290)
03-28 03:45:52.759: E/AndroidRuntime(2625): at android.app.Activity.setContentView(Activity.java:1929)
03-28 03:45:52.759: E/AndroidRuntime(2625): at com.example.gpsdemo.MainActivity.onCreate(MainActivity.java:26)
03-28 03:45:52.759: E/AndroidRuntime(2625): at android.app.Activity.performCreate(Activity.java:5231)
03-28 03:45:52.759: E/AndroidRuntime(2625): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
03-28 03:45:52.759: E/AndroidRuntime(2625): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
03-28 03:45:52.759: E/AndroidRuntime(2625): ... 11 more
03-28 03:45:52.759: E/AndroidRuntime(2625): Caused by: android.app.Fragment$InstantiationException: Unable to instantiate fragment com.google.android.gms.maps.MapFragment: make sure class name exists, is public, and has an empty constructor that is public
03-28 03:45:52.759: E/AndroidRuntime(2625): at android.app.Fragment.instantiate(Fragment.java:597)
03-28 03:45:52.759: E/AndroidRuntime(2625): at android.app.Fragment.instantiate(Fragment.java:561)
03-28 03:45:52.759: E/AndroidRuntime(2625): at android.app.Activity.onCreateView(Activity.java:4778)
03-28 03:45:52.759: E/AndroidRuntime(2625): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:689)
03-28 03:45:52.759: E/AndroidRuntime(2625): ... 20 more
03-28 03:45:52.759: E/AndroidRuntime(2625): Caused by: java.lang.ClassNotFoundException: Didn't find class "com.google.android.gms.maps.MapFragment" on path: DexPathList[[zip file "/data/app/com.example.gpsdemo-2.apk"],nativeLibraryDirectories=[/data/app-lib/com.example.gpsdemo-2, /system/lib]]
03-28 03:45:52.759: E/AndroidRuntime(2625): at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
03-28 03:45:52.759: E/AndroidRuntime(2625): at java.lang.ClassLoader.loadClass(ClassLoader.java:497)
03-28 03:45:52.759: E/AndroidRuntime(2625): at java.lang.ClassLoader.loadClass(ClassLoader.java:457)
03-28 03:45:52.759: E/AndroidRuntime(2625): at android.app.Fragment.instantiate(Fragment.java:583)
03-28 03:45:52.759: E/AndroidRuntime(2625): ... 23 more
```
Here is the manifest file:-
```
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.gpsdemo"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="7"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-feature
android:glEsVersion="0x00020000"
android:required="true"/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.gpsdemo.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="" />
</application>
</manifest>
```
|
2014/03/28
|
['https://Stackoverflow.com/questions/22706628', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3467204/']
|
This is [documented](http://docs.python.org/2/library/itertools.html#itertools.groupby):
>
> The returned group is itself an iterator that shares the underlying iterable with `groupby()`. Because the source is shared, when the `groupby()` object is advanced, the previous group is no longer visible.
>
>
>
When you do `list(groupby(...))`, you advance the groupby object all the way to the end, this losing all groups except the last. If you need to save the groups, do as shown in the documentation and save each one while iterating over the groupby object.
|
The example in the documentation is not as nice as:
```
list((key, list(group)) for key, group in itertools.groupby(...))
```
in turning the iterator into a list of tuples of keys and lists of groups: `[(key,[group])]` if that is what is desired.
|
53,473,475 |
What does `_` mean in this example code:
```
if (_(abc.content).has("abc")){
console.log("abc found");
}
```
Many people say "\_" means a private member, but if `abc` or `content` is a private member, shouldn't we use `_abc.content` or `abc._content`?
Thank you
|
2018/11/26
|
['https://Stackoverflow.com/questions/53473475', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7025179/']
|
For that to be valid, `_` must refer to a *function*. Perhaps the script is using [`underscore`](https://underscorejs.org/#has), in which case `_(abc.content).has("abc")` returns a Boolean - `true` if the `abc.content` object has a *key* of `abc`, and `false` otherwise:
```js
const abc = { content: { key1: 'foo', abc: 'bar' } };
if (_(abc.content).has("abc")){
console.log("abc found");
}
console.log(_(abc.content).has("keyThatDoesNotExist"))
```
```html
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"></script>
```
It probably has nothing to do with private properties, because `_` is a *standalone* function.
The library used might also be lodash:
```js
const abc = { content: { key1: 'foo', abc: 'bar' } };
if (_(abc.content).has("abc")){
console.log("abc found");
}
console.log(_(abc.content).has("keyThatDoesNotExist"))
```
```html
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.core.min.js"></script>
```
But to be sure, you'll have to examine `_` - `console.log` it, or see where it's defined, to get some idea.
|
That's just a variable name. You are right, conventions suggest that underscore refer to private members in an object such as:
```
const num = 2;
function Multiply(num) {
this._multiplier = 2;
this._input = num;
this.start = function(){
return this._multiplier * this._input;
}
}
const product = new Multiply(num).start(); //4
```
But the concept of private members has nothing to do with your example.
In your case, `_()` is actually a function;
```
function _ (){
return "I love potatoes";
}
```
a function that returns an object that contains the `.has()` method. The structure of that function of yours could be dumbed down to something like
```
function _(args){
const content = args;
return {
has: function(data){
//do something
return true; //some boolean expression
}
}
}
```
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.