qid
int64
1
74.7M
question
stringlengths
0
58.3k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
2
48.3k
response_k
stringlengths
2
40.5k
148,963
Keeping the GUI responsive while the application does some CPU-heavy processing is one of the challenges of effective GUI programming. [Here's a good discussion](http://wiki.wxpython.org/LongRunningTasks) of how to do this in wxPython. To summarize, there are 3 ways: 1. Use threads 2. Use wxYield 3. Chunk the work and do it in the IDLE event handler Which method have *you* found to be the most effective ? Techniques from other frameworks (like Qt, GTK or Windows API) are also welcome.
2008/09/29
[ "https://Stackoverflow.com/questions/148963", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8206/" ]
Definitely threads. Why? The future is multi-core. Almost any new CPU has more than one core or if it has just one, it might support hyperthreading and thus pretending it has more than one. To effectively make use of multi-core CPUs (and Intel is planing to go up to 32 cores in the not so far future), you need multiple threads. If you run all in one main thread (usually the UI thread is the main thread), users will have CPUs with 8, 16 and one day 32 cores and your application never uses more than one of these, IOW it runs much, much slower than it could run. Actual if you plan an application nowadays, I would go away of the classical design and think of a master/slave relationship. Your UI is the master, it's only task is to interact with the user. That is displaying data to the user and gathering user input. Whenever you app needs to "process any data" (even small amounts and much more important big ones), create a "task" of any kind, forward this task to a background thread and make the thread perform the task, providing feedback to the UI (e.g. how many percent it has completed or just if the task is still running or not, so the UI can show a "work-in-progress indicator"). If possible, split the task into many small, independent sub-tasks and run more than one background process, feeding one sub-task to each of them. That way your application can really benefit from multi-core and get faster the more cores CPUs have. Actually companies like Apple and Microsoft are already planing on how to make their still most single threaded UIs themselves multithreaded. Even with the approach above, you may one day have the situation that the UI is the bottleneck itself. The background processes can process data much faster than the UI can present it to the user or ask the user for input. Today many UI frameworks are little thread-safe, many not thread-safe at all, but that will change. Serial processing (doing one task after another) is a dying design, parallel processing (doing many task at once) is where the future goes. Just look at graphic adapters. Even the most modern NVidia card has a pitiful performance, if you look at the processing speed in MHz/GHz of the GPU alone. How comes it can beat the crap out of CPUs when it comes to 3D calculations? Simple: Instead of calculating one polygon point or one texture pixel after another, it calculates many of them in parallel (actually a whole bunch at the same time) and that way it reaches a throughput that still makes CPUs cry. E.g. the ATI X1900 (to name the competitor as well) has 48 shader units!
This answer doesn't apply to the OP's question regarding Python, but is more of a meta-response. The easy way is threads. However, not every platform has pre-emptive threading (e.g. BREW, some other embedded systems) If possibly, simply chunk the work and do it in the IDLE event handler. Another problem with using threads in BREW is that it doesn't clean up C++ stack objects, so it's way too easy to leak memory if you simply kill the thread.
148,963
Keeping the GUI responsive while the application does some CPU-heavy processing is one of the challenges of effective GUI programming. [Here's a good discussion](http://wiki.wxpython.org/LongRunningTasks) of how to do this in wxPython. To summarize, there are 3 ways: 1. Use threads 2. Use wxYield 3. Chunk the work and do it in the IDLE event handler Which method have *you* found to be the most effective ? Techniques from other frameworks (like Qt, GTK or Windows API) are also welcome.
2008/09/29
[ "https://Stackoverflow.com/questions/148963", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8206/" ]
Definitely threads. Why? The future is multi-core. Almost any new CPU has more than one core or if it has just one, it might support hyperthreading and thus pretending it has more than one. To effectively make use of multi-core CPUs (and Intel is planing to go up to 32 cores in the not so far future), you need multiple threads. If you run all in one main thread (usually the UI thread is the main thread), users will have CPUs with 8, 16 and one day 32 cores and your application never uses more than one of these, IOW it runs much, much slower than it could run. Actual if you plan an application nowadays, I would go away of the classical design and think of a master/slave relationship. Your UI is the master, it's only task is to interact with the user. That is displaying data to the user and gathering user input. Whenever you app needs to "process any data" (even small amounts and much more important big ones), create a "task" of any kind, forward this task to a background thread and make the thread perform the task, providing feedback to the UI (e.g. how many percent it has completed or just if the task is still running or not, so the UI can show a "work-in-progress indicator"). If possible, split the task into many small, independent sub-tasks and run more than one background process, feeding one sub-task to each of them. That way your application can really benefit from multi-core and get faster the more cores CPUs have. Actually companies like Apple and Microsoft are already planing on how to make their still most single threaded UIs themselves multithreaded. Even with the approach above, you may one day have the situation that the UI is the bottleneck itself. The background processes can process data much faster than the UI can present it to the user or ask the user for input. Today many UI frameworks are little thread-safe, many not thread-safe at all, but that will change. Serial processing (doing one task after another) is a dying design, parallel processing (doing many task at once) is where the future goes. Just look at graphic adapters. Even the most modern NVidia card has a pitiful performance, if you look at the processing speed in MHz/GHz of the GPU alone. How comes it can beat the crap out of CPUs when it comes to 3D calculations? Simple: Instead of calculating one polygon point or one texture pixel after another, it calculates many of them in parallel (actually a whole bunch at the same time) and that way it reaches a throughput that still makes CPUs cry. E.g. the ATI X1900 (to name the competitor as well) has 48 shader units!
Threads - Let's use a simple 2-layer view (GUI, application logic). The application logic work should be done in a separate Python thread. For Asynchronous events that need to propagate up to the GUI layer, use wx's event system to post custom events. Posting wx events is thread safe so you could conceivably do it from multiple contexts. Working in the other direction (GUI input events triggering application logic), I have found it best to home-roll a custom event system. Use the Queue module to have a thread-safe way of pushing and popping event objects. Then, for every synchronous member function, pair it with an async version that pushes the sync function object and the parameters onto the event queue. This works particularly well if only a single application logic-level operation can be performed at a time. The benefit of this model is that synchronization is simple - each synchronous function works within it's own context sequentially from start to end without worry of pre-emption or hand-coded yielding. You will not need locks to protect your critical sections. At the end of the function, post an event to the GUI layer indicating that the operation is complete. You could scale this to allow multiple application-level threads to exist, but the usual concerns with synchronization will re-appear. *edit* - Forgot to mention the beauty of this is that it is possible to completely decouple the application logic from the GUI code. The modularity helps if you ever decide to use a different framework or use provide a command-line version of the app. To do this, you will need an intermediate event dispatcher (application level -> GUI) that is implemented by the GUI layer.
148,963
Keeping the GUI responsive while the application does some CPU-heavy processing is one of the challenges of effective GUI programming. [Here's a good discussion](http://wiki.wxpython.org/LongRunningTasks) of how to do this in wxPython. To summarize, there are 3 ways: 1. Use threads 2. Use wxYield 3. Chunk the work and do it in the IDLE event handler Which method have *you* found to be the most effective ? Techniques from other frameworks (like Qt, GTK or Windows API) are also welcome.
2008/09/29
[ "https://Stackoverflow.com/questions/148963", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8206/" ]
Threads. They're what I always go for because you can do it in every framework you need. And once you're used to multi-threading and parallel processing in one language/framework, you're good on all frameworks.
Definitely threads. Why? The future is multi-core. Almost any new CPU has more than one core or if it has just one, it might support hyperthreading and thus pretending it has more than one. To effectively make use of multi-core CPUs (and Intel is planing to go up to 32 cores in the not so far future), you need multiple threads. If you run all in one main thread (usually the UI thread is the main thread), users will have CPUs with 8, 16 and one day 32 cores and your application never uses more than one of these, IOW it runs much, much slower than it could run. Actual if you plan an application nowadays, I would go away of the classical design and think of a master/slave relationship. Your UI is the master, it's only task is to interact with the user. That is displaying data to the user and gathering user input. Whenever you app needs to "process any data" (even small amounts and much more important big ones), create a "task" of any kind, forward this task to a background thread and make the thread perform the task, providing feedback to the UI (e.g. how many percent it has completed or just if the task is still running or not, so the UI can show a "work-in-progress indicator"). If possible, split the task into many small, independent sub-tasks and run more than one background process, feeding one sub-task to each of them. That way your application can really benefit from multi-core and get faster the more cores CPUs have. Actually companies like Apple and Microsoft are already planing on how to make their still most single threaded UIs themselves multithreaded. Even with the approach above, you may one day have the situation that the UI is the bottleneck itself. The background processes can process data much faster than the UI can present it to the user or ask the user for input. Today many UI frameworks are little thread-safe, many not thread-safe at all, but that will change. Serial processing (doing one task after another) is a dying design, parallel processing (doing many task at once) is where the future goes. Just look at graphic adapters. Even the most modern NVidia card has a pitiful performance, if you look at the processing speed in MHz/GHz of the GPU alone. How comes it can beat the crap out of CPUs when it comes to 3D calculations? Simple: Instead of calculating one polygon point or one texture pixel after another, it calculates many of them in parallel (actually a whole bunch at the same time) and that way it reaches a throughput that still makes CPUs cry. E.g. the ATI X1900 (to name the competitor as well) has 48 shader units!
148,963
Keeping the GUI responsive while the application does some CPU-heavy processing is one of the challenges of effective GUI programming. [Here's a good discussion](http://wiki.wxpython.org/LongRunningTasks) of how to do this in wxPython. To summarize, there are 3 ways: 1. Use threads 2. Use wxYield 3. Chunk the work and do it in the IDLE event handler Which method have *you* found to be the most effective ? Techniques from other frameworks (like Qt, GTK or Windows API) are also welcome.
2008/09/29
[ "https://Stackoverflow.com/questions/148963", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8206/" ]
Definitely threads. Why? The future is multi-core. Almost any new CPU has more than one core or if it has just one, it might support hyperthreading and thus pretending it has more than one. To effectively make use of multi-core CPUs (and Intel is planing to go up to 32 cores in the not so far future), you need multiple threads. If you run all in one main thread (usually the UI thread is the main thread), users will have CPUs with 8, 16 and one day 32 cores and your application never uses more than one of these, IOW it runs much, much slower than it could run. Actual if you plan an application nowadays, I would go away of the classical design and think of a master/slave relationship. Your UI is the master, it's only task is to interact with the user. That is displaying data to the user and gathering user input. Whenever you app needs to "process any data" (even small amounts and much more important big ones), create a "task" of any kind, forward this task to a background thread and make the thread perform the task, providing feedback to the UI (e.g. how many percent it has completed or just if the task is still running or not, so the UI can show a "work-in-progress indicator"). If possible, split the task into many small, independent sub-tasks and run more than one background process, feeding one sub-task to each of them. That way your application can really benefit from multi-core and get faster the more cores CPUs have. Actually companies like Apple and Microsoft are already planing on how to make their still most single threaded UIs themselves multithreaded. Even with the approach above, you may one day have the situation that the UI is the bottleneck itself. The background processes can process data much faster than the UI can present it to the user or ask the user for input. Today many UI frameworks are little thread-safe, many not thread-safe at all, but that will change. Serial processing (doing one task after another) is a dying design, parallel processing (doing many task at once) is where the future goes. Just look at graphic adapters. Even the most modern NVidia card has a pitiful performance, if you look at the processing speed in MHz/GHz of the GPU alone. How comes it can beat the crap out of CPUs when it comes to 3D calculations? Simple: Instead of calculating one polygon point or one texture pixel after another, it calculates many of them in parallel (actually a whole bunch at the same time) and that way it reaches a throughput that still makes CPUs cry. E.g. the ATI X1900 (to name the competitor as well) has 48 shader units!
Working with Qt/C++ for Win32. We divide the major work units into different processes. The GUI runs as a separate process and is able to command/receive data from the "worker" processes as needed. Works nicely in todays multi-core world.
148,963
Keeping the GUI responsive while the application does some CPU-heavy processing is one of the challenges of effective GUI programming. [Here's a good discussion](http://wiki.wxpython.org/LongRunningTasks) of how to do this in wxPython. To summarize, there are 3 ways: 1. Use threads 2. Use wxYield 3. Chunk the work and do it in the IDLE event handler Which method have *you* found to be the most effective ? Techniques from other frameworks (like Qt, GTK or Windows API) are also welcome.
2008/09/29
[ "https://Stackoverflow.com/questions/148963", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8206/" ]
Threads - Let's use a simple 2-layer view (GUI, application logic). The application logic work should be done in a separate Python thread. For Asynchronous events that need to propagate up to the GUI layer, use wx's event system to post custom events. Posting wx events is thread safe so you could conceivably do it from multiple contexts. Working in the other direction (GUI input events triggering application logic), I have found it best to home-roll a custom event system. Use the Queue module to have a thread-safe way of pushing and popping event objects. Then, for every synchronous member function, pair it with an async version that pushes the sync function object and the parameters onto the event queue. This works particularly well if only a single application logic-level operation can be performed at a time. The benefit of this model is that synchronization is simple - each synchronous function works within it's own context sequentially from start to end without worry of pre-emption or hand-coded yielding. You will not need locks to protect your critical sections. At the end of the function, post an event to the GUI layer indicating that the operation is complete. You could scale this to allow multiple application-level threads to exist, but the usual concerns with synchronization will re-appear. *edit* - Forgot to mention the beauty of this is that it is possible to completely decouple the application logic from the GUI code. The modularity helps if you ever decide to use a different framework or use provide a command-line version of the app. To do this, you will need an intermediate event dispatcher (application level -> GUI) that is implemented by the GUI layer.
Working with Qt/C++ for Win32. We divide the major work units into different processes. The GUI runs as a separate process and is able to command/receive data from the "worker" processes as needed. Works nicely in todays multi-core world.
56,631,624
I try to return a specific .xls file with FindFirstFile(). Howerver it also returns .xlsx, due to naming convention. It is possible to use "\*.xls" in the file explorer to return only .xls files. Does this work for the functi
2019/06/17
[ "https://Stackoverflow.com/questions/56631624", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10191057/" ]
As @Hans Passant said you got bitten by the legacy support for [8.3 MSDOS names](https://en.wikipedia.org/wiki/8.3_filename). Your `LovelyTable.xlsx` also has a secondary name, something like `LOVELY~1.XLS` and this second name is what `FindFirstFile()/FindNextFile()` gives you. The only robust way to avoid such results is to recheck what is returned back to you. If you don't want to change the application you can also remove short names from the volume and also disable their generation. You can check the [fsutil](https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/fsutil) command (its `8dot3name` sub-command) for that but beware that this might break some software even nowadays. (For example software believing it is installed under `C:\PROGRA~2\`) --- I thought that [`FindFirstFileEx()`](https://learn.microsoft.com/en-us/windows/desktop/api/fileapi/nf-fileapi-findfirstfileexw) can filter-out the 8.3 names: ``` FindFirstFileEx(searchPattern, FindExInfoBasic, ...) ``` but it cannot. Thanks to @RbMm for clearing this out. `FindExInfoBasic` only avoids filling in the `WIN32_FIND_DATA`'s `cAlternateFileName` field. You still receive files discovered by their short names.
This is a consequence of support for short 8.3 filenames. Your .xlsx file is given a short name with .xls extension. And it is the short file name that is matching. Whilst you can turn off support for short filenames of drives that you control, that option is not practical for machines that you don't control. So realistically you will have to apply your own filtering.
25,691,677
I do not know much about iframes (never really used them) and I am using it to display a form on one of our pages. Currently we are using wufoo forms and use their embed code, but our seo team discovered that the embed form is adding h1 tags to things that we do not want. So we are taking the form and putting it to our server. I have the form created here <http://tinyurl.com/qdtfu9g> I would like the form to look like this (embed code from wufoo) <http://tinyurl.com/m7v833w> This is my poor attempt <http://tinyurl.com/kfvshed> How could I make the contents inside the iframe responsive, like they have done with their embed code. Only reason why I am using the iframe is there javascript and css files mess with the current theme, so I kept them separate.
2014/09/05
[ "https://Stackoverflow.com/questions/25691677", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1649697/" ]
Sorry, but it seems you cannot do this in Smarty2. I tried a few ways but it doesn't work. There is no `scope` property in Smarty3. You looked at documentation of Smarty3 and you should look at [documentation for Smarty2](http://www.smarty.net/docsv2/en/)
I was making the assumption that using {include file='mytemplate.tpl'} would find the "file" however it did not work until I used the full absolute path such as: {include file='/home/username/public\_html/mysite/custom\_template.tpl} and getting the variable using the format: {$smarty.capture.myvariable\_name} so I answered my own question but Marcin got me on the right track so thanks for that! I spoke too soon. it appears I can only capture static text and not a "{foreach}" loop any ideas greatly appreciated
19,690,653
I am using the decorator pattern for a `List<WebElement>`.Part of this decoration entails using a proxy. When I call `get(index)` with an index that is out of bounds, it throws an `IndexOutOfBounds` exception, which is then caught by the proxy, and wrapped with an `UndeclaredThrowableException`. My understanding is that it should **only** do this if its a checked exception. `IndexOutOfBounds` is an *unchecked* exception, so why is it getting wrapped? It still gets wrapped even if I add `throws IndexOutOfBounds` to my `invoke` function. Here's my code: ``` @SuppressWarnings("unchecked") public WebElementList findWebElementList(final By by){ return new WebElementList( (List<WebElement>) Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class<?>[] { List.class }, new InvocationHandler() { // Lazy initialized instance of WebElement private List<WebElement> webElements; public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (webElements == null) { webElements = findElements(by); } return method.invoke(webElements, args); } }), driver); } ``` Here's part of my stacktrace: ``` java.lang.reflect.UndeclaredThrowableException at com.sun.proxy.$Proxy30.get(Unknown Source) at org.lds.ldsp.enhancements.WebElementList.get(WebElementList.java:29) ... Caused by: java.lang.IndexOutOfBoundsException: Index: 1, Size: 1 at java.util.ArrayList.rangeCheck(ArrayList.java:604) at java.util.ArrayList.get(ArrayList.java:382) ... 41 more ```
2013/10/30
[ "https://Stackoverflow.com/questions/19690653", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1769273/" ]
Vic Jang is right. You need to wrap the invocation in try-catch and rethrow the inner exception. ``` try { return method.invoke(webElements, args); } catch (InvocationTargetException ite) { throw ite.getCause(); } ``` The reason is that "Method.invoke" wraps in InvocationTargetException those exceptions which are thrown in the method's code. **java.lang.reflect.Method:** > > Throws: > > ... > > InvocationTargetException - if the underlying method > throws an exception. > > > **java.lang.reflect.InvocationTargetException:** > > InvocationTargetException is a checked exception that wraps an > exception thrown by an invoked method or constructor. > > > The proxy object's class doesn't have InvocationTargetException declared among its "throws". That leads to UndeclaredThrowableException.
I don't have enough reputation to comment. Your problem seems very similar to [this one](http://amitstechblog.wordpress.com/2011/07/24/java-proxies-and-undeclaredthrowableexception/) You can look at the solution there and see if that works. In short, you need to wrap your `method.invoke` into `try{}`, `catch` the exception, and `throw` it again.
56,372,208
I have two variables and want to assign same value to both the variables at the same time something like below: ``` var allGood: Boolean = false val deviceId: String = "3550200583" var isValidId: Boolean = false allGood = isValidId = deviceId.length > 0 && deviceId.length <= 16 ``` is there any way to achieve this?
2019/05/30
[ "https://Stackoverflow.com/questions/56372208", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3629588/" ]
Because assignment is not an expression in Kotlin, you can't do multiple assignments that way.  But there are other ways.  The most obvious is simply: ``` isValidId = deviceId.length > 0 && deviceId.length <= 16 allGood = isValidId ``` A more idiomatic (if longer) way is: ``` (deviceId.length > 0 && deviceId.length <= 16).let { allGood = it isValidId = it } ``` (By the way, you can simplify the condition to `deviceId.length in 1..16`.) There are a couple of reasons why Kotlin doesn't allow this.  The main one [is](https://discuss.kotlinlang.org/t/assignments-as-expressions/1564) that it's incompatible with the syntax for calling a function with named parameters: `fn(paramName = value)`.  But it also avoids any confusion between `=` and `==` (which could otherwise cause hard-to-spot bugs).  See also [here](https://discuss.kotlinlang.org/t/assignment-not-allow-in-while-expression/339/15).
Another way is to do it like this: ``` val deviceId: String = "3550200583"; val condition = deviceId.length > 0 && deviceId.length <= 16 var (allGood, isValidId) = arrayOf(condition, condition); ```
56,372,208
I have two variables and want to assign same value to both the variables at the same time something like below: ``` var allGood: Boolean = false val deviceId: String = "3550200583" var isValidId: Boolean = false allGood = isValidId = deviceId.length > 0 && deviceId.length <= 16 ``` is there any way to achieve this?
2019/05/30
[ "https://Stackoverflow.com/questions/56372208", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3629588/" ]
Because assignment is not an expression in Kotlin, you can't do multiple assignments that way.  But there are other ways.  The most obvious is simply: ``` isValidId = deviceId.length > 0 && deviceId.length <= 16 allGood = isValidId ``` A more idiomatic (if longer) way is: ``` (deviceId.length > 0 && deviceId.length <= 16).let { allGood = it isValidId = it } ``` (By the way, you can simplify the condition to `deviceId.length in 1..16`.) There are a couple of reasons why Kotlin doesn't allow this.  The main one [is](https://discuss.kotlinlang.org/t/assignments-as-expressions/1564) that it's incompatible with the syntax for calling a function with named parameters: `fn(paramName = value)`.  But it also avoids any confusion between `=` and `==` (which could otherwise cause hard-to-spot bugs).  See also [here](https://discuss.kotlinlang.org/t/assignment-not-allow-in-while-expression/339/15).
What about: ``` var allGood: Boolean = false val deviceId: String = ... val isValidId: Boolean = (deviceId.length in 1..16).also { allGood = it } ``` `.also` allows you to perform additional operations with the value that it receives and then returns the original value.
56,372,208
I have two variables and want to assign same value to both the variables at the same time something like below: ``` var allGood: Boolean = false val deviceId: String = "3550200583" var isValidId: Boolean = false allGood = isValidId = deviceId.length > 0 && deviceId.length <= 16 ``` is there any way to achieve this?
2019/05/30
[ "https://Stackoverflow.com/questions/56372208", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3629588/" ]
What about: ``` var allGood: Boolean = false val deviceId: String = ... val isValidId: Boolean = (deviceId.length in 1..16).also { allGood = it } ``` `.also` allows you to perform additional operations with the value that it receives and then returns the original value.
Another way is to do it like this: ``` val deviceId: String = "3550200583"; val condition = deviceId.length > 0 && deviceId.length <= 16 var (allGood, isValidId) = arrayOf(condition, condition); ```
28,044,180
I have looked on the web and I cannot find anything that helps me, all I can find is changing the characters into ASCII or Hexadecimal. However I would like to do it a different way. For example, say the string that got passed in was `abcdef`, I would like to have a key which changes these characters into another string such as `qwpolz`. Is there an easier way than declaring each character in the alphabet to be another character like: ``` Dim sText As String = "Hello" Dim sEncode As String = "" Dim iLength As Integer Dim i As Integer iLength = Len(sText) For i = 1 To iLength sEncode = sEncode ???? Next Return sEncode ``` And then have a very lengthy loop which checks for these loops? There must be a much simpler way. Can anybody help by pointing me in the right direction? Edit: Why downvote? Seriously, it's a legitimate question. Instead of downvoting for no reason, just move onto another question.
2015/01/20
[ "https://Stackoverflow.com/questions/28044180", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4366103/" ]
Because `%` is a format specifier escape sequence (as in `%d` would print an `int`). To get the program to print the actual symbol, you write `%%`. The same goes for `\` (although fundamentally different, you still need to to print one).
``` "%%" ``` in printf is an escaped '%' sign. See this Stack Overflow answer: *[How to escape the % (percent) sign in C's printf](https://stackoverflow.com/questions/1860159/how-to-escape-the-sign-in-cs-printf)*
28,044,180
I have looked on the web and I cannot find anything that helps me, all I can find is changing the characters into ASCII or Hexadecimal. However I would like to do it a different way. For example, say the string that got passed in was `abcdef`, I would like to have a key which changes these characters into another string such as `qwpolz`. Is there an easier way than declaring each character in the alphabet to be another character like: ``` Dim sText As String = "Hello" Dim sEncode As String = "" Dim iLength As Integer Dim i As Integer iLength = Len(sText) For i = 1 To iLength sEncode = sEncode ???? Next Return sEncode ``` And then have a very lengthy loop which checks for these loops? There must be a much simpler way. Can anybody help by pointing me in the right direction? Edit: Why downvote? Seriously, it's a legitimate question. Instead of downvoting for no reason, just move onto another question.
2015/01/20
[ "https://Stackoverflow.com/questions/28044180", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4366103/" ]
Because `%` is a format specifier escape sequence (as in `%d` would print an `int`). To get the program to print the actual symbol, you write `%%`. The same goes for `\` (although fundamentally different, you still need to to print one).
The `"%"` is a special character, and it's used to specify format specifiers. To print a literal `"%"`, you need a sequence of two `"%%"`. The `"%"` is used in the format string to specify a placeholder that will be replaced by a corresponding argument passed to the functions that format their output, like `printf()`/`fprintf()`/`sprintf()`. So how can you print a literal `"%"`? * Escaping it with another `"%"`. If you for example wish to print an integral percentage value, you need to specify as the `"%d"` the format specifier and a literal `"%"`, so you would do it this way: ``` printf("%d%%\n", value): ``` Read [this](http://man7.org/linux/man-pages/man3/printf.3.html) to learn more about it.
28,044,180
I have looked on the web and I cannot find anything that helps me, all I can find is changing the characters into ASCII or Hexadecimal. However I would like to do it a different way. For example, say the string that got passed in was `abcdef`, I would like to have a key which changes these characters into another string such as `qwpolz`. Is there an easier way than declaring each character in the alphabet to be another character like: ``` Dim sText As String = "Hello" Dim sEncode As String = "" Dim iLength As Integer Dim i As Integer iLength = Len(sText) For i = 1 To iLength sEncode = sEncode ???? Next Return sEncode ``` And then have a very lengthy loop which checks for these loops? There must be a much simpler way. Can anybody help by pointing me in the right direction? Edit: Why downvote? Seriously, it's a legitimate question. Instead of downvoting for no reason, just move onto another question.
2015/01/20
[ "https://Stackoverflow.com/questions/28044180", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4366103/" ]
The `"%"` is a special character, and it's used to specify format specifiers. To print a literal `"%"`, you need a sequence of two `"%%"`. The `"%"` is used in the format string to specify a placeholder that will be replaced by a corresponding argument passed to the functions that format their output, like `printf()`/`fprintf()`/`sprintf()`. So how can you print a literal `"%"`? * Escaping it with another `"%"`. If you for example wish to print an integral percentage value, you need to specify as the `"%d"` the format specifier and a literal `"%"`, so you would do it this way: ``` printf("%d%%\n", value): ``` Read [this](http://man7.org/linux/man-pages/man3/printf.3.html) to learn more about it.
``` "%%" ``` in printf is an escaped '%' sign. See this Stack Overflow answer: *[How to escape the % (percent) sign in C's printf](https://stackoverflow.com/questions/1860159/how-to-escape-the-sign-in-cs-printf)*
55,922,994
I'm currently working on a game in monogame. The game is heavily based on clicking buttons and this is where the problem occurs. Whenever I hold down the left mouse button and then move it over a button in the game, that button gets clicked instantly. I've tried to fix the issue in many ways, by rearrange the if statements in different ways, adding an extra bool to check if the mouse button is clicked, etc.. but without any luck. Haven't found any solutions anywhere either. ``` public override void Update(GameTime gameTime) { MouseState state = Mouse.GetState(); if (new Rectangle((position - ElementCenter).ToPoint(), sprite.Bounds.Size) .Contains(state.Position) && oldState.LeftButton == ButtonState.Released) { renderColor = Color.LightSlateGray; if (state.LeftButton == ButtonState.Pressed && oldState.LeftButton == ButtonState.Released) { switch (button) { case "UI/submit": if (GameWorld.Instance.Team.UserTeamName.Length > 0) { GameWorld.Instance.SubmitTeamName(); } break; case "UI/teammanager": GameWorld.Instance.TeamManager(); break; default: break; } } } else { renderColor = Color.White; } oldState = state; } ``` Ideally I would like that a button gets clicked only if the left mouse button has been released before clicking a button.
2019/04/30
[ "https://Stackoverflow.com/questions/55922994", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10792784/" ]
If `oldState` is declared as instance field, different instances of this class will have different versions of it. I.e., the old state may get lost. Declare `oldState` as `static`! ``` private static MouseState oldState = Mouse.GetState(); ```
I usually use a class like this to read the input ``` public class InputManager { KeyboardState currentKeyboard, previousKeyboard; MouseState currentMouse, previousMouse; public bool LeftKeyIsHeldDown { get; private set; } public bool RightKeyIsHeldDown { get; private set; } public bool JumpWasJustPressed { get; private set; } public bool FireWasJustPressed { get; private set; } public void Update() { previousKeyboard = currentKeyboard; currentKeyboard = Keyboard.GetState(); previousMouse = currentMouse; currentMouse = Mouse.GetState(); LeftKeyIsHeldDown = currentKeyboard.IsKeyDown(Keys.A); RightKeyIsHeldDown = currentKeyboard.IsKeyDown(Keys.D); JumpWasJustPressed = currentKeyboard.IsKeyDown(Keys.Space) && previousKeyboard.IsKeyUp(Keys.Space); FireWasJustPressed = currentMouse.LeftButton == ButtonState.Pressed && previousMouse.LeftButton == ButtonState.Released; } } ```
16,436,094
I have a code some thing like this ``` dxMemOrdered : TdxMemData; while not qrySandbox2.EOF do begin dxMemOrdered.append; dxMemOrderedTotal.asCurrency := qrySandbox2.FieldByName('TOTAL').asCurrency; dxMemOrdered.post; qrySandbox2.Next; end; ``` this code executes in a thread. When there are huge records say "400000" it is taking around 25 minutes to parse through it. Is there any way that i can reduce the size by optimizing the loop? Any help would be appreciated. **Update** Based on the suggestions i made the following changes ``` dxMemOrdered : TdxMemData; qrySandbox2.DisableControls; while not qrySandbox2.Recordset.EOF do begin dxMemOrdered.append; dxMemOrderedTotal.asCurrency := Recordset.Fields['TOTAL'].Value; dxMemOrdered.post; qrySandbox2.Next; end; qrySandbox2.EnableControls; ``` and my output time have improved from 15 mins to 2 mins. Thank you guys
2013/05/08
[ "https://Stackoverflow.com/questions/16436094", "https://Stackoverflow.com", "https://Stackoverflow.com/users/462467/" ]
Some ideas in order of performance gain vs work to do by you: 1) Check if the SQL dialect that you are using lets you use queries that directly SELECT from/INSERT to. This depends on the database you're using. 2) Make sure that if your datasets are not coupled to visual controls, that you call DisableControls/EnableControls around this loop 3) Does this code have to run in the main program thread? Maybe you can send if off to a separate thread while the user/program continues doing something else 4) When you have to deal with really large data, bulk insertion is the way to go. Many databases have options to bulk insert data from text files. Writing to a text file first and then bulk inserting is way faster than individual inserts. Again, this depends on your database type. [Edit: I just see you inserting the info that it's TdxMemData, so some of these no longer apply. And you're already threading, missed that ;-). I leave this suggestions in for other readers with similar problems]
Without seeing more code, the only suggestion I can make is make sure that any visual control that is using the memory table is disabled. Suppose you have a cxgrid called `Grid` that is linked to your dxMemOrdered memory table: ``` var dxMemOrdered: TdxMemData; ... Grid.BeginUpdate; try while not qrySandbox2.EOF do begin dxMemOrdered.append; dxMemOrderedTotal.asCurrency := qrySandbox2.FieldByName('TOTAL').asCurrency; dxMemOrdered.Post; qrySandbox2.Next; end; finally Grid.EndUpdate; end; ```
16,436,094
I have a code some thing like this ``` dxMemOrdered : TdxMemData; while not qrySandbox2.EOF do begin dxMemOrdered.append; dxMemOrderedTotal.asCurrency := qrySandbox2.FieldByName('TOTAL').asCurrency; dxMemOrdered.post; qrySandbox2.Next; end; ``` this code executes in a thread. When there are huge records say "400000" it is taking around 25 minutes to parse through it. Is there any way that i can reduce the size by optimizing the loop? Any help would be appreciated. **Update** Based on the suggestions i made the following changes ``` dxMemOrdered : TdxMemData; qrySandbox2.DisableControls; while not qrySandbox2.Recordset.EOF do begin dxMemOrdered.append; dxMemOrderedTotal.asCurrency := Recordset.Fields['TOTAL'].Value; dxMemOrdered.post; qrySandbox2.Next; end; qrySandbox2.EnableControls; ``` and my output time have improved from 15 mins to 2 mins. Thank you guys
2013/05/08
[ "https://Stackoverflow.com/questions/16436094", "https://Stackoverflow.com", "https://Stackoverflow.com/users/462467/" ]
Some ideas in order of performance gain vs work to do by you: 1) Check if the SQL dialect that you are using lets you use queries that directly SELECT from/INSERT to. This depends on the database you're using. 2) Make sure that if your datasets are not coupled to visual controls, that you call DisableControls/EnableControls around this loop 3) Does this code have to run in the main program thread? Maybe you can send if off to a separate thread while the user/program continues doing something else 4) When you have to deal with really large data, bulk insertion is the way to go. Many databases have options to bulk insert data from text files. Writing to a text file first and then bulk inserting is way faster than individual inserts. Again, this depends on your database type. [Edit: I just see you inserting the info that it's TdxMemData, so some of these no longer apply. And you're already threading, missed that ;-). I leave this suggestions in for other readers with similar problems]
It's much better to let SQL do the work instead of iterating though a loop in Delphi. Try a query such as ``` insert into dxMemOrdered (total) select total from qrySandbox2 ``` Is 'total' the only field in dxMemOrdered? I hope that it's not the primary key otherwise you are likely to have collisions, meaning that rows will not be added.
16,436,094
I have a code some thing like this ``` dxMemOrdered : TdxMemData; while not qrySandbox2.EOF do begin dxMemOrdered.append; dxMemOrderedTotal.asCurrency := qrySandbox2.FieldByName('TOTAL').asCurrency; dxMemOrdered.post; qrySandbox2.Next; end; ``` this code executes in a thread. When there are huge records say "400000" it is taking around 25 minutes to parse through it. Is there any way that i can reduce the size by optimizing the loop? Any help would be appreciated. **Update** Based on the suggestions i made the following changes ``` dxMemOrdered : TdxMemData; qrySandbox2.DisableControls; while not qrySandbox2.Recordset.EOF do begin dxMemOrdered.append; dxMemOrderedTotal.asCurrency := Recordset.Fields['TOTAL'].Value; dxMemOrdered.post; qrySandbox2.Next; end; qrySandbox2.EnableControls; ``` and my output time have improved from 15 mins to 2 mins. Thank you guys
2013/05/08
[ "https://Stackoverflow.com/questions/16436094", "https://Stackoverflow.com", "https://Stackoverflow.com/users/462467/" ]
Some ideas in order of performance gain vs work to do by you: 1) Check if the SQL dialect that you are using lets you use queries that directly SELECT from/INSERT to. This depends on the database you're using. 2) Make sure that if your datasets are not coupled to visual controls, that you call DisableControls/EnableControls around this loop 3) Does this code have to run in the main program thread? Maybe you can send if off to a separate thread while the user/program continues doing something else 4) When you have to deal with really large data, bulk insertion is the way to go. Many databases have options to bulk insert data from text files. Writing to a text file first and then bulk inserting is way faster than individual inserts. Again, this depends on your database type. [Edit: I just see you inserting the info that it's TdxMemData, so some of these no longer apply. And you're already threading, missed that ;-). I leave this suggestions in for other readers with similar problems]
There's actually a lot you could do to speed up your thread. The first would be to look at the problem in a broader perspective: * Am I fetching data from a cached / fast disk, possibly moved in memory? * Am I doing the right thing, when aggregating totals by hand? SQL engines are expecially optimized to do those things, all you'd need to do is to define an additional logical field where to store the SQL aggregated result. Another little optimization that may bring an improvement over large amounts of looping is to not use constructs like: * Recordset.Fields['TOTAL'].Value * Recordset.FieldByName('TOTAL').Value but to add the fields with the fields editor and then directly accessing the right field. You'll save a whole loop through the fields collection, that otherwise is performed on every field, on every next record.
16,436,094
I have a code some thing like this ``` dxMemOrdered : TdxMemData; while not qrySandbox2.EOF do begin dxMemOrdered.append; dxMemOrderedTotal.asCurrency := qrySandbox2.FieldByName('TOTAL').asCurrency; dxMemOrdered.post; qrySandbox2.Next; end; ``` this code executes in a thread. When there are huge records say "400000" it is taking around 25 minutes to parse through it. Is there any way that i can reduce the size by optimizing the loop? Any help would be appreciated. **Update** Based on the suggestions i made the following changes ``` dxMemOrdered : TdxMemData; qrySandbox2.DisableControls; while not qrySandbox2.Recordset.EOF do begin dxMemOrdered.append; dxMemOrderedTotal.asCurrency := Recordset.Fields['TOTAL'].Value; dxMemOrdered.post; qrySandbox2.Next; end; qrySandbox2.EnableControls; ``` and my output time have improved from 15 mins to 2 mins. Thank you guys
2013/05/08
[ "https://Stackoverflow.com/questions/16436094", "https://Stackoverflow.com", "https://Stackoverflow.com/users/462467/" ]
Without seeing more code, the only suggestion I can make is make sure that any visual control that is using the memory table is disabled. Suppose you have a cxgrid called `Grid` that is linked to your dxMemOrdered memory table: ``` var dxMemOrdered: TdxMemData; ... Grid.BeginUpdate; try while not qrySandbox2.EOF do begin dxMemOrdered.append; dxMemOrderedTotal.asCurrency := qrySandbox2.FieldByName('TOTAL').asCurrency; dxMemOrdered.Post; qrySandbox2.Next; end; finally Grid.EndUpdate; end; ```
It's much better to let SQL do the work instead of iterating though a loop in Delphi. Try a query such as ``` insert into dxMemOrdered (total) select total from qrySandbox2 ``` Is 'total' the only field in dxMemOrdered? I hope that it's not the primary key otherwise you are likely to have collisions, meaning that rows will not be added.
16,436,094
I have a code some thing like this ``` dxMemOrdered : TdxMemData; while not qrySandbox2.EOF do begin dxMemOrdered.append; dxMemOrderedTotal.asCurrency := qrySandbox2.FieldByName('TOTAL').asCurrency; dxMemOrdered.post; qrySandbox2.Next; end; ``` this code executes in a thread. When there are huge records say "400000" it is taking around 25 minutes to parse through it. Is there any way that i can reduce the size by optimizing the loop? Any help would be appreciated. **Update** Based on the suggestions i made the following changes ``` dxMemOrdered : TdxMemData; qrySandbox2.DisableControls; while not qrySandbox2.Recordset.EOF do begin dxMemOrdered.append; dxMemOrderedTotal.asCurrency := Recordset.Fields['TOTAL'].Value; dxMemOrdered.post; qrySandbox2.Next; end; qrySandbox2.EnableControls; ``` and my output time have improved from 15 mins to 2 mins. Thank you guys
2013/05/08
[ "https://Stackoverflow.com/questions/16436094", "https://Stackoverflow.com", "https://Stackoverflow.com/users/462467/" ]
Without seeing more code, the only suggestion I can make is make sure that any visual control that is using the memory table is disabled. Suppose you have a cxgrid called `Grid` that is linked to your dxMemOrdered memory table: ``` var dxMemOrdered: TdxMemData; ... Grid.BeginUpdate; try while not qrySandbox2.EOF do begin dxMemOrdered.append; dxMemOrderedTotal.asCurrency := qrySandbox2.FieldByName('TOTAL').asCurrency; dxMemOrdered.Post; qrySandbox2.Next; end; finally Grid.EndUpdate; end; ```
There's actually a lot you could do to speed up your thread. The first would be to look at the problem in a broader perspective: * Am I fetching data from a cached / fast disk, possibly moved in memory? * Am I doing the right thing, when aggregating totals by hand? SQL engines are expecially optimized to do those things, all you'd need to do is to define an additional logical field where to store the SQL aggregated result. Another little optimization that may bring an improvement over large amounts of looping is to not use constructs like: * Recordset.Fields['TOTAL'].Value * Recordset.FieldByName('TOTAL').Value but to add the fields with the fields editor and then directly accessing the right field. You'll save a whole loop through the fields collection, that otherwise is performed on every field, on every next record.
57,582,901
I am trying to make a new version of AuthenticationStateProvider so that I can use the data already in my db. I called it ServerAuthenticationStateProvider: ``` using Microsoft.AspNetCore.Components; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; namespace BadgerWatchWeb.Services { public class ServerAuthenticationStateProvider : AuthenticationStateProvider { string UserId; string Password; bool IsAuthenticated = false; public void LoadUser(string _UserId, string _Password) { UserId = _UserId; Password = _Password; } public async Task LoadUserData() { var securityService = new SharedServiceLogic.Security(); try { var passwordCheck = await securityService.ValidatePassword(UserId, Password); IsAuthenticated = passwordCheck == true ? true : false; } catch(Exception ex) { Console.WriteLine(ex); } } public override async Task<AuthenticationState> GetAuthenticationStateAsync() { var userService = new UserService(); var identity = IsAuthenticated ? new ClaimsIdentity(await userService.GetClaims(UserId)) : new ClaimsIdentity(); var result = new AuthenticationState(new ClaimsPrincipal(identity)); return result; } } ``` } My configure services looks like: ``` public void ConfigureServices(IServiceCollection services) { services.AddRazorPages(); services.AddServerSideBlazor(); services.AddSingleton<UserService>(); services.AddScoped<AuthenticationStateProvider, ServerAuthenticationStateProvider>(); services.AddAuthorizationCore(); } ``` I then inject `@inject ServerAuthenticationStateProvider AuthenticationStateProvider` into my razor view file. When I run the code I get `InvalidOperationException: Cannot provide a value for property 'AuthenticationStateProvider' on type 'BadgerWatchWeb.Pages.Index'. There is no registered service of type 'BadgerWatchWeb.Services.ServerAuthenticationStateProvider'.`
2019/08/21
[ "https://Stackoverflow.com/questions/57582901", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You should replace ``` @inject ServerAuthenticationStateProvider AuthenticationStateProvider ``` with ``` @inject AuthenticationStateProvider AuthenticationStateProvider ``` because that is how you registered it.
Note: When you add a service to the DI container, the left-side parameter should be an interface ( or an abstract class), whereas the right-side parameter should be the concrete class, like the following: ``` services.AddScoped<IJSRuntime, RemoteJSRuntime>(); ``` And you can inject the type IJSRuntime into your component like this: ``` @inject IJSRuntime JSRuntime ``` IJSRuntime is the type to inject, JSRuntime is the name of the property which will contain the injected instance Why do you call your class **ServerAuthenticationStateProvider** This is the very same name of the AuthenticationStateProvider added to your DI container by the Blazor framework: *ComponentServiceCollectionExtensions.AddServerSideBlazor method:* ``` services.AddScoped<AuthenticationStateProvider, ServerAuthenticationStateProvider>(); ``` Please, modify your app according to the comments above, run your app, and come to report of errors,if any... **Important** * Make sure you understand the role and functionality of the AuthenticationStateProvider type, how it is populated with the authentication state data, when, and by whom. You should have derived your custom AuthenticationStateProvider from the ServerAuthenticationStateProvider type defined by Blazor, as this type has a method which is called by the CircuitHost to set the authentication state... * I did not peruse the code in your custom implementation of AuthenticationStateProvider, but I'd say that it has to contain logic that only pertains to authentication state, and nothing else (separation of concerns). And, yes, use it only if is necessary. Hope this helps...
57,582,901
I am trying to make a new version of AuthenticationStateProvider so that I can use the data already in my db. I called it ServerAuthenticationStateProvider: ``` using Microsoft.AspNetCore.Components; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; namespace BadgerWatchWeb.Services { public class ServerAuthenticationStateProvider : AuthenticationStateProvider { string UserId; string Password; bool IsAuthenticated = false; public void LoadUser(string _UserId, string _Password) { UserId = _UserId; Password = _Password; } public async Task LoadUserData() { var securityService = new SharedServiceLogic.Security(); try { var passwordCheck = await securityService.ValidatePassword(UserId, Password); IsAuthenticated = passwordCheck == true ? true : false; } catch(Exception ex) { Console.WriteLine(ex); } } public override async Task<AuthenticationState> GetAuthenticationStateAsync() { var userService = new UserService(); var identity = IsAuthenticated ? new ClaimsIdentity(await userService.GetClaims(UserId)) : new ClaimsIdentity(); var result = new AuthenticationState(new ClaimsPrincipal(identity)); return result; } } ``` } My configure services looks like: ``` public void ConfigureServices(IServiceCollection services) { services.AddRazorPages(); services.AddServerSideBlazor(); services.AddSingleton<UserService>(); services.AddScoped<AuthenticationStateProvider, ServerAuthenticationStateProvider>(); services.AddAuthorizationCore(); } ``` I then inject `@inject ServerAuthenticationStateProvider AuthenticationStateProvider` into my razor view file. When I run the code I get `InvalidOperationException: Cannot provide a value for property 'AuthenticationStateProvider' on type 'BadgerWatchWeb.Pages.Index'. There is no registered service of type 'BadgerWatchWeb.Services.ServerAuthenticationStateProvider'.`
2019/08/21
[ "https://Stackoverflow.com/questions/57582901", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You should replace ``` @inject ServerAuthenticationStateProvider AuthenticationStateProvider ``` with ``` @inject AuthenticationStateProvider AuthenticationStateProvider ``` because that is how you registered it.
In my case it didn't work because i had a **mutated vowel** in my **Database Name**: My db name was "Bücher.dbo" and the "**ü**" wasn't accepted. I changed the name to "Books.dbo" and it worked perfectly fine.
57,582,901
I am trying to make a new version of AuthenticationStateProvider so that I can use the data already in my db. I called it ServerAuthenticationStateProvider: ``` using Microsoft.AspNetCore.Components; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; namespace BadgerWatchWeb.Services { public class ServerAuthenticationStateProvider : AuthenticationStateProvider { string UserId; string Password; bool IsAuthenticated = false; public void LoadUser(string _UserId, string _Password) { UserId = _UserId; Password = _Password; } public async Task LoadUserData() { var securityService = new SharedServiceLogic.Security(); try { var passwordCheck = await securityService.ValidatePassword(UserId, Password); IsAuthenticated = passwordCheck == true ? true : false; } catch(Exception ex) { Console.WriteLine(ex); } } public override async Task<AuthenticationState> GetAuthenticationStateAsync() { var userService = new UserService(); var identity = IsAuthenticated ? new ClaimsIdentity(await userService.GetClaims(UserId)) : new ClaimsIdentity(); var result = new AuthenticationState(new ClaimsPrincipal(identity)); return result; } } ``` } My configure services looks like: ``` public void ConfigureServices(IServiceCollection services) { services.AddRazorPages(); services.AddServerSideBlazor(); services.AddSingleton<UserService>(); services.AddScoped<AuthenticationStateProvider, ServerAuthenticationStateProvider>(); services.AddAuthorizationCore(); } ``` I then inject `@inject ServerAuthenticationStateProvider AuthenticationStateProvider` into my razor view file. When I run the code I get `InvalidOperationException: Cannot provide a value for property 'AuthenticationStateProvider' on type 'BadgerWatchWeb.Pages.Index'. There is no registered service of type 'BadgerWatchWeb.Services.ServerAuthenticationStateProvider'.`
2019/08/21
[ "https://Stackoverflow.com/questions/57582901", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Note: When you add a service to the DI container, the left-side parameter should be an interface ( or an abstract class), whereas the right-side parameter should be the concrete class, like the following: ``` services.AddScoped<IJSRuntime, RemoteJSRuntime>(); ``` And you can inject the type IJSRuntime into your component like this: ``` @inject IJSRuntime JSRuntime ``` IJSRuntime is the type to inject, JSRuntime is the name of the property which will contain the injected instance Why do you call your class **ServerAuthenticationStateProvider** This is the very same name of the AuthenticationStateProvider added to your DI container by the Blazor framework: *ComponentServiceCollectionExtensions.AddServerSideBlazor method:* ``` services.AddScoped<AuthenticationStateProvider, ServerAuthenticationStateProvider>(); ``` Please, modify your app according to the comments above, run your app, and come to report of errors,if any... **Important** * Make sure you understand the role and functionality of the AuthenticationStateProvider type, how it is populated with the authentication state data, when, and by whom. You should have derived your custom AuthenticationStateProvider from the ServerAuthenticationStateProvider type defined by Blazor, as this type has a method which is called by the CircuitHost to set the authentication state... * I did not peruse the code in your custom implementation of AuthenticationStateProvider, but I'd say that it has to contain logic that only pertains to authentication state, and nothing else (separation of concerns). And, yes, use it only if is necessary. Hope this helps...
In my case it didn't work because i had a **mutated vowel** in my **Database Name**: My db name was "Bücher.dbo" and the "**ü**" wasn't accepted. I changed the name to "Books.dbo" and it worked perfectly fine.
36,343,214
I am trying to select specific columns from a large tab-delimited CSV file and output only certain columns to a new CSV file. Furthermore, I want to recode the data as this happens. If the cell has a value of 0 then just output 0. However, if the cell has a value of greater than 0, then just output 1 (i.e., all values greater than 0 are coded as 1). Here's what I have so far: ``` import csv outputFile = open('output.csv', 'wb') outputWriter = csv.writer(outputFile) included_cols = range(9,2844) with open('source.txt', 'rb') as f: reader = csv.reader(f, delimiter='\t') for row in reader: content = list(row[i] for i in included_cols) outputWriter.writerow(content) ``` The first issue I am having is that I want to also take from column 6. I wasn't sure how to write column 6 and then columns 9-2844. Second, I wasn't sure how to do the recoding on the fly as I write the new CSV.
2016/03/31
[ "https://Stackoverflow.com/questions/36343214", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5323539/" ]
The first operation in most `Throwable` constructors is to [fill in the stack trace,](https://docs.oracle.com/javase/8/docs/api/java/lang/Throwable.html#fillInStackTrace--) which is where most of the expense is. There is, however, a protected constructor with a flag to disable the stack trace. [This constructor](https://docs.oracle.com/javase/8/docs/api/java/lang/Exception.html#Exception-java.lang.String-java.lang.Throwable-boolean-boolean-) is accessible when extending `Exception` as well. If you create a custom exception type, you can avoid the stack trace creation and get better performance at the expense of less information. If you create a single exception of any type by normal means, you can re-throw it many times without the overhead of filling in the stack trace. However, its stack trace will reflect where it was constructed, not where it was thrown in a particular instance. Current versions of Java make some attempts to optimize stack trace creation. Native code is invoked to fill in the stack trace, which records the trace in a lighter-weight, native structure. Corresponding Java [`StackTraceElement`](https://docs.oracle.com/javase/8/docs/api/java/lang/StackTraceElement.html) objects are lazily created from this record only when the `getStackTrace()`, `printStackTrace()`, or other methods that require the trace are called. If you eliminate stack trace generation, the other main cost is unwinding the stack between the throw and the catch. The fewer intervening frames encountered before the exception is caught, the faster this will be. Design your program so that exceptions are thrown only in truly exceptional cases, and optimizations like these are hard to justify.
Using @AustinD's answer as a starting point, I made some tweaks. Code at the bottom. In addition to adding the case where one Exception instance is thrown repeatedly, I also turned off compiler optimization so that we can get accurate performance results. I added `-Djava.compiler=NONE` to the VM arguments, as per [this answer](https://stackoverflow.com/a/5242430/1021426). (In eclipse, edit the Run Configuration → Arguments to set this VM argument) The results: ``` new Exception + throw/catch = 643.5 new Exception only = 510.7 throw/catch only = 115.2 new String (benchmark) = 669.8 ``` So creating the exception costs about 5x as much as throwing + catching it. Assuming the compiler doesn't optimize away much of the cost. For comparison, here's the same test run without disabling optimization: ``` new Exception + throw/catch = 382.6 new Exception only = 379.5 throw/catch only = 0.3 new String (benchmark) = 15.6 ``` Code: ``` public class ExceptionPerformanceTest { private static final int NUM_TRIES = 1000000; public static void main(String[] args) { double numIterations = 10; long exceptionPlusCatchTime = 0, excepTime = 0, strTime = 0, throwTime = 0; for (int i = 0; i < numIterations; i++) { exceptionPlusCatchTime += exceptionPlusCatchBlock(); excepTime += createException(); throwTime += catchBlock(); strTime += createString(); } System.out.println("new Exception + throw/catch = " + exceptionPlusCatchTime / numIterations); System.out.println("new Exception only = " + excepTime / numIterations); System.out.println("throw/catch only = " + throwTime / numIterations); System.out.println("new String (benchmark) = " + strTime / numIterations); } private static long exceptionPlusCatchBlock() { long start = System.currentTimeMillis(); for (int i = 0; i < NUM_TRIES; i++) { try { throw new Exception(); } catch (Exception e) { // do nothing } } long stop = System.currentTimeMillis(); return stop - start; } private static long createException() { long start = System.currentTimeMillis(); for (int i = 0; i < NUM_TRIES; i++) { Exception e = new Exception(); } long stop = System.currentTimeMillis(); return stop - start; } private static long createString() { long start = System.currentTimeMillis(); for (int i = 0; i < NUM_TRIES; i++) { Object o = new String("" + i); } long stop = System.currentTimeMillis(); return stop - start; } private static long catchBlock() { Exception ex = new Exception(); //Instantiated here long start = System.currentTimeMillis(); for (int i = 0; i < NUM_TRIES; i++) { try { throw ex; //repeatedly thrown } catch (Exception e) { // do nothing } } long stop = System.currentTimeMillis(); return stop - start; } } ```
36,343,214
I am trying to select specific columns from a large tab-delimited CSV file and output only certain columns to a new CSV file. Furthermore, I want to recode the data as this happens. If the cell has a value of 0 then just output 0. However, if the cell has a value of greater than 0, then just output 1 (i.e., all values greater than 0 are coded as 1). Here's what I have so far: ``` import csv outputFile = open('output.csv', 'wb') outputWriter = csv.writer(outputFile) included_cols = range(9,2844) with open('source.txt', 'rb') as f: reader = csv.reader(f, delimiter='\t') for row in reader: content = list(row[i] for i in included_cols) outputWriter.writerow(content) ``` The first issue I am having is that I want to also take from column 6. I wasn't sure how to write column 6 and then columns 9-2844. Second, I wasn't sure how to do the recoding on the fly as I write the new CSV.
2016/03/31
[ "https://Stackoverflow.com/questions/36343214", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5323539/" ]
**Creating** an exception object is not *necessarily* more expensive than creating other regular objects. The main cost is hidden in native [`fillInStackTrace`](http://docs.oracle.com/javase/8/docs/api/java/lang/Throwable.html#fillInStackTrace--) method which walks through the call stack and collects all required information to build a stack trace: classes, method names, line numbers etc. Most of `Throwable` constructors implicitly call `fillInStackTrace`. This is where the idea that creating exceptions is slow comes from. However, there is one [constructor](http://docs.oracle.com/javase/8/docs/api/java/lang/Throwable.html#Throwable-java.lang.String-java.lang.Throwable-boolean-boolean-) to create a `Throwable` without a stack trace. It allows you to make throwables that are very fast to instantiate. Another way to create lightweight exceptions is to override `fillInStackTrace`. --- Now what about **throwing** an exception? In fact, it depends on where a thrown exception is **caught**. If it is caught in the same method (or, more precisely, in the same context, since the context can include several methods due to inlining), then `throw` is as fast and simple as `goto` (of course, after JIT compilation). However if a `catch` block is somewhere deeper in the stack, then JVM needs to unwind the stack frames, and this can take significantly longer. It takes even longer, if there are `synchronized` blocks or methods involved, because unwinding implies releasing of monitors owned by removed stack frames. --- I could confirm the above statements by proper benchmarks, but fortunately I don't need to do this, since all the aspects are already perfectly covered in the post of HotSpot's performance engineer Alexey Shipilev: [The Exceptional Performance of Lil' Exception](http://shipilev.net/blog/2014/exceptional-performance/).
The creation of the `Exception` with a `null` stack trace takes about as much time as the `throw` and `try-catch` block together. However, **filling the stack trace takes on average 5x longer**. I created the following benchmark to demonstrate the impact on performance. I added the `-Djava.compiler=NONE` to the Run Configuration to disable compiler optimization. To measure the impact of building the stack trace, I extended the `Exception` class to take advantage of the stack-free constructor: ``` class NoStackException extends Exception{ public NoStackException() { super("",null,false,false); } } ``` The benchmark code is as follows: ``` public class ExceptionBenchmark { private static final int NUM_TRIES = 100000; public static void main(String[] args) { long throwCatchTime = 0, newExceptionTime = 0, newObjectTime = 0, noStackExceptionTime = 0; for (int i = 0; i < 30; i++) { throwCatchTime += throwCatchLoop(); newExceptionTime += newExceptionLoop(); newObjectTime += newObjectLoop(); noStackExceptionTime += newNoStackExceptionLoop(); } System.out.println("throwCatchTime = " + throwCatchTime / 30); System.out.println("newExceptionTime = " + newExceptionTime / 30); System.out.println("newStringTime = " + newObjectTime / 30); System.out.println("noStackExceptionTime = " + noStackExceptionTime / 30); } private static long throwCatchLoop() { Exception ex = new Exception(); //Instantiated here long start = System.currentTimeMillis(); for (int i = 0; i < NUM_TRIES; i++) { try { throw ex; //repeatedly thrown } catch (Exception e) { // do nothing } } long stop = System.currentTimeMillis(); return stop - start; } private static long newExceptionLoop() { long start = System.currentTimeMillis(); for (int i = 0; i < NUM_TRIES; i++) { Exception e = new Exception(); } long stop = System.currentTimeMillis(); return stop - start; } private static long newObjectLoop() { long start = System.currentTimeMillis(); for (int i = 0; i < NUM_TRIES; i++) { Object o = new Object(); } long stop = System.currentTimeMillis(); return stop - start; } private static long newNoStackExceptionLoop() { long start = System.currentTimeMillis(); for (int i = 0; i < NUM_TRIES; i++) { NoStackException e = new NoStackException(); } long stop = System.currentTimeMillis(); return stop - start; } } ``` **Output:** ``` throwCatchTime = 19 newExceptionTime = 77 newObjectTime = 3 noStackExceptionTime = 15 ``` This implies that creating a `NoStackException` is approximately as expensive as repeatedly throwing the same `Exception`. It also shows that creating an `Exception` and filling its stack trace takes approximately **4x** longer.
36,343,214
I am trying to select specific columns from a large tab-delimited CSV file and output only certain columns to a new CSV file. Furthermore, I want to recode the data as this happens. If the cell has a value of 0 then just output 0. However, if the cell has a value of greater than 0, then just output 1 (i.e., all values greater than 0 are coded as 1). Here's what I have so far: ``` import csv outputFile = open('output.csv', 'wb') outputWriter = csv.writer(outputFile) included_cols = range(9,2844) with open('source.txt', 'rb') as f: reader = csv.reader(f, delimiter='\t') for row in reader: content = list(row[i] for i in included_cols) outputWriter.writerow(content) ``` The first issue I am having is that I want to also take from column 6. I wasn't sure how to write column 6 and then columns 9-2844. Second, I wasn't sure how to do the recoding on the fly as I write the new CSV.
2016/03/31
[ "https://Stackoverflow.com/questions/36343214", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5323539/" ]
The creation of the `Exception` with a `null` stack trace takes about as much time as the `throw` and `try-catch` block together. However, **filling the stack trace takes on average 5x longer**. I created the following benchmark to demonstrate the impact on performance. I added the `-Djava.compiler=NONE` to the Run Configuration to disable compiler optimization. To measure the impact of building the stack trace, I extended the `Exception` class to take advantage of the stack-free constructor: ``` class NoStackException extends Exception{ public NoStackException() { super("",null,false,false); } } ``` The benchmark code is as follows: ``` public class ExceptionBenchmark { private static final int NUM_TRIES = 100000; public static void main(String[] args) { long throwCatchTime = 0, newExceptionTime = 0, newObjectTime = 0, noStackExceptionTime = 0; for (int i = 0; i < 30; i++) { throwCatchTime += throwCatchLoop(); newExceptionTime += newExceptionLoop(); newObjectTime += newObjectLoop(); noStackExceptionTime += newNoStackExceptionLoop(); } System.out.println("throwCatchTime = " + throwCatchTime / 30); System.out.println("newExceptionTime = " + newExceptionTime / 30); System.out.println("newStringTime = " + newObjectTime / 30); System.out.println("noStackExceptionTime = " + noStackExceptionTime / 30); } private static long throwCatchLoop() { Exception ex = new Exception(); //Instantiated here long start = System.currentTimeMillis(); for (int i = 0; i < NUM_TRIES; i++) { try { throw ex; //repeatedly thrown } catch (Exception e) { // do nothing } } long stop = System.currentTimeMillis(); return stop - start; } private static long newExceptionLoop() { long start = System.currentTimeMillis(); for (int i = 0; i < NUM_TRIES; i++) { Exception e = new Exception(); } long stop = System.currentTimeMillis(); return stop - start; } private static long newObjectLoop() { long start = System.currentTimeMillis(); for (int i = 0; i < NUM_TRIES; i++) { Object o = new Object(); } long stop = System.currentTimeMillis(); return stop - start; } private static long newNoStackExceptionLoop() { long start = System.currentTimeMillis(); for (int i = 0; i < NUM_TRIES; i++) { NoStackException e = new NoStackException(); } long stop = System.currentTimeMillis(); return stop - start; } } ``` **Output:** ``` throwCatchTime = 19 newExceptionTime = 77 newObjectTime = 3 noStackExceptionTime = 15 ``` This implies that creating a `NoStackException` is approximately as expensive as repeatedly throwing the same `Exception`. It also shows that creating an `Exception` and filling its stack trace takes approximately **4x** longer.
Using @AustinD's answer as a starting point, I made some tweaks. Code at the bottom. In addition to adding the case where one Exception instance is thrown repeatedly, I also turned off compiler optimization so that we can get accurate performance results. I added `-Djava.compiler=NONE` to the VM arguments, as per [this answer](https://stackoverflow.com/a/5242430/1021426). (In eclipse, edit the Run Configuration → Arguments to set this VM argument) The results: ``` new Exception + throw/catch = 643.5 new Exception only = 510.7 throw/catch only = 115.2 new String (benchmark) = 669.8 ``` So creating the exception costs about 5x as much as throwing + catching it. Assuming the compiler doesn't optimize away much of the cost. For comparison, here's the same test run without disabling optimization: ``` new Exception + throw/catch = 382.6 new Exception only = 379.5 throw/catch only = 0.3 new String (benchmark) = 15.6 ``` Code: ``` public class ExceptionPerformanceTest { private static final int NUM_TRIES = 1000000; public static void main(String[] args) { double numIterations = 10; long exceptionPlusCatchTime = 0, excepTime = 0, strTime = 0, throwTime = 0; for (int i = 0; i < numIterations; i++) { exceptionPlusCatchTime += exceptionPlusCatchBlock(); excepTime += createException(); throwTime += catchBlock(); strTime += createString(); } System.out.println("new Exception + throw/catch = " + exceptionPlusCatchTime / numIterations); System.out.println("new Exception only = " + excepTime / numIterations); System.out.println("throw/catch only = " + throwTime / numIterations); System.out.println("new String (benchmark) = " + strTime / numIterations); } private static long exceptionPlusCatchBlock() { long start = System.currentTimeMillis(); for (int i = 0; i < NUM_TRIES; i++) { try { throw new Exception(); } catch (Exception e) { // do nothing } } long stop = System.currentTimeMillis(); return stop - start; } private static long createException() { long start = System.currentTimeMillis(); for (int i = 0; i < NUM_TRIES; i++) { Exception e = new Exception(); } long stop = System.currentTimeMillis(); return stop - start; } private static long createString() { long start = System.currentTimeMillis(); for (int i = 0; i < NUM_TRIES; i++) { Object o = new String("" + i); } long stop = System.currentTimeMillis(); return stop - start; } private static long catchBlock() { Exception ex = new Exception(); //Instantiated here long start = System.currentTimeMillis(); for (int i = 0; i < NUM_TRIES; i++) { try { throw ex; //repeatedly thrown } catch (Exception e) { // do nothing } } long stop = System.currentTimeMillis(); return stop - start; } } ```
36,343,214
I am trying to select specific columns from a large tab-delimited CSV file and output only certain columns to a new CSV file. Furthermore, I want to recode the data as this happens. If the cell has a value of 0 then just output 0. However, if the cell has a value of greater than 0, then just output 1 (i.e., all values greater than 0 are coded as 1). Here's what I have so far: ``` import csv outputFile = open('output.csv', 'wb') outputWriter = csv.writer(outputFile) included_cols = range(9,2844) with open('source.txt', 'rb') as f: reader = csv.reader(f, delimiter='\t') for row in reader: content = list(row[i] for i in included_cols) outputWriter.writerow(content) ``` The first issue I am having is that I want to also take from column 6. I wasn't sure how to write column 6 and then columns 9-2844. Second, I wasn't sure how to do the recoding on the fly as I write the new CSV.
2016/03/31
[ "https://Stackoverflow.com/questions/36343214", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5323539/" ]
**Creating** an exception object is not *necessarily* more expensive than creating other regular objects. The main cost is hidden in native [`fillInStackTrace`](http://docs.oracle.com/javase/8/docs/api/java/lang/Throwable.html#fillInStackTrace--) method which walks through the call stack and collects all required information to build a stack trace: classes, method names, line numbers etc. Most of `Throwable` constructors implicitly call `fillInStackTrace`. This is where the idea that creating exceptions is slow comes from. However, there is one [constructor](http://docs.oracle.com/javase/8/docs/api/java/lang/Throwable.html#Throwable-java.lang.String-java.lang.Throwable-boolean-boolean-) to create a `Throwable` without a stack trace. It allows you to make throwables that are very fast to instantiate. Another way to create lightweight exceptions is to override `fillInStackTrace`. --- Now what about **throwing** an exception? In fact, it depends on where a thrown exception is **caught**. If it is caught in the same method (or, more precisely, in the same context, since the context can include several methods due to inlining), then `throw` is as fast and simple as `goto` (of course, after JIT compilation). However if a `catch` block is somewhere deeper in the stack, then JVM needs to unwind the stack frames, and this can take significantly longer. It takes even longer, if there are `synchronized` blocks or methods involved, because unwinding implies releasing of monitors owned by removed stack frames. --- I could confirm the above statements by proper benchmarks, but fortunately I don't need to do this, since all the aspects are already perfectly covered in the post of HotSpot's performance engineer Alexey Shipilev: [The Exceptional Performance of Lil' Exception](http://shipilev.net/blog/2014/exceptional-performance/).
Using @AustinD's answer as a starting point, I made some tweaks. Code at the bottom. In addition to adding the case where one Exception instance is thrown repeatedly, I also turned off compiler optimization so that we can get accurate performance results. I added `-Djava.compiler=NONE` to the VM arguments, as per [this answer](https://stackoverflow.com/a/5242430/1021426). (In eclipse, edit the Run Configuration → Arguments to set this VM argument) The results: ``` new Exception + throw/catch = 643.5 new Exception only = 510.7 throw/catch only = 115.2 new String (benchmark) = 669.8 ``` So creating the exception costs about 5x as much as throwing + catching it. Assuming the compiler doesn't optimize away much of the cost. For comparison, here's the same test run without disabling optimization: ``` new Exception + throw/catch = 382.6 new Exception only = 379.5 throw/catch only = 0.3 new String (benchmark) = 15.6 ``` Code: ``` public class ExceptionPerformanceTest { private static final int NUM_TRIES = 1000000; public static void main(String[] args) { double numIterations = 10; long exceptionPlusCatchTime = 0, excepTime = 0, strTime = 0, throwTime = 0; for (int i = 0; i < numIterations; i++) { exceptionPlusCatchTime += exceptionPlusCatchBlock(); excepTime += createException(); throwTime += catchBlock(); strTime += createString(); } System.out.println("new Exception + throw/catch = " + exceptionPlusCatchTime / numIterations); System.out.println("new Exception only = " + excepTime / numIterations); System.out.println("throw/catch only = " + throwTime / numIterations); System.out.println("new String (benchmark) = " + strTime / numIterations); } private static long exceptionPlusCatchBlock() { long start = System.currentTimeMillis(); for (int i = 0; i < NUM_TRIES; i++) { try { throw new Exception(); } catch (Exception e) { // do nothing } } long stop = System.currentTimeMillis(); return stop - start; } private static long createException() { long start = System.currentTimeMillis(); for (int i = 0; i < NUM_TRIES; i++) { Exception e = new Exception(); } long stop = System.currentTimeMillis(); return stop - start; } private static long createString() { long start = System.currentTimeMillis(); for (int i = 0; i < NUM_TRIES; i++) { Object o = new String("" + i); } long stop = System.currentTimeMillis(); return stop - start; } private static long catchBlock() { Exception ex = new Exception(); //Instantiated here long start = System.currentTimeMillis(); for (int i = 0; i < NUM_TRIES; i++) { try { throw ex; //repeatedly thrown } catch (Exception e) { // do nothing } } long stop = System.currentTimeMillis(); return stop - start; } } ```
36,343,214
I am trying to select specific columns from a large tab-delimited CSV file and output only certain columns to a new CSV file. Furthermore, I want to recode the data as this happens. If the cell has a value of 0 then just output 0. However, if the cell has a value of greater than 0, then just output 1 (i.e., all values greater than 0 are coded as 1). Here's what I have so far: ``` import csv outputFile = open('output.csv', 'wb') outputWriter = csv.writer(outputFile) included_cols = range(9,2844) with open('source.txt', 'rb') as f: reader = csv.reader(f, delimiter='\t') for row in reader: content = list(row[i] for i in included_cols) outputWriter.writerow(content) ``` The first issue I am having is that I want to also take from column 6. I wasn't sure how to write column 6 and then columns 9-2844. Second, I wasn't sure how to do the recoding on the fly as I write the new CSV.
2016/03/31
[ "https://Stackoverflow.com/questions/36343214", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5323539/" ]
The first operation in most `Throwable` constructors is to [fill in the stack trace,](https://docs.oracle.com/javase/8/docs/api/java/lang/Throwable.html#fillInStackTrace--) which is where most of the expense is. There is, however, a protected constructor with a flag to disable the stack trace. [This constructor](https://docs.oracle.com/javase/8/docs/api/java/lang/Exception.html#Exception-java.lang.String-java.lang.Throwable-boolean-boolean-) is accessible when extending `Exception` as well. If you create a custom exception type, you can avoid the stack trace creation and get better performance at the expense of less information. If you create a single exception of any type by normal means, you can re-throw it many times without the overhead of filling in the stack trace. However, its stack trace will reflect where it was constructed, not where it was thrown in a particular instance. Current versions of Java make some attempts to optimize stack trace creation. Native code is invoked to fill in the stack trace, which records the trace in a lighter-weight, native structure. Corresponding Java [`StackTraceElement`](https://docs.oracle.com/javase/8/docs/api/java/lang/StackTraceElement.html) objects are lazily created from this record only when the `getStackTrace()`, `printStackTrace()`, or other methods that require the trace are called. If you eliminate stack trace generation, the other main cost is unwinding the stack between the throw and the catch. The fewer intervening frames encountered before the exception is caught, the faster this will be. Design your program so that exceptions are thrown only in truly exceptional cases, and optimizations like these are hard to justify.
This part of the question... > > Another way of asking this is, if I made one instance of Exception and > threw and caught it over and over, would that be significantly faster > than creating a new Exception every time I throw? > > > Seems to be asking if creating an exception and caching it somewhere improves performance. Yes it does. It's the same as turning off the stack being written on object creation because it's already been done. These are timings I got, please read caveat after this... ``` |Depth| WriteStack(ms)| !WriteStack(ms)| Diff(%)| | 16| 193| 251| 77 (%)| | 15| 390| 406| 96 (%)| | 14| 394| 401| 98 (%)| | 13| 381| 385| 99 (%)| | 12| 387| 370| 105 (%)| | 11| 368| 376| 98 (%)| | 10| 188| 192| 98 (%)| | 9| 193| 195| 99 (%)| | 8| 200| 188| 106 (%)| | 7| 187| 184| 102 (%)| | 6| 196| 200| 98 (%)| | 5| 197| 193| 102 (%)| | 4| 198| 190| 104 (%)| | 3| 193| 183| 105 (%)| ``` Of course the problem with this is your stack trace now points to where you instantiated the object not where it was thrown from.
36,343,214
I am trying to select specific columns from a large tab-delimited CSV file and output only certain columns to a new CSV file. Furthermore, I want to recode the data as this happens. If the cell has a value of 0 then just output 0. However, if the cell has a value of greater than 0, then just output 1 (i.e., all values greater than 0 are coded as 1). Here's what I have so far: ``` import csv outputFile = open('output.csv', 'wb') outputWriter = csv.writer(outputFile) included_cols = range(9,2844) with open('source.txt', 'rb') as f: reader = csv.reader(f, delimiter='\t') for row in reader: content = list(row[i] for i in included_cols) outputWriter.writerow(content) ``` The first issue I am having is that I want to also take from column 6. I wasn't sure how to write column 6 and then columns 9-2844. Second, I wasn't sure how to do the recoding on the fly as I write the new CSV.
2016/03/31
[ "https://Stackoverflow.com/questions/36343214", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5323539/" ]
**Creating** an exception object is not *necessarily* more expensive than creating other regular objects. The main cost is hidden in native [`fillInStackTrace`](http://docs.oracle.com/javase/8/docs/api/java/lang/Throwable.html#fillInStackTrace--) method which walks through the call stack and collects all required information to build a stack trace: classes, method names, line numbers etc. Most of `Throwable` constructors implicitly call `fillInStackTrace`. This is where the idea that creating exceptions is slow comes from. However, there is one [constructor](http://docs.oracle.com/javase/8/docs/api/java/lang/Throwable.html#Throwable-java.lang.String-java.lang.Throwable-boolean-boolean-) to create a `Throwable` without a stack trace. It allows you to make throwables that are very fast to instantiate. Another way to create lightweight exceptions is to override `fillInStackTrace`. --- Now what about **throwing** an exception? In fact, it depends on where a thrown exception is **caught**. If it is caught in the same method (or, more precisely, in the same context, since the context can include several methods due to inlining), then `throw` is as fast and simple as `goto` (of course, after JIT compilation). However if a `catch` block is somewhere deeper in the stack, then JVM needs to unwind the stack frames, and this can take significantly longer. It takes even longer, if there are `synchronized` blocks or methods involved, because unwinding implies releasing of monitors owned by removed stack frames. --- I could confirm the above statements by proper benchmarks, but fortunately I don't need to do this, since all the aspects are already perfectly covered in the post of HotSpot's performance engineer Alexey Shipilev: [The Exceptional Performance of Lil' Exception](http://shipilev.net/blog/2014/exceptional-performance/).
The first operation in most `Throwable` constructors is to [fill in the stack trace,](https://docs.oracle.com/javase/8/docs/api/java/lang/Throwable.html#fillInStackTrace--) which is where most of the expense is. There is, however, a protected constructor with a flag to disable the stack trace. [This constructor](https://docs.oracle.com/javase/8/docs/api/java/lang/Exception.html#Exception-java.lang.String-java.lang.Throwable-boolean-boolean-) is accessible when extending `Exception` as well. If you create a custom exception type, you can avoid the stack trace creation and get better performance at the expense of less information. If you create a single exception of any type by normal means, you can re-throw it many times without the overhead of filling in the stack trace. However, its stack trace will reflect where it was constructed, not where it was thrown in a particular instance. Current versions of Java make some attempts to optimize stack trace creation. Native code is invoked to fill in the stack trace, which records the trace in a lighter-weight, native structure. Corresponding Java [`StackTraceElement`](https://docs.oracle.com/javase/8/docs/api/java/lang/StackTraceElement.html) objects are lazily created from this record only when the `getStackTrace()`, `printStackTrace()`, or other methods that require the trace are called. If you eliminate stack trace generation, the other main cost is unwinding the stack between the throw and the catch. The fewer intervening frames encountered before the exception is caught, the faster this will be. Design your program so that exceptions are thrown only in truly exceptional cases, and optimizations like these are hard to justify.
36,343,214
I am trying to select specific columns from a large tab-delimited CSV file and output only certain columns to a new CSV file. Furthermore, I want to recode the data as this happens. If the cell has a value of 0 then just output 0. However, if the cell has a value of greater than 0, then just output 1 (i.e., all values greater than 0 are coded as 1). Here's what I have so far: ``` import csv outputFile = open('output.csv', 'wb') outputWriter = csv.writer(outputFile) included_cols = range(9,2844) with open('source.txt', 'rb') as f: reader = csv.reader(f, delimiter='\t') for row in reader: content = list(row[i] for i in included_cols) outputWriter.writerow(content) ``` The first issue I am having is that I want to also take from column 6. I wasn't sure how to write column 6 and then columns 9-2844. Second, I wasn't sure how to do the recoding on the fly as I write the new CSV.
2016/03/31
[ "https://Stackoverflow.com/questions/36343214", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5323539/" ]
Theres a good write up on Exceptions here. <http://shipilev.net/blog/2014/exceptional-performance/> The conclusion being that stack trace construction and stack unwinding are the expensive parts. The code below takes advantage of a feature in `1.7` where we can turn stack traces on and off. We can then use this to see what sort of costs different scenarios have The following are timings for Object creation alone. I've added `String` here so you can see that without the stack being written there's almost no difference in creating a `JavaException` Object and a `String`. With stack writing turned on the difference is dramatic ie at least one order of magnitude slower. ``` Time to create million String objects: 41.41 (ms) Time to create million JavaException objects with stack: 608.89 (ms) Time to create million JavaException objects without stack: 43.50 (ms) ``` The following shows how long it took to return from a throw at a particular depth a million times. ``` |Depth| WriteStack(ms)| !WriteStack(ms)| Diff(%)| | 16| 1428| 243| 588 (%)| | 15| 1763| 393| 449 (%)| | 14| 1746| 390| 448 (%)| | 13| 1703| 384| 443 (%)| | 12| 1697| 391| 434 (%)| | 11| 1707| 410| 416 (%)| | 10| 1226| 197| 622 (%)| | 9| 1242| 206| 603 (%)| | 8| 1251| 207| 604 (%)| | 7| 1213| 208| 583 (%)| | 6| 1164| 206| 565 (%)| | 5| 1134| 205| 553 (%)| | 4| 1106| 203| 545 (%)| | 3| 1043| 192| 543 (%)| ``` The following is almost certainly a gross over simplification... If we take a depth of 16 with stack writing on then object creation is taking approximately ~40% of the time, the actual stack trace accounts for the vast majority of this. ~93% of instantiating the JavaException object is due to the stack trace being taken. This means that unwinding the stack in this case is taking the other 50% of the time. When we turn off the stack trace object creation accounts for a much smaller fraction ie 20% and stack unwinding now accounts for 80% of the time. In both cases stack unwinding takes a large portion of the overall time. ``` public class JavaException extends Exception { JavaException(String reason, int mode) { super(reason, null, false, false); } JavaException(String reason) { super(reason); } public static void main(String[] args) { int iterations = 1000000; long create_time_with = 0; long create_time_without = 0; long create_string = 0; for (int i = 0; i < iterations; i++) { long start = System.nanoTime(); JavaException jex = new JavaException("testing"); long stop = System.nanoTime(); create_time_with += stop - start; start = System.nanoTime(); JavaException jex2 = new JavaException("testing", 1); stop = System.nanoTime(); create_time_without += stop - start; start = System.nanoTime(); String str = new String("testing"); stop = System.nanoTime(); create_string += stop - start; } double interval_with = ((double)create_time_with)/1000000; double interval_without = ((double)create_time_without)/1000000; double interval_string = ((double)create_string)/1000000; System.out.printf("Time to create %d String objects: %.2f (ms)\n", iterations, interval_string); System.out.printf("Time to create %d JavaException objects with stack: %.2f (ms)\n", iterations, interval_with); System.out.printf("Time to create %d JavaException objects without stack: %.2f (ms)\n", iterations, interval_without); JavaException jex = new JavaException("testing"); int depth = 14; int i = depth; double[] with_stack = new double[20]; double[] without_stack = new double[20]; for(; i > 0 ; --i) { without_stack[i] = jex.timerLoop(i, iterations, 0)/1000000; with_stack[i] = jex.timerLoop(i, iterations, 1)/1000000; } i = depth; System.out.printf("|Depth| WriteStack(ms)| !WriteStack(ms)| Diff(%%)|\n"); for(; i > 0 ; --i) { double ratio = (with_stack[i] / (double) without_stack[i]) * 100; System.out.printf("|%5d| %14.0f| %15.0f| %2.0f (%%)| \n", i + 2, with_stack[i] , without_stack[i], ratio); //System.out.printf("%d\t%.2f (ms)\n", i, ratio); } } private int thrower(int i, int mode) throws JavaException { ExArg.time_start[i] = System.nanoTime(); if(mode == 0) { throw new JavaException("without stack", 1); } throw new JavaException("with stack"); } private int catcher1(int i, int mode) throws JavaException{ return this.stack_of_calls(i, mode); } private long timerLoop(int depth, int iterations, int mode) { for (int i = 0; i < iterations; i++) { try { this.catcher1(depth, mode); } catch (JavaException e) { ExArg.time_accum[depth] += (System.nanoTime() - ExArg.time_start[depth]); } } //long stop = System.nanoTime(); return ExArg.time_accum[depth]; } private int bad_method14(int i, int mode) throws JavaException { if(i > 0) { this.thrower(i, mode); } return i; } private int bad_method13(int i, int mode) throws JavaException { if(i == 13) { this.thrower(i, mode); } return bad_method14(i,mode); } private int bad_method12(int i, int mode) throws JavaException{ if(i == 12) { this.thrower(i, mode); } return bad_method13(i,mode); } private int bad_method11(int i, int mode) throws JavaException{ if(i == 11) { this.thrower(i, mode); } return bad_method12(i,mode); } private int bad_method10(int i, int mode) throws JavaException{ if(i == 10) { this.thrower(i, mode); } return bad_method11(i,mode); } private int bad_method9(int i, int mode) throws JavaException{ if(i == 9) { this.thrower(i, mode); } return bad_method10(i,mode); } private int bad_method8(int i, int mode) throws JavaException{ if(i == 8) { this.thrower(i, mode); } return bad_method9(i,mode); } private int bad_method7(int i, int mode) throws JavaException{ if(i == 7) { this.thrower(i, mode); } return bad_method8(i,mode); } private int bad_method6(int i, int mode) throws JavaException{ if(i == 6) { this.thrower(i, mode); } return bad_method7(i,mode); } private int bad_method5(int i, int mode) throws JavaException{ if(i == 5) { this.thrower(i, mode); } return bad_method6(i,mode); } private int bad_method4(int i, int mode) throws JavaException{ if(i == 4) { this.thrower(i, mode); } return bad_method5(i,mode); } protected int bad_method3(int i, int mode) throws JavaException{ if(i == 3) { this.thrower(i, mode); } return bad_method4(i,mode); } private int bad_method2(int i, int mode) throws JavaException{ if(i == 2) { this.thrower(i, mode); } return bad_method3(i,mode); } private int bad_method1(int i, int mode) throws JavaException{ if(i == 1) { this.thrower(i, mode); } return bad_method2(i,mode); } private int stack_of_calls(int i, int mode) throws JavaException{ if(i == 0) { this.thrower(i, mode); } return bad_method1(i,mode); } } class ExArg { public static long[] time_start; public static long[] time_accum; static { time_start = new long[20]; time_accum = new long[20]; }; } ``` The stack frames in this example are tiny compared to what you'd normally find. You can peek at the bytecode using javap ``` javap -c -v -constants JavaException.class ``` ie this is for method 4... ``` protected int bad_method3(int, int) throws JavaException; flags: ACC_PROTECTED Code: stack=3, locals=3, args_size=3 0: iload_1 1: iconst_3 2: if_icmpne 12 5: aload_0 6: iload_1 7: iload_2 8: invokespecial #6 // Method thrower:(II)I 11: pop 12: aload_0 13: iload_1 14: iload_2 15: invokespecial #17 // Method bad_method4:(II)I 18: ireturn LineNumberTable: line 63: 0 line 64: 12 StackMapTable: number_of_entries = 1 frame_type = 12 /* same */ Exceptions: throws JavaException ```
This part of the question... > > Another way of asking this is, if I made one instance of Exception and > threw and caught it over and over, would that be significantly faster > than creating a new Exception every time I throw? > > > Seems to be asking if creating an exception and caching it somewhere improves performance. Yes it does. It's the same as turning off the stack being written on object creation because it's already been done. These are timings I got, please read caveat after this... ``` |Depth| WriteStack(ms)| !WriteStack(ms)| Diff(%)| | 16| 193| 251| 77 (%)| | 15| 390| 406| 96 (%)| | 14| 394| 401| 98 (%)| | 13| 381| 385| 99 (%)| | 12| 387| 370| 105 (%)| | 11| 368| 376| 98 (%)| | 10| 188| 192| 98 (%)| | 9| 193| 195| 99 (%)| | 8| 200| 188| 106 (%)| | 7| 187| 184| 102 (%)| | 6| 196| 200| 98 (%)| | 5| 197| 193| 102 (%)| | 4| 198| 190| 104 (%)| | 3| 193| 183| 105 (%)| ``` Of course the problem with this is your stack trace now points to where you instantiated the object not where it was thrown from.
36,343,214
I am trying to select specific columns from a large tab-delimited CSV file and output only certain columns to a new CSV file. Furthermore, I want to recode the data as this happens. If the cell has a value of 0 then just output 0. However, if the cell has a value of greater than 0, then just output 1 (i.e., all values greater than 0 are coded as 1). Here's what I have so far: ``` import csv outputFile = open('output.csv', 'wb') outputWriter = csv.writer(outputFile) included_cols = range(9,2844) with open('source.txt', 'rb') as f: reader = csv.reader(f, delimiter='\t') for row in reader: content = list(row[i] for i in included_cols) outputWriter.writerow(content) ``` The first issue I am having is that I want to also take from column 6. I wasn't sure how to write column 6 and then columns 9-2844. Second, I wasn't sure how to do the recoding on the fly as I write the new CSV.
2016/03/31
[ "https://Stackoverflow.com/questions/36343214", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5323539/" ]
Theres a good write up on Exceptions here. <http://shipilev.net/blog/2014/exceptional-performance/> The conclusion being that stack trace construction and stack unwinding are the expensive parts. The code below takes advantage of a feature in `1.7` where we can turn stack traces on and off. We can then use this to see what sort of costs different scenarios have The following are timings for Object creation alone. I've added `String` here so you can see that without the stack being written there's almost no difference in creating a `JavaException` Object and a `String`. With stack writing turned on the difference is dramatic ie at least one order of magnitude slower. ``` Time to create million String objects: 41.41 (ms) Time to create million JavaException objects with stack: 608.89 (ms) Time to create million JavaException objects without stack: 43.50 (ms) ``` The following shows how long it took to return from a throw at a particular depth a million times. ``` |Depth| WriteStack(ms)| !WriteStack(ms)| Diff(%)| | 16| 1428| 243| 588 (%)| | 15| 1763| 393| 449 (%)| | 14| 1746| 390| 448 (%)| | 13| 1703| 384| 443 (%)| | 12| 1697| 391| 434 (%)| | 11| 1707| 410| 416 (%)| | 10| 1226| 197| 622 (%)| | 9| 1242| 206| 603 (%)| | 8| 1251| 207| 604 (%)| | 7| 1213| 208| 583 (%)| | 6| 1164| 206| 565 (%)| | 5| 1134| 205| 553 (%)| | 4| 1106| 203| 545 (%)| | 3| 1043| 192| 543 (%)| ``` The following is almost certainly a gross over simplification... If we take a depth of 16 with stack writing on then object creation is taking approximately ~40% of the time, the actual stack trace accounts for the vast majority of this. ~93% of instantiating the JavaException object is due to the stack trace being taken. This means that unwinding the stack in this case is taking the other 50% of the time. When we turn off the stack trace object creation accounts for a much smaller fraction ie 20% and stack unwinding now accounts for 80% of the time. In both cases stack unwinding takes a large portion of the overall time. ``` public class JavaException extends Exception { JavaException(String reason, int mode) { super(reason, null, false, false); } JavaException(String reason) { super(reason); } public static void main(String[] args) { int iterations = 1000000; long create_time_with = 0; long create_time_without = 0; long create_string = 0; for (int i = 0; i < iterations; i++) { long start = System.nanoTime(); JavaException jex = new JavaException("testing"); long stop = System.nanoTime(); create_time_with += stop - start; start = System.nanoTime(); JavaException jex2 = new JavaException("testing", 1); stop = System.nanoTime(); create_time_without += stop - start; start = System.nanoTime(); String str = new String("testing"); stop = System.nanoTime(); create_string += stop - start; } double interval_with = ((double)create_time_with)/1000000; double interval_without = ((double)create_time_without)/1000000; double interval_string = ((double)create_string)/1000000; System.out.printf("Time to create %d String objects: %.2f (ms)\n", iterations, interval_string); System.out.printf("Time to create %d JavaException objects with stack: %.2f (ms)\n", iterations, interval_with); System.out.printf("Time to create %d JavaException objects without stack: %.2f (ms)\n", iterations, interval_without); JavaException jex = new JavaException("testing"); int depth = 14; int i = depth; double[] with_stack = new double[20]; double[] without_stack = new double[20]; for(; i > 0 ; --i) { without_stack[i] = jex.timerLoop(i, iterations, 0)/1000000; with_stack[i] = jex.timerLoop(i, iterations, 1)/1000000; } i = depth; System.out.printf("|Depth| WriteStack(ms)| !WriteStack(ms)| Diff(%%)|\n"); for(; i > 0 ; --i) { double ratio = (with_stack[i] / (double) without_stack[i]) * 100; System.out.printf("|%5d| %14.0f| %15.0f| %2.0f (%%)| \n", i + 2, with_stack[i] , without_stack[i], ratio); //System.out.printf("%d\t%.2f (ms)\n", i, ratio); } } private int thrower(int i, int mode) throws JavaException { ExArg.time_start[i] = System.nanoTime(); if(mode == 0) { throw new JavaException("without stack", 1); } throw new JavaException("with stack"); } private int catcher1(int i, int mode) throws JavaException{ return this.stack_of_calls(i, mode); } private long timerLoop(int depth, int iterations, int mode) { for (int i = 0; i < iterations; i++) { try { this.catcher1(depth, mode); } catch (JavaException e) { ExArg.time_accum[depth] += (System.nanoTime() - ExArg.time_start[depth]); } } //long stop = System.nanoTime(); return ExArg.time_accum[depth]; } private int bad_method14(int i, int mode) throws JavaException { if(i > 0) { this.thrower(i, mode); } return i; } private int bad_method13(int i, int mode) throws JavaException { if(i == 13) { this.thrower(i, mode); } return bad_method14(i,mode); } private int bad_method12(int i, int mode) throws JavaException{ if(i == 12) { this.thrower(i, mode); } return bad_method13(i,mode); } private int bad_method11(int i, int mode) throws JavaException{ if(i == 11) { this.thrower(i, mode); } return bad_method12(i,mode); } private int bad_method10(int i, int mode) throws JavaException{ if(i == 10) { this.thrower(i, mode); } return bad_method11(i,mode); } private int bad_method9(int i, int mode) throws JavaException{ if(i == 9) { this.thrower(i, mode); } return bad_method10(i,mode); } private int bad_method8(int i, int mode) throws JavaException{ if(i == 8) { this.thrower(i, mode); } return bad_method9(i,mode); } private int bad_method7(int i, int mode) throws JavaException{ if(i == 7) { this.thrower(i, mode); } return bad_method8(i,mode); } private int bad_method6(int i, int mode) throws JavaException{ if(i == 6) { this.thrower(i, mode); } return bad_method7(i,mode); } private int bad_method5(int i, int mode) throws JavaException{ if(i == 5) { this.thrower(i, mode); } return bad_method6(i,mode); } private int bad_method4(int i, int mode) throws JavaException{ if(i == 4) { this.thrower(i, mode); } return bad_method5(i,mode); } protected int bad_method3(int i, int mode) throws JavaException{ if(i == 3) { this.thrower(i, mode); } return bad_method4(i,mode); } private int bad_method2(int i, int mode) throws JavaException{ if(i == 2) { this.thrower(i, mode); } return bad_method3(i,mode); } private int bad_method1(int i, int mode) throws JavaException{ if(i == 1) { this.thrower(i, mode); } return bad_method2(i,mode); } private int stack_of_calls(int i, int mode) throws JavaException{ if(i == 0) { this.thrower(i, mode); } return bad_method1(i,mode); } } class ExArg { public static long[] time_start; public static long[] time_accum; static { time_start = new long[20]; time_accum = new long[20]; }; } ``` The stack frames in this example are tiny compared to what you'd normally find. You can peek at the bytecode using javap ``` javap -c -v -constants JavaException.class ``` ie this is for method 4... ``` protected int bad_method3(int, int) throws JavaException; flags: ACC_PROTECTED Code: stack=3, locals=3, args_size=3 0: iload_1 1: iconst_3 2: if_icmpne 12 5: aload_0 6: iload_1 7: iload_2 8: invokespecial #6 // Method thrower:(II)I 11: pop 12: aload_0 13: iload_1 14: iload_2 15: invokespecial #17 // Method bad_method4:(II)I 18: ireturn LineNumberTable: line 63: 0 line 64: 12 StackMapTable: number_of_entries = 1 frame_type = 12 /* same */ Exceptions: throws JavaException ```
The creation of the `Exception` with a `null` stack trace takes about as much time as the `throw` and `try-catch` block together. However, **filling the stack trace takes on average 5x longer**. I created the following benchmark to demonstrate the impact on performance. I added the `-Djava.compiler=NONE` to the Run Configuration to disable compiler optimization. To measure the impact of building the stack trace, I extended the `Exception` class to take advantage of the stack-free constructor: ``` class NoStackException extends Exception{ public NoStackException() { super("",null,false,false); } } ``` The benchmark code is as follows: ``` public class ExceptionBenchmark { private static final int NUM_TRIES = 100000; public static void main(String[] args) { long throwCatchTime = 0, newExceptionTime = 0, newObjectTime = 0, noStackExceptionTime = 0; for (int i = 0; i < 30; i++) { throwCatchTime += throwCatchLoop(); newExceptionTime += newExceptionLoop(); newObjectTime += newObjectLoop(); noStackExceptionTime += newNoStackExceptionLoop(); } System.out.println("throwCatchTime = " + throwCatchTime / 30); System.out.println("newExceptionTime = " + newExceptionTime / 30); System.out.println("newStringTime = " + newObjectTime / 30); System.out.println("noStackExceptionTime = " + noStackExceptionTime / 30); } private static long throwCatchLoop() { Exception ex = new Exception(); //Instantiated here long start = System.currentTimeMillis(); for (int i = 0; i < NUM_TRIES; i++) { try { throw ex; //repeatedly thrown } catch (Exception e) { // do nothing } } long stop = System.currentTimeMillis(); return stop - start; } private static long newExceptionLoop() { long start = System.currentTimeMillis(); for (int i = 0; i < NUM_TRIES; i++) { Exception e = new Exception(); } long stop = System.currentTimeMillis(); return stop - start; } private static long newObjectLoop() { long start = System.currentTimeMillis(); for (int i = 0; i < NUM_TRIES; i++) { Object o = new Object(); } long stop = System.currentTimeMillis(); return stop - start; } private static long newNoStackExceptionLoop() { long start = System.currentTimeMillis(); for (int i = 0; i < NUM_TRIES; i++) { NoStackException e = new NoStackException(); } long stop = System.currentTimeMillis(); return stop - start; } } ``` **Output:** ``` throwCatchTime = 19 newExceptionTime = 77 newObjectTime = 3 noStackExceptionTime = 15 ``` This implies that creating a `NoStackException` is approximately as expensive as repeatedly throwing the same `Exception`. It also shows that creating an `Exception` and filling its stack trace takes approximately **4x** longer.
36,343,214
I am trying to select specific columns from a large tab-delimited CSV file and output only certain columns to a new CSV file. Furthermore, I want to recode the data as this happens. If the cell has a value of 0 then just output 0. However, if the cell has a value of greater than 0, then just output 1 (i.e., all values greater than 0 are coded as 1). Here's what I have so far: ``` import csv outputFile = open('output.csv', 'wb') outputWriter = csv.writer(outputFile) included_cols = range(9,2844) with open('source.txt', 'rb') as f: reader = csv.reader(f, delimiter='\t') for row in reader: content = list(row[i] for i in included_cols) outputWriter.writerow(content) ``` The first issue I am having is that I want to also take from column 6. I wasn't sure how to write column 6 and then columns 9-2844. Second, I wasn't sure how to do the recoding on the fly as I write the new CSV.
2016/03/31
[ "https://Stackoverflow.com/questions/36343214", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5323539/" ]
**Creating** an exception object is not *necessarily* more expensive than creating other regular objects. The main cost is hidden in native [`fillInStackTrace`](http://docs.oracle.com/javase/8/docs/api/java/lang/Throwable.html#fillInStackTrace--) method which walks through the call stack and collects all required information to build a stack trace: classes, method names, line numbers etc. Most of `Throwable` constructors implicitly call `fillInStackTrace`. This is where the idea that creating exceptions is slow comes from. However, there is one [constructor](http://docs.oracle.com/javase/8/docs/api/java/lang/Throwable.html#Throwable-java.lang.String-java.lang.Throwable-boolean-boolean-) to create a `Throwable` without a stack trace. It allows you to make throwables that are very fast to instantiate. Another way to create lightweight exceptions is to override `fillInStackTrace`. --- Now what about **throwing** an exception? In fact, it depends on where a thrown exception is **caught**. If it is caught in the same method (or, more precisely, in the same context, since the context can include several methods due to inlining), then `throw` is as fast and simple as `goto` (of course, after JIT compilation). However if a `catch` block is somewhere deeper in the stack, then JVM needs to unwind the stack frames, and this can take significantly longer. It takes even longer, if there are `synchronized` blocks or methods involved, because unwinding implies releasing of monitors owned by removed stack frames. --- I could confirm the above statements by proper benchmarks, but fortunately I don't need to do this, since all the aspects are already perfectly covered in the post of HotSpot's performance engineer Alexey Shipilev: [The Exceptional Performance of Lil' Exception](http://shipilev.net/blog/2014/exceptional-performance/).
This part of the question... > > Another way of asking this is, if I made one instance of Exception and > threw and caught it over and over, would that be significantly faster > than creating a new Exception every time I throw? > > > Seems to be asking if creating an exception and caching it somewhere improves performance. Yes it does. It's the same as turning off the stack being written on object creation because it's already been done. These are timings I got, please read caveat after this... ``` |Depth| WriteStack(ms)| !WriteStack(ms)| Diff(%)| | 16| 193| 251| 77 (%)| | 15| 390| 406| 96 (%)| | 14| 394| 401| 98 (%)| | 13| 381| 385| 99 (%)| | 12| 387| 370| 105 (%)| | 11| 368| 376| 98 (%)| | 10| 188| 192| 98 (%)| | 9| 193| 195| 99 (%)| | 8| 200| 188| 106 (%)| | 7| 187| 184| 102 (%)| | 6| 196| 200| 98 (%)| | 5| 197| 193| 102 (%)| | 4| 198| 190| 104 (%)| | 3| 193| 183| 105 (%)| ``` Of course the problem with this is your stack trace now points to where you instantiated the object not where it was thrown from.
36,343,214
I am trying to select specific columns from a large tab-delimited CSV file and output only certain columns to a new CSV file. Furthermore, I want to recode the data as this happens. If the cell has a value of 0 then just output 0. However, if the cell has a value of greater than 0, then just output 1 (i.e., all values greater than 0 are coded as 1). Here's what I have so far: ``` import csv outputFile = open('output.csv', 'wb') outputWriter = csv.writer(outputFile) included_cols = range(9,2844) with open('source.txt', 'rb') as f: reader = csv.reader(f, delimiter='\t') for row in reader: content = list(row[i] for i in included_cols) outputWriter.writerow(content) ``` The first issue I am having is that I want to also take from column 6. I wasn't sure how to write column 6 and then columns 9-2844. Second, I wasn't sure how to do the recoding on the fly as I write the new CSV.
2016/03/31
[ "https://Stackoverflow.com/questions/36343214", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5323539/" ]
**Creating** an exception object is not *necessarily* more expensive than creating other regular objects. The main cost is hidden in native [`fillInStackTrace`](http://docs.oracle.com/javase/8/docs/api/java/lang/Throwable.html#fillInStackTrace--) method which walks through the call stack and collects all required information to build a stack trace: classes, method names, line numbers etc. Most of `Throwable` constructors implicitly call `fillInStackTrace`. This is where the idea that creating exceptions is slow comes from. However, there is one [constructor](http://docs.oracle.com/javase/8/docs/api/java/lang/Throwable.html#Throwable-java.lang.String-java.lang.Throwable-boolean-boolean-) to create a `Throwable` without a stack trace. It allows you to make throwables that are very fast to instantiate. Another way to create lightweight exceptions is to override `fillInStackTrace`. --- Now what about **throwing** an exception? In fact, it depends on where a thrown exception is **caught**. If it is caught in the same method (or, more precisely, in the same context, since the context can include several methods due to inlining), then `throw` is as fast and simple as `goto` (of course, after JIT compilation). However if a `catch` block is somewhere deeper in the stack, then JVM needs to unwind the stack frames, and this can take significantly longer. It takes even longer, if there are `synchronized` blocks or methods involved, because unwinding implies releasing of monitors owned by removed stack frames. --- I could confirm the above statements by proper benchmarks, but fortunately I don't need to do this, since all the aspects are already perfectly covered in the post of HotSpot's performance engineer Alexey Shipilev: [The Exceptional Performance of Lil' Exception](http://shipilev.net/blog/2014/exceptional-performance/).
Theres a good write up on Exceptions here. <http://shipilev.net/blog/2014/exceptional-performance/> The conclusion being that stack trace construction and stack unwinding are the expensive parts. The code below takes advantage of a feature in `1.7` where we can turn stack traces on and off. We can then use this to see what sort of costs different scenarios have The following are timings for Object creation alone. I've added `String` here so you can see that without the stack being written there's almost no difference in creating a `JavaException` Object and a `String`. With stack writing turned on the difference is dramatic ie at least one order of magnitude slower. ``` Time to create million String objects: 41.41 (ms) Time to create million JavaException objects with stack: 608.89 (ms) Time to create million JavaException objects without stack: 43.50 (ms) ``` The following shows how long it took to return from a throw at a particular depth a million times. ``` |Depth| WriteStack(ms)| !WriteStack(ms)| Diff(%)| | 16| 1428| 243| 588 (%)| | 15| 1763| 393| 449 (%)| | 14| 1746| 390| 448 (%)| | 13| 1703| 384| 443 (%)| | 12| 1697| 391| 434 (%)| | 11| 1707| 410| 416 (%)| | 10| 1226| 197| 622 (%)| | 9| 1242| 206| 603 (%)| | 8| 1251| 207| 604 (%)| | 7| 1213| 208| 583 (%)| | 6| 1164| 206| 565 (%)| | 5| 1134| 205| 553 (%)| | 4| 1106| 203| 545 (%)| | 3| 1043| 192| 543 (%)| ``` The following is almost certainly a gross over simplification... If we take a depth of 16 with stack writing on then object creation is taking approximately ~40% of the time, the actual stack trace accounts for the vast majority of this. ~93% of instantiating the JavaException object is due to the stack trace being taken. This means that unwinding the stack in this case is taking the other 50% of the time. When we turn off the stack trace object creation accounts for a much smaller fraction ie 20% and stack unwinding now accounts for 80% of the time. In both cases stack unwinding takes a large portion of the overall time. ``` public class JavaException extends Exception { JavaException(String reason, int mode) { super(reason, null, false, false); } JavaException(String reason) { super(reason); } public static void main(String[] args) { int iterations = 1000000; long create_time_with = 0; long create_time_without = 0; long create_string = 0; for (int i = 0; i < iterations; i++) { long start = System.nanoTime(); JavaException jex = new JavaException("testing"); long stop = System.nanoTime(); create_time_with += stop - start; start = System.nanoTime(); JavaException jex2 = new JavaException("testing", 1); stop = System.nanoTime(); create_time_without += stop - start; start = System.nanoTime(); String str = new String("testing"); stop = System.nanoTime(); create_string += stop - start; } double interval_with = ((double)create_time_with)/1000000; double interval_without = ((double)create_time_without)/1000000; double interval_string = ((double)create_string)/1000000; System.out.printf("Time to create %d String objects: %.2f (ms)\n", iterations, interval_string); System.out.printf("Time to create %d JavaException objects with stack: %.2f (ms)\n", iterations, interval_with); System.out.printf("Time to create %d JavaException objects without stack: %.2f (ms)\n", iterations, interval_without); JavaException jex = new JavaException("testing"); int depth = 14; int i = depth; double[] with_stack = new double[20]; double[] without_stack = new double[20]; for(; i > 0 ; --i) { without_stack[i] = jex.timerLoop(i, iterations, 0)/1000000; with_stack[i] = jex.timerLoop(i, iterations, 1)/1000000; } i = depth; System.out.printf("|Depth| WriteStack(ms)| !WriteStack(ms)| Diff(%%)|\n"); for(; i > 0 ; --i) { double ratio = (with_stack[i] / (double) without_stack[i]) * 100; System.out.printf("|%5d| %14.0f| %15.0f| %2.0f (%%)| \n", i + 2, with_stack[i] , without_stack[i], ratio); //System.out.printf("%d\t%.2f (ms)\n", i, ratio); } } private int thrower(int i, int mode) throws JavaException { ExArg.time_start[i] = System.nanoTime(); if(mode == 0) { throw new JavaException("without stack", 1); } throw new JavaException("with stack"); } private int catcher1(int i, int mode) throws JavaException{ return this.stack_of_calls(i, mode); } private long timerLoop(int depth, int iterations, int mode) { for (int i = 0; i < iterations; i++) { try { this.catcher1(depth, mode); } catch (JavaException e) { ExArg.time_accum[depth] += (System.nanoTime() - ExArg.time_start[depth]); } } //long stop = System.nanoTime(); return ExArg.time_accum[depth]; } private int bad_method14(int i, int mode) throws JavaException { if(i > 0) { this.thrower(i, mode); } return i; } private int bad_method13(int i, int mode) throws JavaException { if(i == 13) { this.thrower(i, mode); } return bad_method14(i,mode); } private int bad_method12(int i, int mode) throws JavaException{ if(i == 12) { this.thrower(i, mode); } return bad_method13(i,mode); } private int bad_method11(int i, int mode) throws JavaException{ if(i == 11) { this.thrower(i, mode); } return bad_method12(i,mode); } private int bad_method10(int i, int mode) throws JavaException{ if(i == 10) { this.thrower(i, mode); } return bad_method11(i,mode); } private int bad_method9(int i, int mode) throws JavaException{ if(i == 9) { this.thrower(i, mode); } return bad_method10(i,mode); } private int bad_method8(int i, int mode) throws JavaException{ if(i == 8) { this.thrower(i, mode); } return bad_method9(i,mode); } private int bad_method7(int i, int mode) throws JavaException{ if(i == 7) { this.thrower(i, mode); } return bad_method8(i,mode); } private int bad_method6(int i, int mode) throws JavaException{ if(i == 6) { this.thrower(i, mode); } return bad_method7(i,mode); } private int bad_method5(int i, int mode) throws JavaException{ if(i == 5) { this.thrower(i, mode); } return bad_method6(i,mode); } private int bad_method4(int i, int mode) throws JavaException{ if(i == 4) { this.thrower(i, mode); } return bad_method5(i,mode); } protected int bad_method3(int i, int mode) throws JavaException{ if(i == 3) { this.thrower(i, mode); } return bad_method4(i,mode); } private int bad_method2(int i, int mode) throws JavaException{ if(i == 2) { this.thrower(i, mode); } return bad_method3(i,mode); } private int bad_method1(int i, int mode) throws JavaException{ if(i == 1) { this.thrower(i, mode); } return bad_method2(i,mode); } private int stack_of_calls(int i, int mode) throws JavaException{ if(i == 0) { this.thrower(i, mode); } return bad_method1(i,mode); } } class ExArg { public static long[] time_start; public static long[] time_accum; static { time_start = new long[20]; time_accum = new long[20]; }; } ``` The stack frames in this example are tiny compared to what you'd normally find. You can peek at the bytecode using javap ``` javap -c -v -constants JavaException.class ``` ie this is for method 4... ``` protected int bad_method3(int, int) throws JavaException; flags: ACC_PROTECTED Code: stack=3, locals=3, args_size=3 0: iload_1 1: iconst_3 2: if_icmpne 12 5: aload_0 6: iload_1 7: iload_2 8: invokespecial #6 // Method thrower:(II)I 11: pop 12: aload_0 13: iload_1 14: iload_2 15: invokespecial #17 // Method bad_method4:(II)I 18: ireturn LineNumberTable: line 63: 0 line 64: 12 StackMapTable: number_of_entries = 1 frame_type = 12 /* same */ Exceptions: throws JavaException ```
66,959
GF and I have a flight from Montreal (YUL) to Rome (FCO) via Heathrow (LHR) Terminal 5. Both flights are on British Airways and were booked on the BA sites at the same time. Arriving at LHR at Terminal 5 at 9:35am, leaving LHR from Terminal 5 at 10:40am. I don't think I've had such a small delay between flights. The Heathrow web (flight connection) site says it should take about 1 hour to make the connection, all in the same terminal. Questions (maybe I will answer myself). 1. Should We tell the flight attendants when checking in the luggage about the connection ? 2. Is it possible (usual) to ask to get out of the plane before other people if connection time is short ? 3. Is running allowed in the Terminal 5 halls ? :-) Thanks. Max. (question is similar to [Clearing Customs at Heathrow for a connecting domestic flight to Leeds Bradford](https://travel.stackexchange.com/questions/36834/)) Update 1: Currently waiting for my connecting flight out of LHR, transit took about 15 minutes from arriving at the gate , passing security and a small walk to gate b32. Update 2: Landed in Rome with 1/2 of our luggage, GF got hers, mine was in the next flight from LHR; so, we just chilled by the #9 carrousel. waiting for the next flight !!! All is well now.
2016/04/20
[ "https://travel.stackexchange.com/questions/66959", "https://travel.stackexchange.com", "https://travel.stackexchange.com/users/8279/" ]
I'm only a little nervous about your connection. It is *technically* doable, and you can certainly [get from arrival gate to departure gate](http://www.heathrow.com/flight-connections/personal-connection-planner/BA094/BA546/22-APR-2016/22-APR-2016/5/6B) with plenty of time, if queues at security aren't too long. But, BA094 is very often [late into Heathrow](http://flightaware.com/live/flight/BAW94) due to being late leaving Montreal, which can reduce your actual connection time to 45 minutes or less. You have a few options: * On arrival at LHR, inform your flight attendants that you have a tight connection and ask if they can help you make the connecting flight. * On arrival at LHR, if you fail to make the connection because the inbound flight was late, BA will rebook you on the next available flight for free. * You can ask BA to change your connecting flight *before* you travel. You may be charged a change fee for this, though. There are *five* LHR-FCO flights after yours, and they all show up with available seats, so there should be little difficulty getting on a later flight if necessary. Given the frequency of LHR-FCO flights, I'd say odds are good you'll get where you're going, even if you are a couple of hours later into Rome than you expected.
Just to answer a few of your other questions: > > Should We tell the flight attendants when checking in the luggage > about the connection ? > > > No need as they will have all the information required once they enter your reservation number. You can ask them to put a priority handling tag on your checked in luggage (this is usually affixed to business/first class luggage) as you are on a tight connection. > > Is it possible (usual) to ask to get out of the plane before other > people if connection time is short ? > > > No, this is not possible as loading and unloading is done on priority basis. Business/First class are offloaded first (along with their luggage) and then the main cabin is emptied in a queue. From my experience when passengers have tried to jump the queue, they have been held back by the airline crew as it is unfair for all the other passengers. Once you enter the terminal, if you are late for a connection you will find there are staff there waiting to assist you (these staff are authorized to prioritize you in a queue). Similarly you'll find if you need to go through customs for a connection there will be someone announcing flights that are at risk of being delayed and any passengers on these flights are put on a priority queue. Every person and machine at an airport is designed to minimize delays; so you'll find all kinds of scurrying around being done during the normal busy corridor for that airport. At most UK airports morning this is the morning rush hour - as there is a night noise abatement curfew for the main airports in London. > > Is running allowed in the Terminal 5 halls > > > Space permitting, yes.
23,052,035
I am getting an error attempting to start mongo with authorization enabled via the security.authorization configuration parameter (see <http://docs.mongodb.org/manual/reference/configuration-options/#security.authorization>) On running mongod I get ``` Error parsing INI config file: unknown option security.authorization try 'mongod --help' for more information ``` Any idea? Thanks Supporting data: * Mongo version 2.6.0 (installed via homebrew) * OSX Mavericks 10.9.2 start command: ``` mongod -f /usr/local/etc/mongod.conf ``` mongod.conf file (works fine if I comment out security.authorization): ``` # Store data in /usr/local/var/mongodb instead of the default /data/db dbpath = /usr/local/var/mongodb # Append logs to /usr/local/var/log/mongodb/mongo.log logpath = /usr/local/var/log/mongodb/mongo.log logappend = true # Only accept local connections bind_ip = 127.0.0.1 # auth security.authorization = enabled #security.authenticationMechanisms = MONGODB-CR #error occurs with or without this ``` No entry is made in the mongo.log file when this occurs
2014/04/14
[ "https://Stackoverflow.com/questions/23052035", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3530446/" ]
**Note:** I would have written this as a comment, however I do not have the points yet. Just wondering whether what you are trying to achieve is *authentication* instead? If this is the case, all you need to set in `mongodb.conf` is: ``` # auth auth = true # true or false. Whether or not authentication is required. ``` -- UPDATED: Some other steps that are important: **Configure the db location:** Set in `mongodb.conf` as (you already have this, but should check the directory and permissions exist): ``` # Store data in /usr/local/var/mongodb instead of the default /data/db dbpath = /usr/local/var/mongodb # Append logs to /usr/local/var/log/mongodb/mongo.log logpath = /usr/local/var/log/mongodb/mongo.log logappend = true ``` Dont forget to make sure the above `/usr/local/var/mongodb` directory and `/usr/local/var/log/mongodb/` directory exist. The installer that you used may not have made them. **Create an Operating System user for mongodb:** (If one has not already been created - this is how on linux, not sure for osx) - as root: ``` adduser --system --no-create-home --disabled-login --disabled-password --group mongodb ``` Add permissions to folders if they are not already set: ``` chown mongodb:mongodb -R /usr/local/var/mongodb ``` **To setup database user authorization / privileges:** See the command reference here: <http://docs.mongodb.org/manual/reference/command/#database-commands>
MongoDB server config file format changed from version 2.6 and still old format works. <http://docs.mongodb.org/manual/reference/configuration-options/> > > Changed in version 2.6: MongoDB introduces a YAML-based configuration file format. The 2.4 configuration file format remains for backward compatibility. > > > The error is due to the reason your config file is using old format and adding parameter **security.authorization = enabled** using new format.You can fix the problem by using old format settings mentioned at <http://docs.mongodb.org/v2.4/reference/configuration-options> > > auth = true > > > or by converting conf file to new YAML format.
12,916,379
I've been playing with this and so far I haven't been able to find any way to hide or trick `instanceof` into returning `false` by hiding its type through layers of obfuscation, but that doesn't mean it's not possible since I'm far from the most knowledgeable person about Java. So I've come to ask the experts. I've tried the following combinations, and in each case the `instanceof` operator is able to identify the true/base type of the object. ``` public class Test { public static void main(String[] args) { Object o = new TestObject(); printType("Base Class", o); o = (TestSuperObject)(new TestObject()); printType("Super Class", o); o = (TestInterface)(new TestObject()); printType("Interface", o); o = (TestInterface)((TestSuperObject3)(new TestObject3())); printType("Interface on Super Class", o); o = (TestSuperObject3)((TestInterface)(new TestObject3())); printType("Super Class on Interface", o); } private static void printType(String testCase, Object o) { System.out.println(testCase); System.out.println("TestObject:" + (o instanceof TestObject)); System.out.println("TestObject2:" + (o instanceof TestObject2)); System.out.println("TestObject3:" + (o instanceof TestObject3)); System.out.println(); } } ``` The classes are defined as... ``` public class TestObject extends TestSuperObject implements TestInterface public class TestObject2 extends TestSuperObject implements TestInterface public interface TestInterface public class TestSuperObject public class TestObject3 extends TestSuperObject3 public class TestSuperObject3 implements TestInterface ``` So basically, is there any way to hide this information or to somehow lose the type information? I don't ask because I have a reason to do it, but rather would like to know and be wary of it in the future if it *is* possible. Plus, I just find it interesting.
2012/10/16
[ "https://Stackoverflow.com/questions/12916379", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1435657/" ]
It is possible to confuse yourself with `instanceof` but not the JVM. * classes with the same name but in different packages are not the same. This means you can do ``` // in one class ClassA classA = new ClassA(); // package1.ClassA another.test(classA); // calls in another class public void test(Object o) { if (o instanceof ClassA) // package2.ClassA => false ``` * using different class loaders the packages and `o.getClass().getName()` are the same, but as the class loaders are different `instanceof` return false. * The object is `null` and `null instanceof ClassB` is always false, even though `null` can be assigned to any reference type.
> > So basically, is there any way to hide this information or to somehow lose the type information? > > > No it is not possible. Each object has a real type, and Java's strong + static type system makes it impossible to alter the type of an object, or pretend that its actual type is different to what it is. --- (It is hypothetically possible to drop into native code and subvert the Java type system, but the consequences of doing this are likely to be really bad ... crash-the-JVM bad.)
12,916,379
I've been playing with this and so far I haven't been able to find any way to hide or trick `instanceof` into returning `false` by hiding its type through layers of obfuscation, but that doesn't mean it's not possible since I'm far from the most knowledgeable person about Java. So I've come to ask the experts. I've tried the following combinations, and in each case the `instanceof` operator is able to identify the true/base type of the object. ``` public class Test { public static void main(String[] args) { Object o = new TestObject(); printType("Base Class", o); o = (TestSuperObject)(new TestObject()); printType("Super Class", o); o = (TestInterface)(new TestObject()); printType("Interface", o); o = (TestInterface)((TestSuperObject3)(new TestObject3())); printType("Interface on Super Class", o); o = (TestSuperObject3)((TestInterface)(new TestObject3())); printType("Super Class on Interface", o); } private static void printType(String testCase, Object o) { System.out.println(testCase); System.out.println("TestObject:" + (o instanceof TestObject)); System.out.println("TestObject2:" + (o instanceof TestObject2)); System.out.println("TestObject3:" + (o instanceof TestObject3)); System.out.println(); } } ``` The classes are defined as... ``` public class TestObject extends TestSuperObject implements TestInterface public class TestObject2 extends TestSuperObject implements TestInterface public interface TestInterface public class TestSuperObject public class TestObject3 extends TestSuperObject3 public class TestSuperObject3 implements TestInterface ``` So basically, is there any way to hide this information or to somehow lose the type information? I don't ask because I have a reason to do it, but rather would like to know and be wary of it in the future if it *is* possible. Plus, I just find it interesting.
2012/10/16
[ "https://Stackoverflow.com/questions/12916379", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1435657/" ]
> > So basically, is there any way to hide this information or to somehow lose the type information? > > > No it is not possible. Each object has a real type, and Java's strong + static type system makes it impossible to alter the type of an object, or pretend that its actual type is different to what it is. --- (It is hypothetically possible to drop into native code and subvert the Java type system, but the consequences of doing this are likely to be really bad ... crash-the-JVM bad.)
You could run the code through an obfuscator. But this is basically a rename. `TestObject` may be renamed to e.g. `A`, but `instanceof A` still returns the correct result. BTW: naming your classes \*Object is a bad idea (in object oriented languages).
12,916,379
I've been playing with this and so far I haven't been able to find any way to hide or trick `instanceof` into returning `false` by hiding its type through layers of obfuscation, but that doesn't mean it's not possible since I'm far from the most knowledgeable person about Java. So I've come to ask the experts. I've tried the following combinations, and in each case the `instanceof` operator is able to identify the true/base type of the object. ``` public class Test { public static void main(String[] args) { Object o = new TestObject(); printType("Base Class", o); o = (TestSuperObject)(new TestObject()); printType("Super Class", o); o = (TestInterface)(new TestObject()); printType("Interface", o); o = (TestInterface)((TestSuperObject3)(new TestObject3())); printType("Interface on Super Class", o); o = (TestSuperObject3)((TestInterface)(new TestObject3())); printType("Super Class on Interface", o); } private static void printType(String testCase, Object o) { System.out.println(testCase); System.out.println("TestObject:" + (o instanceof TestObject)); System.out.println("TestObject2:" + (o instanceof TestObject2)); System.out.println("TestObject3:" + (o instanceof TestObject3)); System.out.println(); } } ``` The classes are defined as... ``` public class TestObject extends TestSuperObject implements TestInterface public class TestObject2 extends TestSuperObject implements TestInterface public interface TestInterface public class TestSuperObject public class TestObject3 extends TestSuperObject3 public class TestSuperObject3 implements TestInterface ``` So basically, is there any way to hide this information or to somehow lose the type information? I don't ask because I have a reason to do it, but rather would like to know and be wary of it in the future if it *is* possible. Plus, I just find it interesting.
2012/10/16
[ "https://Stackoverflow.com/questions/12916379", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1435657/" ]
> > So basically, is there any way to hide this information or to somehow lose the type information? > > > No it is not possible. Each object has a real type, and Java's strong + static type system makes it impossible to alter the type of an object, or pretend that its actual type is different to what it is. --- (It is hypothetically possible to drop into native code and subvert the Java type system, but the consequences of doing this are likely to be really bad ... crash-the-JVM bad.)
It depends on what the OP really wants, but [this](http://ideone.com/5KtHs) may do it. Basically I make the class private. This means any `object instanceof Class` code will not compile (outside the scope of the private class).
12,916,379
I've been playing with this and so far I haven't been able to find any way to hide or trick `instanceof` into returning `false` by hiding its type through layers of obfuscation, but that doesn't mean it's not possible since I'm far from the most knowledgeable person about Java. So I've come to ask the experts. I've tried the following combinations, and in each case the `instanceof` operator is able to identify the true/base type of the object. ``` public class Test { public static void main(String[] args) { Object o = new TestObject(); printType("Base Class", o); o = (TestSuperObject)(new TestObject()); printType("Super Class", o); o = (TestInterface)(new TestObject()); printType("Interface", o); o = (TestInterface)((TestSuperObject3)(new TestObject3())); printType("Interface on Super Class", o); o = (TestSuperObject3)((TestInterface)(new TestObject3())); printType("Super Class on Interface", o); } private static void printType(String testCase, Object o) { System.out.println(testCase); System.out.println("TestObject:" + (o instanceof TestObject)); System.out.println("TestObject2:" + (o instanceof TestObject2)); System.out.println("TestObject3:" + (o instanceof TestObject3)); System.out.println(); } } ``` The classes are defined as... ``` public class TestObject extends TestSuperObject implements TestInterface public class TestObject2 extends TestSuperObject implements TestInterface public interface TestInterface public class TestSuperObject public class TestObject3 extends TestSuperObject3 public class TestSuperObject3 implements TestInterface ``` So basically, is there any way to hide this information or to somehow lose the type information? I don't ask because I have a reason to do it, but rather would like to know and be wary of it in the future if it *is* possible. Plus, I just find it interesting.
2012/10/16
[ "https://Stackoverflow.com/questions/12916379", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1435657/" ]
It is possible to confuse yourself with `instanceof` but not the JVM. * classes with the same name but in different packages are not the same. This means you can do ``` // in one class ClassA classA = new ClassA(); // package1.ClassA another.test(classA); // calls in another class public void test(Object o) { if (o instanceof ClassA) // package2.ClassA => false ``` * using different class loaders the packages and `o.getClass().getName()` are the same, but as the class loaders are different `instanceof` return false. * The object is `null` and `null instanceof ClassB` is always false, even though `null` can be assigned to any reference type.
You could run the code through an obfuscator. But this is basically a rename. `TestObject` may be renamed to e.g. `A`, but `instanceof A` still returns the correct result. BTW: naming your classes \*Object is a bad idea (in object oriented languages).
12,916,379
I've been playing with this and so far I haven't been able to find any way to hide or trick `instanceof` into returning `false` by hiding its type through layers of obfuscation, but that doesn't mean it's not possible since I'm far from the most knowledgeable person about Java. So I've come to ask the experts. I've tried the following combinations, and in each case the `instanceof` operator is able to identify the true/base type of the object. ``` public class Test { public static void main(String[] args) { Object o = new TestObject(); printType("Base Class", o); o = (TestSuperObject)(new TestObject()); printType("Super Class", o); o = (TestInterface)(new TestObject()); printType("Interface", o); o = (TestInterface)((TestSuperObject3)(new TestObject3())); printType("Interface on Super Class", o); o = (TestSuperObject3)((TestInterface)(new TestObject3())); printType("Super Class on Interface", o); } private static void printType(String testCase, Object o) { System.out.println(testCase); System.out.println("TestObject:" + (o instanceof TestObject)); System.out.println("TestObject2:" + (o instanceof TestObject2)); System.out.println("TestObject3:" + (o instanceof TestObject3)); System.out.println(); } } ``` The classes are defined as... ``` public class TestObject extends TestSuperObject implements TestInterface public class TestObject2 extends TestSuperObject implements TestInterface public interface TestInterface public class TestSuperObject public class TestObject3 extends TestSuperObject3 public class TestSuperObject3 implements TestInterface ``` So basically, is there any way to hide this information or to somehow lose the type information? I don't ask because I have a reason to do it, but rather would like to know and be wary of it in the future if it *is* possible. Plus, I just find it interesting.
2012/10/16
[ "https://Stackoverflow.com/questions/12916379", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1435657/" ]
It is possible to confuse yourself with `instanceof` but not the JVM. * classes with the same name but in different packages are not the same. This means you can do ``` // in one class ClassA classA = new ClassA(); // package1.ClassA another.test(classA); // calls in another class public void test(Object o) { if (o instanceof ClassA) // package2.ClassA => false ``` * using different class loaders the packages and `o.getClass().getName()` are the same, but as the class loaders are different `instanceof` return false. * The object is `null` and `null instanceof ClassB` is always false, even though `null` can be assigned to any reference type.
It depends on what the OP really wants, but [this](http://ideone.com/5KtHs) may do it. Basically I make the class private. This means any `object instanceof Class` code will not compile (outside the scope of the private class).
73,407,561
I am trying to create a simple powershell script which will allow it to display the PID and the starttime of a process. For the moment this is my code --> ``` $proc=$args[0] if (get-process -name $proc -ErrorAction SilentlyContinue) { $time= get-process $proc | Select-Object starttime |format-table -HideTableHeaders starttime write-host $proc $time} else {write-host "non existant"} ``` When i look at the content of the variable $time , this is what is stored ``` > Microsoft.PowerShell.Commands.Internal.Format.FormatStartData > Microsoft.PowerShell.Commands.Internal.Format.GroupStartData Micr > osoft.PowerShell.Commands.Internal.Format.FormatEntryData > Microsoft.PowerShell.Commands.Internal.Format.FormatEntryData > Microsoft.Powe rShell.Commands.Internal.Format.FormatEntryData > Microsoft.PowerShell.Commands.Internal.Format.FormatEntryData > Microsoft.PowerShell.Com mands.Internal.Format.FormatEntryData > Microsoft.PowerShell.Commands.Internal.Format.FormatEntryData > Microsoft.PowerShell.Commands.Inte rnal.Format.FormatEntryData > Microsoft.PowerShell.Commands.Internal.Format.FormatEntryData > Microsoft.PowerShell.Commands.Internal.Forma t.FormatEntryData > Microsoft.PowerShell.Commands.Internal.Format.FormatEntryData > Microsoft.PowerShell.Commands.Internal.Format.FormatEn tryData > Microsoft.PowerShell.Commands.Internal.Format.FormatEntryData > Microsoft.PowerShell.Commands.Internal.Format.GroupEndData Micro > soft.PowerShell.Commands.Internal.Format.FormatEndData ``` Basicaly , what i would like to end with is a script that shows every PID and Startime for a particular application. The $time var would need to store the date "2022-08-18 1:08:39 PM" I would also create another variable called $id which would store the PID of each process. ``` 1408 notepad Started 2022-08-18 1:08:39 PM ``` Or for applications with multiple processes ``` 1409 chrome Started 2022-08-18 1:08:39 PM 14264 chrome Started 2022-08-18 1:08:40 PM 4567 chrome Started 202... ``` For the ones that have multiple processes , I guess I would use an foreach statement and go through every PID available in the variable ? Still new at this so if you have any advice on how to go about it would be appreciated , but in regards to what I know , a foreach statement would help me with this.
2022/08/18
[ "https://Stackoverflow.com/questions/73407561", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17263768/" ]
There are two common problems with your code: * `Format-*` cmdlets emit output objects whose sole purpose is to provide *formatting instructions* to PowerShell's for-display output-formatting system. In short: **only ever use `Format-*` cmdlets to format data *for display*, never for subsequent *programmatic processing*** - see [this answer](https://stackoverflow.com/a/55174715/45375) for more information. * The reason you tried to use `Format-Table` to begin with was in order to get just the `.StartTime` property *value*. The proper way **to get [`Select-Object`](https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/select-object) to output just a property *value*** is to use the **`-ExpandProperty`** parameter, i.e. `-ExpandProperty starttime` instead of `[-Property] starrttime`. + See [this answer](https://stackoverflow.com/q/48807857/45375) for details and alternatives. --- A PowerShell-idiomatic solution would look something like this: ``` $proc = $args[0] # Process all matching processes, if any. Get-Process $proc -ErrorAction SilentlyContinue | ForEach-Object { '{0} {1} Started {2}' -f $_.Id, $_.Name, $_.StartTime } # $? contains $false if an error occurred in the previous statement. if (-not $?) { Write-Warning "Non-existent: $proc" } ``` That is, matching processes are processed one by one using [`ForEach-Object`](https://learn.microsoft.com/powershell/module/microsoft.powershell.core/foreach-object), and in the [script block](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_Script_Blocks) (`{ ... }`) passed to it you can refer to the process-info object ([`System.Diagnostics.Process`](https://learn.microsoft.com/en-US/dotnet/api/System.Diagnostics.Process)) at hand via the [automatic `$_` variable](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_Automatic_Variables#_) variable, allowing you to access the properties of interest directly on that object. The [`-f` operator](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_Operators#format-operator--f) is used to synthesize the output strings in the desired format. Sample output: ```none 56204 bash Started 8/18/2022 2:15:25 PM 56245 bash Started 8/18/2022 2:15:28 PM ```
Found an answer for my own question. If anyone else is wondering why this happens , it is all explained in this post. [How can I store output from Format-Table for later use](https://stackoverflow.com/questions/36358047/how-can-i-store-output-from-format-table-for-later-use)
269,171
For a particular problem, I need to have a list that: 1. supports `O(1)` prepend, and 2. that I can call [`bisect.bisect_left`](https://docs.python.org/3.9/library/bisect.html?highlight=bisect#bisect.bisect_left) on, which means the list must be sorted. Prepending to a list via `list.insert(0, item)` is `O(N)`; however, `O(1)` prepend can be emulated by maintaining the list in reverse order in which case `list.append` emulates `O(1)` `prepend`. This would work, except that `bisect_left` only works for sorted input, not reverse sorted input. Other functions, like `min`, allow for reverse sorted order input (or input of arbitrary ordering) with their `key` argument; unfortunately, `bisect_left` does not have a `key` argument for performance reasons. I have a workaround which I would like reviewed. It's a class that subclasses `list`. The class stores the list in reverse order so that prepend can be implemented via `O(1)` `append`, but overrides `__getitem__` and other methods so that from the outside (including from `bisect_left`'s view), it looks like the list is in normal order. This way, the list can be used by `bisect_left` and other functions that only work on sorted order input, and not on reverse sorted order input. The only indication that I have found so far that the list is in reverse is if you `print` it: ``` class PrependableList(list): '''List with O(1) "prepend". (appending is O(N))''' def __init__(self, l): super().__init__(reversed(l)) def __getitem__(self, index): N = len(self) index = N - 1 - index return super().__getitem__(index) def __setitem__(self, index, item): N = len(self) index = N - 1 - index return super().__setitem__(index, item) def __iter__(self): return reversed(self) def prepend(self, item): super().append(item) # Are there any other `list` methods that I should override? from bisect import bisect_left nums = PrependableList([5,10,15,20]) nums.prepend(0) print(nums) # [20, 15, 10, 5, 0] # <- how to make this print `[0, 5, 10, 15, 20]` instead? for i in range(len(nums)): print(nums[i]) # uses __getitem__ # prints: # 0 # 5 # 10 # 15 # 20 for num in nums: # uses __iter__ print(num) # prints: # 0 # 5 # 10 # 15 # 20 # `bisect_left` works! for num in range(0, 55): print(f'{num}: {bisect_left(nums, num)}') # uses __getitem__ # prints: # 0: 0 # 1: 1 # 2: 1 # 3: 1 # 4: 1 # 5: 1 # 6: 2 # 7: 2 # 8: 2 # 9: 2 # 10: 2 # 11: 3 # 12: 3 # 13: 3 # 14: 3 # 15: 3 # 16: 4 # 17: 4 # 18: 4 # 19: 4 # 20: 4 # 21: 5 # 22: 5 # 23: 5 # 24: 5 # 25: 5 # 26: 5 # 27: 5 # 28: 5 # 29: 5 # 30: 5 # 31: 5 # 32: 5 # 33: 5 # 34: 5 # 35: 5 # 36: 5 # 37: 5 # 38: 5 # 39: 5 # 40: 5 # 41: 5 # 42: 5 # 43: 5 # 44: 5 # 45: 5 # 46: 5 # 47: 5 # 48: 5 # 49: 5 # 50: 5 # 51: 5 # 52: 5 # 53: 5 # 54: 5 ``` Should just use a `deque`?
2021/10/20
[ "https://codereview.stackexchange.com/questions/269171", "https://codereview.stackexchange.com", "https://codereview.stackexchange.com/users/239973/" ]
> > Should just use a `deque`? > > > No. Unless you're ok with `bisect_left` taking O(n log n) instead of O(log n). Your class doesn't support negative indexes, like lists normally do. Not saying you should add that (up to you, doesn't sound like you need it), but you can take advantage of lists supporting it to simplify your methods: ``` def __getitem__(self, index): return super().__getitem__(~index) def __setitem__(self, index, item): return super().__setitem__(~index, item) ``` Benchmark of `bisect_left` searching the middle value of a list, deque or PrependableList of a million elements: ``` 0.41 μs bisect_left(lst, middle) 751.68 μs bisect_left(deq, middle) 5.77 μs bisect_left(ppl, middle) ``` Benchmark code ([Try it online!](https://tio.run/##fVFBasMwELzrFXsJkoJJnARCKeSYWw@9l2KSaJ0KZFmV5NJe@rK@oV9yV5aTGALVQbAzo9ndkfuKb63dPDjf97VvG4i6QR1BN671cawYCxg7BzvgnLNBdmqNwVPUrQ0XrcL3DjN71IHIC5GrymBNTidzCAGePTq06nA0@KRDFIYu@ciAjsIaqkpbHatKBDR1AWak0gmdQy/k4irx@IE@oBJGyonBGaOO2Fw9tFX4OfHxtJG3E7vbg@@sZczSxqsS5nPYskYrZZAAC8slrJkJkYo0t/AHe0ZhqT1FQOAQhCCBZM4ZAu62TVSKku2JfRlm4pOUkqCA3FHy4p6nDv/y1HbKvzJWtx4qCgHysJsxiQRjgve3ZNJe@d8FFjD8fAG2a47od6uyLOVV6by2UfDZdrGu4fcnAIcZiAhzWOFGFoBZmmWy7/8A "Python 3.8 (pre-release) – Try It Online")): ``` from timeit import timeit setup = ''' from collections import deque from bisect import bisect_left class PrependableList(list): def __init__(self, l): super().__init__(reversed(l)) def __getitem__(self, index): return super().__getitem__(~index) n = 10 ** 6 middle = n // 2 lst = list(range(n)) deq = deque(lst) ppl = PrependableList(lst) ''' E = [ 'bisect_left(lst, middle)', 'bisect_left(deq, middle)', 'bisect_left(ppl, middle)', ] for _ in range(3): for e in E: t = timeit(e, setup, number=1000) print('%6.2f μs ' % (t * 1e3), e) print() ```
> > Should I just use a `deque`? > > > Maybe, it depends on what exactly you're trying to do, but probably not - as dont talk just code pointed out, `deque` does not offer efficient access to elements near the middle, which is very much not great for binary search. Which is unfortunate, since this approach does come with a very real risk of missing pieces of functionality, especially if the base `list` class gets updated in future Though the `help` built-in function can help avoid that by providing a list of known methods of a class > > `# Are there any other list methods that I should override?` > > > Well, there are several non-overridden methods which behave in unexpected ways * While `__getitem__` and `__setitem__` do the right thing, `__delitem__` deletes the wrong element * As does `pop`, `insert` and `index` get indexes wrong * Likewise, `append` and `extend` don't append elements but prepend them instead * `__reversed__` returns the same result as `__iter__`, which is probably not a good idea * `sort` effectively sorts in reverse order * `__add__` places the lists in the wrong order - `[1,2] + [3,4] == [1,2,3,4]`, but `PrependableList([1,2]) + PrependableList([3,4]) == PrependableList([3,4,1,2])`. `__iadd__` has the same problem * You yourself noted that the list doesn't get printed in the expected manner - that's because `__repr__` isn't overridden And finally, the current implementations of `__getitem__` and `__setitem__` don't support slices - `PrependableList([1,2,3,4,5])[1:3]` raises a `TypeError`
74,344,367
I have a data frame: ``` pl.DataFrame({'no_of_docs':[[9,4,2], [3,9,1,10], [10,3,2,1], [10,30], [1,2,3,6,4,5]]}) ``` Here the column: no\_of\_docs is a list[int] type one: i would like to add a new column with the max value index from each list? Another case: ``` pl.DataFrame({'no_of_docs':[['9','4','2'], ['3','9','1','10'], ['10','3','2','1'], ['10','30'], ['1','2','3','6','4','5']]}) ``` Here no\_of\_docs is a type of list[str] and how to convert it to int and get an index of max value. Expected output: [![enter image description here](https://i.stack.imgur.com/gBtI5.png)](https://i.stack.imgur.com/gBtI5.png)
2022/11/07
[ "https://Stackoverflow.com/questions/74344367", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9479925/" ]
I have found a way to do it for list[int] type as below: ``` df.with_column(pl.col('no_of_docs').arr.arg_max().alias('idx') ``` The same thing to be done to list[str] type.
Can you try this code please : ```py df['idx']=[sub_list.index(max(sub_list)) for sub_list in df['no_of_docs']] ```
74,344,367
I have a data frame: ``` pl.DataFrame({'no_of_docs':[[9,4,2], [3,9,1,10], [10,3,2,1], [10,30], [1,2,3,6,4,5]]}) ``` Here the column: no\_of\_docs is a list[int] type one: i would like to add a new column with the max value index from each list? Another case: ``` pl.DataFrame({'no_of_docs':[['9','4','2'], ['3','9','1','10'], ['10','3','2','1'], ['10','30'], ['1','2','3','6','4','5']]}) ``` Here no\_of\_docs is a type of list[str] and how to convert it to int and get an index of max value. Expected output: [![enter image description here](https://i.stack.imgur.com/gBtI5.png)](https://i.stack.imgur.com/gBtI5.png)
2022/11/07
[ "https://Stackoverflow.com/questions/74344367", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9479925/" ]
I mean you answered the question mostly yourself, but in case you still need the casting to List[i64]. Here would be the solution ``` df.with_column( pl.col("no_of_docs").cast(pl.List(pl.Int64)).arr.arg_max().alias('idx') ) shape: (5, 2) ┌──────────────────────┬─────┐ │ no_of_docs ┆ idx │ │ --- ┆ --- │ │ list[str] ┆ u32 │ ╞══════════════════════╪═════╡ │ ["9", "4", "2"] ┆ 0 │ ├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌┤ │ ["3", "9", ... "10"] ┆ 3 │ ├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌┤ │ ["10", "3", ... "1"] ┆ 0 │ ├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌┤ │ ["10", "30"] ┆ 1 │ ├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌┤ │ ["1", "2", ... "5"] ┆ 3 │ └──────────────────────┴─────┘ ```
Can you try this code please : ```py df['idx']=[sub_list.index(max(sub_list)) for sub_list in df['no_of_docs']] ```
1,646,326
I'm soon to launch a [beta app](http://www.bestsellerapp.com/) and this have the option to create custom integration scripts on [Python](http://en.wikipedia.org/wiki/Python_(programming_language)). The app will target [Mac OS X](http://en.wikipedia.org/wiki/Mac_OS_X) and Windows, and my problem is with Windows where Python normally is not present. My actual aproach is silently run the Python 2.6 install. However I face the problem that is not activated by default and the path is not set when use the [command line options](http://www.python.org/download/releases/2.5/msi/). And I fear that if Python is installed before and I upgrade to a new version this could break something else... So, I wonder how this can be done cleanly. Is it OK if I copy the whole Python 2.6 directory, and put it in a sub-directory of my app and install everything there? Or with virtualenv is posible run diferents versions of Python (if Python is already installed in the machine?). I also play before embedding Python with a DLL, and found it easy but I lost the ability to debug, so I switch to command-line plug-ins. I execute the plug-ins from command line and read the STDOUT and STDERR output. The app is made with Delphi/Lazarus. I install others modules like JSON and RPC clients, Win32com, ORM, etc. I create the installer with [bitrock](http://bitrock.com/). UPDATE: The end-users are small business owners, and the Python scripts are made by developers. I want to avoid any additional step in the deployment, so I want a fully integrated setup.
2009/10/29
[ "https://Stackoverflow.com/questions/1646326", "https://Stackoverflow.com", "https://Stackoverflow.com/users/53185/" ]
Copy a [Portable Python](http://www.portablepython.com/) folder out of your installer, into the same folder as your Delphi/Lazarus app. Set all paths appropriately for that.
You might try using [py2exe](http://www.py2exe.org/). It creates a .exe file with Python already included!
1,646,326
I'm soon to launch a [beta app](http://www.bestsellerapp.com/) and this have the option to create custom integration scripts on [Python](http://en.wikipedia.org/wiki/Python_(programming_language)). The app will target [Mac OS X](http://en.wikipedia.org/wiki/Mac_OS_X) and Windows, and my problem is with Windows where Python normally is not present. My actual aproach is silently run the Python 2.6 install. However I face the problem that is not activated by default and the path is not set when use the [command line options](http://www.python.org/download/releases/2.5/msi/). And I fear that if Python is installed before and I upgrade to a new version this could break something else... So, I wonder how this can be done cleanly. Is it OK if I copy the whole Python 2.6 directory, and put it in a sub-directory of my app and install everything there? Or with virtualenv is posible run diferents versions of Python (if Python is already installed in the machine?). I also play before embedding Python with a DLL, and found it easy but I lost the ability to debug, so I switch to command-line plug-ins. I execute the plug-ins from command line and read the STDOUT and STDERR output. The app is made with Delphi/Lazarus. I install others modules like JSON and RPC clients, Win32com, ORM, etc. I create the installer with [bitrock](http://bitrock.com/). UPDATE: The end-users are small business owners, and the Python scripts are made by developers. I want to avoid any additional step in the deployment, so I want a fully integrated setup.
2009/10/29
[ "https://Stackoverflow.com/questions/1646326", "https://Stackoverflow.com", "https://Stackoverflow.com/users/53185/" ]
You might try using [py2exe](http://www.py2exe.org/). It creates a .exe file with Python already included!
Integrate the python interpreter into your Delphi app with [P4D](http://python4delphi.googlecode.com/svn/trunk/). These components actually work, and in both directions too (Delphi classes exposed to Python as binary extensions, and Python interpreter inside Delphi). I also saw a patch for Lazarus compatibility on the Google Code "issues" page, but it seems there might be some unresolved issues there.
1,646,326
I'm soon to launch a [beta app](http://www.bestsellerapp.com/) and this have the option to create custom integration scripts on [Python](http://en.wikipedia.org/wiki/Python_(programming_language)). The app will target [Mac OS X](http://en.wikipedia.org/wiki/Mac_OS_X) and Windows, and my problem is with Windows where Python normally is not present. My actual aproach is silently run the Python 2.6 install. However I face the problem that is not activated by default and the path is not set when use the [command line options](http://www.python.org/download/releases/2.5/msi/). And I fear that if Python is installed before and I upgrade to a new version this could break something else... So, I wonder how this can be done cleanly. Is it OK if I copy the whole Python 2.6 directory, and put it in a sub-directory of my app and install everything there? Or with virtualenv is posible run diferents versions of Python (if Python is already installed in the machine?). I also play before embedding Python with a DLL, and found it easy but I lost the ability to debug, so I switch to command-line plug-ins. I execute the plug-ins from command line and read the STDOUT and STDERR output. The app is made with Delphi/Lazarus. I install others modules like JSON and RPC clients, Win32com, ORM, etc. I create the installer with [bitrock](http://bitrock.com/). UPDATE: The end-users are small business owners, and the Python scripts are made by developers. I want to avoid any additional step in the deployment, so I want a fully integrated setup.
2009/10/29
[ "https://Stackoverflow.com/questions/1646326", "https://Stackoverflow.com", "https://Stackoverflow.com/users/53185/" ]
You might try using [py2exe](http://www.py2exe.org/). It creates a .exe file with Python already included!
I think there's no problem combining .EXE packaging with a tool like PyInstaller or py2exe and Python-written plugins. The created .EXE can easily detect where it's installed and the code inside can then simply `import` files from some pre-determined plugin directory. Don't forget that once you package a Python script into an executable, it also packages the Python interpreter inside, so there you have it - a full Python environment customized with your own code.
1,646,326
I'm soon to launch a [beta app](http://www.bestsellerapp.com/) and this have the option to create custom integration scripts on [Python](http://en.wikipedia.org/wiki/Python_(programming_language)). The app will target [Mac OS X](http://en.wikipedia.org/wiki/Mac_OS_X) and Windows, and my problem is with Windows where Python normally is not present. My actual aproach is silently run the Python 2.6 install. However I face the problem that is not activated by default and the path is not set when use the [command line options](http://www.python.org/download/releases/2.5/msi/). And I fear that if Python is installed before and I upgrade to a new version this could break something else... So, I wonder how this can be done cleanly. Is it OK if I copy the whole Python 2.6 directory, and put it in a sub-directory of my app and install everything there? Or with virtualenv is posible run diferents versions of Python (if Python is already installed in the machine?). I also play before embedding Python with a DLL, and found it easy but I lost the ability to debug, so I switch to command-line plug-ins. I execute the plug-ins from command line and read the STDOUT and STDERR output. The app is made with Delphi/Lazarus. I install others modules like JSON and RPC clients, Win32com, ORM, etc. I create the installer with [bitrock](http://bitrock.com/). UPDATE: The end-users are small business owners, and the Python scripts are made by developers. I want to avoid any additional step in the deployment, so I want a fully integrated setup.
2009/10/29
[ "https://Stackoverflow.com/questions/1646326", "https://Stackoverflow.com", "https://Stackoverflow.com/users/53185/" ]
Copy a [Portable Python](http://www.portablepython.com/) folder out of your installer, into the same folder as your Delphi/Lazarus app. Set all paths appropriately for that.
Integrate the python interpreter into your Delphi app with [P4D](http://python4delphi.googlecode.com/svn/trunk/). These components actually work, and in both directions too (Delphi classes exposed to Python as binary extensions, and Python interpreter inside Delphi). I also saw a patch for Lazarus compatibility on the Google Code "issues" page, but it seems there might be some unresolved issues there.
1,646,326
I'm soon to launch a [beta app](http://www.bestsellerapp.com/) and this have the option to create custom integration scripts on [Python](http://en.wikipedia.org/wiki/Python_(programming_language)). The app will target [Mac OS X](http://en.wikipedia.org/wiki/Mac_OS_X) and Windows, and my problem is with Windows where Python normally is not present. My actual aproach is silently run the Python 2.6 install. However I face the problem that is not activated by default and the path is not set when use the [command line options](http://www.python.org/download/releases/2.5/msi/). And I fear that if Python is installed before and I upgrade to a new version this could break something else... So, I wonder how this can be done cleanly. Is it OK if I copy the whole Python 2.6 directory, and put it in a sub-directory of my app and install everything there? Or with virtualenv is posible run diferents versions of Python (if Python is already installed in the machine?). I also play before embedding Python with a DLL, and found it easy but I lost the ability to debug, so I switch to command-line plug-ins. I execute the plug-ins from command line and read the STDOUT and STDERR output. The app is made with Delphi/Lazarus. I install others modules like JSON and RPC clients, Win32com, ORM, etc. I create the installer with [bitrock](http://bitrock.com/). UPDATE: The end-users are small business owners, and the Python scripts are made by developers. I want to avoid any additional step in the deployment, so I want a fully integrated setup.
2009/10/29
[ "https://Stackoverflow.com/questions/1646326", "https://Stackoverflow.com", "https://Stackoverflow.com/users/53185/" ]
Copy a [Portable Python](http://www.portablepython.com/) folder out of your installer, into the same folder as your Delphi/Lazarus app. Set all paths appropriately for that.
I think there's no problem combining .EXE packaging with a tool like PyInstaller or py2exe and Python-written plugins. The created .EXE can easily detect where it's installed and the code inside can then simply `import` files from some pre-determined plugin directory. Don't forget that once you package a Python script into an executable, it also packages the Python interpreter inside, so there you have it - a full Python environment customized with your own code.
1,646,326
I'm soon to launch a [beta app](http://www.bestsellerapp.com/) and this have the option to create custom integration scripts on [Python](http://en.wikipedia.org/wiki/Python_(programming_language)). The app will target [Mac OS X](http://en.wikipedia.org/wiki/Mac_OS_X) and Windows, and my problem is with Windows where Python normally is not present. My actual aproach is silently run the Python 2.6 install. However I face the problem that is not activated by default and the path is not set when use the [command line options](http://www.python.org/download/releases/2.5/msi/). And I fear that if Python is installed before and I upgrade to a new version this could break something else... So, I wonder how this can be done cleanly. Is it OK if I copy the whole Python 2.6 directory, and put it in a sub-directory of my app and install everything there? Or with virtualenv is posible run diferents versions of Python (if Python is already installed in the machine?). I also play before embedding Python with a DLL, and found it easy but I lost the ability to debug, so I switch to command-line plug-ins. I execute the plug-ins from command line and read the STDOUT and STDERR output. The app is made with Delphi/Lazarus. I install others modules like JSON and RPC clients, Win32com, ORM, etc. I create the installer with [bitrock](http://bitrock.com/). UPDATE: The end-users are small business owners, and the Python scripts are made by developers. I want to avoid any additional step in the deployment, so I want a fully integrated setup.
2009/10/29
[ "https://Stackoverflow.com/questions/1646326", "https://Stackoverflow.com", "https://Stackoverflow.com/users/53185/" ]
Integrate the python interpreter into your Delphi app with [P4D](http://python4delphi.googlecode.com/svn/trunk/). These components actually work, and in both directions too (Delphi classes exposed to Python as binary extensions, and Python interpreter inside Delphi). I also saw a patch for Lazarus compatibility on the Google Code "issues" page, but it seems there might be some unresolved issues there.
I think there's no problem combining .EXE packaging with a tool like PyInstaller or py2exe and Python-written plugins. The created .EXE can easily detect where it's installed and the code inside can then simply `import` files from some pre-determined plugin directory. Don't forget that once you package a Python script into an executable, it also packages the Python interpreter inside, so there you have it - a full Python environment customized with your own code.
156,539
I always visit one website which I don't want others to see the title of. I want that whenever I open that site my title of that site changes to something else or hide. There is a addonon in Firefox which can hide the title of window, but I have to manually click on hide title. Is there something which can do it automatically for a particular website?
2010/06/25
[ "https://superuser.com/questions/156539", "https://superuser.com", "https://superuser.com/users/24524/" ]
Use Greasemonkey. Write a script that changes the page title.
Use `F11` to toggle Firefox's **full screen mode** - that will hide the title and URL.
156,539
I always visit one website which I don't want others to see the title of. I want that whenever I open that site my title of that site changes to something else or hide. There is a addonon in Firefox which can hide the title of window, but I have to manually click on hide title. Is there something which can do it automatically for a particular website?
2010/06/25
[ "https://superuser.com/questions/156539", "https://superuser.com", "https://superuser.com/users/24524/" ]
Use Greasemonkey. Write a script that changes the page title.
As Graphain said, use [Greasemonkey](https://addons.mozilla.org/en-US/firefox/addon/748/). And, because it's easy fun, I have written the GM script for you. :) ``` // ==UserScript== // @name Title Changer for web page XXX // @namespace Google // @include YourWebsiteHere.tld/* // ==/UserScript== window.addEventListener ("load", Greasemonkey_main, false); Greasemonkey_main (); function Greasemonkey_main () { document.title = 'This is NOT the Highly Incriminating website you are looking for!'; } ``` . A place to find additional scripts is: <http://userscripts.org/> .
156,539
I always visit one website which I don't want others to see the title of. I want that whenever I open that site my title of that site changes to something else or hide. There is a addonon in Firefox which can hide the title of window, but I have to manually click on hide title. Is there something which can do it automatically for a particular website?
2010/06/25
[ "https://superuser.com/questions/156539", "https://superuser.com", "https://superuser.com/users/24524/" ]
As Graphain said, use [Greasemonkey](https://addons.mozilla.org/en-US/firefox/addon/748/). And, because it's easy fun, I have written the GM script for you. :) ``` // ==UserScript== // @name Title Changer for web page XXX // @namespace Google // @include YourWebsiteHere.tld/* // ==/UserScript== window.addEventListener ("load", Greasemonkey_main, false); Greasemonkey_main (); function Greasemonkey_main () { document.title = 'This is NOT the Highly Incriminating website you are looking for!'; } ``` . A place to find additional scripts is: <http://userscripts.org/> .
Use `F11` to toggle Firefox's **full screen mode** - that will hide the title and URL.
52,547
I need to look for some requests in a huge pile of apache logs. My only requirement is this: I need to only view the requests coming from any IP address that is NOT included in a list of 50 IP ranges I have. How can I make that happen using any combination of regexes awk grep or anything? Can't think of an easy way. The idea would be to get each line, get the first part (the IP address), match it to a file with all the ranges, and if its not there, then display it. No idea on how to go about doing this, so any help is welcome! Samples: a Typical http log line is ``` 123.456.789.012 - - [22/Oct/2012:06:37:48 +0100] "GET /test/test HTTP/1.1" 302 224 "-" "some user agent/4.3.5" ``` A typical line out of my IP ranges file is ``` 192.168.0.1 - 192.168.0.255 ``` Of cours ethe IP ranges file could be converted to 192.168.0.1/24 notation if necessary. The good thing is that all the ranges are Class C (just noticed that), so I guess only the first 3 parts of the IP address could be matched and that should be good enough.
2012/10/22
[ "https://unix.stackexchange.com/questions/52547", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/26150/" ]
A simple and crude way could be to use grep. Create a file ( *ranges.txt* ) with you're ranges something like this: ``` 192\.168\.0\.[0-9]* 10\.0\.0\.[0-9]* ``` To create that file from the range-file you already had you could use `sed` like so: ``` sed -n -e 's/^\([0-9]*\)\.\([0-9]*\)\.\([0-9]*\)\.\([0-9]*\) .*$/^\1\\.\2\\.\3\\.[0-9]* /p' your-range-file > ranges.txt ``` Then exclude lines matching the pattern in that file using grep like so: ``` $ grep -v -f ranges.txt apache-log-file.log ``` or ``` $ cat apache-log-file.log | < do some pre cleaning > | grep -v -f ranges.txt ``` This could help you to get started but its probably not a good solutions if the query should be run often and on big log-files. Good luck!
Log is your log file, and iprange is your file containing the ipranges. Perl part of the solution gets the first 3 components of your ip address, and the for loop prints it if it does not exist in the file ipranges: ``` for i in `perl -lne 'print $1 if (m/(\d{1,3}\.\d{1,3}\.\d{1,3})\.\d{1,3}/);' log` > do > grep -q $i iprange || echo $i; > done ```
53,843,378
In a React project, I want to dynamically access an object property name using a string variable I pass through props. I am able to pass a value as string; however, when I try to use it to access the object property it doesn't work. Here's an example: ``` const passedField = 'title'; // this comes from props const book = { title: 'Sample title', content : 'some content' }; book.passedField; // returns undefined ``` I access title like this `book.title` I want to access it like `book.passedField` but I get undefined on console. How can I achieve this?
2018/12/19
[ "https://Stackoverflow.com/questions/53843378", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1661286/" ]
What you're using is called a [`dot notation`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors#Dot_notation) property accessor. What you need to use is a [`bracket notation`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors#Bracket_notation) property accessor. `book.title` and `book['title']` are the same, which means you can assign `title` to a variable, and use the variable name instead like this. ``` const passedField = 'title'; book[passedField]; // same as book['title'] ``` You might only be familiar with `bracket notation` with Arrays, like `myArray[0]`, but they work with Objects too! (because Arrays in JavaScript are actually objects) ### Solution ```js const books = [ { title: 'The Art of War', contents: 'An ancient Chinese military treatise dating from the Spring and Autumn Period' }, { title: 'Winnie the Pooh', contents: 'Pooh is naive and slow-witted, but he is also friendly, thoughtful, and steadfast.' } ] class Book extends React.Component { constructor(props) { super(props); this.findBookByFilter = this.findBookByFilter.bind(this); } findBookByFilter() { let result = null if (books) { const {passedFilterField, filterText} = this.props; result = books.filter(book => { return book[passedFilterField].toLowerCase().includes(filterText.toLowerCase()); }).map(book => <p>{book.title}</p>) } return result; } render () { return this.findBookByFilter(); } } class App extends React.Component { render() { return ( <Book passedFilterField='contents' filterText='thoughtful' /> ) } } ReactDOM.render(<App />, document.getElementById('root')); ``` ```html <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <div id="root"></div> ``` ### Notes * I moved your `{book && book.filter}` logic to a function called `findBookByFilter` * I used `includes` instead of `indexOf` in the `filter` * I used destructuring assignment for `this.props` * I return the matched title, rather than `<Link />` for demo purposes. ### Documentation <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors> <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes> <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment>
You can access object properties using `book[passedField]`
53,843,378
In a React project, I want to dynamically access an object property name using a string variable I pass through props. I am able to pass a value as string; however, when I try to use it to access the object property it doesn't work. Here's an example: ``` const passedField = 'title'; // this comes from props const book = { title: 'Sample title', content : 'some content' }; book.passedField; // returns undefined ``` I access title like this `book.title` I want to access it like `book.passedField` but I get undefined on console. How can I achieve this?
2018/12/19
[ "https://Stackoverflow.com/questions/53843378", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1661286/" ]
`book.passedField` will be returning undefined because there is no `passedField` in `book`. Instead use bracket notation as below ```js const book = { title: 'abc', pages: 350 }; const passedField = 'pages'; console.log(book[passedField]) ```
You can access object properties using `book[passedField]`
69,177,214
I want to consume messages with AvroConfluent format from kafka topic and store them in a clickhouse table so i created a table with kafka engine and I entered my schema registry url in table settings, but the schema registry server needs basic authentication which I am not sure where and how should I put my user information. like kafka authentication configuration I tried putting my information in config.xml file for clickhouse-server but apparently it is not working
2021/09/14
[ "https://Stackoverflow.com/questions/69177214", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16908481/" ]
This is a bug introduced in KDiff3 version 1.8.6. To fix it, uninstall your version of KDiff3 and install KDiff3 version 1.8.5. It should work. Here is a link to download: <https://download.kde.org/stable/kdiff3/> References: * <https://bugs.freebsd.org/bugzilla/show_bug.cgi?id=256606> * <https://invent.kde.org/sdk/kdiff3/-/issues/25#register-pane> EDIT: This bug will be fixed in 1.9.4 which will be released in few days. <https://bugs.kde.org/show_bug.cgi?id=442199>
FYI, I had this bug with 1.9.4. Upgrading to 1.9.5 fixes that.
39,468,640
I am currently trying to export a trained TensorFlow model as a ProtoBuf file to use it with the TensorFlow C++ API on Android. Therefore, I'm using the [`freeze_graph.py`](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/tools/freeze_graph.py) script. I exported my model using `tf.train.write_graph`: `tf.train.write_graph(graph_def, FLAGS.save_path, out_name, as_text=True)` and I'm using a checkpoint saved with `tf.train.Saver`. I invoke `freeze_graph.py` as described at the top of the script. After compiling, I run ``` bazel-bin/tensorflow/python/tools/freeze_graph \ --input_graph=<path_to_protobuf_file> \ --input_checkpoint=<model_name>.ckpt-10000 \ --output_graph=<output_protobuf_file_path> \ --output_node_names=dropout/mul_1 ``` This gives me the following error message: ``` TypeError: Cannot interpret feed_dict key as Tensor: The name 'save/Const:0' refers to a Tensor which does not exist. The operation, 'save/Const', does not exist in the graph. ``` As the error states I do not have a tensor `save/Const:0` in my exported model. However, the code of `freeze_graph.py` says that one can specify this tensor name by the flag `filename_tensor_name`. Unfortunately I cannot find any information on what this tensor should be and how to set it correctly for my model. Can somebody tell my either how to produce a `save/Const:0` tensor in my exported ProtoBuf model or how to set the flag `filename_tensor_name` correctly?
2016/09/13
[ "https://Stackoverflow.com/questions/39468640", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2206976/" ]
The `--filename_tensor_name` flag is used to specify the name of a placeholder tensor created when you construct a [`tf.train.Saver`](https://www.tensorflow.org/versions/r0.10/api_docs/python/state_ops.html#Saver) for your model.\* In your original program, you can print out the value of `saver.saver_def.filename_tensor_name` to get the value that you should pass for this flag. You may also want to print the value of `saver.saver_def.restore_op_name` to get a value for the `--restore_op_name` flag (since I suspect the default won't be correct for your graph). Alternatively, the [`tf.train.SaverDef` protocol buffer](https://github.com/tensorflow/tensorflow/blob/91a70cbf1c627117b70a3d2dd4c612779369e293/tensorflow/core/protobuf/saver.proto) includes all of the information you need to reconstruct the relevant information for these flags. If you prefer, you can write `saver.saver_def` to a file, and pass the name of that file as the `--input_saver` flag to `freeze_graph.py`. ---  \* The default name scope for a `tf.train.Saver` is `"save/"` and the placeholder is [actually a `tf.constant()`](https://github.com/tensorflow/tensorflow/blob/91a70cbf1c627117b70a3d2dd4c612779369e293/tensorflow/python/training/saver.py#L609) whose name defaults to `"Const:0"`, which explains why the flag defaults to `"save/Const:0"`.
I noticed that error happened to me when I had code arranged like this: ``` sess = tf.Session() tf.train.write_graph(sess.graph_def, '', '/tmp/train.pbtxt') init = tf.initialize_all_variables() saver = tf.train.Saver() sess.run(init) ``` It worked after I changed code layout like this: ``` # Add ops to save and restore all the variables. saver = tf.train.Saver() init = tf.initialize_all_variables() sess = tf.Session() tf.train.write_graph(sess.graph_def, '', '/tmp/train.pbtxt') sess.run(init) ``` I'm not really sure why is that. @mrry could you explain it a bit more?
39,468,640
I am currently trying to export a trained TensorFlow model as a ProtoBuf file to use it with the TensorFlow C++ API on Android. Therefore, I'm using the [`freeze_graph.py`](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/tools/freeze_graph.py) script. I exported my model using `tf.train.write_graph`: `tf.train.write_graph(graph_def, FLAGS.save_path, out_name, as_text=True)` and I'm using a checkpoint saved with `tf.train.Saver`. I invoke `freeze_graph.py` as described at the top of the script. After compiling, I run ``` bazel-bin/tensorflow/python/tools/freeze_graph \ --input_graph=<path_to_protobuf_file> \ --input_checkpoint=<model_name>.ckpt-10000 \ --output_graph=<output_protobuf_file_path> \ --output_node_names=dropout/mul_1 ``` This gives me the following error message: ``` TypeError: Cannot interpret feed_dict key as Tensor: The name 'save/Const:0' refers to a Tensor which does not exist. The operation, 'save/Const', does not exist in the graph. ``` As the error states I do not have a tensor `save/Const:0` in my exported model. However, the code of `freeze_graph.py` says that one can specify this tensor name by the flag `filename_tensor_name`. Unfortunately I cannot find any information on what this tensor should be and how to set it correctly for my model. Can somebody tell my either how to produce a `save/Const:0` tensor in my exported ProtoBuf model or how to set the flag `filename_tensor_name` correctly?
2016/09/13
[ "https://Stackoverflow.com/questions/39468640", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2206976/" ]
The `--filename_tensor_name` flag is used to specify the name of a placeholder tensor created when you construct a [`tf.train.Saver`](https://www.tensorflow.org/versions/r0.10/api_docs/python/state_ops.html#Saver) for your model.\* In your original program, you can print out the value of `saver.saver_def.filename_tensor_name` to get the value that you should pass for this flag. You may also want to print the value of `saver.saver_def.restore_op_name` to get a value for the `--restore_op_name` flag (since I suspect the default won't be correct for your graph). Alternatively, the [`tf.train.SaverDef` protocol buffer](https://github.com/tensorflow/tensorflow/blob/91a70cbf1c627117b70a3d2dd4c612779369e293/tensorflow/core/protobuf/saver.proto) includes all of the information you need to reconstruct the relevant information for these flags. If you prefer, you can write `saver.saver_def` to a file, and pass the name of that file as the `--input_saver` flag to `freeze_graph.py`. ---  \* The default name scope for a `tf.train.Saver` is `"save/"` and the placeholder is [actually a `tf.constant()`](https://github.com/tensorflow/tensorflow/blob/91a70cbf1c627117b70a3d2dd4c612779369e293/tensorflow/python/training/saver.py#L609) whose name defaults to `"Const:0"`, which explains why the flag defaults to `"save/Const:0"`.
It should not be problematic in latest freeze\_graph.py as I could see these removed: `del restore_op_name, filename_tensor_name # Unused by updated loading code.` [source:freeze\_graph.py](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/tools/freeze_graph.py) In earlier version, it was using restore\_op to restore the model `sess.run([restore_op_name], {filename_tensor_name: input_checkpoint})` So, for previous version, if you are writing the graph in .pb file before instantiating saver op, it will problematic. eg.: ``` tf.train.write_graph(sess.graph_def, "./logs", "test2.pb", False) saver = tf.train.Saver() saver.save(sess, "./logs/hello_ck.ckpt", meta_graph_suffix='meta', write_meta_graph=True) ``` This is because graph won't have any save/restore op for restoration of model. To resolve it, write graph after saving the .ckpt file ``` saver = tf.train.Saver() saver.save(sess, "./logs/hello_ck.ckpt", meta_graph_suffix='meta', write_meta_graph=True) tf.train.write_graph(sess.graph_def, "./logs", "test2.pb", False) ``` @mrry, please guide if I interpreted something wrong. I only recently started diving into tensorflow code.
39,468,640
I am currently trying to export a trained TensorFlow model as a ProtoBuf file to use it with the TensorFlow C++ API on Android. Therefore, I'm using the [`freeze_graph.py`](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/tools/freeze_graph.py) script. I exported my model using `tf.train.write_graph`: `tf.train.write_graph(graph_def, FLAGS.save_path, out_name, as_text=True)` and I'm using a checkpoint saved with `tf.train.Saver`. I invoke `freeze_graph.py` as described at the top of the script. After compiling, I run ``` bazel-bin/tensorflow/python/tools/freeze_graph \ --input_graph=<path_to_protobuf_file> \ --input_checkpoint=<model_name>.ckpt-10000 \ --output_graph=<output_protobuf_file_path> \ --output_node_names=dropout/mul_1 ``` This gives me the following error message: ``` TypeError: Cannot interpret feed_dict key as Tensor: The name 'save/Const:0' refers to a Tensor which does not exist. The operation, 'save/Const', does not exist in the graph. ``` As the error states I do not have a tensor `save/Const:0` in my exported model. However, the code of `freeze_graph.py` says that one can specify this tensor name by the flag `filename_tensor_name`. Unfortunately I cannot find any information on what this tensor should be and how to set it correctly for my model. Can somebody tell my either how to produce a `save/Const:0` tensor in my exported ProtoBuf model or how to set the flag `filename_tensor_name` correctly?
2016/09/13
[ "https://Stackoverflow.com/questions/39468640", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2206976/" ]
The `--filename_tensor_name` flag is used to specify the name of a placeholder tensor created when you construct a [`tf.train.Saver`](https://www.tensorflow.org/versions/r0.10/api_docs/python/state_ops.html#Saver) for your model.\* In your original program, you can print out the value of `saver.saver_def.filename_tensor_name` to get the value that you should pass for this flag. You may also want to print the value of `saver.saver_def.restore_op_name` to get a value for the `--restore_op_name` flag (since I suspect the default won't be correct for your graph). Alternatively, the [`tf.train.SaverDef` protocol buffer](https://github.com/tensorflow/tensorflow/blob/91a70cbf1c627117b70a3d2dd4c612779369e293/tensorflow/core/protobuf/saver.proto) includes all of the information you need to reconstruct the relevant information for these flags. If you prefer, you can write `saver.saver_def` to a file, and pass the name of that file as the `--input_saver` flag to `freeze_graph.py`. ---  \* The default name scope for a `tf.train.Saver` is `"save/"` and the placeholder is [actually a `tf.constant()`](https://github.com/tensorflow/tensorflow/blob/91a70cbf1c627117b70a3d2dd4c612779369e293/tensorflow/python/training/saver.py#L609) whose name defaults to `"Const:0"`, which explains why the flag defaults to `"save/Const:0"`.
Some follow-up on @Drag0's answer and why the new code layout fixed the error. When calling `saver = tf.train.Saver()`, you add the different variables related to the `tf.train.Saver()` such as `'save/Const:0'` to the default graph. In the first code arrangement the graph is saved before so without the `tf.train.Saver()` variables. In the second code arrangement it is saved after, so the operation `save/Const` will exist in the graph.
39,468,640
I am currently trying to export a trained TensorFlow model as a ProtoBuf file to use it with the TensorFlow C++ API on Android. Therefore, I'm using the [`freeze_graph.py`](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/tools/freeze_graph.py) script. I exported my model using `tf.train.write_graph`: `tf.train.write_graph(graph_def, FLAGS.save_path, out_name, as_text=True)` and I'm using a checkpoint saved with `tf.train.Saver`. I invoke `freeze_graph.py` as described at the top of the script. After compiling, I run ``` bazel-bin/tensorflow/python/tools/freeze_graph \ --input_graph=<path_to_protobuf_file> \ --input_checkpoint=<model_name>.ckpt-10000 \ --output_graph=<output_protobuf_file_path> \ --output_node_names=dropout/mul_1 ``` This gives me the following error message: ``` TypeError: Cannot interpret feed_dict key as Tensor: The name 'save/Const:0' refers to a Tensor which does not exist. The operation, 'save/Const', does not exist in the graph. ``` As the error states I do not have a tensor `save/Const:0` in my exported model. However, the code of `freeze_graph.py` says that one can specify this tensor name by the flag `filename_tensor_name`. Unfortunately I cannot find any information on what this tensor should be and how to set it correctly for my model. Can somebody tell my either how to produce a `save/Const:0` tensor in my exported ProtoBuf model or how to set the flag `filename_tensor_name` correctly?
2016/09/13
[ "https://Stackoverflow.com/questions/39468640", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2206976/" ]
I noticed that error happened to me when I had code arranged like this: ``` sess = tf.Session() tf.train.write_graph(sess.graph_def, '', '/tmp/train.pbtxt') init = tf.initialize_all_variables() saver = tf.train.Saver() sess.run(init) ``` It worked after I changed code layout like this: ``` # Add ops to save and restore all the variables. saver = tf.train.Saver() init = tf.initialize_all_variables() sess = tf.Session() tf.train.write_graph(sess.graph_def, '', '/tmp/train.pbtxt') sess.run(init) ``` I'm not really sure why is that. @mrry could you explain it a bit more?
It should not be problematic in latest freeze\_graph.py as I could see these removed: `del restore_op_name, filename_tensor_name # Unused by updated loading code.` [source:freeze\_graph.py](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/tools/freeze_graph.py) In earlier version, it was using restore\_op to restore the model `sess.run([restore_op_name], {filename_tensor_name: input_checkpoint})` So, for previous version, if you are writing the graph in .pb file before instantiating saver op, it will problematic. eg.: ``` tf.train.write_graph(sess.graph_def, "./logs", "test2.pb", False) saver = tf.train.Saver() saver.save(sess, "./logs/hello_ck.ckpt", meta_graph_suffix='meta', write_meta_graph=True) ``` This is because graph won't have any save/restore op for restoration of model. To resolve it, write graph after saving the .ckpt file ``` saver = tf.train.Saver() saver.save(sess, "./logs/hello_ck.ckpt", meta_graph_suffix='meta', write_meta_graph=True) tf.train.write_graph(sess.graph_def, "./logs", "test2.pb", False) ``` @mrry, please guide if I interpreted something wrong. I only recently started diving into tensorflow code.
39,468,640
I am currently trying to export a trained TensorFlow model as a ProtoBuf file to use it with the TensorFlow C++ API on Android. Therefore, I'm using the [`freeze_graph.py`](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/tools/freeze_graph.py) script. I exported my model using `tf.train.write_graph`: `tf.train.write_graph(graph_def, FLAGS.save_path, out_name, as_text=True)` and I'm using a checkpoint saved with `tf.train.Saver`. I invoke `freeze_graph.py` as described at the top of the script. After compiling, I run ``` bazel-bin/tensorflow/python/tools/freeze_graph \ --input_graph=<path_to_protobuf_file> \ --input_checkpoint=<model_name>.ckpt-10000 \ --output_graph=<output_protobuf_file_path> \ --output_node_names=dropout/mul_1 ``` This gives me the following error message: ``` TypeError: Cannot interpret feed_dict key as Tensor: The name 'save/Const:0' refers to a Tensor which does not exist. The operation, 'save/Const', does not exist in the graph. ``` As the error states I do not have a tensor `save/Const:0` in my exported model. However, the code of `freeze_graph.py` says that one can specify this tensor name by the flag `filename_tensor_name`. Unfortunately I cannot find any information on what this tensor should be and how to set it correctly for my model. Can somebody tell my either how to produce a `save/Const:0` tensor in my exported ProtoBuf model or how to set the flag `filename_tensor_name` correctly?
2016/09/13
[ "https://Stackoverflow.com/questions/39468640", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2206976/" ]
I noticed that error happened to me when I had code arranged like this: ``` sess = tf.Session() tf.train.write_graph(sess.graph_def, '', '/tmp/train.pbtxt') init = tf.initialize_all_variables() saver = tf.train.Saver() sess.run(init) ``` It worked after I changed code layout like this: ``` # Add ops to save and restore all the variables. saver = tf.train.Saver() init = tf.initialize_all_variables() sess = tf.Session() tf.train.write_graph(sess.graph_def, '', '/tmp/train.pbtxt') sess.run(init) ``` I'm not really sure why is that. @mrry could you explain it a bit more?
Some follow-up on @Drag0's answer and why the new code layout fixed the error. When calling `saver = tf.train.Saver()`, you add the different variables related to the `tf.train.Saver()` such as `'save/Const:0'` to the default graph. In the first code arrangement the graph is saved before so without the `tf.train.Saver()` variables. In the second code arrangement it is saved after, so the operation `save/Const` will exist in the graph.
39,468,640
I am currently trying to export a trained TensorFlow model as a ProtoBuf file to use it with the TensorFlow C++ API on Android. Therefore, I'm using the [`freeze_graph.py`](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/tools/freeze_graph.py) script. I exported my model using `tf.train.write_graph`: `tf.train.write_graph(graph_def, FLAGS.save_path, out_name, as_text=True)` and I'm using a checkpoint saved with `tf.train.Saver`. I invoke `freeze_graph.py` as described at the top of the script. After compiling, I run ``` bazel-bin/tensorflow/python/tools/freeze_graph \ --input_graph=<path_to_protobuf_file> \ --input_checkpoint=<model_name>.ckpt-10000 \ --output_graph=<output_protobuf_file_path> \ --output_node_names=dropout/mul_1 ``` This gives me the following error message: ``` TypeError: Cannot interpret feed_dict key as Tensor: The name 'save/Const:0' refers to a Tensor which does not exist. The operation, 'save/Const', does not exist in the graph. ``` As the error states I do not have a tensor `save/Const:0` in my exported model. However, the code of `freeze_graph.py` says that one can specify this tensor name by the flag `filename_tensor_name`. Unfortunately I cannot find any information on what this tensor should be and how to set it correctly for my model. Can somebody tell my either how to produce a `save/Const:0` tensor in my exported ProtoBuf model or how to set the flag `filename_tensor_name` correctly?
2016/09/13
[ "https://Stackoverflow.com/questions/39468640", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2206976/" ]
Some follow-up on @Drag0's answer and why the new code layout fixed the error. When calling `saver = tf.train.Saver()`, you add the different variables related to the `tf.train.Saver()` such as `'save/Const:0'` to the default graph. In the first code arrangement the graph is saved before so without the `tf.train.Saver()` variables. In the second code arrangement it is saved after, so the operation `save/Const` will exist in the graph.
It should not be problematic in latest freeze\_graph.py as I could see these removed: `del restore_op_name, filename_tensor_name # Unused by updated loading code.` [source:freeze\_graph.py](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/tools/freeze_graph.py) In earlier version, it was using restore\_op to restore the model `sess.run([restore_op_name], {filename_tensor_name: input_checkpoint})` So, for previous version, if you are writing the graph in .pb file before instantiating saver op, it will problematic. eg.: ``` tf.train.write_graph(sess.graph_def, "./logs", "test2.pb", False) saver = tf.train.Saver() saver.save(sess, "./logs/hello_ck.ckpt", meta_graph_suffix='meta', write_meta_graph=True) ``` This is because graph won't have any save/restore op for restoration of model. To resolve it, write graph after saving the .ckpt file ``` saver = tf.train.Saver() saver.save(sess, "./logs/hello_ck.ckpt", meta_graph_suffix='meta', write_meta_graph=True) tf.train.write_graph(sess.graph_def, "./logs", "test2.pb", False) ``` @mrry, please guide if I interpreted something wrong. I only recently started diving into tensorflow code.
29,436,756
I wrote the following class in salesforce: ``` global class ChangeImmo implements Schedulable{ // Execute method global void execute(SchedulableContext SC) { List<Realty_User__c> rs = [SELECT Buttons__c FROM Realty_User__c WHERE not (Buttons__c INCLUDES ('Terminplaner'))]; for(Realty_User__c r : rs){ r.Buttons__c += ';Terminplaner'; update r; } } } ``` Then I sheduled it for a one time run. It worked on our testbox, but not in the live version. We have 1700 users, of which around 730 don't have the "Terminplaner". Does someone know, why this is not working? Edit: I adjusted my code with the guide on DML exceptions by SalesForce and it is still not working: ``` global class ChangeImmo implements Schedulable { // Execute method global void execute(SchedulableContext SC) { for (List < Realty_User__c > lstRu: [SELECT Buttons__c FROM Realty_User__c WHERE not(Buttons__c INCLUDES('Terminplaner'))]) { for (Realty_User__c r : lstRu) { r.Buttons__c += ';Terminplaner'; } update lstRu; } } } ``` Edit 2: Okay I have found the debug log now and the error says: 17:00:14.574 (10574150113)|FATAL\_ERROR|System.ListException: Duplicate id in list: 003b000000ZAhDgAAL
2015/04/03
[ "https://Stackoverflow.com/questions/29436756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2885690/" ]
003 - it's a prefix of Contact object. Looks like you have some trigger in your production that work with contacts after you update Realty\_User\_\_c object.
``` global class ChangeImmo implements Schedulable{ ``` // Execute method ``` global void execute(SchedulableContext SC) { List<Realty_User__c> rs = [SELECT Buttons__c FROM Realty_User__c WHERE not (Buttons__c INCLUDES ('Terminplaner'))]; for(Realty_User__c r : rs){ **r.Buttons__c += ';Terminplaner';** update r; } } ``` } Seems you are not updating values. ex:`r.Buttons__c += 'value1;value2;Terminplaner'; update r;`
64,682
I came across these words: > > Kleingruppe, Reinform > > > Why are they like that? Why not "kleine Gruppe" and "reine Form"? This looks really interesting. Please explain to me how and when can I use this type of adjective. I would like to add it to my German language arsenal.
2021/04/13
[ "https://german.stackexchange.com/questions/64682", "https://german.stackexchange.com", "https://german.stackexchange.com/users/42148/" ]
These words are a special type of compound nouns, but they're more than just a different way to affix an adjective to a noun. They are new words with their own life, and they can have acquired meanings that go beyond just the noun plus the adjective, or a different meaning altogether. E.g., a *Blaulicht* isn't just any blue light that shines blue. It's exclusively used for the flashing light on police, ambulance, and fire department cars. *Kleintier* has a (more or less) fixed definition in veterinary medicine, and a different one in tenancy law. *Rotfront* was a communist paramilitary group in the 1920s and today is sometimes used as a derogatory term for far-left activists. Your examples: *Kleingruppe* is often used with a fixed definition for the context. For example, a railroad company might have special ticket prices for *Kleingruppen*, and then *Kleingruppe* has a fixed definition in their terms and conditions like "a group between 3 and 10 people plus up to 10 children below 13 years". So if you use *Kleingruppe* when buying a ticket, it will be understood to have that definition. *Reinform* is basically a chemical term (pure form of a substance in contrast to a mixture) that can also be used in a figurative sense ("Der Artikel ist marxistische Theorie in Reinform."). So while the literal meaning can in many cases be a guidance in understanding a compound word, in other cases the whole isn't just the sum of its parts. Trying to build new words by concatenating an adjective and a noun won't work in most cases either.
These are no adjectives, but nouns. As a rule of thumb, you can normally combine an adjective ("kleine", "reine") with a general noun ("Gruppe", "Form") to get a compound noun in German. This is used because it is more concise, even though it regularly adds a sense of bureaucracy to the language.
65,129,265
I am making a web page. There is a navigation section on the left that is all nested in `<p>` something like this. ``` <nav> <p>Home</p> <p>About</p> <p>Shop</p> <p>Contact Us</p> </nav> ``` I have used `flexbox` to make this appear on the `left-hand` side of the page and be rendered `vertically`. However, when I make the screen size smaller this has to be rendered horizontally (in one line with fixed spaces) at the top like a header. This is what I have done so far: ``` @media only screen and (max-width: 700px) {nav { width: 100%; display: flex; flex-direction: row;}} ``` **This appears all in one line with no spaces at all**. When I add `justify-content: space-between`, it will add the spaces but as the `screen size decreases` it will all end up squashed. Therefore there is no fixed distance. How do I solve this problem?
2020/12/03
[ "https://Stackoverflow.com/questions/65129265", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9191469/" ]
You should define padding for your p element ``` @media only screen and (max-width: 700px) { nav { width: 100%; display: flex; flex-direction: row; } p { padding: 0 1rem; } } ```
Set a breakpoint and set your `flex-direction` to `column`. ``` nav { width: 40%; display: flex; justify-content: space-between; } @media only screen and (max-width: 700px) { nav { width: 100%; flex-direction: column; } } ```
10,365,510
When I run the following query on browser: ``` http://127.0.0.1:8096/solr/select/?q=june 17&amp;start=0&amp;rows=8&amp;indent=on&amp;hl=on&amp;hl.fl=Data&amp;wt=json ``` I get results. No problems. Notice that there is a space between june and 17 However when I receive that query in my PHP i.e. $q=June 17 I use ``` $url="http://127.0.0.1:8096/solr/select/?q=$q&start=0&rows=8&indent=on&hl=on&hl.fl=Data&wt=json"; $json_O=json_decode(file_get_contents($url),true); ``` After this I see the following on my firebug: ``` <b>Warning</b>: file_get_contents(http://127.0.0.1:8096/solr/select/?q=june 17&amp;start=0&amp;rows=8&amp;indent=on&amp;hl=on&amp;hl.fl=Data&amp;wt=json) [<a href='function.file-get-contents'>function.file-get-contents</a>]: failed to open stream: HTTP request failed! HTTP/1.1 505 HTTP Version Not Supported ``` However note that if there is no space between my query words (I mean if it is a single word) then everything is perfect. Why does it work fine when I issue exactly same query on browser as compared to file\_get\_contents(). Any solutions would be appreciated.
2012/04/28
[ "https://Stackoverflow.com/questions/10365510", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1315930/" ]
There is a space in the `q` parameter's value. Could be that. Try `urlencode()`ing the parameter. ``` $url="http://127.0.0.1:8096/solr/select/?q=".urlencode($q)."&start=0&rows=8&indent=on&hl=on&hl.fl=Data&wt=json"; $json_O=json_decode(file_get_contents($url),true); ```
This is, because the `file_get_contents` function sends a request to a web server in HTTP, which looks like this ``` GET /solr/select/?q=bla HTTP/1.0 Host: 127.0.0.1 ...[more headers here]... ``` Note, that there is a the in HTTP version specified in the request (`HTTP/1.0`) Now, if there is a space in your request string, you send something like ``` GET /solr/select/?q=bla foo HTTP/1.0 Host: 127.0.0.1 ...[more headers here]... ``` Your server seems to parse `foo` as the version and returns `505 HTTP Version Not Supported`. If you encode the space in the string (e.g. by replacing it with `%20`, this should not happen).
69,587,409
A quick question. I use to see the inferred type by option click the property or object on the left of a statement. After upgrade to Xcode 13, for instance, when I option click on below `text` property, there is no quick help popping up. Do u guys meet this same issue? Just Google it, no clue found. ``` let text = "Have a nice day" ``` Quick help is only shown when I option-click on an iOS built-in property, function, etc. It doesn't appear for custom defined things. For code below, when I optional click on `viewDidLoad` or `addSubview` , I could get quick help menu popped up. But without luck for `tableView`, which is a user defined stuff. ``` private lazy var tableView: UITableView = { let table = UITableView() table.register(UITableViewCell.self, forCellReuseIdentifier: "cell") return table }() override func viewDidLoad() { super.viewDidLoad() view.addSubview(tableView) tableView.frame = view.bounds } ```
2021/10/15
[ "https://Stackoverflow.com/questions/69587409", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10158398/" ]
Well, restart your Mac will solve this problem. It seems I had not restarted my Mac since the day I upgrade to Xcode 13. The issue link in Apple forum: [link](https://developer.apple.com/forums/thread/691234)
For me restarting the Mac, cleaning build folder and derived data + quitting Xcode didn't help. Seems like it works only on small projects, but not on the one for the company I work for. It's pretty random and extremely annoying, no idea what could fix it honestly
6,530,980
I want to create a **Sub Menu** in existing **Menu Item** in **Android**. How I can achieve it ? Thanks.
2011/06/30
[ "https://Stackoverflow.com/questions/6530980", "https://Stackoverflow.com", "https://Stackoverflow.com/users/645753/" ]
It's as simple as placing a `menu` inside an `item`. For example: ``` <?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/file" android:icon="@drawable/file" android:title="@string/file" > <!-- "file" submenu --> <menu> <item android:id="@+id/create_new" android:title="@string/create_new" /> <item android:id="@+id/open" android:title="@string/open" /> </menu> </item> </menu> ``` From [Creating Menus | Android Developers](http://developer.android.com/guide/topics/ui/menus.html#submenu)
Try reading [this](http://developer.android.com/guide/topics/ui/menus.html#submenu) first.
29,632,729
I have a model which has a `ForeignKey` field, with `null=True`. The field-semantics are that a NULL entry is permissive, while a non-NULL entry binds it to a single row in the foreign table. I want to build an ORM filter which corresponds to: ``` SELECT * FROM foo WHERE foo.fk_field = ? OR foo.fk_field IS NULL ``` (Where the question mark represents a single value in the foreign table.) Is it possible to do this in the Django ORM, so do I need to resort to a `raw` query?
2015/04/14
[ "https://Stackoverflow.com/questions/29632729", "https://Stackoverflow.com", "https://Stackoverflow.com/users/129805/" ]
Use the [Q objects](https://docs.djangoproject.com/en/1.8/topics/db/queries/#complex-lookups-with-q-objects): ``` from django.db.models import Q Foo.objects.filter(Q(fk_field=fk_value) | Q(fk_field=None)) ```
You can achieve this using [Q](https://docs.djangoproject.com/en/1.8/topics/db/queries/#complex-lookups-with-q-objects) objects: ``` from django.db.models import Q Foo.objects.filter(Q(fk=fk) | Q(fk__isnull=True)) ```
29,632,729
I have a model which has a `ForeignKey` field, with `null=True`. The field-semantics are that a NULL entry is permissive, while a non-NULL entry binds it to a single row in the foreign table. I want to build an ORM filter which corresponds to: ``` SELECT * FROM foo WHERE foo.fk_field = ? OR foo.fk_field IS NULL ``` (Where the question mark represents a single value in the foreign table.) Is it possible to do this in the Django ORM, so do I need to resort to a `raw` query?
2015/04/14
[ "https://Stackoverflow.com/questions/29632729", "https://Stackoverflow.com", "https://Stackoverflow.com/users/129805/" ]
Use the [Q objects](https://docs.djangoproject.com/en/1.8/topics/db/queries/#complex-lookups-with-q-objects): ``` from django.db.models import Q Foo.objects.filter(Q(fk_field=fk_value) | Q(fk_field=None)) ```
I think this is a little more readable than the other answers. Mind you, I'm not sure when this started being supported. ``` Foo.objects.filter(a=b) | Bar.objects.filter(c=d) ```
29,632,729
I have a model which has a `ForeignKey` field, with `null=True`. The field-semantics are that a NULL entry is permissive, while a non-NULL entry binds it to a single row in the foreign table. I want to build an ORM filter which corresponds to: ``` SELECT * FROM foo WHERE foo.fk_field = ? OR foo.fk_field IS NULL ``` (Where the question mark represents a single value in the foreign table.) Is it possible to do this in the Django ORM, so do I need to resort to a `raw` query?
2015/04/14
[ "https://Stackoverflow.com/questions/29632729", "https://Stackoverflow.com", "https://Stackoverflow.com/users/129805/" ]
You can achieve this using [Q](https://docs.djangoproject.com/en/1.8/topics/db/queries/#complex-lookups-with-q-objects) objects: ``` from django.db.models import Q Foo.objects.filter(Q(fk=fk) | Q(fk__isnull=True)) ```
I think this is a little more readable than the other answers. Mind you, I'm not sure when this started being supported. ``` Foo.objects.filter(a=b) | Bar.objects.filter(c=d) ```
25,173,084
Note: This is the first time asking a question about a general curiosity regarding syntax. Because of this I might not be using the correct terminology to describe my question, which may mean its already been answered, and I can't find it because I'm unaware of what terms to use in the search. If that is the case, please post comments so I can edit and refine the question to meet the standard expected by stack overflow. Thank you. Now the question. I've been using the static keyword a lot recently because I have members I need to access from anywhere without an instance. However its becoming increasingly tedious to declare every member and method static, when the class its self is already static. Since if you declare a class static, it means you can't create an instance of that class (that's my current understanding). ``` public static class Foo {} ``` Why does every member have to also be declared static. ``` public static class Foo { public static int X; public static int Y; } ``` I would have thought that since the class, foo in this case, is declared to be static, all its members would automatically be static, and you no longer need to declare each member as static. Obviously you can't do that, you have to declare every subsequent member static. However this feels counter intuitive and redundant to me. Whats the reason for this?
2014/08/07
[ "https://Stackoverflow.com/questions/25173084", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2435221/" ]
Put simply -- it's for readability. You can look solely at the property definition and know that it's static, without having to look at the class definition. Your two-line example may make it look unnecessary, but if you have a class with 500, 1000 or more lines of code, you will appreciate the extra clarity when digging through lots of methods, properties and fields. That's the thing about software development: Never ever worry about a bit of extra typing -- you will *read* your code many more times than you will *write* it.
From what I understand, static on the class is a way to enforce all members are static (remove static from one, and it should give you an error). But yes, there is the requirement of defining the methods static. Technically, you wouldn't need to define static on the class. You could, as an alternative, define a class, instantiate the class, and store the class reference globally, thus not needing the static definition on each member. The singleton pattern acts very similar in nature to static classes, except you define one common instance shared throughout.
25,173,084
Note: This is the first time asking a question about a general curiosity regarding syntax. Because of this I might not be using the correct terminology to describe my question, which may mean its already been answered, and I can't find it because I'm unaware of what terms to use in the search. If that is the case, please post comments so I can edit and refine the question to meet the standard expected by stack overflow. Thank you. Now the question. I've been using the static keyword a lot recently because I have members I need to access from anywhere without an instance. However its becoming increasingly tedious to declare every member and method static, when the class its self is already static. Since if you declare a class static, it means you can't create an instance of that class (that's my current understanding). ``` public static class Foo {} ``` Why does every member have to also be declared static. ``` public static class Foo { public static int X; public static int Y; } ``` I would have thought that since the class, foo in this case, is declared to be static, all its members would automatically be static, and you no longer need to declare each member as static. Obviously you can't do that, you have to declare every subsequent member static. However this feels counter intuitive and redundant to me. Whats the reason for this?
2014/08/07
[ "https://Stackoverflow.com/questions/25173084", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2435221/" ]
From what I understand, static on the class is a way to enforce all members are static (remove static from one, and it should give you an error). But yes, there is the requirement of defining the methods static. Technically, you wouldn't need to define static on the class. You could, as an alternative, define a class, instantiate the class, and store the class reference globally, thus not needing the static definition on each member. The singleton pattern acts very similar in nature to static classes, except you define one common instance shared throughout.
For consistency - uniformity of meaning. Making a class static doesn't change anything about the class; all it does is forbid the declaration of instance members. The class itself is neither instance nor static. It would be more concise if static on a class implied all members static, but one could argue that doing so would introduce a variable interpretation for a member declaration where not declared static. As it is, members are instance unless the static modifier is used.
25,173,084
Note: This is the first time asking a question about a general curiosity regarding syntax. Because of this I might not be using the correct terminology to describe my question, which may mean its already been answered, and I can't find it because I'm unaware of what terms to use in the search. If that is the case, please post comments so I can edit and refine the question to meet the standard expected by stack overflow. Thank you. Now the question. I've been using the static keyword a lot recently because I have members I need to access from anywhere without an instance. However its becoming increasingly tedious to declare every member and method static, when the class its self is already static. Since if you declare a class static, it means you can't create an instance of that class (that's my current understanding). ``` public static class Foo {} ``` Why does every member have to also be declared static. ``` public static class Foo { public static int X; public static int Y; } ``` I would have thought that since the class, foo in this case, is declared to be static, all its members would automatically be static, and you no longer need to declare each member as static. Obviously you can't do that, you have to declare every subsequent member static. However this feels counter intuitive and redundant to me. Whats the reason for this?
2014/08/07
[ "https://Stackoverflow.com/questions/25173084", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2435221/" ]
Put simply -- it's for readability. You can look solely at the property definition and know that it's static, without having to look at the class definition. Your two-line example may make it look unnecessary, but if you have a class with 500, 1000 or more lines of code, you will appreciate the extra clarity when digging through lots of methods, properties and fields. That's the thing about software development: Never ever worry about a bit of extra typing -- you will *read* your code many more times than you will *write* it.
For consistency - uniformity of meaning. Making a class static doesn't change anything about the class; all it does is forbid the declaration of instance members. The class itself is neither instance nor static. It would be more concise if static on a class implied all members static, but one could argue that doing so would introduce a variable interpretation for a member declaration where not declared static. As it is, members are instance unless the static modifier is used.
1,624,159
I have a Axis 1.4 (with Spring) web service client consuming a PHP web service (running on Apache). This works perfectly in the development environment, but in the production environment the code execution hangs somewhere in the Axis library directly after the client has received the SOAP response. I have identified with Wireshark that the only difference from the client perspective is that in development environment the HTTP header of the SOAP Response contains the entry ``` Connection: close ``` which is missing in production environment. My assumption is that this is the reason the code execution hangs, because Axis is expecting the connection close header field. Is there something I can do to remedy this by configuring the client? If not, any hints for configuring Apache + PHP to close the connection correctly are appreciated.
2009/10/26
[ "https://Stackoverflow.com/questions/1624159", "https://Stackoverflow.com", "https://Stackoverflow.com/users/76777/" ]
Try setting the -Dhttp.keepAlive=false system property in your application, if can afford disabling keep alives in other parts of the application. This will prevent certain hangs with the java-internal HttpClient class trying to eagerly fill a BufferedInputStream from the open connection. For details see also <http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4479751> . If this has a chance of helping you have a look at the stack trace of your hanging client, it should look like this: java.lang.Thread.State: RUNNABLE at java.net.SocketInputStream.socketRead0(Native Method) at java.net.SocketInputStream.read(SocketInputStream.java:129) at java.io.BufferedInputStream.fill(BufferedInputStream.java:218) at java.io.BufferedInputStream.read1(BufferedInputStream.java:258) at java.io.BufferedInputStream.read(BufferedInputStream.java:317) - locked <0xab82fa30> (a java.io.BufferedInputStream) at sun.net.www.http.HttpClient.parseHTTPHeader(HttpClient.java:687) at sun.net.www.http.HttpClient.parseHTTP(HttpClient.java:632) at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1072) - locked <0xab82c838> (a sun.net.www.protocol.http.HttpURLConnection) The http.keepAlive setting essentially ensures that the HttpClient will always send a 'connection: close' as suggested by HeavyWave.
You might try sending Http Header "Connection: close" with your request.
46,468,392
I have a text file. I would like to use python v3.6 to read the text file line by line, append each line with a sub-string and replace the existing line with the appended string line by line. To be clearer, here is the original text file; ``` 1,2,3 4,5,6 ``` The desired output text file should look like this; ``` appended_text,1,2,3 appended_text,4,5,6 ``` This is how my code looks like; ``` with open(filename, 'r+') as myfile: for line in myfile: newline = "appended_text" + "," + line myfile.write(newline) ``` I did not get what I want. What I got instead was a huge line of text appended at the end of the file. How should the code be modified? Is there a better way to implement what I want?
2017/09/28
[ "https://Stackoverflow.com/questions/46468392", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3848207/" ]
There's no such thing as "replacing an existing line" in a file. For what you want to do, you have to write a new file with the modified content and then replace the old file with the new one. Example code: ``` with open("old.file") as old, open("new.file", "w") as new: for line in old: line = modify(line.lstrip()) new.write(line + "\n") os.rename("new.file", "old.file") ```
I believe to get what you want you need to put `myfile.readlines()` before your `for` loop.
46,468,392
I have a text file. I would like to use python v3.6 to read the text file line by line, append each line with a sub-string and replace the existing line with the appended string line by line. To be clearer, here is the original text file; ``` 1,2,3 4,5,6 ``` The desired output text file should look like this; ``` appended_text,1,2,3 appended_text,4,5,6 ``` This is how my code looks like; ``` with open(filename, 'r+') as myfile: for line in myfile: newline = "appended_text" + "," + line myfile.write(newline) ``` I did not get what I want. What I got instead was a huge line of text appended at the end of the file. How should the code be modified? Is there a better way to implement what I want?
2017/09/28
[ "https://Stackoverflow.com/questions/46468392", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3848207/" ]
You cannot, in general, modify a file in place like this. Instead, write a copy to a new file, then replace the original with the new one. ``` with open(filename, 'r') as myfile: with open("copy", 'w') as newfile: for line in myfile: newline = "appended_text" + "," + line newfile.write(newline) os.rename("copy", filename) ```
I believe to get what you want you need to put `myfile.readlines()` before your `for` loop.
46,468,392
I have a text file. I would like to use python v3.6 to read the text file line by line, append each line with a sub-string and replace the existing line with the appended string line by line. To be clearer, here is the original text file; ``` 1,2,3 4,5,6 ``` The desired output text file should look like this; ``` appended_text,1,2,3 appended_text,4,5,6 ``` This is how my code looks like; ``` with open(filename, 'r+') as myfile: for line in myfile: newline = "appended_text" + "," + line myfile.write(newline) ``` I did not get what I want. What I got instead was a huge line of text appended at the end of the file. How should the code be modified? Is there a better way to implement what I want?
2017/09/28
[ "https://Stackoverflow.com/questions/46468392", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3848207/" ]
Here is what I would do: ``` with open(filename, 'r+') as f: lines = [] for line in f: lines.append("appended_text" + "," + line) f.seek(0) for line in lines: f.write(line) ``` For example: **sample.txt before**: ``` hello there world ``` **code:** ``` fp = r"C:\Users\Me\Desktop\sample.txt" with open(fp, 'r+') as f: lines = [] for line in f: lines.append("something," + line) lines.append(line.strip() + ",something\n") f.seek(0) for line in lines: f.write(line) ``` **sample.txt after:** ``` something,hello hello,something something,there there,something something,world world,something ``` A couple of notes: 1. This assumes you are going to append to the front of each line. Thus the newline (`'\n'`) is kept with the original content of each line. If you are appending to the end, I would change to: `lines.append(line.strip() + "," + "appended_text")`. 2. You can probably combine `"appended_text"` and the `","` to `"appended_text,"`. Unless `"appended_text"` is a varable like `appended_text = "something"`. 3. Though contextually correct as a solution to your question; I'd look to writing a new file with the changes desired and replacing the old one with the new one as recommend in other answers.
I believe to get what you want you need to put `myfile.readlines()` before your `for` loop.
46,468,392
I have a text file. I would like to use python v3.6 to read the text file line by line, append each line with a sub-string and replace the existing line with the appended string line by line. To be clearer, here is the original text file; ``` 1,2,3 4,5,6 ``` The desired output text file should look like this; ``` appended_text,1,2,3 appended_text,4,5,6 ``` This is how my code looks like; ``` with open(filename, 'r+') as myfile: for line in myfile: newline = "appended_text" + "," + line myfile.write(newline) ``` I did not get what I want. What I got instead was a huge line of text appended at the end of the file. How should the code be modified? Is there a better way to implement what I want?
2017/09/28
[ "https://Stackoverflow.com/questions/46468392", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3848207/" ]
If you want to write it to the same file: ``` f = open(filename, 'r') lines = f.readlines() f.close() lines = ['appended_text, ' + l for l in lines] f = open(filename, 'w') f.writelines(lines) f.close() ```
I believe to get what you want you need to put `myfile.readlines()` before your `for` loop.
46,468,392
I have a text file. I would like to use python v3.6 to read the text file line by line, append each line with a sub-string and replace the existing line with the appended string line by line. To be clearer, here is the original text file; ``` 1,2,3 4,5,6 ``` The desired output text file should look like this; ``` appended_text,1,2,3 appended_text,4,5,6 ``` This is how my code looks like; ``` with open(filename, 'r+') as myfile: for line in myfile: newline = "appended_text" + "," + line myfile.write(newline) ``` I did not get what I want. What I got instead was a huge line of text appended at the end of the file. How should the code be modified? Is there a better way to implement what I want?
2017/09/28
[ "https://Stackoverflow.com/questions/46468392", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3848207/" ]
There's no such thing as "replacing an existing line" in a file. For what you want to do, you have to write a new file with the modified content and then replace the old file with the new one. Example code: ``` with open("old.file") as old, open("new.file", "w") as new: for line in old: line = modify(line.lstrip()) new.write(line + "\n") os.rename("new.file", "old.file") ```
You cannot, in general, modify a file in place like this. Instead, write a copy to a new file, then replace the original with the new one. ``` with open(filename, 'r') as myfile: with open("copy", 'w') as newfile: for line in myfile: newline = "appended_text" + "," + line newfile.write(newline) os.rename("copy", filename) ```
46,468,392
I have a text file. I would like to use python v3.6 to read the text file line by line, append each line with a sub-string and replace the existing line with the appended string line by line. To be clearer, here is the original text file; ``` 1,2,3 4,5,6 ``` The desired output text file should look like this; ``` appended_text,1,2,3 appended_text,4,5,6 ``` This is how my code looks like; ``` with open(filename, 'r+') as myfile: for line in myfile: newline = "appended_text" + "," + line myfile.write(newline) ``` I did not get what I want. What I got instead was a huge line of text appended at the end of the file. How should the code be modified? Is there a better way to implement what I want?
2017/09/28
[ "https://Stackoverflow.com/questions/46468392", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3848207/" ]
There's no such thing as "replacing an existing line" in a file. For what you want to do, you have to write a new file with the modified content and then replace the old file with the new one. Example code: ``` with open("old.file") as old, open("new.file", "w") as new: for line in old: line = modify(line.lstrip()) new.write(line + "\n") os.rename("new.file", "old.file") ```
Here is what I would do: ``` with open(filename, 'r+') as f: lines = [] for line in f: lines.append("appended_text" + "," + line) f.seek(0) for line in lines: f.write(line) ``` For example: **sample.txt before**: ``` hello there world ``` **code:** ``` fp = r"C:\Users\Me\Desktop\sample.txt" with open(fp, 'r+') as f: lines = [] for line in f: lines.append("something," + line) lines.append(line.strip() + ",something\n") f.seek(0) for line in lines: f.write(line) ``` **sample.txt after:** ``` something,hello hello,something something,there there,something something,world world,something ``` A couple of notes: 1. This assumes you are going to append to the front of each line. Thus the newline (`'\n'`) is kept with the original content of each line. If you are appending to the end, I would change to: `lines.append(line.strip() + "," + "appended_text")`. 2. You can probably combine `"appended_text"` and the `","` to `"appended_text,"`. Unless `"appended_text"` is a varable like `appended_text = "something"`. 3. Though contextually correct as a solution to your question; I'd look to writing a new file with the changes desired and replacing the old one with the new one as recommend in other answers.
46,468,392
I have a text file. I would like to use python v3.6 to read the text file line by line, append each line with a sub-string and replace the existing line with the appended string line by line. To be clearer, here is the original text file; ``` 1,2,3 4,5,6 ``` The desired output text file should look like this; ``` appended_text,1,2,3 appended_text,4,5,6 ``` This is how my code looks like; ``` with open(filename, 'r+') as myfile: for line in myfile: newline = "appended_text" + "," + line myfile.write(newline) ``` I did not get what I want. What I got instead was a huge line of text appended at the end of the file. How should the code be modified? Is there a better way to implement what I want?
2017/09/28
[ "https://Stackoverflow.com/questions/46468392", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3848207/" ]
There's no such thing as "replacing an existing line" in a file. For what you want to do, you have to write a new file with the modified content and then replace the old file with the new one. Example code: ``` with open("old.file") as old, open("new.file", "w") as new: for line in old: line = modify(line.lstrip()) new.write(line + "\n") os.rename("new.file", "old.file") ```
If you want to write it to the same file: ``` f = open(filename, 'r') lines = f.readlines() f.close() lines = ['appended_text, ' + l for l in lines] f = open(filename, 'w') f.writelines(lines) f.close() ```
46,468,392
I have a text file. I would like to use python v3.6 to read the text file line by line, append each line with a sub-string and replace the existing line with the appended string line by line. To be clearer, here is the original text file; ``` 1,2,3 4,5,6 ``` The desired output text file should look like this; ``` appended_text,1,2,3 appended_text,4,5,6 ``` This is how my code looks like; ``` with open(filename, 'r+') as myfile: for line in myfile: newline = "appended_text" + "," + line myfile.write(newline) ``` I did not get what I want. What I got instead was a huge line of text appended at the end of the file. How should the code be modified? Is there a better way to implement what I want?
2017/09/28
[ "https://Stackoverflow.com/questions/46468392", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3848207/" ]
You cannot, in general, modify a file in place like this. Instead, write a copy to a new file, then replace the original with the new one. ``` with open(filename, 'r') as myfile: with open("copy", 'w') as newfile: for line in myfile: newline = "appended_text" + "," + line newfile.write(newline) os.rename("copy", filename) ```
Here is what I would do: ``` with open(filename, 'r+') as f: lines = [] for line in f: lines.append("appended_text" + "," + line) f.seek(0) for line in lines: f.write(line) ``` For example: **sample.txt before**: ``` hello there world ``` **code:** ``` fp = r"C:\Users\Me\Desktop\sample.txt" with open(fp, 'r+') as f: lines = [] for line in f: lines.append("something," + line) lines.append(line.strip() + ",something\n") f.seek(0) for line in lines: f.write(line) ``` **sample.txt after:** ``` something,hello hello,something something,there there,something something,world world,something ``` A couple of notes: 1. This assumes you are going to append to the front of each line. Thus the newline (`'\n'`) is kept with the original content of each line. If you are appending to the end, I would change to: `lines.append(line.strip() + "," + "appended_text")`. 2. You can probably combine `"appended_text"` and the `","` to `"appended_text,"`. Unless `"appended_text"` is a varable like `appended_text = "something"`. 3. Though contextually correct as a solution to your question; I'd look to writing a new file with the changes desired and replacing the old one with the new one as recommend in other answers.
46,468,392
I have a text file. I would like to use python v3.6 to read the text file line by line, append each line with a sub-string and replace the existing line with the appended string line by line. To be clearer, here is the original text file; ``` 1,2,3 4,5,6 ``` The desired output text file should look like this; ``` appended_text,1,2,3 appended_text,4,5,6 ``` This is how my code looks like; ``` with open(filename, 'r+') as myfile: for line in myfile: newline = "appended_text" + "," + line myfile.write(newline) ``` I did not get what I want. What I got instead was a huge line of text appended at the end of the file. How should the code be modified? Is there a better way to implement what I want?
2017/09/28
[ "https://Stackoverflow.com/questions/46468392", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3848207/" ]
You cannot, in general, modify a file in place like this. Instead, write a copy to a new file, then replace the original with the new one. ``` with open(filename, 'r') as myfile: with open("copy", 'w') as newfile: for line in myfile: newline = "appended_text" + "," + line newfile.write(newline) os.rename("copy", filename) ```
If you want to write it to the same file: ``` f = open(filename, 'r') lines = f.readlines() f.close() lines = ['appended_text, ' + l for l in lines] f = open(filename, 'w') f.writelines(lines) f.close() ```
740
R U RLY NT A LWYR? PRVE IT! PPL MAY NT UNDRSTND SHRT ACRNYMS LIK DIS! IANAL, TINLA, I<3OS! AAMOF, N BTW, WHT M I DOIN? OMG WHT M I SYIN? WL, THX THX TQ FOR LSTNING! --- Translated as... > > Are you really not a lawyer? Prove it! People may not understand short acronyms, like this! *I am not a lawyer*, *This is not legal advice*, *I love open source!* As a matter of fact, and by the way, what am I doing? Oh my goodness, what am I saying? Well, thanks, thank you for listening! > > > Don't worry. I don't use short forms either. I just searched all that up on the internet. How many of us easily understood the first part of this post? If you have to look closely, or double check, then it's a sign that the post is trouble. Oddly enough, short forms in posts, have started becoming the norm. Acronyms, such as IANAL, and TINLA, are becoming more and more common. For new users to the site, seeing such acronyms can possibly be confusing for many users on the site, whether they asked the question you answered or not. I get it. You don't want to be providing legal advice to strangers on the internet. And neither do I. ***I'm not asking to remove those acronyms.*** I'm simply asking that we use the long form: *I am not a lawyer, and this is not legal advice.* If we write the longer form, and limit our use of acronyms, we will be able to create posts that are more professional and high quality (if not aesthetically pleasing too). So can we do this? Thoughts?
2016/08/18
[ "https://opensource.meta.stackexchange.com/questions/740", "https://opensource.meta.stackexchange.com", "https://opensource.meta.stackexchange.com/users/69/" ]
I think we could even go further: could the opening page of the board simply say that none of the questions, answers or comments should be considered as legal advice even if they may look like it. And that we are not a lawyers, and even if some are, they are not your lawyer, and this is not legal advice. And explain in the help that IANAL/TINAL are not needed at all.
Personally I like it the way it is. I'd like to keep the acronyms, because although they may require some research the first time a reader encounters them, once I'm used to it I can read IANAL or TINLA more quickly than the spelled-out form. Just like [TANSTAAFL](https://en.wikipedia.org/wiki/There_ain%27t_no_such_thing_as_a_free_lunch "There ain't no such thing as a free lunch") or [RSVP](https://en.wikipedia.org/wiki/RSVP_(invitations) "Please respond – Répondez s'il vous plaît") or [DRY](https://en.wikipedia.org/wiki/Don%27t_repeat_yourself "Don't repeat yourself") each describe a common phrase which is readily understood in certain circles, and which can avoid considerable repetition (i.e. make the writing more DRY, if you want) for both writer and readers than spelling them out each time you encounter them. Contrary to Philippe, I'd also vote to keep the notice in the posts, because although we might well add a global disclaimer somewhere, many people will not keep it in mind while reading and thinking about posts. Furthermore, the exact placement of the acronym (or phrase) may cause it to affect one paragraph in particular. If you decide to avoid these phrases in posts, people will simply use some other phrase to indicate that they don't trust a particular statement to hold up in court.
24,063,445
I need to use Java on the command line so I can use a tool called sencha command. I have java 1.6 and 1.7 installed, but for whatever reason 1.4 is showing up in my command line. Has anyone any idea why this is happeneing and how to fix it. I've searched everywhere for this version on my machine and can't find it. Has anybody got any ideas. Thanks See screenshot attached. ![enter image description here](https://i.stack.imgur.com/HCtoo.jpg)
2014/06/05
[ "https://Stackoverflow.com/questions/24063445", "https://Stackoverflow.com", "https://Stackoverflow.com/users/967797/" ]
It seems as if your PATH environment variable is pointing to the old installation of Java. Go to Control Panel->System->Advanced System Settings->Advanced(Tab)->Environment Variables... Under the "System Variables" header, you should see a "JAVA\_HOME" environment variable, ensure that points to the JRE7 install directory. Similarly, check the "Path" environment variable and make sure the same JRE7 path is in there, in place of the JRE6 install path.
That is pretty weird. What I would do first is go to your environment path in windows and make sure that the correct path for the latest java is there. That will make it so the java is executed. Open your environment paths: **Windows 8** ``` Drag the Mouse pointer to the Right bottom corner of the screen Click on the Search icon and type: Control Panel Click on -> Control Panel -> System -> Advanced Click on Environment Variables, under System Variables, find PATH, and click on it. In the Edit windows, modify PATH by adding the location of the new java installation. Close the window. Reopen Command prompt window, and run your java -version. ``` **Windows 7** ``` Select Computer from the Start menu Choose System Properties from the context menu Click Advanced system settings > Advanced tab Click on Environment Variables, under System Variables, find PATH, and click on it. In the Edit windows, modify PATH by adding the location of the new java installation. Reopen Command prompt window, and run your java -version. ``` **Windows XP** ``` Start -> Control Panel -> System -> Advanced Click on Environment Variables, under System Variables, find PATH, and click on it. In the Edit windows, modify PATH by adding the location of the new java installation. Close the window. Reopen Command prompt window, and run your java -version. ```
24,063,445
I need to use Java on the command line so I can use a tool called sencha command. I have java 1.6 and 1.7 installed, but for whatever reason 1.4 is showing up in my command line. Has anyone any idea why this is happeneing and how to fix it. I've searched everywhere for this version on my machine and can't find it. Has anybody got any ideas. Thanks See screenshot attached. ![enter image description here](https://i.stack.imgur.com/HCtoo.jpg)
2014/06/05
[ "https://Stackoverflow.com/questions/24063445", "https://Stackoverflow.com", "https://Stackoverflow.com/users/967797/" ]
It seems as if your PATH environment variable is pointing to the old installation of Java. Go to Control Panel->System->Advanced System Settings->Advanced(Tab)->Environment Variables... Under the "System Variables" header, you should see a "JAVA\_HOME" environment variable, ensure that points to the JRE7 install directory. Similarly, check the "Path" environment variable and make sure the same JRE7 path is in there, in place of the JRE6 install path.
Assuming your machine is setup the "usual" way, go to your System environment variables and change your "JAVA\_HOME" path. Also, on a 64-bit machine you should probably install a 64-bit version of Java, but given what you have here (on the command line) - ``` set "JAVA_HOME=c:\Program Files (x86)\Java\jdk1.7.0_07" ```
18,319,436
The code works fine but problem is that i want 3 columns and three rows.. But output shows 6 columns instead of three rows and three columns Here is a code in which problem appears.. Here is a main class: ``` import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import games.board.Board; import games.board.Cell; import games.board.Mark; import javax.swing.JFrame; import javax.swing.SwingUtilities; public class TicTacToeGUIGame extends JFrame { /** * @param args */ private Board gb; private int turn; private void takeTurn(Cell c) { Mark curMark = (turn++ % 2 == 0)? Mark.NOUGHT : Mark.CROSS; gb.setCell(curMark, c.getRow(), c.getColumn()); } private TicTacToeGUIGame() { gb = new Board(3, 3, new ActionListener() { public void actionPerformed(ActionEvent ae) { Cell c = (Cell) ae.getSource(); takeTurn(c); } }); this.add(gb); this.setDefaultCloseOperation(EXIT_ON_CLOSE); this.setTitle("TIC-TAC-TOE"); this.setSize(300, 300); this.setVisible(true); } public static void main(String[] args) { // TODO Auto-generated method stub SwingUtilities.invokeLater( new Runnable () { public void run() { new TicTacToeGUIGame(); } }); } } ``` Here is a board class: ``` package games.board; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JPanel; import javax.swing.JFrame; public class Board extends JPanel { private Cell[][] cells; public Board(int rows, int columns) { cells = new Cell[rows][columns]; for( int r = 0; r < cells[0].length; r++ ) { for (int c = 0; c < cells[1].length; c++) { cells[r][c] = new Cell(r,c); } } } public Board(int rows, int columns, ActionListener ah) { cells = new Cell[rows][columns]; this.setLayout(new GridLayout()); for( int r = 0; r < cells.length; r++ ) { for (int c = 0; c < cells[r].length; c++) { cells[r][c] = new Cell(r,c); this.add(cells[r][c]); cells[r][c].addActionListener(ah); } } } public void setCell(Mark mark, int row, int column) throws IllegalArgumentException { if (cells[row][column].getContent() == Mark.EMPTY) cells[row][column].setContent(mark); else throw new IllegalArgumentException("Player already there!"); } public Cell getCell(int row, int column) { return cells[row][column]; } public String toString() { StringBuilder str = new StringBuilder(); for( int r = 0; r < cells.length; r++ ) { str.append("|"); for (int c = 0; c < cells[r].length; c++) { switch(cells[r][c].getContent()) { case NOUGHT: str.append("O"); break; case CROSS: str.append("X"); break; case YELLOW: str.append("Y"); break; case RED: str.append("R"); break; case BLUE: str.append("B"); break; case GREEN: str.append("G"); break; case MAGENTA: str.append("M"); break; case ORANGE: str.append("M"); break; default: //Empty str.append(""); } str.append("|"); } str.append("\n"); } return str.toString(); } } ```
2013/08/19
[ "https://Stackoverflow.com/questions/18319436", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2694776/" ]
> > i want 3 columns and three rows.. But output shows 6 columns > > > You need to specify proper parameters to the GridLayout: ``` this.setLayout(new GridLayout(0, 3)); ``` This will tell the grid to contain 3 columns. The number of rows will depend on the number of components you add.
Change in your Board class: ``` for( int r = 0; r < cells[0].length; r++ ) { for (int c = 0; c < cells[1].length; c++) { cells[r][c] = new Cell(r,c); } } ``` To ``` for( int r = 0; r < cells[0].length; r++ ) { for (int c = 0; c < cells[r].length; c++) { cells[r][c] = new Cell(r,c); } } ```
18,319,436
The code works fine but problem is that i want 3 columns and three rows.. But output shows 6 columns instead of three rows and three columns Here is a code in which problem appears.. Here is a main class: ``` import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import games.board.Board; import games.board.Cell; import games.board.Mark; import javax.swing.JFrame; import javax.swing.SwingUtilities; public class TicTacToeGUIGame extends JFrame { /** * @param args */ private Board gb; private int turn; private void takeTurn(Cell c) { Mark curMark = (turn++ % 2 == 0)? Mark.NOUGHT : Mark.CROSS; gb.setCell(curMark, c.getRow(), c.getColumn()); } private TicTacToeGUIGame() { gb = new Board(3, 3, new ActionListener() { public void actionPerformed(ActionEvent ae) { Cell c = (Cell) ae.getSource(); takeTurn(c); } }); this.add(gb); this.setDefaultCloseOperation(EXIT_ON_CLOSE); this.setTitle("TIC-TAC-TOE"); this.setSize(300, 300); this.setVisible(true); } public static void main(String[] args) { // TODO Auto-generated method stub SwingUtilities.invokeLater( new Runnable () { public void run() { new TicTacToeGUIGame(); } }); } } ``` Here is a board class: ``` package games.board; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JPanel; import javax.swing.JFrame; public class Board extends JPanel { private Cell[][] cells; public Board(int rows, int columns) { cells = new Cell[rows][columns]; for( int r = 0; r < cells[0].length; r++ ) { for (int c = 0; c < cells[1].length; c++) { cells[r][c] = new Cell(r,c); } } } public Board(int rows, int columns, ActionListener ah) { cells = new Cell[rows][columns]; this.setLayout(new GridLayout()); for( int r = 0; r < cells.length; r++ ) { for (int c = 0; c < cells[r].length; c++) { cells[r][c] = new Cell(r,c); this.add(cells[r][c]); cells[r][c].addActionListener(ah); } } } public void setCell(Mark mark, int row, int column) throws IllegalArgumentException { if (cells[row][column].getContent() == Mark.EMPTY) cells[row][column].setContent(mark); else throw new IllegalArgumentException("Player already there!"); } public Cell getCell(int row, int column) { return cells[row][column]; } public String toString() { StringBuilder str = new StringBuilder(); for( int r = 0; r < cells.length; r++ ) { str.append("|"); for (int c = 0; c < cells[r].length; c++) { switch(cells[r][c].getContent()) { case NOUGHT: str.append("O"); break; case CROSS: str.append("X"); break; case YELLOW: str.append("Y"); break; case RED: str.append("R"); break; case BLUE: str.append("B"); break; case GREEN: str.append("G"); break; case MAGENTA: str.append("M"); break; case ORANGE: str.append("M"); break; default: //Empty str.append(""); } str.append("|"); } str.append("\n"); } return str.toString(); } } ```
2013/08/19
[ "https://Stackoverflow.com/questions/18319436", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2694776/" ]
> > i want 3 columns and three rows.. But output shows 6 columns > > > You need to specify proper parameters to the GridLayout: ``` this.setLayout(new GridLayout(0, 3)); ``` This will tell the grid to contain 3 columns. The number of rows will depend on the number of components you add.
> > I want 3 columns and three rows... But output shows 6 columns > > > Use, `this.setLayout(new GridLayout(nRows, nColumns));` Change `nRows` and `nColumns` accordingly to how many columns and rows you want, ie, if you wanted a `20x20` game you would use, `this.setLayout(new GridLayout(20, 20));`
10,879,761
> > **Possible Duplicate:** > > [What is the Java equivalent for LINQ?](https://stackoverflow.com/questions/1217228/what-is-the-java-equivalent-for-linq) > > > There are numerous questions asking whether there is a Java equivalent for LINQ. But most of them are incorrectly specifying that there is nothing.
2012/06/04
[ "https://Stackoverflow.com/questions/10879761", "https://Stackoverflow.com", "https://Stackoverflow.com/users/195524/" ]
This library provides a full LINQ API: <https://github.com/nicholas22/jpropel-light> It does so with functional-style constructs and it also uses deferred execution. ``` // select names starting with j, using LINQ-style statements new String[] { "james", "john", "john", "eddie" }.where(startsWith("j")).distinct().all(println()); ```
Another one that I've tried myself is jaque: <http://code.google.com/p/jaque/>
38,918,332
I need to change the 8080 port on my spring boot application, getting it from an external config file. I have my application.properties in /config directory and I added server.port = 8090 When the app starts, the logger says something like: ``` 2016-08-12 14:41:04 INFO Http11NioProtocol:180 - Initializing ProtocolHandler ["http-nio-8090"] 2016-08-12 14:41:05 INFO Http11NioProtocol:180 - Starting ProtocolHandler ["http-nio-8090"] ``` so i think that the property has been taken... but if i try to reach a web service on it ``` 10.10.8.133:8090/client?numeroClient=4 ``` I got a 0 error and if I try to call ``` 10.10.8.133:8080/client?numeroClient=4 ``` I got the right response... Which is the problem?
2016/08/12
[ "https://Stackoverflow.com/questions/38918332", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5550833/" ]
In fact, there's, as far as I know, 2 ways to change default server port for spring boot : **application.properties** In your application.properties file, you just have to add : ``` server.port=9080 ``` If it's not working, it's most likely because your `application.properties` configuration file is not taken into account. You can still change the location with JVM properties like : ``` java -Dspring.config.location=/random/location/directory -jar spring-boot-application.jar ``` From Spring docs : <https://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html> **JVM properties** When you start your spring boot application you can add JVM properties like : ``` java -Dserver.port=9080 -jar spring-boot-application.jar ``` **Documentation :** * Change the HTTP port : <https://docs.spring.io/spring-boot/docs/current/reference/html/howto-embedded-servlet-containers.html#howto-change-the-http-port> * Customizing embedded servlet containers : <https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-developing-web-applications.html#boot-features-customizing-embedded-containers>
By default spring uses port 8080 and depending on your system it may be in use, thus causing problems for Spring, so: Modify the application.properties file and only add server.port = XXXX
38,918,332
I need to change the 8080 port on my spring boot application, getting it from an external config file. I have my application.properties in /config directory and I added server.port = 8090 When the app starts, the logger says something like: ``` 2016-08-12 14:41:04 INFO Http11NioProtocol:180 - Initializing ProtocolHandler ["http-nio-8090"] 2016-08-12 14:41:05 INFO Http11NioProtocol:180 - Starting ProtocolHandler ["http-nio-8090"] ``` so i think that the property has been taken... but if i try to reach a web service on it ``` 10.10.8.133:8090/client?numeroClient=4 ``` I got a 0 error and if I try to call ``` 10.10.8.133:8080/client?numeroClient=4 ``` I got the right response... Which is the problem?
2016/08/12
[ "https://Stackoverflow.com/questions/38918332", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5550833/" ]
In fact, there's, as far as I know, 2 ways to change default server port for spring boot : **application.properties** In your application.properties file, you just have to add : ``` server.port=9080 ``` If it's not working, it's most likely because your `application.properties` configuration file is not taken into account. You can still change the location with JVM properties like : ``` java -Dspring.config.location=/random/location/directory -jar spring-boot-application.jar ``` From Spring docs : <https://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html> **JVM properties** When you start your spring boot application you can add JVM properties like : ``` java -Dserver.port=9080 -jar spring-boot-application.jar ``` **Documentation :** * Change the HTTP port : <https://docs.spring.io/spring-boot/docs/current/reference/html/howto-embedded-servlet-containers.html#howto-change-the-http-port> * Customizing embedded servlet containers : <https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-developing-web-applications.html#boot-features-customizing-embedded-containers>
If your project is maven modular, make sure in your pom file packaging type is `jar, becuase if your root project packageing type is pom, then configuring application.properties for changing server port not affected.
38,918,332
I need to change the 8080 port on my spring boot application, getting it from an external config file. I have my application.properties in /config directory and I added server.port = 8090 When the app starts, the logger says something like: ``` 2016-08-12 14:41:04 INFO Http11NioProtocol:180 - Initializing ProtocolHandler ["http-nio-8090"] 2016-08-12 14:41:05 INFO Http11NioProtocol:180 - Starting ProtocolHandler ["http-nio-8090"] ``` so i think that the property has been taken... but if i try to reach a web service on it ``` 10.10.8.133:8090/client?numeroClient=4 ``` I got a 0 error and if I try to call ``` 10.10.8.133:8080/client?numeroClient=4 ``` I got the right response... Which is the problem?
2016/08/12
[ "https://Stackoverflow.com/questions/38918332", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5550833/" ]
If your project is maven modular, make sure in your pom file packaging type is `jar, becuase if your root project packageing type is pom, then configuring application.properties for changing server port not affected.
By default spring uses port 8080 and depending on your system it may be in use, thus causing problems for Spring, so: Modify the application.properties file and only add server.port = XXXX
74,166,243
I have a .csv file that is about 5mb (~45,000 rows). What I need to do is run through each row of the file and check if the ID in each line is already in a table in my database. If it is, I can delete that row from the file. I did a good amount of research on the most memory efficient way to do this, so I've been using a method of writing lines that don't need to get deleted to a temporary file and then renaming that file as the original. Code below: ``` $file= fopen($filename, 'r'); $temp = fopen($tempFilename, 'w'); while(($row = fgetcsv($file)) != FALSE){ // id is the 7th value in the row $id = $row[6]; // check table to see if id exists $sql = "SELECT id FROM table WHERE id = $id"; $result = mysqli_query($conn, $sql); // if id is in the database, skip to next row if(mysqli_num_rows($result) > 0){ continue; } // else write line to temp file fputcsv($temp, $row); } fclose($file); fclose($temp); // overwrite original file rename($tempFilename, $filename); ``` Problem is, I'm running into a timeout while executing this bit of code. Anything I can do to make the code more efficient?
2022/10/22
[ "https://Stackoverflow.com/questions/74166243", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13872573/" ]
You fire a database query per line, aka 45.000 queries... that takes too much time. Better you do a query before the loop and read the existing id into a lookup array, then only check this array in the loop. Pseudo code: ``` $st = query('SELECT id FROM table'); while ($row = $st->fetch()) { $lookup[ $row['id'] ] = $row['id']; } // now read CSV while($row = fgetcsv($h)) { $id = $row[6]; if (isset($lookup[ $id ])) { // exist... continue; } // write the non-existing id to different file... } ``` edit: Assume memory isn't sufficient to hold 1 million integer from the database. How can it still be done efficiently? Collect ids from CSV into an array. Write a single query to find all those ids in the database and collect (it can be maximal so many as in the CSV). Now `array_diff()` the ids from file with the ids from database - those ids remaining exist in CSV but not in database. Pseudo code: ``` $ids_csv = []; while($row = fgetcsv($h)) { $id = row[6]; $ids_csv[] = intval($id); } $sql = sprintf('SELECT id FROM table WHERE id IN(%s)', implode(',', $ids_csv)); $ids_db = []; $st = query($sql); while ($row = $st->fetch()) { $ids_db[] = $row['id']; } $missing_in_db = array_diff($ids_csv, $ids_db); ```
1. I would use `LOAD DATA INFILE`: <https://dev.mysql.com/doc/refman/8.0/en/load-data.html> Your database user needs to have `FILE` priveleges on the database to use. to read the csv file into a separate table. 2. Then you can run one query to delete id's already exist (delete from join ...) 3. And export the rows that were left intact. Other option is use your loop to insert your csv file into a seperate table, and then proceed with step 2. **Update:** I use `LOAD DATA INFILE` with csv files up to 2 million rows (at the moment) and do some bulk data manipulation with big queries, it's blazingly fast and I would recommend this route for files containing > 100k lines.
66,612,578
I have this folder structure: ``` sass/main.sass css/main.css js/... img/... ``` I want the sass output to go to the css folder, but each time I run sass watcher it creates a new css file within the sass directory among sass files.
2021/03/13
[ "https://Stackoverflow.com/questions/66612578", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15328189/" ]
Thx for information about using 'Live SASS Compiler' in VS Code. To set special otuput pathes to your project you need to add the settings for output pathes to the `settigns.json` of your project: File: `projectDIR/.vscode/settings.json' Example for setting the save pathes to output directory: ``` "settings": { // output: generate files to ... // ~ = path starts relative from scss-file "liveSassCompile.settings.formats":[ { "format": "expanded", "extensionName": ".css", "savePath": "~/../assets" }, // ad a compressed version { "format": "compressed", "extensionName": ".min.css", "savePath": "~/../assets" } // optional: add more outputs ... ], } ``` See also official example in web: <https://github.com/ritwickdey/vscode-live-sass-compiler/blob/master/docs/settings.md> --- **Additional hint: VERSION OFF 'LIVE SASS COMPILER' MAY BE OUTDATED** The actual commmon used Extension `Live Sass Compiler` is not longer supported (for years now). It uses an outdated SASS Version. The most recent features like `@use` are not supported in that version. You use that outdated version if author is 'Ritwick Dey'. But there is an active supported fork with same name 'Live SASS Compiler' build by 'Glenn Marks'. As fork it works the same way and the settings are almost the same. Or you can use another actual compiler which is faster as you can use an direct installed SASS Version on your system. In that case you need to change the settings for your project. Information about that you will find here: <https://stackoverflow.com/a/66207572/9268485> --- ***Updated:*** *Correction name of author of supported extension 'Live SASS Compiler' to correct identification of extension.*
Go to path: C:\Users\your user\AppData\Roaming\Code\User\settings.json and change there the "liveSassCompile.settings.formats" section for example: the parameter : "savePath": "/Python/CSS", [![enter image description here](https://i.stack.imgur.com/WT9rO.png)](https://i.stack.imgur.com/WT9rO.png)
249,956
Does this table comply with 1NF, even if **CourseNo** and **StudentNo**? ``` Student(StudentNo, StudentName, Major, CourseNo, CourseName, InstructorNo, InstructorName, InstructorLocation, Grade) ```
2019/09/30
[ "https://dba.stackexchange.com/questions/249956", "https://dba.stackexchange.com", "https://dba.stackexchange.com/users/191413/" ]
If all the attributes/columns of that relation/table always contain *atomic* values (i.e., they accept *exactly one* value —neither no value, nor two or more, nor NULL marks— of the corresponding *simple domain*1, 2 per tuple/row), then yes, that relation/table meets first normal form (1NF); otherwise, no, it is not in 1NF, it is unnormalized. Naturally, I do not know the informational characteristics of the business environment of relevance (e.g., what meaning is ascribed to each attribute/column by the end users and business experts, how each attribute/column is associated with the others, etc.), so who knows. The question so far lacks any sample values (paramount factor to determine the respective domains), lacks any description about the business scenario at hand, lacks details about how the data points of significance are associated with each other, etc. (yes, the attributes/columns are represented by certain words, but the same word may carry different meanings in different contexts, thus an unrelated reader cannot know with exactitude what their connotations are in the scenario under consideration); therefore, as the post stands, it is impossible to evaluate properly the relation/table included in it. The fact that the question does not contain that kind of necessary information is understandable if you are starting to learn about *normalization* according to the *relational* paradigm, but be aware that making guesses when laying out a database is counterproductive. In this regard, it is worth to point out that working closely with the business experts is indispensable in any professional database design project (including normalization at the logical layer, of course). In case you are involved in a training/school course, I would highly recommend that you request an appropriate contextualization of the exercises from your teacher. If, on the contrary, you are learning on your own, you should look for [sound materials](http://dblp.uni-trier.de/pers/hd/c/Codd:E=_F=.html) in the relational field to optimize your efforts (this advice is more fitting now that you have clarified [via comments](https://dba.stackexchange.com/questions/249956/is-this-really-1nf#comment492736_249962) that you are learning by yourself). In agreement with the deliberations above, it is opportune to remark that relational database design is a craft that demands *high precision*. --- 1 Basically speaking, a *domain* is a set of values of the same type. *N* constraints can be attached to a domain. *N* relations/tables of a database can have *n* attributes/columns which draw their values from the same domain. An attribute/column can have, in turn, specific constraints only applicable to itself. 2 A domain is *simple* if (a) it is not comprised of relations/tables and (b) its values cannot be decomposed by the database management system. Avoiding non-simple domains when delineating a database is useful so as to take full advantage of the declarative power of a data sublanguage, which in practice facilitates the implementation of constraints and manipulation operations.
The table comply with 1NF. The page you link to (<https://opentextbc.ca/dbdesign01/chapter/chapter-12-normalization/>) is incorrect. The page states that the example has a "repeating group" because there can be multiple courses per student and therefore is not in 1NF. But this is a misunderstanding of 1NF. 1NF is about eliminating domains which have relations as elements. This means no columns should have tables as values. A "repeating group" in the context of 1NF is another word for table-valued attribute. It does not seem like any of the columns in the example have tables as values, so the example is in 1NF. The example violates 2NF though. Assuming SudentNo and CourseNo combined is key, then the other attributes only depend on parts of the keys. So you have to split it into three tables to comply with 2NF. Basically the page confuses 1NF with 2NF.
15,481,759
I am trying to convert a nested JSON object on an ASP.NET server. The incoming JSON string looks something like this - ```js data: { user_id: 1, taskid: "1234", list: { "item-1": { one: 1, two: 2 }, "item-2": { one: 1, two: 2 } //.. where number of items is unknown } } ``` I have tried to decode the data using [JSON.Decode](http://msdn.microsoft.com/en-us/library/system.web.helpers.json.decode%28v=vs.111%29.aspx) this way ``` public class Data { public int user_id { get; set; } public string taskid { get; set; } public List<object> list { get; set; } } public class DataList { List<Data> data { get; set; } } // if isPost etc.. var decodedData = JSON.Decode<DataList>(Request["data"]) ``` But when I try and iterate over decodedData I am getting an error - > > foreach statement cannot operate on variables of type > 'ASP.\_Page\_that\_cshtml.DataList' because > 'ASP.\_Page\_that\_cshtml.DataList' does not contain a public definition > for 'GetEnumerator' > > > When I try casting the decodedData to a List this way - ``` List<Data> decodedData = JSON.Decode<DataList>(Request["data"]) ``` I throw another error > > CS0030: Cannot convert type '`ASP._Page_that_cshtml.DataList`' to '`System.Collections.Generic.List<ASP._Page_that_cshtml.DataList>`' > > > Could you please suggest an appropriate method to convert nested JSON objects into a C# object and iterating over it? PS: trailing semi-colons omitted on-purpose
2013/03/18
[ "https://Stackoverflow.com/questions/15481759", "https://Stackoverflow.com", "https://Stackoverflow.com/users/95055/" ]
``` List<Data> decodedData = JSON.Decode<DataList>(Request["data"]) ``` Should Be ``` var decodedData = JSON.Decode<List<Data>>(Request["data"]) var myDataList = new DataList() { data = decodedData; } ```
Try iterating over `decodedData.data` instead. `decodedData` is a `DataList`, and the `DataList` class has a member `data` which is a `List<Data>`. `List<Data>` has a `GetEnumerator` method, as required by `foreach`. Alternatively, you could add a `GetEnumerator` method to `DataList`: ``` public IEnumerator GetEnumerator() { return data.GetEnumerator(); } ```
15,481,759
I am trying to convert a nested JSON object on an ASP.NET server. The incoming JSON string looks something like this - ```js data: { user_id: 1, taskid: "1234", list: { "item-1": { one: 1, two: 2 }, "item-2": { one: 1, two: 2 } //.. where number of items is unknown } } ``` I have tried to decode the data using [JSON.Decode](http://msdn.microsoft.com/en-us/library/system.web.helpers.json.decode%28v=vs.111%29.aspx) this way ``` public class Data { public int user_id { get; set; } public string taskid { get; set; } public List<object> list { get; set; } } public class DataList { List<Data> data { get; set; } } // if isPost etc.. var decodedData = JSON.Decode<DataList>(Request["data"]) ``` But when I try and iterate over decodedData I am getting an error - > > foreach statement cannot operate on variables of type > 'ASP.\_Page\_that\_cshtml.DataList' because > 'ASP.\_Page\_that\_cshtml.DataList' does not contain a public definition > for 'GetEnumerator' > > > When I try casting the decodedData to a List this way - ``` List<Data> decodedData = JSON.Decode<DataList>(Request["data"]) ``` I throw another error > > CS0030: Cannot convert type '`ASP._Page_that_cshtml.DataList`' to '`System.Collections.Generic.List<ASP._Page_that_cshtml.DataList>`' > > > Could you please suggest an appropriate method to convert nested JSON objects into a C# object and iterating over it? PS: trailing semi-colons omitted on-purpose
2013/03/18
[ "https://Stackoverflow.com/questions/15481759", "https://Stackoverflow.com", "https://Stackoverflow.com/users/95055/" ]
Try iterating over `decodedData.data` instead. `decodedData` is a `DataList`, and the `DataList` class has a member `data` which is a `List<Data>`. `List<Data>` has a `GetEnumerator` method, as required by `foreach`. Alternatively, you could add a `GetEnumerator` method to `DataList`: ``` public IEnumerator GetEnumerator() { return data.GetEnumerator(); } ```
You can try decoding the JSON into an array of Data objects, and then calling the ToList() extension method on that array. ``` var dataArray = JSON.Decode<Data[]>(Request["data"]); var list = dataArray.ToList(); ```
15,481,759
I am trying to convert a nested JSON object on an ASP.NET server. The incoming JSON string looks something like this - ```js data: { user_id: 1, taskid: "1234", list: { "item-1": { one: 1, two: 2 }, "item-2": { one: 1, two: 2 } //.. where number of items is unknown } } ``` I have tried to decode the data using [JSON.Decode](http://msdn.microsoft.com/en-us/library/system.web.helpers.json.decode%28v=vs.111%29.aspx) this way ``` public class Data { public int user_id { get; set; } public string taskid { get; set; } public List<object> list { get; set; } } public class DataList { List<Data> data { get; set; } } // if isPost etc.. var decodedData = JSON.Decode<DataList>(Request["data"]) ``` But when I try and iterate over decodedData I am getting an error - > > foreach statement cannot operate on variables of type > 'ASP.\_Page\_that\_cshtml.DataList' because > 'ASP.\_Page\_that\_cshtml.DataList' does not contain a public definition > for 'GetEnumerator' > > > When I try casting the decodedData to a List this way - ``` List<Data> decodedData = JSON.Decode<DataList>(Request["data"]) ``` I throw another error > > CS0030: Cannot convert type '`ASP._Page_that_cshtml.DataList`' to '`System.Collections.Generic.List<ASP._Page_that_cshtml.DataList>`' > > > Could you please suggest an appropriate method to convert nested JSON objects into a C# object and iterating over it? PS: trailing semi-colons omitted on-purpose
2013/03/18
[ "https://Stackoverflow.com/questions/15481759", "https://Stackoverflow.com", "https://Stackoverflow.com/users/95055/" ]
``` List<Data> decodedData = JSON.Decode<DataList>(Request["data"]) ``` Should Be ``` var decodedData = JSON.Decode<List<Data>>(Request["data"]) var myDataList = new DataList() { data = decodedData; } ```
Your example is not [valid json](http://jsonlint.com/). You should have a collection `[]` for list: ``` data: { "user_id": 1, "taskid": "1234", "list": [ { "one": 1, "two": 2 }, { "one": 1, "two": 2 } ] } ```