qid
int64
1
74.7M
question
stringlengths
15
58.3k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
4
30.2k
response_k
stringlengths
11
36.5k
16,086,851
In spreadsheet cell B1, the value is -1200. I want cell B2 to copy the value of B1 and limit (validate?) it to no less than -800. I'm using google docs but can also use excel if those functions are not available in google docs. Edit: If B1 has the value of 2000, B2 should have the value of 2000. If B1 has the value of -2000, B2 should have the value of -800
2013/04/18
[ "https://Stackoverflow.com/questions/16086851", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2295658/" ]
Excel & Google Spreadsheets ``` =Max(B1,-800) ```
You don't need any maths here. I'm using Excel but I think it is pretty similar in Google. Suppose that B3 holds floor, no constants in formulae :-) B2 => =if( b1 > $b$3; b1; $b$3) b3 position is fixed so you can copy the expression
7,553,865
Good day, i have mongodb database filled with some data, i ensured that data stored in correct charset, to fetch data i use following snippet: ``` {-# LANGUAGE OverloadedStrings #-} import Network.Wai import Network.Wai.Handler.Warp (run) import Data.Enumerator (Iteratee (..)) import Data.Either (either) import Control.Monad (join) import Data.Maybe (fromMaybe) import Network.HTTP.Types (statusOK, status404) import qualified Data.ByteString as B import qualified Data.ByteString.Lazy as L import Data.ByteString.Char8 (unpack) import Data.ByteString.Lazy.Char8 (pack) import qualified Data.Text.Lazy as T import Data.Text (Text(..)) import Control.Monad.IO.Class (liftIO, MonadIO) import Data.Aeson (encode) import qualified Data.Map as Map import qualified Database.MongoDB as DB application dbpipe req = do case unpack $ rawPathInfo req of "/items" -> itemsJSON dbpipe req _ -> return $ responseLBS status404 [("Content-Type", "text/plain")] "404" indexPage :: Iteratee B.ByteString IO Response indexPage = do page <- liftIO $ processTemplate "templates/index.html" [] return $ responseLBS statusOK [("Content-Type", "text/html; charset=utf-8")] page processTemplate f attrs = do page <- L.readFile f return page itemsJSON :: DB.Pipe -> Request -> Iteratee B.ByteString IO Response itemsJSON dbpipe req = do dbresult <- liftIO $ rundb dbpipe $ DB.find (DB.select [] $ tu "table") >>= DB.rest let docs = either (const []) id dbresult -- liftIO $ L.putStrLn $ encode $ show $ map docToMap docs return $ responseLBS statusOK [("Content-Type", "text/plain; charset=utf-8")] (encode $ map docToMap docs) docToMap doc = Map.fromList $ map (\f -> (T.dropAround (== '"') $ T.pack $ show $ DB.label f, T.dropAround (== '"') $ T.pack $ show $ DB.value f)) doc main = do pipe <- DB.runIOE $ DB.connect $ DB.host "127.0.0.1" run 3000 $ application pipe rundb pipe act = DB.access pipe DB.master database act tu :: B.ByteString -> UString tu = DB.u . C8.unpack ``` Then the result is suprprising, DB.label works well, but DB.value giving me native characters as some escape codes, so the result is look like: `curl <http://localhost:3000/items>` gives: ``` [{"Марка": "\1058\1080\1087 \1087\1086\1076", "Model": "BD-W LG BP06LU10 Slim \1058\1080\1087 \1087\1086\1076\1082\1083\1102\1095\1077\1085\1080\1103"}, ... ] ``` This happens in case i trying to print data and also in case i return data encoded as JSON Any idea how correctly extract values from MongoDB driver ?
2011/09/26
[ "https://Stackoverflow.com/questions/7553865", "https://Stackoverflow.com", "https://Stackoverflow.com/users/250944/" ]
Your frined is `ABAddressBook`: <http://developer.apple.com/library/mac/#documentation/UserExperience/Reference/AddressBook/Classes/ABAddressBook_Class/Reference/Reference.html> It has `(NSArray *)people` that returns you all contacts. You can use that as the source for your table. I do not have complete sample code available but I think that is not the point of Stack Overflow. Search here at SO to find how to implement `UITableView`.
[**Here**](https://stackoverflow.com/questions/7118772/how-to-get-contacts-detail-of-iphone-and-make-csv-file-of-that-contact/7119251#7119251) is the solution that you are looking for. In that, you will get required data from the method **-(void)collectContacts**.
7,553,865
Good day, i have mongodb database filled with some data, i ensured that data stored in correct charset, to fetch data i use following snippet: ``` {-# LANGUAGE OverloadedStrings #-} import Network.Wai import Network.Wai.Handler.Warp (run) import Data.Enumerator (Iteratee (..)) import Data.Either (either) import Control.Monad (join) import Data.Maybe (fromMaybe) import Network.HTTP.Types (statusOK, status404) import qualified Data.ByteString as B import qualified Data.ByteString.Lazy as L import Data.ByteString.Char8 (unpack) import Data.ByteString.Lazy.Char8 (pack) import qualified Data.Text.Lazy as T import Data.Text (Text(..)) import Control.Monad.IO.Class (liftIO, MonadIO) import Data.Aeson (encode) import qualified Data.Map as Map import qualified Database.MongoDB as DB application dbpipe req = do case unpack $ rawPathInfo req of "/items" -> itemsJSON dbpipe req _ -> return $ responseLBS status404 [("Content-Type", "text/plain")] "404" indexPage :: Iteratee B.ByteString IO Response indexPage = do page <- liftIO $ processTemplate "templates/index.html" [] return $ responseLBS statusOK [("Content-Type", "text/html; charset=utf-8")] page processTemplate f attrs = do page <- L.readFile f return page itemsJSON :: DB.Pipe -> Request -> Iteratee B.ByteString IO Response itemsJSON dbpipe req = do dbresult <- liftIO $ rundb dbpipe $ DB.find (DB.select [] $ tu "table") >>= DB.rest let docs = either (const []) id dbresult -- liftIO $ L.putStrLn $ encode $ show $ map docToMap docs return $ responseLBS statusOK [("Content-Type", "text/plain; charset=utf-8")] (encode $ map docToMap docs) docToMap doc = Map.fromList $ map (\f -> (T.dropAround (== '"') $ T.pack $ show $ DB.label f, T.dropAround (== '"') $ T.pack $ show $ DB.value f)) doc main = do pipe <- DB.runIOE $ DB.connect $ DB.host "127.0.0.1" run 3000 $ application pipe rundb pipe act = DB.access pipe DB.master database act tu :: B.ByteString -> UString tu = DB.u . C8.unpack ``` Then the result is suprprising, DB.label works well, but DB.value giving me native characters as some escape codes, so the result is look like: `curl <http://localhost:3000/items>` gives: ``` [{"Марка": "\1058\1080\1087 \1087\1086\1076", "Model": "BD-W LG BP06LU10 Slim \1058\1080\1087 \1087\1086\1076\1082\1083\1102\1095\1077\1085\1080\1103"}, ... ] ``` This happens in case i trying to print data and also in case i return data encoded as JSON Any idea how correctly extract values from MongoDB driver ?
2011/09/26
[ "https://Stackoverflow.com/questions/7553865", "https://Stackoverflow.com", "https://Stackoverflow.com/users/250944/" ]
Your frined is `ABAddressBook`: <http://developer.apple.com/library/mac/#documentation/UserExperience/Reference/AddressBook/Classes/ABAddressBook_Class/Reference/Reference.html> It has `(NSArray *)people` that returns you all contacts. You can use that as the source for your table. I do not have complete sample code available but I think that is not the point of Stack Overflow. Search here at SO to find how to implement `UITableView`.
Yeah, I got the solution... Use this code ``` // creating the picker ABPeoplePickerNavigationController *picker = [[ABPeoplePickerNavigationController alloc] init]; // place the delegate of the picker to the controll picker.peoplePickerDelegate = self; // showing the picker [self presentModalViewController:picker animated:NO]; // releasing [picker release]; ``` and It will display all contacts from iPhone as shown in figure..but not display that type of view in simulator..you have to run it in device... Happy Coding...
7,553,865
Good day, i have mongodb database filled with some data, i ensured that data stored in correct charset, to fetch data i use following snippet: ``` {-# LANGUAGE OverloadedStrings #-} import Network.Wai import Network.Wai.Handler.Warp (run) import Data.Enumerator (Iteratee (..)) import Data.Either (either) import Control.Monad (join) import Data.Maybe (fromMaybe) import Network.HTTP.Types (statusOK, status404) import qualified Data.ByteString as B import qualified Data.ByteString.Lazy as L import Data.ByteString.Char8 (unpack) import Data.ByteString.Lazy.Char8 (pack) import qualified Data.Text.Lazy as T import Data.Text (Text(..)) import Control.Monad.IO.Class (liftIO, MonadIO) import Data.Aeson (encode) import qualified Data.Map as Map import qualified Database.MongoDB as DB application dbpipe req = do case unpack $ rawPathInfo req of "/items" -> itemsJSON dbpipe req _ -> return $ responseLBS status404 [("Content-Type", "text/plain")] "404" indexPage :: Iteratee B.ByteString IO Response indexPage = do page <- liftIO $ processTemplate "templates/index.html" [] return $ responseLBS statusOK [("Content-Type", "text/html; charset=utf-8")] page processTemplate f attrs = do page <- L.readFile f return page itemsJSON :: DB.Pipe -> Request -> Iteratee B.ByteString IO Response itemsJSON dbpipe req = do dbresult <- liftIO $ rundb dbpipe $ DB.find (DB.select [] $ tu "table") >>= DB.rest let docs = either (const []) id dbresult -- liftIO $ L.putStrLn $ encode $ show $ map docToMap docs return $ responseLBS statusOK [("Content-Type", "text/plain; charset=utf-8")] (encode $ map docToMap docs) docToMap doc = Map.fromList $ map (\f -> (T.dropAround (== '"') $ T.pack $ show $ DB.label f, T.dropAround (== '"') $ T.pack $ show $ DB.value f)) doc main = do pipe <- DB.runIOE $ DB.connect $ DB.host "127.0.0.1" run 3000 $ application pipe rundb pipe act = DB.access pipe DB.master database act tu :: B.ByteString -> UString tu = DB.u . C8.unpack ``` Then the result is suprprising, DB.label works well, but DB.value giving me native characters as some escape codes, so the result is look like: `curl <http://localhost:3000/items>` gives: ``` [{"Марка": "\1058\1080\1087 \1087\1086\1076", "Model": "BD-W LG BP06LU10 Slim \1058\1080\1087 \1087\1086\1076\1082\1083\1102\1095\1077\1085\1080\1103"}, ... ] ``` This happens in case i trying to print data and also in case i return data encoded as JSON Any idea how correctly extract values from MongoDB driver ?
2011/09/26
[ "https://Stackoverflow.com/questions/7553865", "https://Stackoverflow.com", "https://Stackoverflow.com/users/250944/" ]
[**Here**](https://stackoverflow.com/questions/7118772/how-to-get-contacts-detail-of-iphone-and-make-csv-file-of-that-contact/7119251#7119251) is the solution that you are looking for. In that, you will get required data from the method **-(void)collectContacts**.
Yeah, I got the solution... Use this code ``` // creating the picker ABPeoplePickerNavigationController *picker = [[ABPeoplePickerNavigationController alloc] init]; // place the delegate of the picker to the controll picker.peoplePickerDelegate = self; // showing the picker [self presentModalViewController:picker animated:NO]; // releasing [picker release]; ``` and It will display all contacts from iPhone as shown in figure..but not display that type of view in simulator..you have to run it in device... Happy Coding...
73,567,318
I have a problem with some Observable and error handling. I have to make a call to an API for deleting a resource, but if this resource is used from some other element the DB send an error back. I've used the try-catch statement too, but it doesn't work. That's the function: ``` try { this.itemService.delete(this.item).subscribe( val => console.log('val:', val), err => console.log('err:', err), () => this.router.navigate(['items/']) ); } catch (e) { console.log('error from catch:', e); } } ``` The delete function in the itemService just takes the item, fetch the ID from it and make an http request that replies with an Observable. If I try to delete an unused item it works perfectly: the "val: ..." is in the console and finally it sends me to the "items/" page. But if the db replies with an error because the item is used, I expected to see "err: ..." or "error from catch: ..." in the console. But I only receive the DB error from the backend. That's the response from my backend: ``` {"statusCode":400,"message":"Can't delete Item de1b8d07-xxx: Item de1b8d07-xxx contains nested dependencies, please remove all dependencies first and then remove this Item again.","error":"Bad Request"} ``` Why it can't understand the error and show me the "err:" or "error from catch:"? Where am I wrong? Thanks in advance! *Edit after Vivek kushwaha reply:* I tried this too: ``` this.a = this.itemService.delete(this.item); this.a.pipe( catchError(err => { console.log('catcherror:', err); return throwError(err); }) ) .subscribe( res => console.log('HTTP response', res), err => console.log('HTTP Error', err), () => console.log('HTTP request completed.') ); ``` But nothing changes: when it works it replies with "HTTP response ...", but when the backend replies with an error nothing happens in the console but the DB error.
2022/09/01
[ "https://Stackoverflow.com/questions/73567318", "https://Stackoverflow.com", "https://Stackoverflow.com/users/785053/" ]
If you want to use the catch() of the Observable you need to use Observable.throw() method before delegating the error response to a method ```js import { Injectable } from '@angular/core'; import { Headers, Http, ResponseOptions} from '@angular/http'; import { AuthHttp } from 'angular2-jwt'; import { MEAT_API } from '../app.api'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; @Injectable() export class CompareNfeService { constructor(private http: AuthHttp) {} envirArquivos(order): Observable < any > { const headers = new Headers(); return this.http.post(`${MEAT_API}compare/arquivo`, order, new ResponseOptions({ headers: headers })) .map(response => response.json()) .catch((e: any) => Observable.throw(this.errorHandler(e))); } errorHandler(error: any): void { console.log(error) } } ```
try catch block won't work here, unless there is a system exception. Try to use pipe and catchError operator from rxjs. Or you could use tap operator from rxjs to debug the error. Also, check if you are using http interceptor in the application, which might be intercepting the delete request and handling the error
73,567,318
I have a problem with some Observable and error handling. I have to make a call to an API for deleting a resource, but if this resource is used from some other element the DB send an error back. I've used the try-catch statement too, but it doesn't work. That's the function: ``` try { this.itemService.delete(this.item).subscribe( val => console.log('val:', val), err => console.log('err:', err), () => this.router.navigate(['items/']) ); } catch (e) { console.log('error from catch:', e); } } ``` The delete function in the itemService just takes the item, fetch the ID from it and make an http request that replies with an Observable. If I try to delete an unused item it works perfectly: the "val: ..." is in the console and finally it sends me to the "items/" page. But if the db replies with an error because the item is used, I expected to see "err: ..." or "error from catch: ..." in the console. But I only receive the DB error from the backend. That's the response from my backend: ``` {"statusCode":400,"message":"Can't delete Item de1b8d07-xxx: Item de1b8d07-xxx contains nested dependencies, please remove all dependencies first and then remove this Item again.","error":"Bad Request"} ``` Why it can't understand the error and show me the "err:" or "error from catch:"? Where am I wrong? Thanks in advance! *Edit after Vivek kushwaha reply:* I tried this too: ``` this.a = this.itemService.delete(this.item); this.a.pipe( catchError(err => { console.log('catcherror:', err); return throwError(err); }) ) .subscribe( res => console.log('HTTP response', res), err => console.log('HTTP Error', err), () => console.log('HTTP request completed.') ); ``` But nothing changes: when it works it replies with "HTTP response ...", but when the backend replies with an error nothing happens in the console but the DB error.
2022/09/01
[ "https://Stackoverflow.com/questions/73567318", "https://Stackoverflow.com", "https://Stackoverflow.com/users/785053/" ]
You are not throwing error from your API, You are sending Ok({YourObject}). You need to send 404/error from your API or need cast your response object and manually check the error information like. ``` `this.yourservice.delete(this.item).subscribe( res => { if(res.statusCode==400){ // here is your error.. } }, err => console.log('HTTP Error', err), () => console.log('HTTP request completed.') );` ```
try catch block won't work here, unless there is a system exception. Try to use pipe and catchError operator from rxjs. Or you could use tap operator from rxjs to debug the error. Also, check if you are using http interceptor in the application, which might be intercepting the delete request and handling the error
2,291,249
I am trying to understand the history of my codebase, which resides in TFS 2005, and I encountered a changeset where all changes were marked as both branch and merge. ``` Name Change Folder ------------------------------------------------ A.cs merge, branch $/Root/Solution/Project ``` I am unable to find anything (especially on MSDN) describing what the various combinations of Add, Edit, Delete, Branch, Merge, Undelete, Encoding, etc mean. Each is pretty self explanatory when used alone and some do not make sense together like Add and Delete so I am looking for information on the legal combinations and what they mean.
2010/02/18
[ "https://Stackoverflow.com/questions/2291249", "https://Stackoverflow.com", "https://Stackoverflow.com/users/252344/" ]
Merge can be combined with anything except Add. On its own, Merge just means that (1) whatever happened is the result of invoking the Merge command (2) when you checkin, TFS will record the appropriate merge history metadata in addition to the changes themselves. The remaining operation(s) in the list of changetypes tells you exactly what kind of change is being applied to the target item. Thus: Merge, Branch = an item that exists in the source branch but not the target branch is being copied over to the target for the first time
This might make sense if the file were created during a branch operation and changes from the source branch were then merged into the new branch without having checked in at any point.
2,546,868
I have a pool of MySQL connections for a web-based data service. When it starts to service a request, it takes a connection from the pool to use. The problem is that if there has been a significant pause since that particular connection has been used, the server may have timed it out and closed its end. I'd like to be able to detect this in the pool management code. The trick is this: The environment in which I'm coding gives me only a very abstract API into the connection. I can basically only execute SQL statements. I don't have access to the actual socket or direct access to the MySQL client API. **So, the question is:** What is the cheapest MySQL statement I can execute on the connection to determine if it is working. For example `SELECT 1;` should work, but I'm wondering if there is something even cheaper? Perhaps something that doesn't even go across the wire, but is handled in the MySQL client lib and effectively answers the same question? **Clarification:** I'm not concerned about checking if the MySQL server is running, or if it's database configuration is up enough to answer queries. If those things are down, then the subsequent SQL the service executes will get and handle the appropriate error. I'm only really concerned with if the TCP connection is open… since if the server closed it, then the web service's SQL will get an error that means "just reconnect and try again", and that would be inconvenient to do once down in the muck of the service code. **Closure:** The `/* ping */` hack is exactly the sort of thing I was looking for, but alas is only available via JDBC. Reading through the docs for that hack, it is clear it was put there for *exactly* the same reason I wanted it. For the curious, I'm working in [Haskel](http://www.haskell.org/), using [HDBC](http://hackage.haskell.org/package/HDBC) and [HDBC-mysql](http://hackage.haskell.org/package/HDBC-mysql). I'm going to ask the author of HDBC-mysql to add a way to call `mysql_ping()` either directly or via a similar hack. Vlad's `DO 1` was also the kind of thing I was after, and since the other hack isn't available outside of JDBC, I'll be using it. Thanks for all the great discussion, especially @Vlad!
2010/03/30
[ "https://Stackoverflow.com/questions/2546868", "https://Stackoverflow.com", "https://Stackoverflow.com/users/138311/" ]
You **will not know the real state of the connection without going over the wire**, and `SELECT 1` is a good enough candidate (arguably you could come up with a shorter command which takes less time to parse, but compared to network or even loopback latency those savings would be insignificant.) This being said, I would argue that **pinging a connection *before* checking it out from the pool is not the best approach**. You should probably simply have your connection pool manager **enforce its own keep-alive (timeout) policy** to avoid being disconnected by the server (short of a more serious intervening connectivity issue, which could affect you smack in the middle of regular operations anyway -- and which your connection pool manager would be unable to help with anyway), as well as **in order not to hog the database** (think filehandles and memory usage) needlessly. It is therefore questionable, in my opinion, what value testing for connectivity condition before checking out a connection from the pool really has. It may be worth testing connection status **before a connection is checked in back into the pool**, but that can be done implicitly by simply marking the connection as dirty when an SQL hard error (or equivalent exception) arises (unless the API you are using already exposes a `is-bad`-like call for you.) I would therefore recommend: * implementing a client-side keep-alive policty * not performing any checks when checking out connections from the pool * performing dirty checks before a connection is returned to the pool * let the application code deal with other (non-timeout) exceptional connection conditions ### UPDATE It would appear from your comments that you really *really* want to ping the connection (I assume that is because you don't have full control over, or knowledge of, timeout characteristics on the MySQL server or intervening network equipment such as proxies etc.) In this case you can use [`DO 1`](http://dev.mysql.com/doc/refman/5.1/en/do.html) as an alternative to `SELECT 1`; it is *marginally* faster -- shorter to parse, and it does not return actual data (although you *will* get the TCP `ack`s, so you will still do the roundtrip validating that the connection is still established.) ### UPDATE 2 Regarding [Joshua's post](https://stackoverflow.com/posts/2546868#2549438), here's packet capture traces for various scenarios: ``` SELECT 1; 13:51:01.463112 IP client.45893 > server.mysql: P 2270604498:2270604511(13) ack 2531191393 win 1460 <nop,nop,timestamp 2983462950 59680547> 13:51:01.463682 IP server.mysql > client.45893: P 1:57(56) ack 13 win 65306 <nop,nop,timestamp 59680938 2983462950> 13:51:01.463698 IP client.45893 > server.mysql: . ack 57 win 1460 <nop,nop,timestamp 2983462951 59680938> DO 1; 13:51:27.415520 IP client.45893 > server.mysql: P 13:22(9) ack 57 win 1460 <nop,nop,timestamp 2983488906 59680938> 13:51:27.415931 IP server.mysql > client.45893: P 57:68(11) ack 22 win 65297 <nop,nop,timestamp 59681197 2983488906> 13:51:27.415948 IP client.45893 > server.mysql: . ack 68 win 1460 <nop,nop,timestamp 2983488907 59681197> mysql_ping 14:54:05.545860 IP client.46156 > server.mysql: P 69:74(5) ack 78 win 1460 <nop,nop,timestamp 2987247459 59718745> 14:54:05.546076 IP server.mysql > client.46156: P 78:89(11) ack 74 win 65462 <nop,nop,timestamp 59718776 2987247459> 14:54:05.546092 IP client.46156 > server.mysql: . ack 89 win 1460 <nop,nop,timestamp 2987247459 59718776> ``` As you can see, except for the fact that the `mysql_ping` packet is 5 bytes instead of `DO 1;`'s 9 bytes, the number of roundtrips (and consequently, network-induced latency) is exactly the same. The only extra cost you are paying with `DO 1` as opposed to `mysql_ping` is the parsing of `DO 1`, which is trivial.
"Connection" in this case has multiple meanings. MySQL listens on a socket- that's the network-level "connection." MySQL maintains "database connections," which include a context for query execution and other overhead. If you just want to know if the service is listening, you should be able to execute a network-level call to see if the port (don't know what the default is) is listening on the target IP. If you want to get the MySQL engine to respond, I think your `SELECT 1` idea is good- it doesn't actually fetch any data from the database but does confirm that the engine is spun up and responding.
2,546,868
I have a pool of MySQL connections for a web-based data service. When it starts to service a request, it takes a connection from the pool to use. The problem is that if there has been a significant pause since that particular connection has been used, the server may have timed it out and closed its end. I'd like to be able to detect this in the pool management code. The trick is this: The environment in which I'm coding gives me only a very abstract API into the connection. I can basically only execute SQL statements. I don't have access to the actual socket or direct access to the MySQL client API. **So, the question is:** What is the cheapest MySQL statement I can execute on the connection to determine if it is working. For example `SELECT 1;` should work, but I'm wondering if there is something even cheaper? Perhaps something that doesn't even go across the wire, but is handled in the MySQL client lib and effectively answers the same question? **Clarification:** I'm not concerned about checking if the MySQL server is running, or if it's database configuration is up enough to answer queries. If those things are down, then the subsequent SQL the service executes will get and handle the appropriate error. I'm only really concerned with if the TCP connection is open… since if the server closed it, then the web service's SQL will get an error that means "just reconnect and try again", and that would be inconvenient to do once down in the muck of the service code. **Closure:** The `/* ping */` hack is exactly the sort of thing I was looking for, but alas is only available via JDBC. Reading through the docs for that hack, it is clear it was put there for *exactly* the same reason I wanted it. For the curious, I'm working in [Haskel](http://www.haskell.org/), using [HDBC](http://hackage.haskell.org/package/HDBC) and [HDBC-mysql](http://hackage.haskell.org/package/HDBC-mysql). I'm going to ask the author of HDBC-mysql to add a way to call `mysql_ping()` either directly or via a similar hack. Vlad's `DO 1` was also the kind of thing I was after, and since the other hack isn't available outside of JDBC, I'll be using it. Thanks for all the great discussion, especially @Vlad!
2010/03/30
[ "https://Stackoverflow.com/questions/2546868", "https://Stackoverflow.com", "https://Stackoverflow.com/users/138311/" ]
I'm not sure what API you are currently using (or what language), but for Java, there is a special trick the JDBC driver can do. The standard test query is: ``` select 1 ``` as you've indicated. If you modify it to: ``` /* ping */ select 1 ``` the JDBC driver will notice this, and send only a single packet to the MySQL server to get a response. I learned about this at a Sun 'Deep Dive' episode titled [MySQL Tips for Java Developers With Mark Matthews](http://blogs.oracle.com/SDNChannel/entry/mysql_tips_for_java_developers). Even if you aren't using Java, maybe this same trick has been implemented in other mysql drivers? I assume the server would need to be aware of this special packet so it can send a response...
"Connection" in this case has multiple meanings. MySQL listens on a socket- that's the network-level "connection." MySQL maintains "database connections," which include a context for query execution and other overhead. If you just want to know if the service is listening, you should be able to execute a network-level call to see if the port (don't know what the default is) is listening on the target IP. If you want to get the MySQL engine to respond, I think your `SELECT 1` idea is good- it doesn't actually fetch any data from the database but does confirm that the engine is spun up and responding.
2,546,868
I have a pool of MySQL connections for a web-based data service. When it starts to service a request, it takes a connection from the pool to use. The problem is that if there has been a significant pause since that particular connection has been used, the server may have timed it out and closed its end. I'd like to be able to detect this in the pool management code. The trick is this: The environment in which I'm coding gives me only a very abstract API into the connection. I can basically only execute SQL statements. I don't have access to the actual socket or direct access to the MySQL client API. **So, the question is:** What is the cheapest MySQL statement I can execute on the connection to determine if it is working. For example `SELECT 1;` should work, but I'm wondering if there is something even cheaper? Perhaps something that doesn't even go across the wire, but is handled in the MySQL client lib and effectively answers the same question? **Clarification:** I'm not concerned about checking if the MySQL server is running, or if it's database configuration is up enough to answer queries. If those things are down, then the subsequent SQL the service executes will get and handle the appropriate error. I'm only really concerned with if the TCP connection is open… since if the server closed it, then the web service's SQL will get an error that means "just reconnect and try again", and that would be inconvenient to do once down in the muck of the service code. **Closure:** The `/* ping */` hack is exactly the sort of thing I was looking for, but alas is only available via JDBC. Reading through the docs for that hack, it is clear it was put there for *exactly* the same reason I wanted it. For the curious, I'm working in [Haskel](http://www.haskell.org/), using [HDBC](http://hackage.haskell.org/package/HDBC) and [HDBC-mysql](http://hackage.haskell.org/package/HDBC-mysql). I'm going to ask the author of HDBC-mysql to add a way to call `mysql_ping()` either directly or via a similar hack. Vlad's `DO 1` was also the kind of thing I was after, and since the other hack isn't available outside of JDBC, I'll be using it. Thanks for all the great discussion, especially @Vlad!
2010/03/30
[ "https://Stackoverflow.com/questions/2546868", "https://Stackoverflow.com", "https://Stackoverflow.com/users/138311/" ]
You **will not know the real state of the connection without going over the wire**, and `SELECT 1` is a good enough candidate (arguably you could come up with a shorter command which takes less time to parse, but compared to network or even loopback latency those savings would be insignificant.) This being said, I would argue that **pinging a connection *before* checking it out from the pool is not the best approach**. You should probably simply have your connection pool manager **enforce its own keep-alive (timeout) policy** to avoid being disconnected by the server (short of a more serious intervening connectivity issue, which could affect you smack in the middle of regular operations anyway -- and which your connection pool manager would be unable to help with anyway), as well as **in order not to hog the database** (think filehandles and memory usage) needlessly. It is therefore questionable, in my opinion, what value testing for connectivity condition before checking out a connection from the pool really has. It may be worth testing connection status **before a connection is checked in back into the pool**, but that can be done implicitly by simply marking the connection as dirty when an SQL hard error (or equivalent exception) arises (unless the API you are using already exposes a `is-bad`-like call for you.) I would therefore recommend: * implementing a client-side keep-alive policty * not performing any checks when checking out connections from the pool * performing dirty checks before a connection is returned to the pool * let the application code deal with other (non-timeout) exceptional connection conditions ### UPDATE It would appear from your comments that you really *really* want to ping the connection (I assume that is because you don't have full control over, or knowledge of, timeout characteristics on the MySQL server or intervening network equipment such as proxies etc.) In this case you can use [`DO 1`](http://dev.mysql.com/doc/refman/5.1/en/do.html) as an alternative to `SELECT 1`; it is *marginally* faster -- shorter to parse, and it does not return actual data (although you *will* get the TCP `ack`s, so you will still do the roundtrip validating that the connection is still established.) ### UPDATE 2 Regarding [Joshua's post](https://stackoverflow.com/posts/2546868#2549438), here's packet capture traces for various scenarios: ``` SELECT 1; 13:51:01.463112 IP client.45893 > server.mysql: P 2270604498:2270604511(13) ack 2531191393 win 1460 <nop,nop,timestamp 2983462950 59680547> 13:51:01.463682 IP server.mysql > client.45893: P 1:57(56) ack 13 win 65306 <nop,nop,timestamp 59680938 2983462950> 13:51:01.463698 IP client.45893 > server.mysql: . ack 57 win 1460 <nop,nop,timestamp 2983462951 59680938> DO 1; 13:51:27.415520 IP client.45893 > server.mysql: P 13:22(9) ack 57 win 1460 <nop,nop,timestamp 2983488906 59680938> 13:51:27.415931 IP server.mysql > client.45893: P 57:68(11) ack 22 win 65297 <nop,nop,timestamp 59681197 2983488906> 13:51:27.415948 IP client.45893 > server.mysql: . ack 68 win 1460 <nop,nop,timestamp 2983488907 59681197> mysql_ping 14:54:05.545860 IP client.46156 > server.mysql: P 69:74(5) ack 78 win 1460 <nop,nop,timestamp 2987247459 59718745> 14:54:05.546076 IP server.mysql > client.46156: P 78:89(11) ack 74 win 65462 <nop,nop,timestamp 59718776 2987247459> 14:54:05.546092 IP client.46156 > server.mysql: . ack 89 win 1460 <nop,nop,timestamp 2987247459 59718776> ``` As you can see, except for the fact that the `mysql_ping` packet is 5 bytes instead of `DO 1;`'s 9 bytes, the number of roundtrips (and consequently, network-induced latency) is exactly the same. The only extra cost you are paying with `DO 1` as opposed to `mysql_ping` is the parsing of `DO 1`, which is trivial.
I'm not sure what API you are currently using (or what language), but for Java, there is a special trick the JDBC driver can do. The standard test query is: ``` select 1 ``` as you've indicated. If you modify it to: ``` /* ping */ select 1 ``` the JDBC driver will notice this, and send only a single packet to the MySQL server to get a response. I learned about this at a Sun 'Deep Dive' episode titled [MySQL Tips for Java Developers With Mark Matthews](http://blogs.oracle.com/SDNChannel/entry/mysql_tips_for_java_developers). Even if you aren't using Java, maybe this same trick has been implemented in other mysql drivers? I assume the server would need to be aware of this special packet so it can send a response...
60,162,164
In my **PostgreSQL** database I have table with such structure: ``` | organization_id | organization_name | parent_organization_id | tree_organization_id | |-----------------|-------------------|------------------------|----------------------| | 1 | Alphabet | | | | 2 | Google | 1 | \1\2 | | 3 | Google X | 2 | \1\2\3 | ``` As you can see, the table stores a hierarchical relationship between organizations. Let's say as input I have an array of ids. For simplicity, let's say I have the following array `[3]`. How do I get a list of all parent organizations from an array? In my case, the final result which I want to see is this: ``` | organization_id | organization_name | parent_organization_id | tree_organization_id | |-----------------|-------------------|------------------------|----------------------| | 1 | Alphabet | | | | 2 | Google | 1 | \1\2 | ``` Do I need to focus on the `tree_organization_id` column or recursively iterate over the `parent_organization_id` column? **PostgreSQL version:** ``` PostgreSQL 11.4 (Debian 11.4-1.pgdg90+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 6.3.0-18+deb9u1) 6.3.0 20170516, 64-bit ``` **Columns types:** ``` | Column name | Column type | |------------------------|-------------| | organization_id | int8 | | organization_name | varchar | | parent_organization_id | int8 | | tree_organization_id | varchar | ```
2020/02/11
[ "https://Stackoverflow.com/questions/60162164", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4332480/" ]
Use [Common Table Expression(CTE)](https://www.postgresql.org/docs/current/queries-with.html) to list all the parent or children relationship. With the help of CTE, you can eliminate the tree\_organization\_id column. The [link](https://dzone.com/articles/understanding-recursive-queries-in-postgres) provides a very good tutorial for CTE beginners.
it's either way you can follow, i would prefer to recursively iterate over `parent_organisation_id`. here is the Query Below. ``` select * from company where organization_id in( select parent_organization_id from company where parent_organization_id is not null); ``` you can find the [working example from here](http://sqlfiddle.com/#!17/e340e/9/0)
44,736,006
I'm working on a application using node.js and I'm wondering whether I should add it to the npm registry so that it's easy to install. It's not a module that you would be able to use, which is what the majority of packages on npm are. If npm isn't the right place to publish it, is there another place I can publish it so that users don't have to use the `git clone; npm install` method to install it.
2017/06/24
[ "https://Stackoverflow.com/questions/44736006", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
One way to publish your application is to create a website and store your releases on it. Fortunately github offers a way to create a website out of your github repository. For more information you can go to this [link](https://pages.github.com/) Forcing users to download your application through `npm` is not a good idea.
I do that all the time (publish to npmjs), but I put it under an organization. Check out [NPM org](https://www.npmjs.com/features) You can make your code available in the path by setting the [bin](https://docs.npmjs.com/files/package.json#bin) section of `package.json`. All the user now needs to do to use your application would be: ``` npm install -g @your-org/your-app ``` and given a proper setup of the `bin` section above mentioned, you could allow the user to run your app (again, I'm not sure what type of application we are talking about). This works for any type. If you do not wish to install it globally, the executable would be available in `node_modules/.bin/your-app-name-as-in-bin-of-package-json` Please explain more what your application does so that we can help you better.
2,069,832
i want to restrict certain emails to my website. an example would be that i only want people with gmail accounts to register to my website. ``` { /* Check if valid email address */ $regex = "^[_+a-z0-9-]+(\.[_+a-z0-9-]+)*" ."@[a-z0-9-]+(\.[a-z0-9-]{1,})*" ."\.([a-z]{2,}){1}$"; if(!eregi($regex,$subemail)){ $form->setError($field, "* Email invalid"); } $subemail = stripslashes($subemail); } ``` this is what i have so far to check if its a valid email.
2010/01/15
[ "https://Stackoverflow.com/questions/2069832", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Don't use a single regex for checking the entire address. Use strrpos() split the address to local part and domain name, check them separately. Domain is easy to check, the local part is almost impossible (and you shouldn't even care about it).
I suggest you keep an array of regex patterns that you would like the email address to match against. then write a loop to iterate over the array and check the address. whenever a check failed, set some validation flag to false. after the loop, by checking the validation flag you can make sure that the email address is exactly what you want.
2,069,832
i want to restrict certain emails to my website. an example would be that i only want people with gmail accounts to register to my website. ``` { /* Check if valid email address */ $regex = "^[_+a-z0-9-]+(\.[_+a-z0-9-]+)*" ."@[a-z0-9-]+(\.[a-z0-9-]{1,})*" ."\.([a-z]{2,}){1}$"; if(!eregi($regex,$subemail)){ $form->setError($field, "* Email invalid"); } $subemail = stripslashes($subemail); } ``` this is what i have so far to check if its a valid email.
2010/01/15
[ "https://Stackoverflow.com/questions/2069832", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Don't use a single regex for checking the entire address. Use strrpos() split the address to local part and domain name, check them separately. Domain is easy to check, the local part is almost impossible (and you shouldn't even care about it).
How about doing something like: ``` list(,$domain) = explode('@',$email); if ($domain != 'gmail.com') echo 'not possible to register'; else echo 'Will register'; ``` If you want to validate the email use the filter functions
58,468,493
Is this valid: <https://godbolt.org/z/_i9dwf> ``` #include <typeinfo> #include <iostream> template<typename T> struct Container { }; void fn() { return; } template<typename T, typename...type_pack> void fn(const Container<T>& head, const Container<type_pack>&... args) { std::cout << "I am an " << typeid(T).name() << "\n"; fn(args...); return; } int main() { fn(Container<int>{}, Container<float>{}); return 0; } ``` Does C++ actually allow such expansions, or is this implementation defined based on compiler? I don't believe I have seen this type of syntax used elsewhere: `Container<type_pack>&...`. It's just something I came up with for what I wanted to achieve, and surprisingly it works. So my question is, is this UB, or is there an actual mention in the standard that this is well-defined?
2019/10/19
[ "https://Stackoverflow.com/questions/58468493", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2448032/" ]
In order to avoid this kind of behaviour I suggest you to put all your code in a main function, so that everything is loaded when you need it E.G. ``` #!/bin/bash main() { if [[ $adapter == "1" ]]; then usepreferredadapter elif [[ $adapter == "2" ]]; then ... fi } function usepreferredadapter(){ ... } main "$@" ``` This way, it doesn't matter where you define your method as long you call the main method at the bottom of your script
Try shifting the function definition before the line where the function is called, i.e. shift your function definition at line #89 to some place before line #66.
21,320,108
Ok, I have wrote this RandomNumberGenerator.java class and I am getting an error. Logically it looks like it would work but it is not. I need to have a random number between the two input's that the user input's. Would someone take a look at my code and see where I am going wrong. Here is my code: ``` import java.util.*; public class NumberGenerator { // Begin public static void main(String[] args){ Scanner input; int max, min, range; Random gen; public static int genRandom(int mod){ Random r = new Random(); } input = new Scanner(System.in); System.out.println("Please enter a max value: "); max = input.nextInt(); // Ask user to input max value System.out.println(" Please enter a minimum value: "); min = input.nextInt(); // Ask user to input min value range = Math.abs(r.nextInt()) % (max - min + 1) + min; // Get random integer between min and max values using % System.out.println(" Your generated number is: " + range ); } } ```
2014/01/23
[ "https://Stackoverflow.com/questions/21320108", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1252911/" ]
Your code structure is incorrect. The getRandom(..) method is defined inside your main method. You also have scoping issues (you're defining the 'r' variable inside one method and attempting to use it in another). Try starting small and concentrate on getting your indentation right, then these kinds of errors will become more apparent.
Your method, ``` public static int genRandom(int mod){ Random r = new Random(); } ``` is inside of your main method. You can't declare one method inside of another just like that. You should declare it outside of your main method. Also, you've declared it to return an int, which means you actually have to make it return an int or it won't compile. So do it like this: ``` public static int genRandom(int mod){ Random r = new Random(); return r.nextInt(); // Add this line to return an int. } public static void main(String[] args) { ... // Call getRandom() in here where appropriate } ``` **NOTE** The gist of this answer is to help you understand why your code isn't compiling. Even if you get your code to compile, it still probably won't behave correctly. The other answers give you good solutions to make it work correctly.
21,320,108
Ok, I have wrote this RandomNumberGenerator.java class and I am getting an error. Logically it looks like it would work but it is not. I need to have a random number between the two input's that the user input's. Would someone take a look at my code and see where I am going wrong. Here is my code: ``` import java.util.*; public class NumberGenerator { // Begin public static void main(String[] args){ Scanner input; int max, min, range; Random gen; public static int genRandom(int mod){ Random r = new Random(); } input = new Scanner(System.in); System.out.println("Please enter a max value: "); max = input.nextInt(); // Ask user to input max value System.out.println(" Please enter a minimum value: "); min = input.nextInt(); // Ask user to input min value range = Math.abs(r.nextInt()) % (max - min + 1) + min; // Get random integer between min and max values using % System.out.println(" Your generated number is: " + range ); } } ```
2014/01/23
[ "https://Stackoverflow.com/questions/21320108", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1252911/" ]
Your code structure is incorrect. The getRandom(..) method is defined inside your main method. You also have scoping issues (you're defining the 'r' variable inside one method and attempting to use it in another). Try starting small and concentrate on getting your indentation right, then these kinds of errors will become more apparent.
try this ``` public class RandomRange { public static void main(String[] args) { int min = 50; int max = 100; for (int i = 0; i < 10; i++) { int rnd = (int) ((Math.random() * (max + 1 - min))) + min; System.out.println(rnd); } } } ```
21,320,108
Ok, I have wrote this RandomNumberGenerator.java class and I am getting an error. Logically it looks like it would work but it is not. I need to have a random number between the two input's that the user input's. Would someone take a look at my code and see where I am going wrong. Here is my code: ``` import java.util.*; public class NumberGenerator { // Begin public static void main(String[] args){ Scanner input; int max, min, range; Random gen; public static int genRandom(int mod){ Random r = new Random(); } input = new Scanner(System.in); System.out.println("Please enter a max value: "); max = input.nextInt(); // Ask user to input max value System.out.println(" Please enter a minimum value: "); min = input.nextInt(); // Ask user to input min value range = Math.abs(r.nextInt()) % (max - min + 1) + min; // Get random integer between min and max values using % System.out.println(" Your generated number is: " + range ); } } ```
2014/01/23
[ "https://Stackoverflow.com/questions/21320108", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1252911/" ]
Your code structure is incorrect. The getRandom(..) method is defined inside your main method. You also have scoping issues (you're defining the 'r' variable inside one method and attempting to use it in another). Try starting small and concentrate on getting your indentation right, then these kinds of errors will become more apparent.
Following Code Will Work. Basically you have a non final method inside main method. ``` import java.util.Random; import java.util.Scanner; public class NumberGenerator { // Begin static Random r = new Random(); public static void main(String[] args) { Scanner input; int max, min, range; Random gen; input = new Scanner(System.in); System.out.println("Please enter a max value: "); max = input.nextInt(); // Ask user to input max value System.out.println(" Please enter a minimum value: "); min = input.nextInt(); // Ask user to input min value range = Math.abs(r.nextInt()) % (max - min + 1) + min; // Get random integer between min and max values using % System.out.println(" Your generated number is: " + range); } } ```
21,320,108
Ok, I have wrote this RandomNumberGenerator.java class and I am getting an error. Logically it looks like it would work but it is not. I need to have a random number between the two input's that the user input's. Would someone take a look at my code and see where I am going wrong. Here is my code: ``` import java.util.*; public class NumberGenerator { // Begin public static void main(String[] args){ Scanner input; int max, min, range; Random gen; public static int genRandom(int mod){ Random r = new Random(); } input = new Scanner(System.in); System.out.println("Please enter a max value: "); max = input.nextInt(); // Ask user to input max value System.out.println(" Please enter a minimum value: "); min = input.nextInt(); // Ask user to input min value range = Math.abs(r.nextInt()) % (max - min + 1) + min; // Get random integer between min and max values using % System.out.println(" Your generated number is: " + range ); } } ```
2014/01/23
[ "https://Stackoverflow.com/questions/21320108", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1252911/" ]
Your code structure is incorrect. The getRandom(..) method is defined inside your main method. You also have scoping issues (you're defining the 'r' variable inside one method and attempting to use it in another). Try starting small and concentrate on getting your indentation right, then these kinds of errors will become more apparent.
You declare an object: ``` Random gen; ``` Then you create a method called `genRandom(int mod)` which instantiates a new Random object '`r`'. Which is INSIDE your main method. Which isn't correct. Then when you go to call a method to get a random number you choose to use '`r`' which is not in the scope of the statement. Developers don't let developers code recklessly. Now I'ma need to take your keyboard.
21,320,108
Ok, I have wrote this RandomNumberGenerator.java class and I am getting an error. Logically it looks like it would work but it is not. I need to have a random number between the two input's that the user input's. Would someone take a look at my code and see where I am going wrong. Here is my code: ``` import java.util.*; public class NumberGenerator { // Begin public static void main(String[] args){ Scanner input; int max, min, range; Random gen; public static int genRandom(int mod){ Random r = new Random(); } input = new Scanner(System.in); System.out.println("Please enter a max value: "); max = input.nextInt(); // Ask user to input max value System.out.println(" Please enter a minimum value: "); min = input.nextInt(); // Ask user to input min value range = Math.abs(r.nextInt()) % (max - min + 1) + min; // Get random integer between min and max values using % System.out.println(" Your generated number is: " + range ); } } ```
2014/01/23
[ "https://Stackoverflow.com/questions/21320108", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1252911/" ]
Your method, ``` public static int genRandom(int mod){ Random r = new Random(); } ``` is inside of your main method. You can't declare one method inside of another just like that. You should declare it outside of your main method. Also, you've declared it to return an int, which means you actually have to make it return an int or it won't compile. So do it like this: ``` public static int genRandom(int mod){ Random r = new Random(); return r.nextInt(); // Add this line to return an int. } public static void main(String[] args) { ... // Call getRandom() in here where appropriate } ``` **NOTE** The gist of this answer is to help you understand why your code isn't compiling. Even if you get your code to compile, it still probably won't behave correctly. The other answers give you good solutions to make it work correctly.
try this ``` public class RandomRange { public static void main(String[] args) { int min = 50; int max = 100; for (int i = 0; i < 10; i++) { int rnd = (int) ((Math.random() * (max + 1 - min))) + min; System.out.println(rnd); } } } ```
21,320,108
Ok, I have wrote this RandomNumberGenerator.java class and I am getting an error. Logically it looks like it would work but it is not. I need to have a random number between the two input's that the user input's. Would someone take a look at my code and see where I am going wrong. Here is my code: ``` import java.util.*; public class NumberGenerator { // Begin public static void main(String[] args){ Scanner input; int max, min, range; Random gen; public static int genRandom(int mod){ Random r = new Random(); } input = new Scanner(System.in); System.out.println("Please enter a max value: "); max = input.nextInt(); // Ask user to input max value System.out.println(" Please enter a minimum value: "); min = input.nextInt(); // Ask user to input min value range = Math.abs(r.nextInt()) % (max - min + 1) + min; // Get random integer between min and max values using % System.out.println(" Your generated number is: " + range ); } } ```
2014/01/23
[ "https://Stackoverflow.com/questions/21320108", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1252911/" ]
Your method, ``` public static int genRandom(int mod){ Random r = new Random(); } ``` is inside of your main method. You can't declare one method inside of another just like that. You should declare it outside of your main method. Also, you've declared it to return an int, which means you actually have to make it return an int or it won't compile. So do it like this: ``` public static int genRandom(int mod){ Random r = new Random(); return r.nextInt(); // Add this line to return an int. } public static void main(String[] args) { ... // Call getRandom() in here where appropriate } ``` **NOTE** The gist of this answer is to help you understand why your code isn't compiling. Even if you get your code to compile, it still probably won't behave correctly. The other answers give you good solutions to make it work correctly.
You declare an object: ``` Random gen; ``` Then you create a method called `genRandom(int mod)` which instantiates a new Random object '`r`'. Which is INSIDE your main method. Which isn't correct. Then when you go to call a method to get a random number you choose to use '`r`' which is not in the scope of the statement. Developers don't let developers code recklessly. Now I'ma need to take your keyboard.
21,320,108
Ok, I have wrote this RandomNumberGenerator.java class and I am getting an error. Logically it looks like it would work but it is not. I need to have a random number between the two input's that the user input's. Would someone take a look at my code and see where I am going wrong. Here is my code: ``` import java.util.*; public class NumberGenerator { // Begin public static void main(String[] args){ Scanner input; int max, min, range; Random gen; public static int genRandom(int mod){ Random r = new Random(); } input = new Scanner(System.in); System.out.println("Please enter a max value: "); max = input.nextInt(); // Ask user to input max value System.out.println(" Please enter a minimum value: "); min = input.nextInt(); // Ask user to input min value range = Math.abs(r.nextInt()) % (max - min + 1) + min; // Get random integer between min and max values using % System.out.println(" Your generated number is: " + range ); } } ```
2014/01/23
[ "https://Stackoverflow.com/questions/21320108", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1252911/" ]
Following Code Will Work. Basically you have a non final method inside main method. ``` import java.util.Random; import java.util.Scanner; public class NumberGenerator { // Begin static Random r = new Random(); public static void main(String[] args) { Scanner input; int max, min, range; Random gen; input = new Scanner(System.in); System.out.println("Please enter a max value: "); max = input.nextInt(); // Ask user to input max value System.out.println(" Please enter a minimum value: "); min = input.nextInt(); // Ask user to input min value range = Math.abs(r.nextInt()) % (max - min + 1) + min; // Get random integer between min and max values using % System.out.println(" Your generated number is: " + range); } } ```
try this ``` public class RandomRange { public static void main(String[] args) { int min = 50; int max = 100; for (int i = 0; i < 10; i++) { int rnd = (int) ((Math.random() * (max + 1 - min))) + min; System.out.println(rnd); } } } ```
21,320,108
Ok, I have wrote this RandomNumberGenerator.java class and I am getting an error. Logically it looks like it would work but it is not. I need to have a random number between the two input's that the user input's. Would someone take a look at my code and see where I am going wrong. Here is my code: ``` import java.util.*; public class NumberGenerator { // Begin public static void main(String[] args){ Scanner input; int max, min, range; Random gen; public static int genRandom(int mod){ Random r = new Random(); } input = new Scanner(System.in); System.out.println("Please enter a max value: "); max = input.nextInt(); // Ask user to input max value System.out.println(" Please enter a minimum value: "); min = input.nextInt(); // Ask user to input min value range = Math.abs(r.nextInt()) % (max - min + 1) + min; // Get random integer between min and max values using % System.out.println(" Your generated number is: " + range ); } } ```
2014/01/23
[ "https://Stackoverflow.com/questions/21320108", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1252911/" ]
Following Code Will Work. Basically you have a non final method inside main method. ``` import java.util.Random; import java.util.Scanner; public class NumberGenerator { // Begin static Random r = new Random(); public static void main(String[] args) { Scanner input; int max, min, range; Random gen; input = new Scanner(System.in); System.out.println("Please enter a max value: "); max = input.nextInt(); // Ask user to input max value System.out.println(" Please enter a minimum value: "); min = input.nextInt(); // Ask user to input min value range = Math.abs(r.nextInt()) % (max - min + 1) + min; // Get random integer between min and max values using % System.out.println(" Your generated number is: " + range); } } ```
You declare an object: ``` Random gen; ``` Then you create a method called `genRandom(int mod)` which instantiates a new Random object '`r`'. Which is INSIDE your main method. Which isn't correct. Then when you go to call a method to get a random number you choose to use '`r`' which is not in the scope of the statement. Developers don't let developers code recklessly. Now I'ma need to take your keyboard.
67,354
Bismillah. Dear brothers of faith, may peace be upon you all. I am recent convert to Islam and got some worries about cremation rituals for my non Muslim family. My old religion encourages burning cremation ceremony and as I am elder one I would need to step up to light the fire. What is the ruling on this. Is it forbidden or discouraged to step up for lighting fire.
2021/04/08
[ "https://islam.stackexchange.com/questions/67354", "https://islam.stackexchange.com", "https://islam.stackexchange.com/users/43533/" ]
It is required for you to bury the bodies of those who have departed from this world. God has provided us in the Holy Quran on what to do with the corpse, with the example of a crow scratching in the ground, as seen in the following verse within the Holy Quran, *Thereupon Allah sent forth a raven who began to scratch the earth to show him how he might cover the corpse of his brother. So seeing he cried: 'Woe unto me! Was I unable even to be like this raven and find a way to cover the corpse of my brother? Then he became full of remorse at his doing.* -Quran 5:31 It is also noted within the traditions of the Prophet that one must not harm or deform the corpse, especially the breaking of the bones, which would most likely happen upon a cremation procedure. The Prophet Muhammad said: *Breaking a dead man's bone is like breaking it when he is alive.* -Sunan Abi Dawud 3207 Therefore, it is clear that in accordance with the laws of God that the burial of the corpse is the most appropriate way to proceed with.
It is clear that Islam prescribes burial, not cremation. You may to opt for burial, if this is not encouraged but permitted in the religion of your relatives (you did not say what other religion you mean). If this is excluded, you might also assist cremation. The following Hadit implies that Allah may forgive you in this case. [al-Bukhari 3478](https://sunnah.com/bukhari:3478) > > The Prophet (ﷺ) said, "Amongst the people preceding your age, there > was a man whom Allah had given a lot of money. While he was in his > death-bed, he called his sons and said, 'What type of father have I > been to you? They replied, 'You have been a good father.' He said, 'I > have never done a single good deed; so when I die, burn me, crush my > body, and scatter the resulting ashes on a windy day.' His sons did > accordingly, but Allah gathered his particles and asked (him), 'What > made you do so?' He replied, "Fear of you.' So Allah bestowed His > Mercy upon him. (forgave him). > > > P.S. Muslim are allowed to assist a non-Muslim funeral and it's unusual to bury a non-Muslim according to the prescriptions of Islam. P.P.S. I have added the last sentence according to my education and our practise, where we are mostly attending or assisting the funeral of Christians which are to a larger part compatible with Islam. This [fatwa](https://muftiwp.gov.my/en/artikel/irsyad-fatwa/irsyad-fatwa-umum-cat/3720-irsyad-al-fatwa-series-321-attending-the-funeral-of-non-muslim-neighbour) treats the subject, in conclusion confirming that we may attend and support the funeral but not fulfill rites that contradict Islam. It also confirms that we are not supposed to give a Muslim funeral to a non-Muslim.
67,354
Bismillah. Dear brothers of faith, may peace be upon you all. I am recent convert to Islam and got some worries about cremation rituals for my non Muslim family. My old religion encourages burning cremation ceremony and as I am elder one I would need to step up to light the fire. What is the ruling on this. Is it forbidden or discouraged to step up for lighting fire.
2021/04/08
[ "https://islam.stackexchange.com/questions/67354", "https://islam.stackexchange.com", "https://islam.stackexchange.com/users/43533/" ]
It is not allowed for you to assist in cremation. That is a tradition of Hinduism and not allowed in Islam. If the funeral were up to you, you would simply bury him. A fatwa on this topic: > > Q. Can a Muslim male (only boy to his parents) perform funeral rites for his Hindu father? There may be no one else to do it. > > > A. In performing such rites, one will have to perform certain rituals which are connected to the beliefs and ideologies of another religion, which are opposed to the teachings of Islam. Hence, it will not be permissible for the Muslim son to perform the funeral rites of his hindu father which is done according to the practices of Hinduism. If it is a matter of burial, then the Muslim son can do this, however, when it is connected to cremating the body, shaving the head and other similar rituals, these are totally unlawful in Islam, and one is prohibited from doing these. > > > And Allah knows best. > > > Mufti Waseem Khan > (<https://islamqa.org/hanafi/darululoomtt/52291>) > > > Similarly, you will find plenty of fatawa explaining that you need to bury anyone who dies even if non-Muslim. You cannot assist them in rituals and traditions of another religion like cremation or anything related to that.
It is clear that Islam prescribes burial, not cremation. You may to opt for burial, if this is not encouraged but permitted in the religion of your relatives (you did not say what other religion you mean). If this is excluded, you might also assist cremation. The following Hadit implies that Allah may forgive you in this case. [al-Bukhari 3478](https://sunnah.com/bukhari:3478) > > The Prophet (ﷺ) said, "Amongst the people preceding your age, there > was a man whom Allah had given a lot of money. While he was in his > death-bed, he called his sons and said, 'What type of father have I > been to you? They replied, 'You have been a good father.' He said, 'I > have never done a single good deed; so when I die, burn me, crush my > body, and scatter the resulting ashes on a windy day.' His sons did > accordingly, but Allah gathered his particles and asked (him), 'What > made you do so?' He replied, "Fear of you.' So Allah bestowed His > Mercy upon him. (forgave him). > > > P.S. Muslim are allowed to assist a non-Muslim funeral and it's unusual to bury a non-Muslim according to the prescriptions of Islam. P.P.S. I have added the last sentence according to my education and our practise, where we are mostly attending or assisting the funeral of Christians which are to a larger part compatible with Islam. This [fatwa](https://muftiwp.gov.my/en/artikel/irsyad-fatwa/irsyad-fatwa-umum-cat/3720-irsyad-al-fatwa-series-321-attending-the-funeral-of-non-muslim-neighbour) treats the subject, in conclusion confirming that we may attend and support the funeral but not fulfill rites that contradict Islam. It also confirms that we are not supposed to give a Muslim funeral to a non-Muslim.
19,893,249
How do I get the customer group id from a sales/order\_item collection? I realise I may need to traverse back up the sales tree but don't know how to do this? Thanks in advance! **EDIT** I realise I was pretty vague with this question. What I need to do is get the total sales for a product, but only where purchased by a certain customer\_group\_id. I need to join the orders table to the order\_items table to check the customer\_group\_id, but it's not working for me. This is what I have: ``` $collection = Mage::getModel('sales/order_item')->getCollection() ->addExpressionFieldToSelect('ordered','SUM({{qty_ordered}})', array('qty_ordered'=>'qty_ordered')) ->addAttributeToFilter('product_id', '123') ->addAttributeToFilter('created_at', array( 'from' => reverse_date($_REQUEST['startdate']), 'to' => reverse_date($_REQUEST['enddate']), )) ->join( array('orders_table' => $collection->getTable('sales/order')), 'orders_table.entity_id = main_table.order_id AND orders_table.customer_group_id = 1', array('customer_group_id'=>'value') ); ``` The error I'm getting is: ``` 'Can't retrieve entity config: sales/sales_flat_order' ```
2013/11/10
[ "https://Stackoverflow.com/questions/19893249", "https://Stackoverflow.com", "https://Stackoverflow.com/users/509607/" ]
If the collection you have is of type `Mage_Sales_Model_Resource_Order_Item_Collection` then you can do the following. Assuming that your collection is `$orderItems`. ``` $order = $orderItems->getSalesOrder(); $customerGroupId = $order->getCustomerGroupId(); ```
I have got it working. I add the join after the initial "build" of the query like so: ``` $collection = Mage::getModel('sales/order_item')->getCollection() ->addExpressionFieldToSelect('ordered','SUM({{qty_ordered}})' , array('qty_ordered'=>'qty_ordered')) ->addAttributeToFilter('main_table.product_id', $product->getId()) ->addAttributeToFilter('main_table.created_at', array( 'from' => reverse_date($_REQUEST['startdate']), 'to' => reverse_date($_REQUEST['enddate']), )); $collection->getSelect()->join( array('orders_table' => $tableName), 'orders_table.entity_id = main_table.order_id AND (orders_table.customer_group_id = 1 OR orders_table.customer_group_id = 0)' ); ``` I'm not sure why it works this way and not the other, but hey ho!
19,893,249
How do I get the customer group id from a sales/order\_item collection? I realise I may need to traverse back up the sales tree but don't know how to do this? Thanks in advance! **EDIT** I realise I was pretty vague with this question. What I need to do is get the total sales for a product, but only where purchased by a certain customer\_group\_id. I need to join the orders table to the order\_items table to check the customer\_group\_id, but it's not working for me. This is what I have: ``` $collection = Mage::getModel('sales/order_item')->getCollection() ->addExpressionFieldToSelect('ordered','SUM({{qty_ordered}})', array('qty_ordered'=>'qty_ordered')) ->addAttributeToFilter('product_id', '123') ->addAttributeToFilter('created_at', array( 'from' => reverse_date($_REQUEST['startdate']), 'to' => reverse_date($_REQUEST['enddate']), )) ->join( array('orders_table' => $collection->getTable('sales/order')), 'orders_table.entity_id = main_table.order_id AND orders_table.customer_group_id = 1', array('customer_group_id'=>'value') ); ``` The error I'm getting is: ``` 'Can't retrieve entity config: sales/sales_flat_order' ```
2013/11/10
[ "https://Stackoverflow.com/questions/19893249", "https://Stackoverflow.com", "https://Stackoverflow.com/users/509607/" ]
If the collection you have is of type `Mage_Sales_Model_Resource_Order_Item_Collection` then you can do the following. Assuming that your collection is `$orderItems`. ``` $order = $orderItems->getSalesOrder(); $customerGroupId = $order->getCustomerGroupId(); ```
Instead of using, `$collection->getTable('sales/order')` use, `'sales_flat_order'`. So your line would be, `array('orders_table' => 'sales_flat_order'),`
57,666
I'm writing some documentation for a web-based application that will run on Android tablets at the factory at which I am employed. I am having trouble wording the steps where the users must interact with the onscreen buttons via touch. For example "1. Enter or scan your clock number and then"... "click the button", "press the button"? Click sounds most natural to me, but it still doesn't "feel" right. Is the word "click" ubiquitous while explaining interaction with an onscreen button regardless of if there is a mouse involved?
2014/05/21
[ "https://ux.stackexchange.com/questions/57666", "https://ux.stackexchange.com", "https://ux.stackexchange.com/users/45745/" ]
The Android setup screen used to instruct the user to **touch** the Android to begin, but I personally use **tap** for everything touch-related, as it's smaller, thus making instructions as simplistic as possible. It is worth noting that if your buttons merely say **Tap here** then you should consider changing the text to just state their purpose, for instance **Add to contacts**. Finally, if it is not clear to the user that they must tap a button, then you should consider redesigning your buttons.
Personally I would think that 'tap' is the preferred description, as this also infers a touch of a short duration. If asked to touch something, a user could reasonably continue touching the thing for a significant period of time. Many UIs interpret a touch-and-hold as an alternate gesture (e.g. iOS). 'Click', 'push' and 'press' all suggest some sort of mechanical operation, and 'select' suggests that a choice of several options is being made.
57,666
I'm writing some documentation for a web-based application that will run on Android tablets at the factory at which I am employed. I am having trouble wording the steps where the users must interact with the onscreen buttons via touch. For example "1. Enter or scan your clock number and then"... "click the button", "press the button"? Click sounds most natural to me, but it still doesn't "feel" right. Is the word "click" ubiquitous while explaining interaction with an onscreen button regardless of if there is a mouse involved?
2014/05/21
[ "https://ux.stackexchange.com/questions/57666", "https://ux.stackexchange.com", "https://ux.stackexchange.com/users/45745/" ]
As you will be using Android, perhaps refer to their own [Design Principles documentation](https://developer.apple.com/library/ios/documentation/userexperience/conceptual/MobileHIG/InteractivityInput.html#//apple_ref/doc/uid/TP40006556-CH55-SW1)? They use 'touch'; > > Access the entire collection of apps and widgets by touching the All Apps button at the center of the Favorites Tray. > > > I would also say you 'touch the button' because isn't that exactly what you are doing on a touch screen device? That surely is the equivalent to clicking a button with a mouse. E.g; > > 1. Enter or scan your clock number and then touch the 'Confirm' button to continue... > > > FWIW, Apple use 'tap' in their [iOS Human Interface Guidelines](https://developer.apple.com/library/ios/documentation/userexperience/conceptual/MobileHIG/InteractivityInput.html#//apple_ref/doc/uid/TP40006556-CH55-SW1): > > People use gestures—such as tap, drag, and pinch—to interact with apps and their iOS devices. > > >
**Click** implies the pressing of a physical switch which then creates a 'click' *sound* - typically on devices with input devices attached (such as a mouse) **Push** implies moving something out of its original position, typical of a physical button, again similar to a mouse (or moreso key) input **Press** implies moving into physical contact with something, the thing being moved and the target are up for interpretation, as such this can refer to any number of motions involving contact **Select** implies the choice of something over something of equal standing, typically an item from a list so is likely less appropriate for the on/off or yes/no functionality of a switch As such, for device agnostic purposes, I'd go with 'press' if limited to the supplied list. **Tap** as noted above in the answers tends to be associated with touch screen devices, in which case it would be entirely appropriate to mention in relation to button interaction
57,666
I'm writing some documentation for a web-based application that will run on Android tablets at the factory at which I am employed. I am having trouble wording the steps where the users must interact with the onscreen buttons via touch. For example "1. Enter or scan your clock number and then"... "click the button", "press the button"? Click sounds most natural to me, but it still doesn't "feel" right. Is the word "click" ubiquitous while explaining interaction with an onscreen button regardless of if there is a mouse involved?
2014/05/21
[ "https://ux.stackexchange.com/questions/57666", "https://ux.stackexchange.com", "https://ux.stackexchange.com/users/45745/" ]
As you will be using Android, perhaps refer to their own [Design Principles documentation](https://developer.apple.com/library/ios/documentation/userexperience/conceptual/MobileHIG/InteractivityInput.html#//apple_ref/doc/uid/TP40006556-CH55-SW1)? They use 'touch'; > > Access the entire collection of apps and widgets by touching the All Apps button at the center of the Favorites Tray. > > > I would also say you 'touch the button' because isn't that exactly what you are doing on a touch screen device? That surely is the equivalent to clicking a button with a mouse. E.g; > > 1. Enter or scan your clock number and then touch the 'Confirm' button to continue... > > > FWIW, Apple use 'tap' in their [iOS Human Interface Guidelines](https://developer.apple.com/library/ios/documentation/userexperience/conceptual/MobileHIG/InteractivityInput.html#//apple_ref/doc/uid/TP40006556-CH55-SW1): > > People use gestures—such as tap, drag, and pinch—to interact with apps and their iOS devices. > > >
The Android setup screen used to instruct the user to **touch** the Android to begin, but I personally use **tap** for everything touch-related, as it's smaller, thus making instructions as simplistic as possible. It is worth noting that if your buttons merely say **Tap here** then you should consider changing the text to just state their purpose, for instance **Add to contacts**. Finally, if it is not clear to the user that they must tap a button, then you should consider redesigning your buttons.
57,666
I'm writing some documentation for a web-based application that will run on Android tablets at the factory at which I am employed. I am having trouble wording the steps where the users must interact with the onscreen buttons via touch. For example "1. Enter or scan your clock number and then"... "click the button", "press the button"? Click sounds most natural to me, but it still doesn't "feel" right. Is the word "click" ubiquitous while explaining interaction with an onscreen button regardless of if there is a mouse involved?
2014/05/21
[ "https://ux.stackexchange.com/questions/57666", "https://ux.stackexchange.com", "https://ux.stackexchange.com/users/45745/" ]
As you will be using Android, perhaps refer to their own [Design Principles documentation](https://developer.apple.com/library/ios/documentation/userexperience/conceptual/MobileHIG/InteractivityInput.html#//apple_ref/doc/uid/TP40006556-CH55-SW1)? They use 'touch'; > > Access the entire collection of apps and widgets by touching the All Apps button at the center of the Favorites Tray. > > > I would also say you 'touch the button' because isn't that exactly what you are doing on a touch screen device? That surely is the equivalent to clicking a button with a mouse. E.g; > > 1. Enter or scan your clock number and then touch the 'Confirm' button to continue... > > > FWIW, Apple use 'tap' in their [iOS Human Interface Guidelines](https://developer.apple.com/library/ios/documentation/userexperience/conceptual/MobileHIG/InteractivityInput.html#//apple_ref/doc/uid/TP40006556-CH55-SW1): > > People use gestures—such as tap, drag, and pinch—to interact with apps and their iOS devices. > > >
Personally I would think that 'tap' is the preferred description, as this also infers a touch of a short duration. If asked to touch something, a user could reasonably continue touching the thing for a significant period of time. Many UIs interpret a touch-and-hold as an alternate gesture (e.g. iOS). 'Click', 'push' and 'press' all suggest some sort of mechanical operation, and 'select' suggests that a choice of several options is being made.
57,666
I'm writing some documentation for a web-based application that will run on Android tablets at the factory at which I am employed. I am having trouble wording the steps where the users must interact with the onscreen buttons via touch. For example "1. Enter or scan your clock number and then"... "click the button", "press the button"? Click sounds most natural to me, but it still doesn't "feel" right. Is the word "click" ubiquitous while explaining interaction with an onscreen button regardless of if there is a mouse involved?
2014/05/21
[ "https://ux.stackexchange.com/questions/57666", "https://ux.stackexchange.com", "https://ux.stackexchange.com/users/45745/" ]
The Android setup screen used to instruct the user to **touch** the Android to begin, but I personally use **tap** for everything touch-related, as it's smaller, thus making instructions as simplistic as possible. It is worth noting that if your buttons merely say **Tap here** then you should consider changing the text to just state their purpose, for instance **Add to contacts**. Finally, if it is not clear to the user that they must tap a button, then you should consider redesigning your buttons.
I would go with "select", since in fact many touchscreen applications are now touch-to-highlight/drag-to-choose/lift-to-commit. That interaction sequence deals with initially erroneous touches, and calibration issues, MUCH more smoothly than anything else. You *can* tap with that system, but you get better accuracy if you don't... and it subtly trains you into using the version with built-in confirmation/correction. (I know IBM developed this approach as part of the ITS project and the 1992 World's Fair kiosks; I don't know whether anyone had independently stumbled on it and published earlier.) (Boston's public transit system has had serious ongoing problems with their choice of "tap" as the verb for presenting a proximity card to a reader. People who do what "tap" normally means don't give the system enough time to read the card. "Hold" would have been a much better description of the actual interaction. Unfortunately, since people do learn despite their documentation, they haven't been motivated to change it.)
57,666
I'm writing some documentation for a web-based application that will run on Android tablets at the factory at which I am employed. I am having trouble wording the steps where the users must interact with the onscreen buttons via touch. For example "1. Enter or scan your clock number and then"... "click the button", "press the button"? Click sounds most natural to me, but it still doesn't "feel" right. Is the word "click" ubiquitous while explaining interaction with an onscreen button regardless of if there is a mouse involved?
2014/05/21
[ "https://ux.stackexchange.com/questions/57666", "https://ux.stackexchange.com", "https://ux.stackexchange.com/users/45745/" ]
As you will be using Android, perhaps refer to their own [Design Principles documentation](https://developer.apple.com/library/ios/documentation/userexperience/conceptual/MobileHIG/InteractivityInput.html#//apple_ref/doc/uid/TP40006556-CH55-SW1)? They use 'touch'; > > Access the entire collection of apps and widgets by touching the All Apps button at the center of the Favorites Tray. > > > I would also say you 'touch the button' because isn't that exactly what you are doing on a touch screen device? That surely is the equivalent to clicking a button with a mouse. E.g; > > 1. Enter or scan your clock number and then touch the 'Confirm' button to continue... > > > FWIW, Apple use 'tap' in their [iOS Human Interface Guidelines](https://developer.apple.com/library/ios/documentation/userexperience/conceptual/MobileHIG/InteractivityInput.html#//apple_ref/doc/uid/TP40006556-CH55-SW1): > > People use gestures—such as tap, drag, and pinch—to interact with apps and their iOS devices. > > >
A button (that will trigger some action) is **pressed**, **pushed** or **activated**. To do so in a web form, you can either point your mouse at it and **click** it (on a desktop PC) or **tap** at the element (on a touch device). I would not use the term "select", that sounds as if you were choosing one from a set of buttons.
57,666
I'm writing some documentation for a web-based application that will run on Android tablets at the factory at which I am employed. I am having trouble wording the steps where the users must interact with the onscreen buttons via touch. For example "1. Enter or scan your clock number and then"... "click the button", "press the button"? Click sounds most natural to me, but it still doesn't "feel" right. Is the word "click" ubiquitous while explaining interaction with an onscreen button regardless of if there is a mouse involved?
2014/05/21
[ "https://ux.stackexchange.com/questions/57666", "https://ux.stackexchange.com", "https://ux.stackexchange.com/users/45745/" ]
There's no 'right' answer here. What is more important is that you are consistent within your own documentation. Regarding touch interfaces, the typical interaction is 'tap'. Regarding desktops, the typical interaction is 'click'. In both cases, it's not the ONLY interaction, however, as both touch devices and desktops can be navigated in other ways (such as via the keyboard). Personally, I prefer a more generic term such as 'select' that can be used agnostically across devices--though some have pointed out that 'select' is often reserved specifically for selecting an option.
A button (that will trigger some action) is **pressed**, **pushed** or **activated**. To do so in a web form, you can either point your mouse at it and **click** it (on a desktop PC) or **tap** at the element (on a touch device). I would not use the term "select", that sounds as if you were choosing one from a set of buttons.
57,666
I'm writing some documentation for a web-based application that will run on Android tablets at the factory at which I am employed. I am having trouble wording the steps where the users must interact with the onscreen buttons via touch. For example "1. Enter or scan your clock number and then"... "click the button", "press the button"? Click sounds most natural to me, but it still doesn't "feel" right. Is the word "click" ubiquitous while explaining interaction with an onscreen button regardless of if there is a mouse involved?
2014/05/21
[ "https://ux.stackexchange.com/questions/57666", "https://ux.stackexchange.com", "https://ux.stackexchange.com/users/45745/" ]
A button (that will trigger some action) is **pressed**, **pushed** or **activated**. To do so in a web form, you can either point your mouse at it and **click** it (on a desktop PC) or **tap** at the element (on a touch device). I would not use the term "select", that sounds as if you were choosing one from a set of buttons.
I would go with "select", since in fact many touchscreen applications are now touch-to-highlight/drag-to-choose/lift-to-commit. That interaction sequence deals with initially erroneous touches, and calibration issues, MUCH more smoothly than anything else. You *can* tap with that system, but you get better accuracy if you don't... and it subtly trains you into using the version with built-in confirmation/correction. (I know IBM developed this approach as part of the ITS project and the 1992 World's Fair kiosks; I don't know whether anyone had independently stumbled on it and published earlier.) (Boston's public transit system has had serious ongoing problems with their choice of "tap" as the verb for presenting a proximity card to a reader. People who do what "tap" normally means don't give the system enough time to read the card. "Hold" would have been a much better description of the actual interaction. Unfortunately, since people do learn despite their documentation, they haven't been motivated to change it.)
57,666
I'm writing some documentation for a web-based application that will run on Android tablets at the factory at which I am employed. I am having trouble wording the steps where the users must interact with the onscreen buttons via touch. For example "1. Enter or scan your clock number and then"... "click the button", "press the button"? Click sounds most natural to me, but it still doesn't "feel" right. Is the word "click" ubiquitous while explaining interaction with an onscreen button regardless of if there is a mouse involved?
2014/05/21
[ "https://ux.stackexchange.com/questions/57666", "https://ux.stackexchange.com", "https://ux.stackexchange.com/users/45745/" ]
As you will be using Android, perhaps refer to their own [Design Principles documentation](https://developer.apple.com/library/ios/documentation/userexperience/conceptual/MobileHIG/InteractivityInput.html#//apple_ref/doc/uid/TP40006556-CH55-SW1)? They use 'touch'; > > Access the entire collection of apps and widgets by touching the All Apps button at the center of the Favorites Tray. > > > I would also say you 'touch the button' because isn't that exactly what you are doing on a touch screen device? That surely is the equivalent to clicking a button with a mouse. E.g; > > 1. Enter or scan your clock number and then touch the 'Confirm' button to continue... > > > FWIW, Apple use 'tap' in their [iOS Human Interface Guidelines](https://developer.apple.com/library/ios/documentation/userexperience/conceptual/MobileHIG/InteractivityInput.html#//apple_ref/doc/uid/TP40006556-CH55-SW1): > > People use gestures—such as tap, drag, and pinch—to interact with apps and their iOS devices. > > >
I would go with "select", since in fact many touchscreen applications are now touch-to-highlight/drag-to-choose/lift-to-commit. That interaction sequence deals with initially erroneous touches, and calibration issues, MUCH more smoothly than anything else. You *can* tap with that system, but you get better accuracy if you don't... and it subtly trains you into using the version with built-in confirmation/correction. (I know IBM developed this approach as part of the ITS project and the 1992 World's Fair kiosks; I don't know whether anyone had independently stumbled on it and published earlier.) (Boston's public transit system has had serious ongoing problems with their choice of "tap" as the verb for presenting a proximity card to a reader. People who do what "tap" normally means don't give the system enough time to read the card. "Hold" would have been a much better description of the actual interaction. Unfortunately, since people do learn despite their documentation, they haven't been motivated to change it.)
57,666
I'm writing some documentation for a web-based application that will run on Android tablets at the factory at which I am employed. I am having trouble wording the steps where the users must interact with the onscreen buttons via touch. For example "1. Enter or scan your clock number and then"... "click the button", "press the button"? Click sounds most natural to me, but it still doesn't "feel" right. Is the word "click" ubiquitous while explaining interaction with an onscreen button regardless of if there is a mouse involved?
2014/05/21
[ "https://ux.stackexchange.com/questions/57666", "https://ux.stackexchange.com", "https://ux.stackexchange.com/users/45745/" ]
On a mobile device you use gestural movements, in this case it would be TAP. You can use the word click but it will be read as being out of date or out of touch.
I would go with "select", since in fact many touchscreen applications are now touch-to-highlight/drag-to-choose/lift-to-commit. That interaction sequence deals with initially erroneous touches, and calibration issues, MUCH more smoothly than anything else. You *can* tap with that system, but you get better accuracy if you don't... and it subtly trains you into using the version with built-in confirmation/correction. (I know IBM developed this approach as part of the ITS project and the 1992 World's Fair kiosks; I don't know whether anyone had independently stumbled on it and published earlier.) (Boston's public transit system has had serious ongoing problems with their choice of "tap" as the verb for presenting a proximity card to a reader. People who do what "tap" normally means don't give the system enough time to read the card. "Hold" would have been a much better description of the actual interaction. Unfortunately, since people do learn despite their documentation, they haven't been motivated to change it.)
71,931,690
I need help making the following query only display one result, the one with the `MAX Procurement Rate`. Currently the query works, but displays all results not just the one with the output of the `MAX` function ``` SELECT SalesPeople.SalesPersonID, FirstName, LastName, Region, SalesRevenueYear1, ProcurementCost FROM ProductRevenueAndCosts INNER JOIN SalesPeople ON ProductRevenueAndCosts.SalesPersonID = SalesPeople.SalesPersonID WHERE SalesPeople.Region = 'Central' AND ( SELECT MAX (ProcurementCost) FROM ProductRevenueAndCosts WHERE SalesPeople.Region = 'Central' ) ```
2022/04/19
[ "https://Stackoverflow.com/questions/71931690", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18864860/" ]
If you add a LIMIT 1 clause at the end of your SQL, then only the first record will be shown. If you add an ORDER BY `column_name`, then the results will be ordered by that column. Using these two together is a quick way to get the max or min without having to worry about aggregate functions. <https://www.w3schools.com/mysql/mysql_limit.asp> Otherwise, you can try aggregating the results with a max function: <https://www.w3schools.com/mysql/mysql_min_max.asp>
As mentioned, you need to correlate the subquery to outer query. Be sure to use aliases between same named columns and exercise good practice in qualifying all columns with table names or aliases especially in `JOIN` queries: ```sql SELECT sp.SalesPersonID, sp.FirstName, sp.LastName, sp.Region, sp.SalesRevenueYear1, prc.ProcurementCost FROM ProductRevenueAndCosts prc INNER JOIN SalesPeople sp ON prc.SalesPersonID = prc.SalesPersonID WHERE sp.Region = 'Central' AND prc.ProcurementCost = ( -- CORRELATE OUTER QUERY WITH SUBQUERY SELECT MAX(ProcurementCost) FROM ProductRevenueAndCosts ) ``` Note: If running in MS Access, remove the comment
32,649,085
My String is > > "Success Entries and Failed Entries: {FAILED\_ENTRIES={}, > SUCCESS\_ENTRIES={123=1509170142065114105}}" > > > Here i want to filter out only **1509170142065114105** this string here 123 can be anything. how can I do it ?
2015/09/18
[ "https://Stackoverflow.com/questions/32649085", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1941853/" ]
You can use regex `.*(?:\\D|^)(\\d+).*` to get last number in the `String`. **USE:** ``` public static void main(String[] args) { String s = "{FAILED_ENTRIES={}, SUCCESS_ENTRIES={123=1509170142065114105}}"; System.out.println(s.replaceAll(".*(?:\\D|^)(\\d+).*", "$1")); } ``` **OUTPUT:** ``` 1509170142065114105 ``` **DEMO:** [Check here a working demo](https://ideone.com/6evlGB).
A regex will work for you. ``` public static void main(String args[]) { String s = "{FAILED_ENTRIES={}, SUCCESS_ENTRIES={123=1509170142065114105}}"; System.out.println(s.replaceAll(".*=(\\d+).*", "$1")); } ``` O/P : ``` 1509170142065114105 ```
32,649,085
My String is > > "Success Entries and Failed Entries: {FAILED\_ENTRIES={}, > SUCCESS\_ENTRIES={123=1509170142065114105}}" > > > Here i want to filter out only **1509170142065114105** this string here 123 can be anything. how can I do it ?
2015/09/18
[ "https://Stackoverflow.com/questions/32649085", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1941853/" ]
You can use regex `.*(?:\\D|^)(\\d+).*` to get last number in the `String`. **USE:** ``` public static void main(String[] args) { String s = "{FAILED_ENTRIES={}, SUCCESS_ENTRIES={123=1509170142065114105}}"; System.out.println(s.replaceAll(".*(?:\\D|^)(\\d+).*", "$1")); } ``` **OUTPUT:** ``` 1509170142065114105 ``` **DEMO:** [Check here a working demo](https://ideone.com/6evlGB).
If all your strings are of same format then you can use `lastIndexOf` and `substring`. ``` String s = "{FAILED_ENTRIES={}, SUCCESS_ENTRIES={123=1509170142065114105}}"; int lastEqualIndex = s.lastIndexOf("="); String lastNumber = s.substring(lastEqualIndex + 1, s.length() - 2); System.out.println(lastNumber); ``` Output `1509170142065114105` If your sting formats can vary then the `regex` solutions posted by @Jordi Castilla should be better.
988,083
**Definition:** Let $(X,d)$ be a metric space. A collection $\{v\_n\}$ of subsets is said to be a base for $X$ if for every $x \in X$ and every open set $G \subset X$, such that $x \in G$ we have $x \in \{V\_n\} \subset G$ for some $N$. > > The notation is what is giving me a hard time here. I just don't understand how it translates into "Every open set in $X$ is the union of a subcollection of $\{V\_n\}$". > > > I don't understand how this is the case if that collection is always a subset of $G$, not equal to $G$?
2014/10/23
[ "https://math.stackexchange.com/questions/988083", "https://math.stackexchange.com", "https://math.stackexchange.com/users/186785/" ]
Take an open set $O$, and $x\in O$. By definition, there exists $V=V\_x$ in your base such that $x\in V\subseteq O$. This means that $O=\bigcup \{x:x\in O\}\subseteq \bigcup V\_x\subseteq O$; so $O=\bigcup V\_x$ is a union of open basic sets.
"Every open set in X is the union of a subcollection of $\{V\_n\}$" means that any open set $U$ can be written as $$U=\bigcup V\_i,$$ where $V\_i$ belong to the base for any $i$. E.g. in $\mathbb{R}$ with Euclidean topology, a base could be $$\{B(x,r):x,r\in \mathbb{Q}\}.$$
47,337,926
I want to read and store the DataKeyNames value for the corresponding row that is selected from the GridView so that I can pass that value as a condition in my UPDATE query. I have a GridView in which I am displaying the following: ``` <asp:GridView ID="GridViewSavingsTracker" AutoGenerateColumns="false" runat="server" DataKeyNames="ID" OnRowCommand="GridViewSavingsTracker_RowCommand"> <Columns> <asp:CommandField ShowSelectButton="true" /> <asp:BoundField DataField="creditorName" HeaderText="Creditor Name" /> <asp:BoundField DataField="amount" HeaderText="Principal Amount" /> <asp:BoundField DataField="interestRate" HeaderText="Interest Rate" /> <asp:BoundField DataField="interestType" HeaderText="Interest Type" /> <asp:BoundField DataField="interestCalculationMethod" HeaderText="Interest Calculation Method" /> </Columns> </asp:GridView> ``` My database has an ID field that I am not displaying on the GridView. When I click the button, I should be able to update the selected row in the GridView where; the WHERE clause of the UPDATE SQL command has to be the ID of the row that is selected. This ID is stored in the database and is not visible in the GridView. So, the corresponding ID value has to be read from the database. My Button Click event is the following: ``` protected void ButtonUpdate_Click(object sender, EventArgs e) { con.Open(); string updateCommand = "UPDATE table_name SET employeeName = '" +TextBoxEmployeeName.Text+"' WHERE ID=...<The ID value that will be read from the Database has to come here>..."; OleDBCommand updateCommand = new OleDBCommand(updateQuery,con); updateCommand.ExecuteNonQuery(); con.Close(); ShowGrid(); // Method to populate and display the GridView on the screen. } ``` I am populating the TextBoxes using the RowCommand where I am reading the rowID in the following manner: ``` protected void GridViewSavingsTracker_RowCommand(object sender, GridViewCommandEventArgs e) { if (e.CommandName == "Select") { int rowID = Convert.ToInt32(e.CommandArgument); } } ``` In a nutshell, I need to read the ID value from the MS Access Database (where the ID is a column in my database and each tuple has a unique ID value) when a particular row is selected in the GridView. This has to be done when I click the "Update" button on the web page. Once I am able to do that, then I will be able to put that value in the SQL command in the code and do the update. I am trying to do what David mentioned in his answer here: <https://stackoverflow.com/a/19824029/8930129> But "row" is getting a null value, because of which I am getting an System.NullReferenceException. ``` // ****Update Command **** // protected void ButtonUpdate_Click(object sender, EventArgs e) { try { int rowIndex = GridViewSavingsTracker.SelectedRow.RowIndex; int tupleID = Convert.ToInt32(GridViewSavingsTracker.DataKeys[rowIndex].Values[0]); con.Open(); string ConnString = GetConnString(); string updateQuery = "UPDATE tbl_savings SET creditorName = ?, amount = ?, interestRate = ?, interestType = ?, interestCalculationMethod = ? WHERE ID=" + tupleID + ""; using (OleDbConnection conn = new OleDbConnection(ConnString)) { using (OleDbCommand commandUpdate = new OleDbCommand(updateQuery, conn)) { commandUpdate.CommandType = CommandType.Text; commandUpdate.Parameters.AddWithValue("creditorName", TextBoxCreditorName.Text); commandUpdate.Parameters.AddWithValue("amount", TextBoxPrincipalAmount.Text); commandUpdate.Parameters.AddWithValue("interestRate", TextBoxInterestRate.Text); commandUpdate.Parameters.AddWithValue("interestType", RadioButtonListInterestType.SelectedValue); commandUpdate.Parameters.AddWithValue("interestCalculationMethod",DropDownListInterestCalculationMethod.SelectedValue); } } OleDbCommand updateCommand = new OleDbCommand(updateQuery, con); updateCommand.ExecuteNonQuery(); con.Close(); ShowGridView(); // Function to populate data in GridView } catch (Exception ex) { Response.Write(ex.ToString()); // Some code... } finally { // Some code... } } ```
2017/11/16
[ "https://Stackoverflow.com/questions/47337926", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Troubleshoot QMHSNDPM: Before calling QMHRMVPM' and after calling QMHSNDPM look at the messages for the interactive job (system request 3 then option 10 then f10 then f18) if you don't see your message something is wrong with the program sending the message. If you do see the message press f1 with cursor on the message then press F9 to see where the message was delivered. Probably you need a msgCallStack of 2 or 3 for your program or 4 or 5 if you want the message back at the command line. I put in oldschool format to see the variable names. ``` call 'QMHSNDPM' parm msgIdIN parm msgLoc parm msgRplDta parm msgRplDtaLen parm msgType parm msgQueue parm 3 msgCallStack parm msgKey parm msgErr ``` That should shoot the message up from a procedure in the model back to the view. For MVC style program in rpg interactive you start with the view then call down to the model which shoots the message back up to the view. Maybe you have a controller that calls the view.
Keeping track of the current stack level can be tricky. Keep in mind that when you're inside of a procedure the stack level is increased by 1. So if your current stack level is 1 and you call a procedure, the stack level inside of the procedure is 2. In my apps I declare a global variable that's initialized to 1. Upon entry to a procedure I add 1 to that variable and upon exiting I subtract 1. That variable is passed to the QMHSNDPM API. As an aside, a call to a subroutine does not add 1 to the stack. Hope this helps.
47,337,926
I want to read and store the DataKeyNames value for the corresponding row that is selected from the GridView so that I can pass that value as a condition in my UPDATE query. I have a GridView in which I am displaying the following: ``` <asp:GridView ID="GridViewSavingsTracker" AutoGenerateColumns="false" runat="server" DataKeyNames="ID" OnRowCommand="GridViewSavingsTracker_RowCommand"> <Columns> <asp:CommandField ShowSelectButton="true" /> <asp:BoundField DataField="creditorName" HeaderText="Creditor Name" /> <asp:BoundField DataField="amount" HeaderText="Principal Amount" /> <asp:BoundField DataField="interestRate" HeaderText="Interest Rate" /> <asp:BoundField DataField="interestType" HeaderText="Interest Type" /> <asp:BoundField DataField="interestCalculationMethod" HeaderText="Interest Calculation Method" /> </Columns> </asp:GridView> ``` My database has an ID field that I am not displaying on the GridView. When I click the button, I should be able to update the selected row in the GridView where; the WHERE clause of the UPDATE SQL command has to be the ID of the row that is selected. This ID is stored in the database and is not visible in the GridView. So, the corresponding ID value has to be read from the database. My Button Click event is the following: ``` protected void ButtonUpdate_Click(object sender, EventArgs e) { con.Open(); string updateCommand = "UPDATE table_name SET employeeName = '" +TextBoxEmployeeName.Text+"' WHERE ID=...<The ID value that will be read from the Database has to come here>..."; OleDBCommand updateCommand = new OleDBCommand(updateQuery,con); updateCommand.ExecuteNonQuery(); con.Close(); ShowGrid(); // Method to populate and display the GridView on the screen. } ``` I am populating the TextBoxes using the RowCommand where I am reading the rowID in the following manner: ``` protected void GridViewSavingsTracker_RowCommand(object sender, GridViewCommandEventArgs e) { if (e.CommandName == "Select") { int rowID = Convert.ToInt32(e.CommandArgument); } } ``` In a nutshell, I need to read the ID value from the MS Access Database (where the ID is a column in my database and each tuple has a unique ID value) when a particular row is selected in the GridView. This has to be done when I click the "Update" button on the web page. Once I am able to do that, then I will be able to put that value in the SQL command in the code and do the update. I am trying to do what David mentioned in his answer here: <https://stackoverflow.com/a/19824029/8930129> But "row" is getting a null value, because of which I am getting an System.NullReferenceException. ``` // ****Update Command **** // protected void ButtonUpdate_Click(object sender, EventArgs e) { try { int rowIndex = GridViewSavingsTracker.SelectedRow.RowIndex; int tupleID = Convert.ToInt32(GridViewSavingsTracker.DataKeys[rowIndex].Values[0]); con.Open(); string ConnString = GetConnString(); string updateQuery = "UPDATE tbl_savings SET creditorName = ?, amount = ?, interestRate = ?, interestType = ?, interestCalculationMethod = ? WHERE ID=" + tupleID + ""; using (OleDbConnection conn = new OleDbConnection(ConnString)) { using (OleDbCommand commandUpdate = new OleDbCommand(updateQuery, conn)) { commandUpdate.CommandType = CommandType.Text; commandUpdate.Parameters.AddWithValue("creditorName", TextBoxCreditorName.Text); commandUpdate.Parameters.AddWithValue("amount", TextBoxPrincipalAmount.Text); commandUpdate.Parameters.AddWithValue("interestRate", TextBoxInterestRate.Text); commandUpdate.Parameters.AddWithValue("interestType", RadioButtonListInterestType.SelectedValue); commandUpdate.Parameters.AddWithValue("interestCalculationMethod",DropDownListInterestCalculationMethod.SelectedValue); } } OleDbCommand updateCommand = new OleDbCommand(updateQuery, con); updateCommand.ExecuteNonQuery(); con.Close(); ShowGridView(); // Function to populate data in GridView } catch (Exception ex) { Response.Write(ex.ToString()); // Some code... } finally { // Some code... } } ```
2017/11/16
[ "https://Stackoverflow.com/questions/47337926", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Troubleshoot QMHSNDPM: Before calling QMHRMVPM' and after calling QMHSNDPM look at the messages for the interactive job (system request 3 then option 10 then f10 then f18) if you don't see your message something is wrong with the program sending the message. If you do see the message press f1 with cursor on the message then press F9 to see where the message was delivered. Probably you need a msgCallStack of 2 or 3 for your program or 4 or 5 if you want the message back at the command line. I put in oldschool format to see the variable names. ``` call 'QMHSNDPM' parm msgIdIN parm msgLoc parm msgRplDta parm msgRplDtaLen parm msgType parm msgQueue parm 3 msgCallStack parm msgKey parm msgErr ``` That should shoot the message up from a procedure in the model back to the view. For MVC style program in rpg interactive you start with the view then call down to the model which shoots the message back up to the view. Maybe you have a controller that calls the view.
> > // The MSGQ parameter is from the PSDS \*PROC > > // I tried having this defined in the view where the DDS file > > // is defined, and I have tried with it defined in the main CNTRL program > > > So on the program stack, each stack entry has a message queue. You are stating that the message queue that you are using to initialize your message subfile is comming from the `PSDS *PROC`. So you need to send your messages to the same stack entry. The way I do this is to populate StackEntry and PGMMSGQ with the same variable, and make the Stack Counter 0. This is my procedure for sending a message to the message subfile (I keep it in a service program): ``` // ---------------------------------------- // SndDspfMsgText - sends an *INFO message to the // message subfile in a display file. // // Parameters: // StackEntry - The program call stack entry to which the message is sent. // Usually the program name. This must be the same value that // is placed in the SFLPGMQ variable in the message subfile // control format. // MsgText - Text of the messqage to be sent. // MsgTextLen - The length of the message text provided above. // ---------------------------------------- dcl-proc SndDspfMsgText Export; dcl-pi *n; StkEnt Char(10) Const; MsgText Char(512) Const Options(*VarSize); MsgTextLen Int(10) Const; end-pi; dcl-ds MsgFile LikeDs(QualName_t) Inz(*LikeDs); dcl-ds ErrorCd LikeDs(ErrorCdType1_t) Inz(*LikeDs); dcl-s pmMsgId Char(7) Inz('CPF9898'); dcl-s pmMsgText Char(512) Inz(''); dcl-s pmMsgTextLen Int(10) Inz(0); dcl-s pmMsgTyp Char(10) Inz('*INFO'); dcl-s pmStkCnt Int(10) Inz(0); dcl-s pmMsgKey Char(4) Inz(''); // if Message Data is provided, if MsgTextLen > 0; pmMsgTextLen = min(%size(MsgText): MsgTextLen); pmMsgText = %subst(MsgText: 1: pmMsgTextLen); endif; MsgFile.Name = 'QCPFMSG'; qmhsndpm(pmMsgId: MsgFile: pmMsgText: pmMsgTextLen: pmMsgTyp: StkEnt: pmStkCnt: pmMsgKey: ErrorCd); end-proc; ``` Here are a couple templates you are going to need to fully understand the above procedure: ``` // Standard Error Code Format dcl-ds ErrorCdType1_t Qualified Template Inz; BytesProv Int(10) Inz(%size(ErrorCdType1_t)); BytesAvail Int(10); MsgId Char(7); Data Char(1024) Pos(17); end-ds; // Qualified Name dcl-s Name_t Char(10) Template Inz(''); dcl-ds QualName_t Qualified Template Inz; Name Like(Name_t) Inz(''); Lib Like(Name_t) Inz('*LIBL'); end-ds; // Call Stack Qualifier - used by message handling APIs dcl-ds CallStackQual_t Qualified Template Inz; Module Like(Name_t) Inz('*NONE'); Program Like(Name_t) Inz('*NONE'); end-ds; // Send Program Message dcl-pr qmhsndpm ExtPgm('QMHSNDPM'); MessageId Char(7) Const; MessageFile LikeDs(QualName_t) Const; MessageDta Char(512) Const Options(*Varsize); MessageLen Int(10) Const; MessageType Char(10) Const; StackEntry Char(4102) Const Options(*Varsize); StackCounter Int(10) Const; MessageKey Char(4); Error LikeDs(ErrorCdType1_t); StackEntryLen Int(10) Const Options(*NoPass); StackEntryQual LikeDs(CallStackQual_t) Const Options(*NoPass); ScreenWaitTime Int(10) Const Options(*NoPass); StackEntryType Char(10) Const Options(*NoPass); Ccsid Int(10) Const Options(*NoPass); end-pr; ```
108,091
Is it possible to Compare two sets namely set A and set B while both contains set of ids. I need to check if set A contains ids which is present in set B. **If it is present then i need to remove from set B.** Example: ``` set<id> SetA= new set<id>{'00524000001IFbNAAW','00524000001IFbVAAW','00524000001IFrHAAW','00524000001IFxDAAW','00524000001IFrEAAW','00524000001IFrGAAW'}; set<id> setB= new set<id>{'00524000001IFbNAAW','00524000001IFbVAAW','00524000001IFrHAAW','00524000001IFxDAAW','00524000001IFrEAAW','00524000001IFrGAAW','00524000001IFmPAAW','00524000001IFnKAAW','00524000001IFgPAAW'}; ``` Thanks !!!
2016/02/05
[ "https://salesforce.stackexchange.com/questions/108091", "https://salesforce.stackexchange.com", "https://salesforce.stackexchange.com/users/25061/" ]
You can use "containsAll" and "removeAll" method of set. list: ``` Boolean containsAll = satb.containsAll(setA); ``` This "ContainsAll" method will store true if all the elements are present in setB. Check this article <https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_set.htm>
You can try like this way ``` Set<Id> setAIds = new set<Id>{'0039000001pJpRH', '0069000000K8YjG'}; Set<Id> setBIds = new set<Id>{'0039000001pJpRH'}; system.debug('====setAIds==='+setAIds); system.debug('====setBIds==='+setBIds); for(Id objId: setAIds){ if(setBIds.contains(objId)) setBIds.remove(objId); } system.debug('====setAIds==='+setAIds); system.debug('====setBIds==='+setBIds); ```
385,852
When I was looking for some information how to convert unbalanced audio signal to balanced, it was hard to find info other than "use transformer" or "buy X device to do this". Then I found this circuit:[![Converter circuit](https://i.stack.imgur.com/nPi5g.gif)](https://i.stack.imgur.com/nPi5g.gif) source: <http://www.fivefish.net/diy/balanced/default.htm> but I'm not sure if this is correct solution. I mean that on this schematic you can see low pass filter which cut-off freq is about 140 kHz, which I think is way to high (changing 220p to 1n would help?), also where op amp in inverting configuration seems rather ok, but non-inverting shouldn't be done differently (according to <https://www.electronics-tutorials.ws/filter/filter_5.html>)? Same thing with capacitor connected to pins 2 and 6 - I think it should rather be connected between output and those pins, not ground, and short between unbalanced signal + and gnd (or it's just compression of image that creates this illusion) Anyway, I'm better in digital electronics than analog, so maybe someone with greater knowledge help me here with this. **EDIT 1:** Based on SSM2142, I created the following circuit that, I think (or rather I hope) should work correctly, making unbalanced audio signal balanced. Am I right or wrong? ![schematic](https://i.stack.imgur.com/dhXOp.png) [simulate this circuit](/plugins/schematics?image=http%3a%2f%2fi.stack.imgur.com%2fdhXOp.png) – Schematic created using [CircuitLab](https://www.circuitlab.com/) Instead of TL081 I was thinking about using LM358.
2018/07/15
[ "https://electronics.stackexchange.com/questions/385852", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/193597/" ]
I see quite a few misstatements and possible misconceptions both in the answers and in the question, so let’s break down what is meant by “noise.” 1. Analog noise within the same bandwidth as the signal. 2. Analog noise outside of the bandwidth of the signal. 3. Quantization noise introduced by the ADC. *I interpreted your question as implying option 1. Increasing the sampling rate will do absolutely nothing regarding that noise. No ifs or buts. That noise is there to stay.* Other answers only apply to options 2 & 3. If your analog filter is not steep enough and you still have strong noise components above the bandwidth of the signal (option 2), particularly near the sampling rate and its multiples, then increasing the sampling rate *and* using an appropriate digital filter will allow you to (1) relax your analog filter requirements and (2) completely remove that out of band noise. Regarding option 3, that’s the basic operating principle that makes sigma-delta converters possible. Increasing sampling rate, using an appropriate digital filter at a higher resolution, and decimating the output of the filter to the needed rate, allows you to increase the resolution of your samples. You can gain 1/2 bit per each doubling of sampling rate, as long as your signal is large enough to remain uncorrelated to the sampling noise. Interestingly, this is one place where out of band noise works in your favor, as it breaks the sampling noise correlation to the signal. I.e., it serves the function of dithering (or, as physicists call it, stochastic resonance). For slow enough signals this is a great advantage, using this technique I have obtained ~20 bits of resolution out of 12 bit converters by purposefully designing the analog anti-alias filter to introduce several bits of out-of-band random noise and oversampling by a factor of 4096.
The SNR would be better, firstly because noise mostly being a higher frequency component would have a lesser chance of being aliased of 1Hz when sampled at 1kHz than at 100Hz Secondly SNR is directly proportional to bandwidth or just look at Hartley shannon’s law C = Blog\_2 (1+SNR) Where C is the digital bandwidth and B is the analog bandwidth
385,852
When I was looking for some information how to convert unbalanced audio signal to balanced, it was hard to find info other than "use transformer" or "buy X device to do this". Then I found this circuit:[![Converter circuit](https://i.stack.imgur.com/nPi5g.gif)](https://i.stack.imgur.com/nPi5g.gif) source: <http://www.fivefish.net/diy/balanced/default.htm> but I'm not sure if this is correct solution. I mean that on this schematic you can see low pass filter which cut-off freq is about 140 kHz, which I think is way to high (changing 220p to 1n would help?), also where op amp in inverting configuration seems rather ok, but non-inverting shouldn't be done differently (according to <https://www.electronics-tutorials.ws/filter/filter_5.html>)? Same thing with capacitor connected to pins 2 and 6 - I think it should rather be connected between output and those pins, not ground, and short between unbalanced signal + and gnd (or it's just compression of image that creates this illusion) Anyway, I'm better in digital electronics than analog, so maybe someone with greater knowledge help me here with this. **EDIT 1:** Based on SSM2142, I created the following circuit that, I think (or rather I hope) should work correctly, making unbalanced audio signal balanced. Am I right or wrong? ![schematic](https://i.stack.imgur.com/dhXOp.png) [simulate this circuit](/plugins/schematics?image=http%3a%2f%2fi.stack.imgur.com%2fdhXOp.png) – Schematic created using [CircuitLab](https://www.circuitlab.com/) Instead of TL081 I was thinking about using LM358.
2018/07/15
[ "https://electronics.stackexchange.com/questions/385852", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/193597/" ]
I see quite a few misstatements and possible misconceptions both in the answers and in the question, so let’s break down what is meant by “noise.” 1. Analog noise within the same bandwidth as the signal. 2. Analog noise outside of the bandwidth of the signal. 3. Quantization noise introduced by the ADC. *I interpreted your question as implying option 1. Increasing the sampling rate will do absolutely nothing regarding that noise. No ifs or buts. That noise is there to stay.* Other answers only apply to options 2 & 3. If your analog filter is not steep enough and you still have strong noise components above the bandwidth of the signal (option 2), particularly near the sampling rate and its multiples, then increasing the sampling rate *and* using an appropriate digital filter will allow you to (1) relax your analog filter requirements and (2) completely remove that out of band noise. Regarding option 3, that’s the basic operating principle that makes sigma-delta converters possible. Increasing sampling rate, using an appropriate digital filter at a higher resolution, and decimating the output of the filter to the needed rate, allows you to increase the resolution of your samples. You can gain 1/2 bit per each doubling of sampling rate, as long as your signal is large enough to remain uncorrelated to the sampling noise. Interestingly, this is one place where out of band noise works in your favor, as it breaks the sampling noise correlation to the signal. I.e., it serves the function of dithering (or, as physicists call it, stochastic resonance). For slow enough signals this is a great advantage, using this technique I have obtained ~20 bits of resolution out of 12 bit converters by purposefully designing the analog anti-alias filter to introduce several bits of out-of-band random noise and oversampling by a factor of 4096.
You have a 1Hz signal, with superimposed noise out to high frequencies. Now impose a 4-pole filter, lowpass filter, at 10Hz. Thus energy at 100 Hz is down 80dB. Or about 12 bits. At 30Hz, the noise energy is only down 40dB, or 7 bits. If the antialias filter is only 4-poles. Thus the ability of more samples to be useful will depend on how you rolloff the noise.
385,852
When I was looking for some information how to convert unbalanced audio signal to balanced, it was hard to find info other than "use transformer" or "buy X device to do this". Then I found this circuit:[![Converter circuit](https://i.stack.imgur.com/nPi5g.gif)](https://i.stack.imgur.com/nPi5g.gif) source: <http://www.fivefish.net/diy/balanced/default.htm> but I'm not sure if this is correct solution. I mean that on this schematic you can see low pass filter which cut-off freq is about 140 kHz, which I think is way to high (changing 220p to 1n would help?), also where op amp in inverting configuration seems rather ok, but non-inverting shouldn't be done differently (according to <https://www.electronics-tutorials.ws/filter/filter_5.html>)? Same thing with capacitor connected to pins 2 and 6 - I think it should rather be connected between output and those pins, not ground, and short between unbalanced signal + and gnd (or it's just compression of image that creates this illusion) Anyway, I'm better in digital electronics than analog, so maybe someone with greater knowledge help me here with this. **EDIT 1:** Based on SSM2142, I created the following circuit that, I think (or rather I hope) should work correctly, making unbalanced audio signal balanced. Am I right or wrong? ![schematic](https://i.stack.imgur.com/dhXOp.png) [simulate this circuit](/plugins/schematics?image=http%3a%2f%2fi.stack.imgur.com%2fdhXOp.png) – Schematic created using [CircuitLab](https://www.circuitlab.com/) Instead of TL081 I was thinking about using LM358.
2018/07/15
[ "https://electronics.stackexchange.com/questions/385852", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/193597/" ]
I see quite a few misstatements and possible misconceptions both in the answers and in the question, so let’s break down what is meant by “noise.” 1. Analog noise within the same bandwidth as the signal. 2. Analog noise outside of the bandwidth of the signal. 3. Quantization noise introduced by the ADC. *I interpreted your question as implying option 1. Increasing the sampling rate will do absolutely nothing regarding that noise. No ifs or buts. That noise is there to stay.* Other answers only apply to options 2 & 3. If your analog filter is not steep enough and you still have strong noise components above the bandwidth of the signal (option 2), particularly near the sampling rate and its multiples, then increasing the sampling rate *and* using an appropriate digital filter will allow you to (1) relax your analog filter requirements and (2) completely remove that out of band noise. Regarding option 3, that’s the basic operating principle that makes sigma-delta converters possible. Increasing sampling rate, using an appropriate digital filter at a higher resolution, and decimating the output of the filter to the needed rate, allows you to increase the resolution of your samples. You can gain 1/2 bit per each doubling of sampling rate, as long as your signal is large enough to remain uncorrelated to the sampling noise. Interestingly, this is one place where out of band noise works in your favor, as it breaks the sampling noise correlation to the signal. I.e., it serves the function of dithering (or, as physicists call it, stochastic resonance). For slow enough signals this is a great advantage, using this technique I have obtained ~20 bits of resolution out of 12 bit converters by purposefully designing the analog anti-alias filter to introduce several bits of out-of-band random noise and oversampling by a factor of 4096.
Oversampling can give you a chance to run an additional high-pass filter digitally. This can reduce out-of-band noise, and you can then reduce your sampling rate. If you don't do that, it still gives an advantage ***if the noise is not correlated with the signal.*** Your signal adds coherently, giving you 6dB of gain for doubling the sample rate. Your noise adds incoherently, giving your 3db for the same doubling. You just got 3dB SNR improvement for 2X the samples. Of course you have to sample at 4X to get 6dB improvement, and 8X for 9dB, so there's practical limitations.
9,447,216
I just saw Bret Victors Keynote called "Inventing on Principle". At around 3:34 Minutes he uses a code editor that - after a change he makes - immediately shows consequences of it. As he types there are instant results. This is the video I am talking about: <http://vimeo.com/36579366> Another example is this [real-time online html editor](http://htmledit.squarefree.com/). Can you tell me which offline editor I could use to work on my web projects (HTML/CSS/JS) this way? Preferably it can be used on OS X. Thanks!
2012/02/25
[ "https://Stackoverflow.com/questions/9447216", "https://Stackoverflow.com", "https://Stackoverflow.com/users/875153/" ]
[Brackets](http://blog.brackets.io/2012/06/25/brackets-open-source-code-editor/) looks nice, but still on development.
<http://www.youtube.com/watch?v=TBUC-7D1LIc> this guy already came up with a similar open source program like the one in the video. He also is going to be putting up the source on Github soon.
9,447,216
I just saw Bret Victors Keynote called "Inventing on Principle". At around 3:34 Minutes he uses a code editor that - after a change he makes - immediately shows consequences of it. As he types there are instant results. This is the video I am talking about: <http://vimeo.com/36579366> Another example is this [real-time online html editor](http://htmledit.squarefree.com/). Can you tell me which offline editor I could use to work on my web projects (HTML/CSS/JS) this way? Preferably it can be used on OS X. Thanks!
2012/02/25
[ "https://Stackoverflow.com/questions/9447216", "https://Stackoverflow.com", "https://Stackoverflow.com/users/875153/" ]
[Brackets](http://blog.brackets.io/2012/06/25/brackets-open-source-code-editor/) looks nice, but still on development.
If you're still looking for an *offline* editor, you could always check out Notepad++. It has a live html preview, but doesn't show most of the newer stuff; just basic layouts as well as basic CSS. [Notepad++ Website](http://notepad-plus-plus.org/)
9,447,216
I just saw Bret Victors Keynote called "Inventing on Principle". At around 3:34 Minutes he uses a code editor that - after a change he makes - immediately shows consequences of it. As he types there are instant results. This is the video I am talking about: <http://vimeo.com/36579366> Another example is this [real-time online html editor](http://htmledit.squarefree.com/). Can you tell me which offline editor I could use to work on my web projects (HTML/CSS/JS) this way? Preferably it can be used on OS X. Thanks!
2012/02/25
[ "https://Stackoverflow.com/questions/9447216", "https://Stackoverflow.com", "https://Stackoverflow.com/users/875153/" ]
I don't know if there are any free ones, but [TextMate](http://macromates.com) has a live preview window. Just don't download the version 2 beta — I don't think it's been implemented there yet. You can also check out [Coda](http://panic.com/coda/) and [BBEdit](http://www.barebones.com/products/bbedit/).
If you're still looking for an *offline* editor, you could always check out Notepad++. It has a live html preview, but doesn't show most of the newer stuff; just basic layouts as well as basic CSS. [Notepad++ Website](http://notepad-plus-plus.org/)
9,447,216
I just saw Bret Victors Keynote called "Inventing on Principle". At around 3:34 Minutes he uses a code editor that - after a change he makes - immediately shows consequences of it. As he types there are instant results. This is the video I am talking about: <http://vimeo.com/36579366> Another example is this [real-time online html editor](http://htmledit.squarefree.com/). Can you tell me which offline editor I could use to work on my web projects (HTML/CSS/JS) this way? Preferably it can be used on OS X. Thanks!
2012/02/25
[ "https://Stackoverflow.com/questions/9447216", "https://Stackoverflow.com", "https://Stackoverflow.com/users/875153/" ]
[Brackets](http://blog.brackets.io/2012/06/25/brackets-open-source-code-editor/) looks nice, but still on development.
Espresso updates the preview window as you type in the editor but it's for mac only
9,447,216
I just saw Bret Victors Keynote called "Inventing on Principle". At around 3:34 Minutes he uses a code editor that - after a change he makes - immediately shows consequences of it. As he types there are instant results. This is the video I am talking about: <http://vimeo.com/36579366> Another example is this [real-time online html editor](http://htmledit.squarefree.com/). Can you tell me which offline editor I could use to work on my web projects (HTML/CSS/JS) this way? Preferably it can be used on OS X. Thanks!
2012/02/25
[ "https://Stackoverflow.com/questions/9447216", "https://Stackoverflow.com", "https://Stackoverflow.com/users/875153/" ]
I don't know if there are any free ones, but [TextMate](http://macromates.com) has a live preview window. Just don't download the version 2 beta — I don't think it's been implemented there yet. You can also check out [Coda](http://panic.com/coda/) and [BBEdit](http://www.barebones.com/products/bbedit/).
CoffeeCup has a [Web Editor in beta](http://www.coffeecup.com/osx/web-editor/) that uses live preview and includes the code-preview connection you see in the video. Select an element in the preview and the corresponding HTML/CSS is selected, or select HTML code and see which element it applies to in the preview.
9,447,216
I just saw Bret Victors Keynote called "Inventing on Principle". At around 3:34 Minutes he uses a code editor that - after a change he makes - immediately shows consequences of it. As he types there are instant results. This is the video I am talking about: <http://vimeo.com/36579366> Another example is this [real-time online html editor](http://htmledit.squarefree.com/). Can you tell me which offline editor I could use to work on my web projects (HTML/CSS/JS) this way? Preferably it can be used on OS X. Thanks!
2012/02/25
[ "https://Stackoverflow.com/questions/9447216", "https://Stackoverflow.com", "https://Stackoverflow.com/users/875153/" ]
CoffeeCup has a [Web Editor in beta](http://www.coffeecup.com/osx/web-editor/) that uses live preview and includes the code-preview connection you see in the video. Select an element in the preview and the corresponding HTML/CSS is selected, or select HTML code and see which element it applies to in the preview.
If you're still looking for an *offline* editor, you could always check out Notepad++. It has a live html preview, but doesn't show most of the newer stuff; just basic layouts as well as basic CSS. [Notepad++ Website](http://notepad-plus-plus.org/)
9,447,216
I just saw Bret Victors Keynote called "Inventing on Principle". At around 3:34 Minutes he uses a code editor that - after a change he makes - immediately shows consequences of it. As he types there are instant results. This is the video I am talking about: <http://vimeo.com/36579366> Another example is this [real-time online html editor](http://htmledit.squarefree.com/). Can you tell me which offline editor I could use to work on my web projects (HTML/CSS/JS) this way? Preferably it can be used on OS X. Thanks!
2012/02/25
[ "https://Stackoverflow.com/questions/9447216", "https://Stackoverflow.com", "https://Stackoverflow.com/users/875153/" ]
CoffeeCup has a [Web Editor in beta](http://www.coffeecup.com/osx/web-editor/) that uses live preview and includes the code-preview connection you see in the video. Select an element in the preview and the corresponding HTML/CSS is selected, or select HTML code and see which element it applies to in the preview.
Espresso updates the preview window as you type in the editor but it's for mac only
9,447,216
I just saw Bret Victors Keynote called "Inventing on Principle". At around 3:34 Minutes he uses a code editor that - after a change he makes - immediately shows consequences of it. As he types there are instant results. This is the video I am talking about: <http://vimeo.com/36579366> Another example is this [real-time online html editor](http://htmledit.squarefree.com/). Can you tell me which offline editor I could use to work on my web projects (HTML/CSS/JS) this way? Preferably it can be used on OS X. Thanks!
2012/02/25
[ "https://Stackoverflow.com/questions/9447216", "https://Stackoverflow.com", "https://Stackoverflow.com/users/875153/" ]
I don't know if there are any free ones, but [TextMate](http://macromates.com) has a live preview window. Just don't download the version 2 beta — I don't think it's been implemented there yet. You can also check out [Coda](http://panic.com/coda/) and [BBEdit](http://www.barebones.com/products/bbedit/).
Espresso updates the preview window as you type in the editor but it's for mac only
9,447,216
I just saw Bret Victors Keynote called "Inventing on Principle". At around 3:34 Minutes he uses a code editor that - after a change he makes - immediately shows consequences of it. As he types there are instant results. This is the video I am talking about: <http://vimeo.com/36579366> Another example is this [real-time online html editor](http://htmledit.squarefree.com/). Can you tell me which offline editor I could use to work on my web projects (HTML/CSS/JS) this way? Preferably it can be used on OS X. Thanks!
2012/02/25
[ "https://Stackoverflow.com/questions/9447216", "https://Stackoverflow.com", "https://Stackoverflow.com/users/875153/" ]
[Brackets](http://blog.brackets.io/2012/06/25/brackets-open-source-code-editor/) looks nice, but still on development.
CoffeeCup has a [Web Editor in beta](http://www.coffeecup.com/osx/web-editor/) that uses live preview and includes the code-preview connection you see in the video. Select an element in the preview and the corresponding HTML/CSS is selected, or select HTML code and see which element it applies to in the preview.
9,447,216
I just saw Bret Victors Keynote called "Inventing on Principle". At around 3:34 Minutes he uses a code editor that - after a change he makes - immediately shows consequences of it. As he types there are instant results. This is the video I am talking about: <http://vimeo.com/36579366> Another example is this [real-time online html editor](http://htmledit.squarefree.com/). Can you tell me which offline editor I could use to work on my web projects (HTML/CSS/JS) this way? Preferably it can be used on OS X. Thanks!
2012/02/25
[ "https://Stackoverflow.com/questions/9447216", "https://Stackoverflow.com", "https://Stackoverflow.com/users/875153/" ]
I don't know if there are any free ones, but [TextMate](http://macromates.com) has a live preview window. Just don't download the version 2 beta — I don't think it's been implemented there yet. You can also check out [Coda](http://panic.com/coda/) and [BBEdit](http://www.barebones.com/products/bbedit/).
<http://www.youtube.com/watch?v=TBUC-7D1LIc> this guy already came up with a similar open source program like the one in the video. He also is going to be putting up the source on Github soon.
12,699,351
I've developed an iPad web app that uses the appcache. It's not intended to be a fully offline app but I use the appcache to store large image files so that they're not sent over 3G. Problem is when the manifest is updated the appcache updates whether the iPad is on wifi or 3G, which could be expensive. Is it possible to have the user decide if the appcache can be updated or not? From what I've seen, this isn't possible, it all happens automatically, you just get events. But perhaps there's some trickery like writing the manifest on the fly or similar. Using PHP on the server side if that helps. Thanks.
2012/10/02
[ "https://Stackoverflow.com/questions/12699351", "https://Stackoverflow.com", "https://Stackoverflow.com/users/76121/" ]
**Connection Type: Theory & Future** There is a [draft spec of Network Information API on W3C](http://www.w3.org/TR/netinfo-api/) that provides the information of the connection type (ethernet wifi 2g 3g 4g etc.), but it hasn't been implemented on any browser yet apart from: * the stock Android browser on Android 2.2+ (not the Google Chrome browser) `navigator.connection.type` // Based on W3C draft, (Implemented on stock Android browser) * and [PhoneGap](http://docs.phonegap.com/en/1.0.0/phonegap_connection_connection.md.html) which is not exactly a browser `navigator.network.connection.type` // on PhoneGap Having that information in the future you could detect if the user has cellular data, then temporarily remove the src of the images and ask the user through a confirmation dialog. You will also probably have to cancel the app cache update using: `window.applicationCache.abort()` ([documentation](http://www.whatwg.org/specs/web-apps/current-work/#dom-appcache-abort)) *Reality* Unfortunately, the Net Info API is not available (at least not widespread) at the moment, but certainly will help in the future. **Long shot** There is [a database](http://www.ip2location.com/ip-country-region-city-latitude-longitude-zipcode-timezone-isp-domain-netspeed-areacode-weather-mobile.aspx) that includes network speed (DIAL = dial up, DSL = broadband/cable, COMP = company/T1), but I haven't used it and I doubt it will help. **Dynamic App Cache** While checking into this, I tried to generate the html tag along with the manifest declaration on the fly, in order to combine it with the Network Info API but the AppCache manifest is loaded before javascript execution and is not affected afterwards. So altering the manifest file on the fly through Javascript is not possible and data URI is not an option. **Alternative solution** HTML5 application cache is an untamed beast at the moment and there are [talks to improve it](http://www.stevesouders.com/blog/2011/10/03/improving-app-cache/). Until it changes to support more complex configurations (bandwidth level flag would be awesome), you could change perspective on the solution, although App Cache may be the best you have at the moment. Depending on how big your images are you could rely on the normal browser cache. You could combine [localStorage](http://diveintohtml5.info/storage.html) and far-future [expiration HTTP headers](http://developer.yahoo.com/blogs/ydn/posts/2007/05/high_performanc_2/). LocalStorage in order to keep track of the loaded/cached images. * First add a far in the future date for expiration on your images HTTP headers * On page load, remove all src from imgs * Loop the images and check localStorage if each image was loaded in the past * If there are images that were not loaded in the past, display a dialog confirming for the downloading of those images * If the image was loaded in the past, then put back the src on the img * For every image that is downloaded, save its URL on localStorage
I don't know what the status of indexedDB is on the iPad, but this could be an alternative solution. In short: Indexeddb is a clientside database. Data is stored in object stores which are key/value pairs. The maximum storage capacity is in theory the maximum of your disk space. For more information about indexeddb: * [Specification](http://www.w3.org/TR/IndexedDB/) * [My blog](http://www.kristofdegrave.be) What you could do with the indexeddb: When someone navigates to a page: * Check every image tag if it is present in the indexeddb * if present + Get the image from the indexeddb and put it in the image tag * if not present + Download it + store it in the indexeddb + put the image in the image tag. As extra (in the future) you can do as discribed by Sev: check the connetion type and only download the image when working on a fast internet connection.
12,699,351
I've developed an iPad web app that uses the appcache. It's not intended to be a fully offline app but I use the appcache to store large image files so that they're not sent over 3G. Problem is when the manifest is updated the appcache updates whether the iPad is on wifi or 3G, which could be expensive. Is it possible to have the user decide if the appcache can be updated or not? From what I've seen, this isn't possible, it all happens automatically, you just get events. But perhaps there's some trickery like writing the manifest on the fly or similar. Using PHP on the server side if that helps. Thanks.
2012/10/02
[ "https://Stackoverflow.com/questions/12699351", "https://Stackoverflow.com", "https://Stackoverflow.com/users/76121/" ]
**Connection Type: Theory & Future** There is a [draft spec of Network Information API on W3C](http://www.w3.org/TR/netinfo-api/) that provides the information of the connection type (ethernet wifi 2g 3g 4g etc.), but it hasn't been implemented on any browser yet apart from: * the stock Android browser on Android 2.2+ (not the Google Chrome browser) `navigator.connection.type` // Based on W3C draft, (Implemented on stock Android browser) * and [PhoneGap](http://docs.phonegap.com/en/1.0.0/phonegap_connection_connection.md.html) which is not exactly a browser `navigator.network.connection.type` // on PhoneGap Having that information in the future you could detect if the user has cellular data, then temporarily remove the src of the images and ask the user through a confirmation dialog. You will also probably have to cancel the app cache update using: `window.applicationCache.abort()` ([documentation](http://www.whatwg.org/specs/web-apps/current-work/#dom-appcache-abort)) *Reality* Unfortunately, the Net Info API is not available (at least not widespread) at the moment, but certainly will help in the future. **Long shot** There is [a database](http://www.ip2location.com/ip-country-region-city-latitude-longitude-zipcode-timezone-isp-domain-netspeed-areacode-weather-mobile.aspx) that includes network speed (DIAL = dial up, DSL = broadband/cable, COMP = company/T1), but I haven't used it and I doubt it will help. **Dynamic App Cache** While checking into this, I tried to generate the html tag along with the manifest declaration on the fly, in order to combine it with the Network Info API but the AppCache manifest is loaded before javascript execution and is not affected afterwards. So altering the manifest file on the fly through Javascript is not possible and data URI is not an option. **Alternative solution** HTML5 application cache is an untamed beast at the moment and there are [talks to improve it](http://www.stevesouders.com/blog/2011/10/03/improving-app-cache/). Until it changes to support more complex configurations (bandwidth level flag would be awesome), you could change perspective on the solution, although App Cache may be the best you have at the moment. Depending on how big your images are you could rely on the normal browser cache. You could combine [localStorage](http://diveintohtml5.info/storage.html) and far-future [expiration HTTP headers](http://developer.yahoo.com/blogs/ydn/posts/2007/05/high_performanc_2/). LocalStorage in order to keep track of the loaded/cached images. * First add a far in the future date for expiration on your images HTTP headers * On page load, remove all src from imgs * Loop the images and check localStorage if each image was loaded in the past * If there are images that were not loaded in the past, display a dialog confirming for the downloading of those images * If the image was loaded in the past, then put back the src on the img * For every image that is downloaded, save its URL on localStorage
I have 'invented' a working solution developing a webapp on the iPad (iOS 6.0.x) that may answer your question. The idea is first to check if a localstorage variable is set/defined or not yet (I use the title of the page, thus the webapp name.) If this localstorage variable exists, then assume (in webapp sandbox context) that its the first time the app is being run. At this point I populate a UUID in conjunction with `$PHP_SESSION($uuid)` to avoid 'cross app contamination' in server-side PHP land. In addition to this I have a dynamic manifest.appcache.php which includes in the CACHE section a list of files to add to the manifest. Thus; ``` <? echo $manifest_file_list[0]."\n"; ?> ``` Using the JS appcache manifest event listeners I then monitor the progress to something like `$('#manifestappcache').html(result);`
12,699,351
I've developed an iPad web app that uses the appcache. It's not intended to be a fully offline app but I use the appcache to store large image files so that they're not sent over 3G. Problem is when the manifest is updated the appcache updates whether the iPad is on wifi or 3G, which could be expensive. Is it possible to have the user decide if the appcache can be updated or not? From what I've seen, this isn't possible, it all happens automatically, you just get events. But perhaps there's some trickery like writing the manifest on the fly or similar. Using PHP on the server side if that helps. Thanks.
2012/10/02
[ "https://Stackoverflow.com/questions/12699351", "https://Stackoverflow.com", "https://Stackoverflow.com/users/76121/" ]
I don't know what the status of indexedDB is on the iPad, but this could be an alternative solution. In short: Indexeddb is a clientside database. Data is stored in object stores which are key/value pairs. The maximum storage capacity is in theory the maximum of your disk space. For more information about indexeddb: * [Specification](http://www.w3.org/TR/IndexedDB/) * [My blog](http://www.kristofdegrave.be) What you could do with the indexeddb: When someone navigates to a page: * Check every image tag if it is present in the indexeddb * if present + Get the image from the indexeddb and put it in the image tag * if not present + Download it + store it in the indexeddb + put the image in the image tag. As extra (in the future) you can do as discribed by Sev: check the connetion type and only download the image when working on a fast internet connection.
I have 'invented' a working solution developing a webapp on the iPad (iOS 6.0.x) that may answer your question. The idea is first to check if a localstorage variable is set/defined or not yet (I use the title of the page, thus the webapp name.) If this localstorage variable exists, then assume (in webapp sandbox context) that its the first time the app is being run. At this point I populate a UUID in conjunction with `$PHP_SESSION($uuid)` to avoid 'cross app contamination' in server-side PHP land. In addition to this I have a dynamic manifest.appcache.php which includes in the CACHE section a list of files to add to the manifest. Thus; ``` <? echo $manifest_file_list[0]."\n"; ?> ``` Using the JS appcache manifest event listeners I then monitor the progress to something like `$('#manifestappcache').html(result);`
34,531,045
I've heard it's a sin to use try-catch for anything that might be expected to happen in normal program flow, and that one should use if-else instead. But, what about the case where we want to use it for initialization (an event that happens once and once only). You may want this when you initialization depends on the first incoming data, as in the following example: ``` class RunningVectorSum{ double[] running_sum; public double[] add(double vec[]){ try{ for (int i=0; i<running_sum.length; i++) running_sum[i]+=vec[i]; } catch(NullPointerException ex){ running_sum = new double[vec.length]; for (int i=0; i<running_sum.length; i++) running_sum[i] = vec[i]; } return running_sum; } } ``` In this case, should it be faster in the long run to use the try-catch vs using: ``` public double[] add(double vec[]){ if (running_sum==null) running_sum = new double[vec.length]; for (int i=0; i<running_sum.length; i++) running_sum[i]+=vec[i]; return running_sum; } ``` instead? edit: Things I'm aware of: * Yes in this particular example, there's a possible problem if vec has a varying length * Yes I know this is a terrible sin. Things I'm not aware of: * Why is it such a terrible sin? * Is it faster to always pass through a try (except once, which amortizes to nothing) than it is to always pass through an if(condition)
2015/12/30
[ "https://Stackoverflow.com/questions/34531045", "https://Stackoverflow.com", "https://Stackoverflow.com/users/851699/" ]
It's bad practice to use exception handling for implementing your business logic. Exception handling is for handling exceptional cases. In your specific example it is even clearer that using exception handling is wrong, since your are duplicating your code in the exception handler. BTW, your method has another potential problem. You have no guarantee that in each call to `add` you'll receive an array of the same length, so you run the risk of ignoring some of the values passed to your method, or getting `ArrayIndexOutOfBoundsException` if `vec` is shorter than `running_sum`.
Runtime exceptions like `NullPointerException` or `ArrayIndexOutOfBoundsException` are an indicator of a bug in your program because you as the developer screwed up. Not the user or some external factor but *your* code. You should never try to catch them, you have to make sure they simply cannot occur. If they occur, track them down and fix your code to make sure they never occur again. If `running_sum` must not be null, enforce that by adding a constructor, that takes the value as parameter and checks for non-null. Having a `add` method without anything to add the input to makes no sense.
57,776
I've got a service that I need to start as a different user to 'Local System' There is a user specific PATH I need to add to the default path in order for the service to work correctly. The default PATH is A;B;C; I've setup the users PATH X; so that when the user logs on interactively the effective PATH is A;B;C;X; This was done by setting HKEY\_USERS\XXXXXXX\Environment\Path All paths are on local hard drives. When the service starts as the user I can watch it search for needed DLLs with ProcMon. It is only searching A;B;C; when started as a service. I've tried altering the service type from 0x10 to 0x110 which should allow desktop interaction to see if that would load the users environment, but it didn't seem to help. Should Windows be loading the environment settings for a user when starting services? Is there a workaround if this is the default behaviour? Thanks
2009/08/24
[ "https://serverfault.com/questions/57776", "https://serverfault.com", "https://serverfault.com/users/5063/" ]
MS has a [program that runs any program as a service](http://support.microsoft.com/kb/137890). One of the parameters is `HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\<name>\Parameters\AppDirectory`, although this may only apply to these wrapped services.
It's Windows Server 2003 specific, but all the same I think this may answer your question: <http://support.microsoft.com/kb/887693>
57,776
I've got a service that I need to start as a different user to 'Local System' There is a user specific PATH I need to add to the default path in order for the service to work correctly. The default PATH is A;B;C; I've setup the users PATH X; so that when the user logs on interactively the effective PATH is A;B;C;X; This was done by setting HKEY\_USERS\XXXXXXX\Environment\Path All paths are on local hard drives. When the service starts as the user I can watch it search for needed DLLs with ProcMon. It is only searching A;B;C; when started as a service. I've tried altering the service type from 0x10 to 0x110 which should allow desktop interaction to see if that would load the users environment, but it didn't seem to help. Should Windows be loading the environment settings for a user when starting services? Is there a workaround if this is the default behaviour? Thanks
2009/08/24
[ "https://serverfault.com/questions/57776", "https://serverfault.com", "https://serverfault.com/users/5063/" ]
Just to close this out. I wrote this in a generic format as I suspected I was dealing with a generic Windows service issue. However it turns out that this is an issue with the service executeables themselves. It appears that the reading of the system path and the user path is somehow depandant on the service executable. I have two services from the same vendor, one of them reads both the system and user path whereas the other just reads the system path.
It's Windows Server 2003 specific, but all the same I think this may answer your question: <http://support.microsoft.com/kb/887693>
57,776
I've got a service that I need to start as a different user to 'Local System' There is a user specific PATH I need to add to the default path in order for the service to work correctly. The default PATH is A;B;C; I've setup the users PATH X; so that when the user logs on interactively the effective PATH is A;B;C;X; This was done by setting HKEY\_USERS\XXXXXXX\Environment\Path All paths are on local hard drives. When the service starts as the user I can watch it search for needed DLLs with ProcMon. It is only searching A;B;C; when started as a service. I've tried altering the service type from 0x10 to 0x110 which should allow desktop interaction to see if that would load the users environment, but it didn't seem to help. Should Windows be loading the environment settings for a user when starting services? Is there a workaround if this is the default behaviour? Thanks
2009/08/24
[ "https://serverfault.com/questions/57776", "https://serverfault.com", "https://serverfault.com/users/5063/" ]
MS has a [program that runs any program as a service](http://support.microsoft.com/kb/137890). One of the parameters is `HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\<name>\Parameters\AppDirectory`, although this may only apply to these wrapped services.
Have you tried using SRVANY turn a script such as a batch file into a service and set the environment there before calling out to your desired app? Note: you may concede service stop/start/restart control if the script backgrounds subsequent processes and exits, since the service controller will be checking to see if the script itself is "running." You could also consider reading PATH from the user registry in the script and using its contents so that the env isn't hardcoded in the script itself.
57,776
I've got a service that I need to start as a different user to 'Local System' There is a user specific PATH I need to add to the default path in order for the service to work correctly. The default PATH is A;B;C; I've setup the users PATH X; so that when the user logs on interactively the effective PATH is A;B;C;X; This was done by setting HKEY\_USERS\XXXXXXX\Environment\Path All paths are on local hard drives. When the service starts as the user I can watch it search for needed DLLs with ProcMon. It is only searching A;B;C; when started as a service. I've tried altering the service type from 0x10 to 0x110 which should allow desktop interaction to see if that would load the users environment, but it didn't seem to help. Should Windows be loading the environment settings for a user when starting services? Is there a workaround if this is the default behaviour? Thanks
2009/08/24
[ "https://serverfault.com/questions/57776", "https://serverfault.com", "https://serverfault.com/users/5063/" ]
MS has a [program that runs any program as a service](http://support.microsoft.com/kb/137890). One of the parameters is `HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\<name>\Parameters\AppDirectory`, although this may only apply to these wrapped services.
Just to close this out. I wrote this in a generic format as I suspected I was dealing with a generic Windows service issue. However it turns out that this is an issue with the service executeables themselves. It appears that the reading of the system path and the user path is somehow depandant on the service executable. I have two services from the same vendor, one of them reads both the system and user path whereas the other just reads the system path.
57,776
I've got a service that I need to start as a different user to 'Local System' There is a user specific PATH I need to add to the default path in order for the service to work correctly. The default PATH is A;B;C; I've setup the users PATH X; so that when the user logs on interactively the effective PATH is A;B;C;X; This was done by setting HKEY\_USERS\XXXXXXX\Environment\Path All paths are on local hard drives. When the service starts as the user I can watch it search for needed DLLs with ProcMon. It is only searching A;B;C; when started as a service. I've tried altering the service type from 0x10 to 0x110 which should allow desktop interaction to see if that would load the users environment, but it didn't seem to help. Should Windows be loading the environment settings for a user when starting services? Is there a workaround if this is the default behaviour? Thanks
2009/08/24
[ "https://serverfault.com/questions/57776", "https://serverfault.com", "https://serverfault.com/users/5063/" ]
Just to close this out. I wrote this in a generic format as I suspected I was dealing with a generic Windows service issue. However it turns out that this is an issue with the service executeables themselves. It appears that the reading of the system path and the user path is somehow depandant on the service executable. I have two services from the same vendor, one of them reads both the system and user path whereas the other just reads the system path.
Have you tried using SRVANY turn a script such as a batch file into a service and set the environment there before calling out to your desired app? Note: you may concede service stop/start/restart control if the script backgrounds subsequent processes and exits, since the service controller will be checking to see if the script itself is "running." You could also consider reading PATH from the user registry in the script and using its contents so that the env isn't hardcoded in the script itself.
41,774,784
I would like to change the PayPal Login button font size, as I noticed it is enough to make the whole button smaller, but it seems that it generates a CSS at the bottom of the head, which will override mines. The button is generated by a script (which I suppose is the one that adds the CSS as well). ``` <li><span id="pp_login_container" font-size: "14px"></span> <script src="https://www.paypalobjects.com/js/external/api.js"></script> <script>paypal.use(['login'], function(login) { login.render ({ 'appid': '<?php echo $client_id; ?>', 'authend': '<?php echo $sandbox; ?>', 'scopes': '<?php echo $scopes; ?>', 'containerid': 'pp_login_container', 'locale': '<?php echo $locale; ?>', 'theme': '<?php echo $button_colour; ?>', 'returnurl': '<?php echo $return_url; ?>' }); }); </script> </span> </li> ``` Here is the output: ``` <span id="pp_login_container"> <button id="LIwPP85447951" class="LIwPP PPBlue"> <svg class="PPTM" xmlns="http://www.w3.org/2000/svg" version="1.1" width="16px" height="17px" viewBox="0 0 16 17"> <path class="PPTM-btm" fill="#0079c1" d="m15.603 3.917c-0.264-0.505-0.651-0.917-1.155-1.231-0.025-0.016-0.055-0.029-0.081-0.044 0.004 0.007 0.009 0.014 0.013 0.021 0.265 0.506 0.396 1.135 0.396 1.891 0 1.715-0.712 3.097-2.138 4.148-1.425 1.052-3.418 1.574-5.979 1.574h-0.597c-0.45 0-0.9 0.359-1.001 0.798l-0.719 3.106c-0.101 0.438-0.552 0.797-1.002 0.797h-1.404l-0.105 0.457c-0.101 0.438 0.184 0.798 0.633 0.798h2.1c0.45 0 0.9-0.359 1.001-0.798l0.718-3.106c0.101-0.438 0.551-0.797 1.002-0.797h0.597c2.562 0 4.554-0.522 5.979-1.574 1.426-1.052 2.139-2.434 2.139-4.149 0-0.755-0.132-1.385-0.397-1.891z"></path> <path class="PPTM-top" fill="#00457c" d="m9.27 6.283c-0.63 0.46-1.511 0.691-2.641 0.691h-0.521c-0.45 0-0.736-0.359-0.635-0.797l0.628-2.72c0.101-0.438 0.552-0.797 1.002-0.797h0.686c0.802 0 1.408 0.136 1.814 0.409 0.409 0.268 0.611 0.683 0.611 1.244 0 0.852-0.315 1.507-0.944 1.97zm3.369-5.42c-0.913-0.566-2.16-0.863-4.288-0.863h-4.372c-0.449 0-0.9 0.359-1.001 0.797l-2.957 12.813c-0.101 0.439 0.185 0.798 0.634 0.798h2.099c0.45 0 0.901-0.358 1.003-0.797l0.717-3.105c0.101-0.438 0.552-0.797 1.001-0.797h0.598c2.562 0 4.554-0.524 5.979-1.575 1.427-1.051 2.139-2.433 2.139-4.148-0.001-1.365-0.439-2.425-1.552-3.123z"></path> </svg> <b>Log In with PayPal</b> </button> </span> ``` And the CSS that changes is something like (positioned at the end of head in the HTML): ``` <style type="text/css">/*!reset via github.com/premasagar/cleanslate*/ .... .LIwPP { ... font-size: 16px !important; ... ``` [Here is the CSS that is using](https://github.com/premasagar/cleanslate) I trying to do this in OpenCart2 into the header.tpl
2017/01/21
[ "https://Stackoverflow.com/questions/41774784", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1587275/" ]
use `iloc` and slice appropriately ``` df.iloc[::-1] 0 7 0 6 11 5 22 4 33 ``` --- In order to preserve the index ***use `iloc`*** ``` df.iloc[:] = df.iloc[::-1].values ``` ***use `numpy`*** ``` pd.DataFrame(df.values[::-1], df.index, df.columns) ``` --- Both yield ``` 0 4 33 5 22 6 11 7 0 ```
You can also set your index into a temporary variable and then reapply index. ``` df = pd.DataFrame(index=range(4,8), data=[33,22,11,00]) idx=df.index.values df.sort_values([0],inplace=True) df.index=idx ``` Not as clever but easy to understand
2,750,644
I have a fictional class: ``` template<typename T> class demonstration { public: demonstration(){} ... T *m_data; } ``` At some point in the program's execution, I want to set `m_data` to a big block of allocated memory and construct an object `T` there. At the moment, I've been using this code: ``` void construct() { *m_data = T(); } ``` Which I've now realised is probably not the best idea... wont work under certain cirumstances, if `T` has a private assignment operator for example. Is there a normal/better way to do what I'm attempting here?
2010/05/01
[ "https://Stackoverflow.com/questions/2750644", "https://Stackoverflow.com", "https://Stackoverflow.com/users/293011/" ]
Use placement `new`: ``` new (m_data) T(); ``` Placement `new` is really just an overload of the `operator new` function that accepts an additional parameter – the memory location where the object should be constructed at. This precisely matches your use-case. In particular, this is how `allocator`s usually implement the [`construct`](http://www.cplusplus.com/reference/std/memory/allocator/construct/) method which is used (among others) by the STL container classes to construct objects. Since placement `new` only *constructs* an object without allocating memory, it’s usually an error to call `delete` to get rid of the memory. Destruction has to happen by calling the destructor directly, *without* freeing the memory: ``` m_data->~T(); ``` Notice that this syntax for calling the destructor doesn’t work for a constructor call, otherwise we wouldn’t need placement new in the first place. I.e. there’s no `m_data->T()`.
Placement `new` operator is what would suit your situation.
10,435,266
In this JsFiddle : <http://jsfiddle.net/maxl/mCXND/> (copied and modified from <http://jsfiddle.net/ud3323/XMgwV/>) I try to create an Ember DatePicker based on JQuery's. The first problem I run into is this line : ``` var ui = jQuery.ui[this.get('uiType')](options, this.get('element')); ``` jQuery.ui[this.get('uiType')] doesn't return a function, so I suppose that the solution that I started with works for some jQueryUI widgets, but not all. I would like a solution that will work for all JQuery-UI widgets, and in particular JQueryUI's Datepicker. Thanks
2012/05/03
[ "https://Stackoverflow.com/questions/10435266", "https://Stackoverflow.com", "https://Stackoverflow.com/users/535782/" ]
If you look at the jqueryui code, you see that some of them are invoked as a function, others not. You can solve it using this: ``` var ui; if (typeof jQuery.ui[this.get('uiType')] === 'function') { ui = jQuery.ui[this.get('uiType')](options, this.get('element')); } else { ui = this.$()[this.get('uiType')](options); } ``` working example: <http://jsfiddle.net/PzsrT/7/>
One more thing about jQuery UI's datepicker widget as a EmberJS Mixin. If you want to supply a callback function to handle the beforeShowDay event, you will raise this error: ``` Uncaught TypeError: Cannot read property '0' of undefined ``` even if your callback function (in your ember view) return an array, like it's specified in the jqueryui doc ``` beforeShowDay: function(date){ some code... return [true, '']; }; ``` This happens because nothing is returned after the callback.call in the \_gatherEvents function ``` _gatherEvents: function(options) { var uiEvents = this.get('uiEvents') || [], self = this; uiEvents.forEach(function(event) { var callback = self[event]; if (callback) { // You can register a handler for a jQuery UI event by passing // it in along with the creation options. Update the options hash // to include any event callbacks. options[event] = function(event, ui) { callback.call(self, event, ui); }; } }); } ``` I fix this by adding a return statement before the callback.call. ``` _gatherEvents: function(options) { var uiEvents = this.get('uiEvents') || [], self = this; uiEvents.forEach(function(event) { var callback = self[event]; if (callback) { // You can register a handler for a jQuery UI event by passing // it in along with the creation options. Update the options hash // to include any event callbacks. options[event] = function(event, ui) { return callback.call(self, event, ui); }; } }); } ``` working example <http://jsfiddle.net/thibault/qf3Yu/>
8,123,032
I have a static page `/story` that has a button that says "make your choice" which is handled by `/choice`. In `/choice` I have this script in the header ``` var count = 0; function writeToStorage() { var user = "user" + count; count++; localStorage.setItem("chooser", user); document.getElementById("form_chooser").value = user; }; ``` So, every time `/choice` is called by `/story` "count" is reset to zero. How do I make "count" persistent so that each time `/choice` is called the current value is used? I asked a [previous question](https://stackoverflow.com/questions/8106644/how-do-i-set-up-var-count-so-that-it-is-initialized-the-first-time-and-then-in) for this, but I think it was not clear what I wanted to do and the answers concentrated on the function `writeToStorage()`. It is true that if I call `writeToStorage` several times in one session ``` writeToStorage(); writeToStorage(); writeToStorage(); ``` "count" is incremented but as soon as `/choice` is run the count is reset to zero. I would like "count" to persist. Thanks.
2011/11/14
[ "https://Stackoverflow.com/questions/8123032", "https://Stackoverflow.com", "https://Stackoverflow.com/users/215094/" ]
Smth along these lines: ``` var count = localStorage.getItem("count") || 0; function writeToStorage() { count++; localStorage.setItem("count", count); document.getElementById("form_chooser").value = "user" + count; }; ``` So, first line gets the current local storage count or 0 if it's undefined ( if the count was never stored, the user camed for the first time to you're page ) , then you increment the count and save it . Then write the current count in the element .
``` function storage (){ var canStore = true; if (typeof(localStorage) == 'undefined' ) { canStore = false; } return canStore; }; function getStorageVal(key){ if (storage()) { return localStorage.getItem(key); } } var count = getStorageVal('chooser'); count++; var user = "user" + count; localStorage.setItem("chooser", user); document.getElementById("form_chooser").value = user; ```
7,940
I override a block class `Mage_Catalog_Block_Navigation` ([link to signature](http://docs.magentocommerce.com/Mage_Catalog/Mage_Catalog_Block_Navigation.html "link to source")) to create a custom menu which displays only subcategories of current category. Inside method `renderCategoriesMenuHtml` ([link to signature](http://docs.magentocommerce.com/Mage_Catalog/Mage_Catalog_Block_Navigation.html#renderCategoriesMenuHtml)) I'm trying to get child categories of selected parent category. So I replaced default code: ``` foreach ($this->getStoreCategories() as $child) { //... } ``` with the following: ``` /** * @param $parent ID of category from which we start * @param $recursionLevel How many levels of subcategories retrieve * getCategories(...) is a method from model Mage_Catalog_Model_Category */ $category = Mage::getModel('catalog/category'); $storeCategories = $category->getCategories($parent, $recursionLevel); foreach ($storeCategories as $child) { //... } ``` This code works perfectly fine and returns subcategories of selected parent, but as soon as I enable the **"Flat Catalog Category"** the `$parent` variable seems to be completely ignored and that code returns all top-level categories, instead of subcategories of category with ID `$parent`. What do I do wrong? Shouldn't `getCategories` method work the same even when flat categories are enabled? EDIT: ===== My real question is 1. Why method `getCategories` from model `Mage_Catalog_Model_Category` ignors parameters `$parent` and `$recursionLevel` when flat categories are enabled? (see source of the method below) 2. Are there more methods which works different with flat catalog? How can I recognize them to avoid problems in the future? I call it like this inside method `renderCategoriesMenuHtml`: ``` $parent = 13; $recursionLevel = 2; $category = Mage::getModel('catalog/category'); $storeCategories = $category->getCategories($parent, $recursionLevel); ``` With non-flat categories this code returns subcategories (2 levels as specified in `$recursionLevel`) of the category with ID 13. But with flat categories enabled I get all top-level categories with all subcategories (limited with value of admin settings `'catalog/navigation/max_depth'`, not by `$recursionLevel`). Method in model `Mage_Catalog_Model_Category`: ``` public function getCategories($parent, $recursionLevel = 0, $sorted=false, $asCollection=false, $toLoad=true) { $categories = $this->getResource() ->getCategories($parent, $recursionLevel, $sorted, $asCollection, $toLoad); return $categories; } ``` calls method in resource model `Mage_Catalog_Model_Resource_Category`: ``` public function getCategories($parent, $recursionLevel = 0, $sorted = false, $asCollection = false, $toLoad = true) { $tree = Mage::getResourceModel('catalog/category_tree'); /* @var $tree Mage_Catalog_Model_Resource_Category_Tree */ $nodes = $tree->loadNode($parent) ->loadChildren($recursionLevel) ->getChildren(); $tree->addCollectionData(null, $sorted, $parent, $toLoad, true); if ($asCollection) { return $tree->getCollection(); } return $nodes; } ```
2013/09/12
[ "https://magento.stackexchange.com/questions/7940", "https://magento.stackexchange.com", "https://magento.stackexchange.com/users/764/" ]
``` $_category = Mage::getModel('catalog/category')->load(CATEGORY-ID); $_categories = $_category ->getCollection() ->addAttributeToSelect(array('name', 'image', 'description')) ->addIdFilter($_category->getChildren()); foreach ($_categories as $_category): echo $_category->getName(); endforeach; ```
``` <?php $parentCategoryId = 107; $cat = Mage::getModel('catalog/category')->load($parentCategoryId); $subcats = $cat->getChildren(); ?> // Get 1 Level sub category of Parent category. <?php foreach(explode(',',$subcats) as $subCatid) { $_category = Mage::getModel('catalog/category')->load($subCatid); if($_category->getIsActive()) { echo '<ul><a href="'.$_category->getURL().'" title="View the products for the "'.$_category->getName().'" category">'.$_category->getName().'</a>'; echo '</ul>'; } } ?> ``` **If you want 2 level , 3 Level, 4 Level or n Level subcategories of parent category than** [**Click Here**](http://magentoo.blogspot.com/2014/01/get-all-subcategories-of-parent-category-magento.html)
11,036,663
I am building a small download module for a larger project I am currently working on, and have run into a bit of an issue. Although it works perfectly for small files, when the browser (any browser) begins downloading a larger file, it simply loads like any page would, and then in the last few seconds "downloads" the whole file (regardless of size) almost instantly. I have gone through HTTP 1.1 standard over and over, and seem to be following them to the letter. One thought that instantly comes to mind is when PHP is actually sending data to the client. The answer SHOULD be as the script runs - I use this principle in other long scripts for debugging. Here is the relevant piece of code (there is much more too it of course, but this is where headers and output is actually sent: ``` header("Content-Type: application/force-download"); header("Content-length: $size"); header('Content-Disposition: attachment; filename="'.$fileData['name'].'"'); for ($i=0; $i<$size; $i+=$step) { $content = fread($file, $step); if ($content === false) $content = ""; echo $content; } die(); ``` Any ideas? I have a feeling this is an obvious issue I just can't see from staring at this block for so long. Thanks in advance!
2012/06/14
[ "https://Stackoverflow.com/questions/11036663", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1456632/" ]
Use "\*", since you're looking for files.
Try something like: ``` Folder = "C:\" Set fso = CreateObject("Scripting.FileSystemObject") Set fold = fso.GetFolder(folder) For Each file in fold.Files If Instr(file, "June") >0 Then Response.Write file.name & " got it in filename!" End if Next Set fold = Nothing Set fso = Nothing ```
65,180,818
I'm trying to get my Django app work with the current user time zone but I'm not getting any results... In my settings.py file I set: `TIME_ZONE = 'UTC'` and in my `views.py` I set at the top of the code: `activate(settings.TIME_ZONE)` But this is not working, while creating a post, is getting my last time zone that was 'Madrid', instead of my current time zone. Is there a way to make this work? Thank you!
2020/12/07
[ "https://Stackoverflow.com/questions/65180818", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13577511/" ]
here is the source of this [django timezone](https://docs.djangoproject.com/en/3.1/topics/i18n/timezones/) Add the following middleware to MIDDLEWARE: ``` import pytz from django.utils import timezone class TimezoneMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): tzname = request.session.get('django_timezone') if tzname: timezone.activate(pytz.timezone(tzname)) else: timezone.deactivate() return self.get_response(request) ``` Create a view that can set the current timezone: ``` from django.shortcuts import redirect, render def set_timezone(request): if request.method == 'POST': request.session['django_timezone'] = request.POST['timezone'] return redirect('/') else: return render(request, 'template.html', {'timezones': pytz.common_timezones}) ``` Include a form in template.html that will POST to this view: ``` {% load tz %} {% get_current_timezone as TIME_ZONE %} <form action="{% url 'set_timezone' %}" method="POST"> {% csrf_token %} <label for="timezone">Time zone:</label> <select name="timezone"> {% for tz in timezones %} <option value="{{ tz }}"{% if tz == TIME_ZONE %} selected{% endif %}>{{ tz }}</option> {% endfor %} </select> <input type="submit" value="Set"> </form> ``` Time zone aware input in forms¶ When you enable time zone support, Django interprets datetimes entered in forms in the current time zone and returns aware datetime objects in cleaned\_data. If the current time zone raises an exception for datetimes that don’t exist or are ambiguous because they fall in a DST transition (the timezones provided by pytz do this), such datetimes will be reported as invalid values. Time zone aware output in templates¶ When you enable time zone support, Django converts aware datetime objects to the current time zone when they’re rendered in templates. This behaves very much like format localization. Warning Django doesn’t convert naive datetime objects, because they could be ambiguous, and because your code should never produce naive datetimes when time zone support is enabled. However, you can force conversion with the template filters described below. Conversion to local time isn’t always appropriate – you may be generating output for computers rather than for humans. The following filters and tags, provided by the tz template tag library, allow you to control the time zone conversions. Template tags¶ localtime¶ Enables or disables conversion of aware datetime objects to the current time zone in the contained block. This tag has exactly the same effects as the USE\_TZ setting as far as the template engine is concerned. It allows a more fine grained control of conversion. To activate or deactivate conversion for a template block, use: ``` {% load tz %} {% localtime on %} {{ value }} {% endlocaltime %} {% localtime off %} {{ value }} {% endlocaltime %} ``` Note The value of USE\_TZ isn’t respected inside of a {% localtime %} block. timezone¶ Sets or unsets the current time zone in the contained block. When the current time zone is unset, the default time zone applies. ``` {% load tz %} {% timezone "Europe/Paris" %} Paris time: {{ value }} {% endtimezone %} {% timezone None %} Server time: {{ value }} {% endtimezone %} ``` get\_current\_timezone¶ You can get the name of the current time zone using the get\_current\_timezone tag: ``` {% get_current_timezone as TIME_ZONE %} ``` Alternatively, you can activate the tz() context processor and use the TIME\_ZONE context variable.
From <https://docs.djangoproject.com/en/3.1/topics/i18n/timezones/> ``` from django.utils import timezone now = timezone.now() ```
65,180,818
I'm trying to get my Django app work with the current user time zone but I'm not getting any results... In my settings.py file I set: `TIME_ZONE = 'UTC'` and in my `views.py` I set at the top of the code: `activate(settings.TIME_ZONE)` But this is not working, while creating a post, is getting my last time zone that was 'Madrid', instead of my current time zone. Is there a way to make this work? Thank you!
2020/12/07
[ "https://Stackoverflow.com/questions/65180818", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13577511/" ]
I hope this can help someone. Since Django can't automatically detect what the user's timezone is, I had the idea of saving the user's timezone in a cookie with JS on the landing page. Place in base.html ``` <script> // Timezone settings const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone; // e.g. "America/New_York" document.cookie = "django_timezone=" + timezone; </script> ``` And I followed the steps that are indicated in the official Django documentation with some slight modifications. ``` class TimezoneMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): try: # get django_timezone from cookie tzname = request.COOKIES.get("django_timezone") if tzname: timezone.activate(zoneinfo.ZoneInfo(tzname)) else: timezone.deactivate() except Exception as e: timezone.deactivate() return self.get_response(request) ```
From <https://docs.djangoproject.com/en/3.1/topics/i18n/timezones/> ``` from django.utils import timezone now = timezone.now() ```
60,588,683
What I want is this: ``` Dic = {'name':{'id':[1,2,3]}} ``` I have seen answers of how to do this but the ones I saw required the list to be known when they are inserting. the problem I have is I don't know when I'll have to insert in `Dic['name']['id']`. Is there a way to make something like this `Dic['name']['id'].append(0)`? What I did before was this ``` Dic={} Dic['name']=[] Dic['name'].append('id') ``` but now I have to store some values of ID too and those are *list* of values.
2020/03/08
[ "https://Stackoverflow.com/questions/60588683", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10667989/" ]
You can use a `defaultdict` to get what you want, for example: ```py from collections import defaultdict d = {'name': defaultdict(list)} d['name']['id'].append(0) d['name']['id'].append(1) d['name']['id'].append(2) print(d) >>> {'name': defaultdict(<class 'list'>, {'id': [0, 1, 2]})} ```
``` Dic = {} Dic['name'] = {} Dic['name']['id'] = [] Dic['name']['id'].append(0) print(Dic) ``` This code segment gives the following output ``` {'name': {'id': [0]}} ``` I think this is the output you need
3,686,629
Using Visual Studio 2008 C++, how can I create a folder using code. For some reason, a simple CreateDirectory isn't working.
2010/09/10
[ "https://Stackoverflow.com/questions/3686629", "https://Stackoverflow.com", "https://Stackoverflow.com/users/436316/" ]
> > remains in tree-conflict > > > means that the directory has been merged and svn has found the directory is missing (or added) when it thinks it should/ shouldn't be. In short, its telling you that something is a big wrong and that you need to sort it out (resolve it) before continuing. You have to `svn resolve` the parent directory before you can do anything with that WC. (ok, you could `svn revert` is you prefer to start again) --- Tree conflicts are basically merges between 2 different directory trees that svn cannot fix by itself. This of a directory as a file with a list of files in it, if you delete lines from this file (eg delete directories) or add lines (add dirs) and then merge this 'file', and svn cannot perform the merge (eg as you've deleted and added the same dir on different merge targets) then it will tell you - by reporting a conflict. Its then up to you to fix things and tell svn you've fixed it.
To delete a directory under MARKT: ``` > cd MARKT > svn delete <dir1> > svn delete <dir2> > svn commit ``` To create a new directory under MARKT: ``` > mkdir <dir1> > mkdir <dir2> > svn add <dir1> > svn add <dir2> > svn commit ```
56,338,146
I came across a problem that in selecting the date for current desired month and year. I tried the 2 statements shown below but failed to execute the query ``` select to_char(sysdate, 'Month') from income select * from income where to_char(sysdate,month) = 'feb' ``` **Update** But after researching and learning more in depth on oracle docs website. What i came out with is to use "between" clause. Specifying the first day and last day of the month . Doing so, it will execute the desired month/year For an example ``` SELECT column_name FROM table_name where column_name = (Your own value) AND column_date >= to_date('01/02/2012', 'dd/mm/yyyy') and column_date < to_date('01/03/2012', 'dd/mm/yyyy') ``` I hope this help :)
2019/05/28
[ "https://Stackoverflow.com/questions/56338146", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2805507/" ]
Are you after something like: ``` select * from income where <date_column> >= to_date('01/05/2019', 'dd/mm/yyyy') and <date_column> < to_date('01/06/2019', 'dd/mm/yyyy') ``` (replacing `<date_column>` with the name of the date column in your income table that you want to filter on)?
I think you can use the following query: ``` select * from income where to_char(<date_column>,'MON-RRRR') = 'MAY-2019'; ```
56,338,146
I came across a problem that in selecting the date for current desired month and year. I tried the 2 statements shown below but failed to execute the query ``` select to_char(sysdate, 'Month') from income select * from income where to_char(sysdate,month) = 'feb' ``` **Update** But after researching and learning more in depth on oracle docs website. What i came out with is to use "between" clause. Specifying the first day and last day of the month . Doing so, it will execute the desired month/year For an example ``` SELECT column_name FROM table_name where column_name = (Your own value) AND column_date >= to_date('01/02/2012', 'dd/mm/yyyy') and column_date < to_date('01/03/2012', 'dd/mm/yyyy') ``` I hope this help :)
2019/05/28
[ "https://Stackoverflow.com/questions/56338146", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2805507/" ]
Are you after something like: ``` select * from income where <date_column> >= to_date('01/05/2019', 'dd/mm/yyyy') and <date_column> < to_date('01/06/2019', 'dd/mm/yyyy') ``` (replacing `<date_column>` with the name of the date column in your income table that you want to filter on)?
If you want to pass in a string like `'May 2012'`, then I would recommend: ``` select i.* from income i where i.datecol >= to_date('May 2012', 'Mon YYYY') and i.datecol < to_date('May 2012', 'Mon YYYY') + interval '1' month; ``` That said, I think your application should turn the string value into a date range and you should use that range in your query: ``` select i.* from income i where i.datecol >= :datestart i.datecol < :dateend + interval '1 day'; ``` I strong encourage you to avoid `between` with dates, particularly in Oracle. The `date` data type has a built-in time component, and that can throw off the comparisons.
39,829,518
I'm implementing a dynamic viewpager using an adapter that extends FragmentStatePagerAdapter. Every time my app goes to the background it crashes. with IndexOutOfBounds on ViewPager: Here's Adapter Code: ``` /** * Created by root on 3/11/15. */ public class FragmentAdapter extends FragmentStatePagerAdapter { private ArrayList<Fragment> mFragList = null; private ArrayList<String> mFragmentNameList = null; public FragmentAdapter(FragmentManager fm, ArrayList<Fragment> mFragList, ArrayList<String> fragmentNameList) { super(fm); this.mFragList = mFragList; this.mFragmentNameList = fragmentNameList; } @Override public Fragment getItem(int position) { if (!AppUtility.isNullOrEmpty(mFragList) && position < mFragList.size()) { return mFragList.get(position); } return null; } @Override public int getCount() { if (mFragList != null) { return mFragList.size(); } return 0; } @Override public CharSequence getPageTitle(int position) { return mFragmentNameList.get(position); } } ``` Here's Fragment Code: ``` public class PagerFragment extends BaseFragment { private final int MAX_PAGES = 4; private ViewPager mViewPager = null; private FragmentAdapter mFragmentAdapter = null; private ArrayList<Fragment> mFragList = new ArrayList<>(MAX_PAGES); private ArrayList<String> mFragmentNameList = new ArrayList<>(MAX_PAGES); private TabLayout mTabLayout = null; @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); initViewById(view); } public void initViewById(View view) { mViewPager = (ViewPager) view.findViewById(R.id.viewpager); mTabLayout = (TabLayout) view.findViewById(R.id.tabs); mFragList.add(new Fragment()); mFragList.add(new Fragment()); mFragList.add(new Fragment()); mFragList.add(new Fragment()); mFragmentNameList.add("Fragment1"); mFragmentNameList.add("Fragment2"); mFragmentNameList.add("Fragment3"); mFragmentNameList.add("Fragment4"); mFragmentAdapter = new FragmentAdapter(getFragmentManager(), mFragList, mFragmentNameList); mViewPager.setOffscreenPageLimit(2); mViewPager.setAdapter(mFragmentAdapter); mViewPager.setPageTransformer(true, new ZoomOutPageTransformer()); mTabLayout.setupWithViewPager(mViewPager); } } ``` It does not shows any line number for my classes but only for viewpager: Error Log: ``` FATAL EXCEPTION: main Process: com.android.myapp.ui, PID: 5897 java.lang.IndexOutOfBoundsException: Invalid index 5, size is 3 at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255) at java.util.ArrayList.get(ArrayList.java:308) at android.support.v4.view.ViewPager.getChildDrawingOrder(ViewPager.java:800) at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3396) at android.view.View.draw(View.java:16384) at android.support.v4.view.ViewPager.draw(ViewPager.java:2415) at android.view.View.updateDisplayListIfDirty(View.java:15378) at android.view.View.draw(View.java:16151) at android.view.ViewGroup.drawChild(ViewGroup.java:3610) at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3400) at android.view.View.updateDisplayListIfDirty(View.java:15373) at android.view.View.draw(View.java:16151) at android.view.ViewGroup.drawChild(ViewGroup.java:3610) at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3400) at android.view.View.draw(View.java:16384) at android.view.View.updateDisplayListIfDirty(View.java:15378) at android.view.View.draw(View.java:16151) at android.view.ViewGroup.drawChild(ViewGroup.java:3610) at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3400) at android.view.View.draw(View.java:16384) at android.view.View.updateDisplayListIfDirty(View.java:15378) at android.view.View.draw(View.java:16151) at android.view.ViewGroup.drawChild(ViewGroup.java:3610) at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3400) at android.view.View.updateDisplayListIfDirty(View.java:15373) at android.view.View.draw(View.java:16151) at android.view.ViewGroup.drawChild(ViewGroup.java:3610) at android.support.v4.widget.DrawerLayout.drawChild(DrawerLayout.java:1383) at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3400) at android.view.View.draw(View.java:16384) at android.view.View.updateDisplayListIfDirty(View.java:15378) at android.view.View.draw(View.java:16151) at android.view.ViewGroup.drawChild(ViewGroup.java:3610) at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3400) at android.view.View.updateDisplayListIfDirty(View.java:15373) at android.view.View.draw(View.java:16151) at android.view.ViewGroup.drawChild(ViewGroup.java:3610) at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3400) at android.view.View.updateDisplayListIfDirty(View.java:15373) at android.view.View.draw(View.java:16151) at android.view.ViewGroup.drawChild(ViewGroup.java:3610) at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3400) at android.view.View.updateDisplayListIfDirty(View.java:15373) at android.view.View.draw(View.java:16151) at android.view.ViewGroup.drawChild(ViewGroup.java:3610) at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3400) at android.view.View.updateDisplayListIfDirty(View.java:15373) at android.view.View.draw(View.java:16151) at android.view.ViewGroup.drawChild(ViewGroup.java:3610) at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3400) at android.view.View.draw(View.java:16384) at com.android.internal.policy.PhoneWindow$DecorView.draw(PhoneWindow.java:2692) at android.view.View.updateDisplayListIfDirty(View.java:15378) at android.view.ThreadedRenderer.updateViewTreeDisplayList(ThreadedRenderer.java:281) at android.view.ThreadedRenderer.updateRootDisplayList(ThreadedRenderer.java:287) at android.view.ThreadedRenderer.draw(ThreadedRenderer.java:322) at android.view.ViewRootImpl.draw(ViewRootImpl.java:2928) at android.view.ViewRootImpl.performDraw(ViewRootImpl.java:2740) at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2358) at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1233) at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6549) at android.view.Choreographer$CallbackRecord.run(Choreographer.java:919) at android.view.Choreographer.doCallbacks(Choreographer.java:710) at android.view.Choreographer.doFrame(Choreographer.java:645) at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:905) at android.os.Han ```
2016/10/03
[ "https://Stackoverflow.com/questions/39829518", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3500742/" ]
Ok i found out the solution, basically the issue was not in the adapter at all, i was putting my viewPager inside of a fragment,for which adapter needs refrence of getChildfragmentManager() instead of getFragmentManager(); I changed the ``` mFragmentAdapter = new FragmentAdapter(getFragmentManager(), mFragList, mFragmentNameList); to mFragmentAdapter = new FragmentAdapter(getChildFragmenManager(), mFragList, mFragmentNameList); ``` and Volla it worked.
Try to use Android debugger to get know at which line it gets crash when app go to background and then let us know . Try to do something in onPause()
197,536
Set 50 years in the future. A supermax or super maximum security prison is a lockup facility to hold dangerous criminals, most of them are being sentenced for at least 1000 years of life imprisonment without parole. Recently in the news there is a plan to convert our moon into a supermax by converting it into a hollow sphere with it's interior filled with just cells and the inmates, the idea is to place them in complete isolation and also to act as a deterrence... most importantly it helps to solve overcrowding issues here on Earth ;D Anyway there will be a space port and a small lunar base for the security personnel on shift on the Moon, the interior of the moon is partitioned up so each and every 2 cubic meters quarter can hold 1 inmate. Everything goes according to plan until the human rights group issued an ultimatum; give them at least 1g or shut down the entire facility! I'm wondering how can I replicate gravitational acceleration of minimum 9.81 meters per second per second for all the occupants? The authority and banks cannot loan us any more money and has blocked our crowdfunding websites so there is a budget constraint, in other words we are left with no investor and only 20 millions USD in cash flow to get it done!
2021/03/10
[ "https://worldbuilding.stackexchange.com/questions/197536", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/8400/" ]
**Spin doesn't work for me** Spin creates artificial gravity, true. But the complexity is a mess. To keep every cell at 1G... * The floor of every cell must be oriented away the axis of rotation, which I'll assume is the lunar polar axis. Remember that the moon does rotate, it just rotates to keep the same face toward Earth (time to rotate once = time to orbit once). * From the north pole to the south pole you'd need floors, like the floors in a building. And each floor is rotating at its own speed because the rotation needed for 1G at the equator is different than the rotation needed at the poles. * From the near-surface outer ring to the core of the moon you also need floors — a series of concentric rings. And the rings near the center of the moon must spin a lot faster than the rings near the surface to generate the same G. OK! Now we have independent floors north-to-south and rings surface-to-core, and every slice of the onion is spinning at a different speed to maintain 1G. * Which means the moon just became a whomping big gyroscope doing heaven only knows what — but I'm sure it'll screw up the moon's orbit. Nope, I can't prove it. But I'm sure of it. * And to make things worse, you can kinda move along the polar axis (at or near zero-G!) so long as you figure out how to spin like a top slower and slower as you descend from a pole to the center. But it's a bit harder from the surface to the core, where you'd need something like a long pair of slots at each ring with a "horizontal elevator" in each slot that could move to accelerate or decelerate into the appropriate ring. That's awfully complex and, like I said, I think the moon would have a tough go with it. **Magnetics?** But, what if every inmate is required to wear clothing with a magnetic micro-mesh? It's not the same as gravity, but it might be close enough. This also has complexities because rather than pushing against the floor you're really pushing against your clothing. Make it a skin-tight suit (popular in sci-fi, right?) and it might even be believable. However, while this might benefit arm & leg muscles, etc. It wouldn't do anything for your heart or circulatory system, which would atrophy in the reduced gravity. And you might have enough magnetism to interfere with the Van Allen Radiation Belts... So... maybe not magnetics. **What if we spin the cells independently?** OK, let's get back to spinning for a sec. Let's assume the infrastructure of the prison doesn't move at all. Only the individual cells spin. Each cell could be oriented to spin to preserve lunar inertia. But we wouldn't be talking about your average 10x10 style cell here, because that wouldn't be a whole lot different from taking a ride in a clothes dryer (we've all done that, right?). So your cells are fairly large, suites really, to ensure a smooth spin. OK, this is yucky, too. The mechanics behind that are almost worse than just spinning on the lunar axis. And I don't even want to think about getting food to the inmates without having to spin down the cells to do it. Ugh. **OK, how about a bit of technobabble?** Let's invent gravity plating. Electromagnetically controlled density that simulates mass and, therefore, gravity... Or maybe you've brought in neutron star material to make the floor plates. It's pure fiction, but it also has a problem. The gravity at the center of a sphere is zero — and we just made it non-zero thanks to the gravity plating. In fact, keeping all those inmates at 1G would raise the "apparent mass" of the moon to something that, well, in an outrageous XKCD kind of way, might make it implode into a micro black hole. **Which brings up the real point of my answer, call this the TL;DR part** You can't do it. It's not an issue of finding a way to achieve it. You obviously can spin the cells in a way to get the artificial gravity. It's the *consequences* that are the problem. You're dealing with a scale where even the smallest forces are a really big deal. Just the heat generated from all that spinning would proverbially ignite the surface of the moon like a second sun. Any energy-type-thing you add to reduce the heat (like magnets rather than bearings and a perfect vacuum) cause problems (like ripping out the fillings from people's teeth and causing the moon to implode from the vacuum force). And then there's the need to discharge enough static electricity to power every household on Earth. All those rotating floors and rings... it's a giant generator. Even if the infrastructure is non-metalic/non-magnetic, you still have a bazillion miles of wire for lights, heating, etc. everywhere... all spinning at different speeds.... All of which would be detectable by the aliens from who knows how many parsecs away.... And they think imprisonment is barbaric. And they just noticed why you're lit up like an intergalactic Christmas tree with crazy EM radiation, heat, and gravity. I can't think of a solution that doesn't have massive consequences that would result in a high-quality Hollywood disaster movie. It was fun to think about... but wouldn't freezing them for their sentences be easier?
### Spin them. You want to spin their cells around such that the moons gravity (down) plus the spin centrifugal force (outwards) adds up to one G (diagonally down and outwards ish). Yes this results in a tilted cell cell if gravity needs to be normal to the floor. We can build ramps so this should be a non issue. You would want to do a whole group of cells together rather than spin each individual block, as a strong gravity gradient would be disorienting, and the noise from a machine that close to your cell would be quite loud. Plus this way each cell only needs a tilted floor, rather than trying to curve a cell floor. However were I in this prison and with zero hope for release back on earth id elect to be kept in 1/6th g - as far as we know the human body still works fine in those gravity levels, movement is 6 times easier, the mattress is 6 times softer, etc.
197,536
Set 50 years in the future. A supermax or super maximum security prison is a lockup facility to hold dangerous criminals, most of them are being sentenced for at least 1000 years of life imprisonment without parole. Recently in the news there is a plan to convert our moon into a supermax by converting it into a hollow sphere with it's interior filled with just cells and the inmates, the idea is to place them in complete isolation and also to act as a deterrence... most importantly it helps to solve overcrowding issues here on Earth ;D Anyway there will be a space port and a small lunar base for the security personnel on shift on the Moon, the interior of the moon is partitioned up so each and every 2 cubic meters quarter can hold 1 inmate. Everything goes according to plan until the human rights group issued an ultimatum; give them at least 1g or shut down the entire facility! I'm wondering how can I replicate gravitational acceleration of minimum 9.81 meters per second per second for all the occupants? The authority and banks cannot loan us any more money and has blocked our crowdfunding websites so there is a budget constraint, in other words we are left with no investor and only 20 millions USD in cash flow to get it done!
2021/03/10
[ "https://worldbuilding.stackexchange.com/questions/197536", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/8400/" ]
**Spin doesn't work for me** Spin creates artificial gravity, true. But the complexity is a mess. To keep every cell at 1G... * The floor of every cell must be oriented away the axis of rotation, which I'll assume is the lunar polar axis. Remember that the moon does rotate, it just rotates to keep the same face toward Earth (time to rotate once = time to orbit once). * From the north pole to the south pole you'd need floors, like the floors in a building. And each floor is rotating at its own speed because the rotation needed for 1G at the equator is different than the rotation needed at the poles. * From the near-surface outer ring to the core of the moon you also need floors — a series of concentric rings. And the rings near the center of the moon must spin a lot faster than the rings near the surface to generate the same G. OK! Now we have independent floors north-to-south and rings surface-to-core, and every slice of the onion is spinning at a different speed to maintain 1G. * Which means the moon just became a whomping big gyroscope doing heaven only knows what — but I'm sure it'll screw up the moon's orbit. Nope, I can't prove it. But I'm sure of it. * And to make things worse, you can kinda move along the polar axis (at or near zero-G!) so long as you figure out how to spin like a top slower and slower as you descend from a pole to the center. But it's a bit harder from the surface to the core, where you'd need something like a long pair of slots at each ring with a "horizontal elevator" in each slot that could move to accelerate or decelerate into the appropriate ring. That's awfully complex and, like I said, I think the moon would have a tough go with it. **Magnetics?** But, what if every inmate is required to wear clothing with a magnetic micro-mesh? It's not the same as gravity, but it might be close enough. This also has complexities because rather than pushing against the floor you're really pushing against your clothing. Make it a skin-tight suit (popular in sci-fi, right?) and it might even be believable. However, while this might benefit arm & leg muscles, etc. It wouldn't do anything for your heart or circulatory system, which would atrophy in the reduced gravity. And you might have enough magnetism to interfere with the Van Allen Radiation Belts... So... maybe not magnetics. **What if we spin the cells independently?** OK, let's get back to spinning for a sec. Let's assume the infrastructure of the prison doesn't move at all. Only the individual cells spin. Each cell could be oriented to spin to preserve lunar inertia. But we wouldn't be talking about your average 10x10 style cell here, because that wouldn't be a whole lot different from taking a ride in a clothes dryer (we've all done that, right?). So your cells are fairly large, suites really, to ensure a smooth spin. OK, this is yucky, too. The mechanics behind that are almost worse than just spinning on the lunar axis. And I don't even want to think about getting food to the inmates without having to spin down the cells to do it. Ugh. **OK, how about a bit of technobabble?** Let's invent gravity plating. Electromagnetically controlled density that simulates mass and, therefore, gravity... Or maybe you've brought in neutron star material to make the floor plates. It's pure fiction, but it also has a problem. The gravity at the center of a sphere is zero — and we just made it non-zero thanks to the gravity plating. In fact, keeping all those inmates at 1G would raise the "apparent mass" of the moon to something that, well, in an outrageous XKCD kind of way, might make it implode into a micro black hole. **Which brings up the real point of my answer, call this the TL;DR part** You can't do it. It's not an issue of finding a way to achieve it. You obviously can spin the cells in a way to get the artificial gravity. It's the *consequences* that are the problem. You're dealing with a scale where even the smallest forces are a really big deal. Just the heat generated from all that spinning would proverbially ignite the surface of the moon like a second sun. Any energy-type-thing you add to reduce the heat (like magnets rather than bearings and a perfect vacuum) cause problems (like ripping out the fillings from people's teeth and causing the moon to implode from the vacuum force). And then there's the need to discharge enough static electricity to power every household on Earth. All those rotating floors and rings... it's a giant generator. Even if the infrastructure is non-metalic/non-magnetic, you still have a bazillion miles of wire for lights, heating, etc. everywhere... all spinning at different speeds.... All of which would be detectable by the aliens from who knows how many parsecs away.... And they think imprisonment is barbaric. And they just noticed why you're lit up like an intergalactic Christmas tree with crazy EM radiation, heat, and gravity. I can't think of a solution that doesn't have massive consequences that would result in a high-quality Hollywood disaster movie. It was fun to think about... but wouldn't freezing them for their sentences be easier?
Use lead garments. Each inmate will wear 5 times his/her/their own weight and you will claim the problem solved. After all, it does provide some excercise and is not like they will ever return. And the human rights organizations will be satisfied, since they do not *really* care, as the other conditions pretty much equal to torture anyway - $2 m^3$ per person is a cubicle $1m\times 1m\times 2m$, quite a coffin...
32,873,276
I have an SQL database that I have to store date and time in the records. I am making a project on Visual Studio and I'm using 2 datetime picker controls to prompt for date and time respectively. I want to know what kind of variable (or class) I should use to store the time and date so that I can store it in the single datetime record in my database.
2015/09/30
[ "https://Stackoverflow.com/questions/32873276", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5394481/" ]
C# has the DateTime type and TimeSpan for this. TimeSpan is not always the best choice and in many cases its better to just use a DateTime and ignore the date part. The DateTime Class in C# has a .Date for extracting just the date component and a .Time For the Time part (returning a TimeSpan class) In SQL you can use DATE and TIME or DATETIME. You can save a C# DateTime into a DATE,TIME or DATETIME (loosing the part you don't need) In summary I would suggest using a C# DateTime for the Date and a TimeSpan for the time. And Saving them into SQL as a DATE and a TIME. But you will need to be carefull with TimeSpan as the TimeSpan Is not 100% comparable with SQLs TIME. A TimeSpan in C# can be for more then one day but a time TIME in SQL can only be for one 24 hour period. Lastly if you have already chosen to use a DATETIME in SQL then why dont you just use a DateTime in C# you can merge the Date And Time thet you get from the UI into one DateTime and just save that in an SQL DATETIME.
Try this : ``` DateTime myDateTime = DateTime.Now; string sqlFormattedDate = myDateTime.ToString("yyyy-MM-dd HH:mm:ss"); ``` Or for more details : [Similar StackOverFlow Question](https://stackoverflow.com/questions/17418258/datetime-format-to-sql-format-using-c-sharp) with a very good solution or [Click here](https://www.google.co.in/search?q=DateTime%20C%23%20to%20sql) to get all solutions for this problem
7,382,466
I have data stored in a session with **Zend\_Session\_Namespace**, Is it possible to recover this session data from another host using an id or something like that. If not, is it possible to recover the data in a **$\_SESSION** from another host?
2011/09/12
[ "https://Stackoverflow.com/questions/7382466", "https://Stackoverflow.com", "https://Stackoverflow.com/users/598932/" ]
Here you have your code modified and working. It is not optimal, it does not take into account the presence of more or less comments in the header and there is not exception handling but it is a start. ``` import sys import numpy as np RGBS = range(16, 255, 16) CHARS = [' ', '.', ',', ':', ';', '+', '=', 'o', 'a', 'e', '0', '$', '@', 'A', '#'] FACTORS = [.3, .59, .11] def main(filename): image = open(filename) #reads header lines color = image.readline() _ = image.readline() size_width, size_height = image.readline().split() max_color = image.readline() size_width = int(size_width) max_color = int(max_color) #reads the body of the file data = [int(p) for p in image.read().split()] #converts to array and reshape data = np.array(data) pixels = data.reshape((len(data)/3, 3)) #calculate rgb value per pixel rgbs = pixels * FACTORS sum_rgbs = rgbs.sum(axis=1) rgb_values = [item * 255 / max_color for item in sum_rgbs] grayscales = [] #pulls out the value of each pixel and coverts it to its grayscale value for indx, rgb_val in enumerate(rgb_values): #if max width, new line if (indx % size_width) == 0 : grayscales.append('\n') for achar, rgb in zip(CHARS, RGBS): if rgb_val <= rgb: character = achar break else: character = 'M' grayscales.append(character) print ''.join(grayscales) main('test.ppm') ``` These are the ppm figure and the ASCII Art result ![enter image description here](https://i.stack.imgur.com/5pEiB.png) And the micro ppm file I used for the example: ``` P3 # test.ppm 4 4 15 0 0 0 0 0 0 0 0 0 15 0 15 0 0 0 0 15 7 0 0 0 0 0 0 0 0 0 0 0 0 0 15 7 0 0 0 15 0 15 0 0 0 0 0 0 0 0 0 ```
I wrote one of these in C# a while ago and I calculated the character to use with this formula: ``` index_into_array = (int)(r_g_b_value * (chars_array_length / (255.0))); ``` As for the width and height, you could average every two lines of vertical pixels to halve the height. Edit 1: in response to comment: The basic idea is that it scales your RGB value from 0 to 255 to 0 to the length of the array and uses that as the index. Edit 2: Updated to correct that I was ignoring your grayscale normalization.
7,382,466
I have data stored in a session with **Zend\_Session\_Namespace**, Is it possible to recover this session data from another host using an id or something like that. If not, is it possible to recover the data in a **$\_SESSION** from another host?
2011/09/12
[ "https://Stackoverflow.com/questions/7382466", "https://Stackoverflow.com", "https://Stackoverflow.com/users/598932/" ]
You can use [`image-to-ansi.py`](https://gist.github.com/1687427) for the conversion. First, download `image-to-ansi.py`: ``` wget https://gist.githubusercontent.com/klange/1687427/raw/image-to-ansi.py ``` Save this script as `ppmimage.py`: ``` # Parses a PPM file and loads it into image-to-ansi.py import re, itertools sep = re.compile("[ \t\r\n]+") def chunks(iterable,size): """ http://stackoverflow.com/a/434314/309483 """ it = iter(iterable) chunk = tuple(itertools.islice(it,size)) while chunk: yield chunk chunk = tuple(itertools.islice(it,size)) """ Emulates the Image class from PIL and some member functions (`getpixel`, `size`). """ class Image: """ This class emulates the PIL Image class, and it can parse "plain" PPM's. You can use PIL instead. """ @staticmethod def fromstdin(): return Image() def __init__(self): # http://netpbm.sourceforge.net/doc/ppm.html self.entities = sep.split("\n".join(list(filter(lambda x: not x.startswith("#"), sys.stdin.read().strip().split("\n"))))) self.size = tuple(list(map(int,self.entities[1:3]))) self.high = int(self.entities[3]) # z.b. 255 self.pixels = list(map(lambda x: tuple(map(lambda y: int(int(y) / self.high * 255), x)), list(chunks(self.entities[4:], 3)))) def getpixel(self, tupl): x = tupl[0] y = tupl[1] pix = self.pixels[y*self.size[0]+x] return pix image_to_ansi = __import__("image-to-ansi") # __import__ because of minuses in filename. From https://gist.github.com/1687427 if __name__ == '__main__': import sys #import Image im = Image.fromstdin() # use Image.open from PIL if using PIL for y in range(im.size[1]): for x in range(im.size[0]): p = im.getpixel((x,y)) h = "%2x%2x%2x" % (p[0],p[1],p[2]) short, rgb = image_to_ansi.rgb2short(h) sys.stdout.write("\033[48;5;%sm " % short) sys.stdout.write("\033[0m\n") sys.stdout.write("\n") ``` You can test the script like this (this assumes you have `netpbm` and `imagemagick` installed): `convert -resize $(($COLUMNS*2))x$(($LINES*2)) logo: pnm:- | pnmtoplainpnm | python3 ppmimage.py` On my machine, it looks like this: ![ImageMagick logo shown in Xterm](https://i.stack.imgur.com/AcVCO.png)
I wrote one of these in C# a while ago and I calculated the character to use with this formula: ``` index_into_array = (int)(r_g_b_value * (chars_array_length / (255.0))); ``` As for the width and height, you could average every two lines of vertical pixels to halve the height. Edit 1: in response to comment: The basic idea is that it scales your RGB value from 0 to 255 to 0 to the length of the array and uses that as the index. Edit 2: Updated to correct that I was ignoring your grayscale normalization.
7,382,466
I have data stored in a session with **Zend\_Session\_Namespace**, Is it possible to recover this session data from another host using an id or something like that. If not, is it possible to recover the data in a **$\_SESSION** from another host?
2011/09/12
[ "https://Stackoverflow.com/questions/7382466", "https://Stackoverflow.com", "https://Stackoverflow.com/users/598932/" ]
You can use [`image-to-ansi.py`](https://gist.github.com/1687427) for the conversion. First, download `image-to-ansi.py`: ``` wget https://gist.githubusercontent.com/klange/1687427/raw/image-to-ansi.py ``` Save this script as `ppmimage.py`: ``` # Parses a PPM file and loads it into image-to-ansi.py import re, itertools sep = re.compile("[ \t\r\n]+") def chunks(iterable,size): """ http://stackoverflow.com/a/434314/309483 """ it = iter(iterable) chunk = tuple(itertools.islice(it,size)) while chunk: yield chunk chunk = tuple(itertools.islice(it,size)) """ Emulates the Image class from PIL and some member functions (`getpixel`, `size`). """ class Image: """ This class emulates the PIL Image class, and it can parse "plain" PPM's. You can use PIL instead. """ @staticmethod def fromstdin(): return Image() def __init__(self): # http://netpbm.sourceforge.net/doc/ppm.html self.entities = sep.split("\n".join(list(filter(lambda x: not x.startswith("#"), sys.stdin.read().strip().split("\n"))))) self.size = tuple(list(map(int,self.entities[1:3]))) self.high = int(self.entities[3]) # z.b. 255 self.pixels = list(map(lambda x: tuple(map(lambda y: int(int(y) / self.high * 255), x)), list(chunks(self.entities[4:], 3)))) def getpixel(self, tupl): x = tupl[0] y = tupl[1] pix = self.pixels[y*self.size[0]+x] return pix image_to_ansi = __import__("image-to-ansi") # __import__ because of minuses in filename. From https://gist.github.com/1687427 if __name__ == '__main__': import sys #import Image im = Image.fromstdin() # use Image.open from PIL if using PIL for y in range(im.size[1]): for x in range(im.size[0]): p = im.getpixel((x,y)) h = "%2x%2x%2x" % (p[0],p[1],p[2]) short, rgb = image_to_ansi.rgb2short(h) sys.stdout.write("\033[48;5;%sm " % short) sys.stdout.write("\033[0m\n") sys.stdout.write("\n") ``` You can test the script like this (this assumes you have `netpbm` and `imagemagick` installed): `convert -resize $(($COLUMNS*2))x$(($LINES*2)) logo: pnm:- | pnmtoplainpnm | python3 ppmimage.py` On my machine, it looks like this: ![ImageMagick logo shown in Xterm](https://i.stack.imgur.com/AcVCO.png)
Here you have your code modified and working. It is not optimal, it does not take into account the presence of more or less comments in the header and there is not exception handling but it is a start. ``` import sys import numpy as np RGBS = range(16, 255, 16) CHARS = [' ', '.', ',', ':', ';', '+', '=', 'o', 'a', 'e', '0', '$', '@', 'A', '#'] FACTORS = [.3, .59, .11] def main(filename): image = open(filename) #reads header lines color = image.readline() _ = image.readline() size_width, size_height = image.readline().split() max_color = image.readline() size_width = int(size_width) max_color = int(max_color) #reads the body of the file data = [int(p) for p in image.read().split()] #converts to array and reshape data = np.array(data) pixels = data.reshape((len(data)/3, 3)) #calculate rgb value per pixel rgbs = pixels * FACTORS sum_rgbs = rgbs.sum(axis=1) rgb_values = [item * 255 / max_color for item in sum_rgbs] grayscales = [] #pulls out the value of each pixel and coverts it to its grayscale value for indx, rgb_val in enumerate(rgb_values): #if max width, new line if (indx % size_width) == 0 : grayscales.append('\n') for achar, rgb in zip(CHARS, RGBS): if rgb_val <= rgb: character = achar break else: character = 'M' grayscales.append(character) print ''.join(grayscales) main('test.ppm') ``` These are the ppm figure and the ASCII Art result ![enter image description here](https://i.stack.imgur.com/5pEiB.png) And the micro ppm file I used for the example: ``` P3 # test.ppm 4 4 15 0 0 0 0 0 0 0 0 0 15 0 15 0 0 0 0 15 7 0 0 0 0 0 0 0 0 0 0 0 0 0 15 7 0 0 0 15 0 15 0 0 0 0 0 0 0 0 0 ```
8,418,628
I have a .txt file with lines (in my situation 2). I need to read lines and convert each to a different Array. Ex: 1 line - A,B,C 2 line - D,E,F,G, etc. and convert this to: [A,B,C] [D,E,F,G] I'm doing this with String.split(", ") ``` ArrayList<String> al_1 = new ArrayList<String>(); ArrayList<String> al_2 = new ArrayList<String>(); while(true){ String[] line = rbuff.readLine().split(","); for(String i : line){ al_1.add(i); } if(line == null) break; } ``` What's the best way to fill the second? Thx.
2011/12/07
[ "https://Stackoverflow.com/questions/8418628", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1078381/" ]
Maybe you must use ``` ArrayList<ArrayList<String>> al = new ArrayList<ArrayList<String>>(); ``` instead of ``` ArrayList<String> al_1 = new ArrayList<String>(); ArrayList<String> al_2 = new ArrayList<String>(); ``` and fullfill this list with **al.add()**
IMO easier to keep a list of lists. ``` List<List<String>> lineLists = new ArrayList<List<String>>(); while (true) { List<String> lineList = new ArrayList<String>(); String[] line = rbuff.readLine().split(","); for (String i : line) { lineList.add(i); } lineLists.add(lineList); if (line == null) break; } ``` (Ignoring that there are any number of ways to split immediately into an array or list w/o the inner loop. Either way, the inner loop should be refactored.)
8,418,628
I have a .txt file with lines (in my situation 2). I need to read lines and convert each to a different Array. Ex: 1 line - A,B,C 2 line - D,E,F,G, etc. and convert this to: [A,B,C] [D,E,F,G] I'm doing this with String.split(", ") ``` ArrayList<String> al_1 = new ArrayList<String>(); ArrayList<String> al_2 = new ArrayList<String>(); while(true){ String[] line = rbuff.readLine().split(","); for(String i : line){ al_1.add(i); } if(line == null) break; } ``` What's the best way to fill the second? Thx.
2011/12/07
[ "https://Stackoverflow.com/questions/8418628", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1078381/" ]
Maybe you must use ``` ArrayList<ArrayList<String>> al = new ArrayList<ArrayList<String>>(); ``` instead of ``` ArrayList<String> al_1 = new ArrayList<String>(); ArrayList<String> al_2 = new ArrayList<String>(); ``` and fullfill this list with **al.add()**
This solution will allow you to add a new ArrayList to the myArrayList for each row your read of your file: ``` List<List<String>> myArrayList = new ArrayList<List<String>>(); List<String> myStrings; while (true) { myStrings = new ArrayList<String>(); String[] line = rbuff.readLine().split(","); for (String i : line) { myStrings.add(i); } myArrayList.add(myStrings); if (line == null) break; } ``` You will have a List with one List inside for each row of your text file. ``` MyArrayList | |_____List('A', 'B', 'C') | |_____List('D', 'E', 'F', 'G') | |_____(...) ```
8,418,628
I have a .txt file with lines (in my situation 2). I need to read lines and convert each to a different Array. Ex: 1 line - A,B,C 2 line - D,E,F,G, etc. and convert this to: [A,B,C] [D,E,F,G] I'm doing this with String.split(", ") ``` ArrayList<String> al_1 = new ArrayList<String>(); ArrayList<String> al_2 = new ArrayList<String>(); while(true){ String[] line = rbuff.readLine().split(","); for(String i : line){ al_1.add(i); } if(line == null) break; } ``` What's the best way to fill the second? Thx.
2011/12/07
[ "https://Stackoverflow.com/questions/8418628", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1078381/" ]
Maybe you must use ``` ArrayList<ArrayList<String>> al = new ArrayList<ArrayList<String>>(); ``` instead of ``` ArrayList<String> al_1 = new ArrayList<String>(); ArrayList<String> al_2 = new ArrayList<String>(); ``` and fullfill this list with **al.add()**
Well that's pretty much what I'd do, but with the mention that if you don't need your lines to inside ArrayList objects, you can use array Strings (String[]). Here's an example: ``` private static String s1 = "A,B,C",s2="D,E,F"; private static List<String> lines = new ArrayList<String>(){{add(s1);add(s2);}}; public static void main(String[] args) throws Throwable { Map<Integer,String[]> linesToArraysMap = new HashMap<Integer,String[]>(); for(int i=1;i<=lines.size();i++) { linesToArraysMap.put(i, lines.get(i-1).split(",")); //if you want to get them as ArrayLists you can do: //List<String> lineList = Arrays.asList(lines.get(i-1).split(",")); } for(String[] stringArr:linesToArraysMap.values()) { System.out.println(Arrays.toString(stringArr)); } } ```
8,418,628
I have a .txt file with lines (in my situation 2). I need to read lines and convert each to a different Array. Ex: 1 line - A,B,C 2 line - D,E,F,G, etc. and convert this to: [A,B,C] [D,E,F,G] I'm doing this with String.split(", ") ``` ArrayList<String> al_1 = new ArrayList<String>(); ArrayList<String> al_2 = new ArrayList<String>(); while(true){ String[] line = rbuff.readLine().split(","); for(String i : line){ al_1.add(i); } if(line == null) break; } ``` What's the best way to fill the second? Thx.
2011/12/07
[ "https://Stackoverflow.com/questions/8418628", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1078381/" ]
IMO easier to keep a list of lists. ``` List<List<String>> lineLists = new ArrayList<List<String>>(); while (true) { List<String> lineList = new ArrayList<String>(); String[] line = rbuff.readLine().split(","); for (String i : line) { lineList.add(i); } lineLists.add(lineList); if (line == null) break; } ``` (Ignoring that there are any number of ways to split immediately into an array or list w/o the inner loop. Either way, the inner loop should be refactored.)
This solution will allow you to add a new ArrayList to the myArrayList for each row your read of your file: ``` List<List<String>> myArrayList = new ArrayList<List<String>>(); List<String> myStrings; while (true) { myStrings = new ArrayList<String>(); String[] line = rbuff.readLine().split(","); for (String i : line) { myStrings.add(i); } myArrayList.add(myStrings); if (line == null) break; } ``` You will have a List with one List inside for each row of your text file. ``` MyArrayList | |_____List('A', 'B', 'C') | |_____List('D', 'E', 'F', 'G') | |_____(...) ```
8,418,628
I have a .txt file with lines (in my situation 2). I need to read lines and convert each to a different Array. Ex: 1 line - A,B,C 2 line - D,E,F,G, etc. and convert this to: [A,B,C] [D,E,F,G] I'm doing this with String.split(", ") ``` ArrayList<String> al_1 = new ArrayList<String>(); ArrayList<String> al_2 = new ArrayList<String>(); while(true){ String[] line = rbuff.readLine().split(","); for(String i : line){ al_1.add(i); } if(line == null) break; } ``` What's the best way to fill the second? Thx.
2011/12/07
[ "https://Stackoverflow.com/questions/8418628", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1078381/" ]
IMO easier to keep a list of lists. ``` List<List<String>> lineLists = new ArrayList<List<String>>(); while (true) { List<String> lineList = new ArrayList<String>(); String[] line = rbuff.readLine().split(","); for (String i : line) { lineList.add(i); } lineLists.add(lineList); if (line == null) break; } ``` (Ignoring that there are any number of ways to split immediately into an array or list w/o the inner loop. Either way, the inner loop should be refactored.)
Well that's pretty much what I'd do, but with the mention that if you don't need your lines to inside ArrayList objects, you can use array Strings (String[]). Here's an example: ``` private static String s1 = "A,B,C",s2="D,E,F"; private static List<String> lines = new ArrayList<String>(){{add(s1);add(s2);}}; public static void main(String[] args) throws Throwable { Map<Integer,String[]> linesToArraysMap = new HashMap<Integer,String[]>(); for(int i=1;i<=lines.size();i++) { linesToArraysMap.put(i, lines.get(i-1).split(",")); //if you want to get them as ArrayLists you can do: //List<String> lineList = Arrays.asList(lines.get(i-1).split(",")); } for(String[] stringArr:linesToArraysMap.values()) { System.out.println(Arrays.toString(stringArr)); } } ```
11,865,042
maybe you guys can help me figure this out: I have a Dictionary and an ItemsControl that is binded to that dictionary. The Key of each entry determines the content of each Item in the ItemsControl and the Value determines the width of each Item. The big problem with this: The width is a percentage value, so it tells me that, for example, my Item needs to be 20% of its parent in size. How can I achieve this? I know Grids are able to work with star-based widths, but since I have to define the GridDefinition at the beginning of the Grid I cannot do this in the ItemsControl.ItemTemplate. Current code: ``` <ItemsControl ItemsSource="{Binding Distribution}" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"> <ItemsControl.ItemsPanel> <ItemsPanelTemplate> <Grid IsItemsHost="True" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" /> </ItemsPanelTemplate> </ItemsControl.ItemsPanel> <ItemsControl.ItemTemplate> <DataTemplate> <!-- I NEED THIS TO BE A CERTAIN PERCENTAGE IN WIDTH --> <Label Content="{Binding Key.Text}" Foreground="{Binding Key.Color}"/> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl> ``` Any ideas on this? Is there any elegant way to solve this? Thanks! *Clarifications*: The percentage is supposed to be based on the ItemControls parent! *And another one*: Each item is supposed to be one column of the grid, not a row. So I need all the items to be next to each other in the same row. **The solution**: Thanks for your help, this problem can be solved by using Multibinding and Binding to the ActualWidth of the ItemsControl. This way, whenever the ItemsControl changes in size, the Items change as well. A Grid is not needed. This solution only creates a relative width, but the same solution can of course be applied to the height of the items. This is a short version, for a more thorough explanation see down below: *XAML*: ``` <ItemsControl ItemsSource="{Binding Distribution}" Name="itemsControl" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"> <ItemsControl.ItemsPanel> <ItemsPanelTemplate> <StackPanel IsItemsHost="True" Orientation="Horizontal" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" /> </ItemsPanelTemplate> </ItemsControl.ItemsPanel> <ItemsControl.ItemTemplate> <DataTemplate> <Label Content="{Binding Key.Text}" Foreground="{Binding Key.Color}"> <Label.Width> <MultiBinding Converter="{StaticResource myConverter}"> <Binding Path="Value"/> <Binding Path="ActualWidth" ElementName="itemsControl"/> </MultiBinding> </Label.Width> </Label> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl> ``` *Converter*: ``` class MyConverter : IMultiValueConverter { public object Convert(object[] value, Type targetType, object parameter, CultureInfo culture) { //[1] contains the ItemsControl.ActualWidth we binded to, [0] the percentage //In this case, I assume the percentage is a double between 0 and 1 return (double)value[1] * (double)value[0]; } public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } ``` And that should do the trick!
2012/08/08
[ "https://Stackoverflow.com/questions/11865042", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1421550/" ]
~~You can implement `IValueConverter`~~. **UPDATE**. `MultiBinding` will help you. Here's the sample: 1) xaml: ``` <Window x:Class="WpfApplication1.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:WpfApplication1" Title="MainWindow" Height="114" Width="404"> <Grid> <Grid.Resources> <local:RelativeWidthConverter x:Key="RelativeWidthConverter"/> </Grid.Resources> <Grid.ColumnDefinitions> <ColumnDefinition Width="*"/> </Grid.ColumnDefinitions> <ItemsControl ItemsSource="{Binding}" x:Name="itemsControl"> <ItemsControl.ItemTemplate> <DataTemplate> <Rectangle Fill="Green" Margin="5" Height="20" HorizontalAlignment="Left"> <Rectangle.Width> <MultiBinding Converter="{StaticResource RelativeWidthConverter}"> <Binding Path="RelativeWidth"/> <Binding Path="ActualWidth" ElementName="itemsControl"/> </MultiBinding> </Rectangle.Width> </Rectangle> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl> </Grid> </Window> ``` 2) converter: ``` public class RelativeWidthConverter : IMultiValueConverter { public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture) { return ((Double)values[0] * (Double)values[1]) / 100.0; } public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } } ``` 3) view model: ``` public class ViewModel : ViewModelBase { public ViewModel() { } public Double RelativeWidth { get { return relativeWidth; } set { if (relativeWidth != value) { relativeWidth = value; OnPropertyChanged("RelativeWidth"); } } } private Double relativeWidth; } ``` 4) code-behind: ``` public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); DataContext = new[] { new ViewModel { RelativeWidth = 20 }, new ViewModel { RelativeWidth = 40 }, new ViewModel { RelativeWidth = 60 }, new ViewModel { RelativeWidth = 100 }, }; } } ``` `MultiBinding` forces to update binding target, when `ActualWidth` changed.
You might try putting a `Grid` in the `ItemTemplate`. This `Grid` would have 2 columns: 1 for the actual content and one for the empty space. You should be able to bind the width of these columns using your dictionary's `Value`, possibly with the aid of an `IValueConverter`. If the content needs to be centered, you'd need to create 3 columns, splitting the empty space between columns 0 and 2.
11,865,042
maybe you guys can help me figure this out: I have a Dictionary and an ItemsControl that is binded to that dictionary. The Key of each entry determines the content of each Item in the ItemsControl and the Value determines the width of each Item. The big problem with this: The width is a percentage value, so it tells me that, for example, my Item needs to be 20% of its parent in size. How can I achieve this? I know Grids are able to work with star-based widths, but since I have to define the GridDefinition at the beginning of the Grid I cannot do this in the ItemsControl.ItemTemplate. Current code: ``` <ItemsControl ItemsSource="{Binding Distribution}" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"> <ItemsControl.ItemsPanel> <ItemsPanelTemplate> <Grid IsItemsHost="True" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" /> </ItemsPanelTemplate> </ItemsControl.ItemsPanel> <ItemsControl.ItemTemplate> <DataTemplate> <!-- I NEED THIS TO BE A CERTAIN PERCENTAGE IN WIDTH --> <Label Content="{Binding Key.Text}" Foreground="{Binding Key.Color}"/> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl> ``` Any ideas on this? Is there any elegant way to solve this? Thanks! *Clarifications*: The percentage is supposed to be based on the ItemControls parent! *And another one*: Each item is supposed to be one column of the grid, not a row. So I need all the items to be next to each other in the same row. **The solution**: Thanks for your help, this problem can be solved by using Multibinding and Binding to the ActualWidth of the ItemsControl. This way, whenever the ItemsControl changes in size, the Items change as well. A Grid is not needed. This solution only creates a relative width, but the same solution can of course be applied to the height of the items. This is a short version, for a more thorough explanation see down below: *XAML*: ``` <ItemsControl ItemsSource="{Binding Distribution}" Name="itemsControl" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"> <ItemsControl.ItemsPanel> <ItemsPanelTemplate> <StackPanel IsItemsHost="True" Orientation="Horizontal" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" /> </ItemsPanelTemplate> </ItemsControl.ItemsPanel> <ItemsControl.ItemTemplate> <DataTemplate> <Label Content="{Binding Key.Text}" Foreground="{Binding Key.Color}"> <Label.Width> <MultiBinding Converter="{StaticResource myConverter}"> <Binding Path="Value"/> <Binding Path="ActualWidth" ElementName="itemsControl"/> </MultiBinding> </Label.Width> </Label> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl> ``` *Converter*: ``` class MyConverter : IMultiValueConverter { public object Convert(object[] value, Type targetType, object parameter, CultureInfo culture) { //[1] contains the ItemsControl.ActualWidth we binded to, [0] the percentage //In this case, I assume the percentage is a double between 0 and 1 return (double)value[1] * (double)value[0]; } public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } ``` And that should do the trick!
2012/08/08
[ "https://Stackoverflow.com/questions/11865042", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1421550/" ]
~~You can implement `IValueConverter`~~. **UPDATE**. `MultiBinding` will help you. Here's the sample: 1) xaml: ``` <Window x:Class="WpfApplication1.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:WpfApplication1" Title="MainWindow" Height="114" Width="404"> <Grid> <Grid.Resources> <local:RelativeWidthConverter x:Key="RelativeWidthConverter"/> </Grid.Resources> <Grid.ColumnDefinitions> <ColumnDefinition Width="*"/> </Grid.ColumnDefinitions> <ItemsControl ItemsSource="{Binding}" x:Name="itemsControl"> <ItemsControl.ItemTemplate> <DataTemplate> <Rectangle Fill="Green" Margin="5" Height="20" HorizontalAlignment="Left"> <Rectangle.Width> <MultiBinding Converter="{StaticResource RelativeWidthConverter}"> <Binding Path="RelativeWidth"/> <Binding Path="ActualWidth" ElementName="itemsControl"/> </MultiBinding> </Rectangle.Width> </Rectangle> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl> </Grid> </Window> ``` 2) converter: ``` public class RelativeWidthConverter : IMultiValueConverter { public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture) { return ((Double)values[0] * (Double)values[1]) / 100.0; } public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } } ``` 3) view model: ``` public class ViewModel : ViewModelBase { public ViewModel() { } public Double RelativeWidth { get { return relativeWidth; } set { if (relativeWidth != value) { relativeWidth = value; OnPropertyChanged("RelativeWidth"); } } } private Double relativeWidth; } ``` 4) code-behind: ``` public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); DataContext = new[] { new ViewModel { RelativeWidth = 20 }, new ViewModel { RelativeWidth = 40 }, new ViewModel { RelativeWidth = 60 }, new ViewModel { RelativeWidth = 100 }, }; } } ``` `MultiBinding` forces to update binding target, when `ActualWidth` changed.
I had a required that couldn't use the Grids. I created a ContentControl that allows me wrap content to add a dynamic percentage width/height. ``` /// <summary> /// This control has a dynamic/percentage width/height /// </summary> public class FluentPanel : ContentControl, IValueConverter { #region Dependencie Properties public static readonly DependencyProperty WidthPercentageProperty = DependencyProperty.Register("WidthPercentage", typeof(int), typeof(FluentPanel), new PropertyMetadata(-1, WidthPercentagePropertyChangedCallback)); private static void WidthPercentagePropertyChangedCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs) { ((FluentPanel)dependencyObject).OnWidthPercentageChange(); } public int WidthPercentage { get { return (int)GetValue(WidthPercentageProperty); } set { SetValue(WidthPercentageProperty, value); } } public static readonly DependencyProperty HeightPercentageProperty = DependencyProperty.Register("HeightPercentage", typeof(int), typeof(FluentPanel), new PropertyMetadata(-1, HeightPercentagePropertyChangedCallback)); private static void HeightPercentagePropertyChangedCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs) { ((FluentPanel)dependencyObject).OnHeightPercentageChanged(); } public int HeightPercentage { get { return (int)GetValue(HeightPercentageProperty); } set { SetValue(HeightPercentageProperty, value); } } #endregion #region Methods private void OnWidthPercentageChange() { if (WidthPercentage == -1) { ClearValue(WidthProperty); } else { SetBinding(WidthProperty, new Binding("ActualWidth") { Source = Parent, Converter = this, ConverterParameter = true }); } } private void OnHeightPercentageChanged() { if (HeightPercentage == -1) { ClearValue(HeightProperty); } else { SetBinding(HeightProperty, new Binding("ActualHeight") { Source = Parent, Converter = this, ConverterParameter = false }); } } #endregion public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { if ((bool)parameter) { // width return (double)value * (WidthPercentage * .01); } else { // height return (double)value * (HeightPercentage * .01); } } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotSupportedException(); } } ```
2,800,910
> > A small course has 3 students, $B$, $C$ and $D$. Based on the previous > testscores of these students we know that $B$ usually scores $80$% > correct on the exam questions, $C$ scores $60$% and $D$ scores $40$%. > The anonymous test that is now corrected has $4$ correct answers out > of $8$. What is the conditional probability distribution for who took > this particular exam? > > > This just doesn't want to work. I know Baye's theorem is of use here and possibly the Law of total probability. Let $B=1, \ C=2$ and $D=3.$ Now also let $A\_i, \ i=1,2,3$ be the event that person $A\_i$ took the test and $X= \ $number of correctly answered question on the test. We are thus looking for $$P(A\_i|X=4)=\frac{P(X=4|A\_i)P(A\_i)}{P(X=4)}.$$ This did not make anything simpler. The only thing I now in the RHS is that $P(A\_i)=1/3.$
2018/05/29
[ "https://math.stackexchange.com/questions/2800910", "https://math.stackexchange.com", "https://math.stackexchange.com/users/114097/" ]
$P(X=4|A) = {8\choose 4} 0.8^4(1-0.8)^4\\ P(X=4|B) = {8\choose 4} 0.6^4(1-0.6)^4$ etc. $P(B|X = 4) = \frac {P(X=4|B)}{P(X=4|A) + P(X=4|B) + P(X=4|C)}$
Based on the information provided, it is not possible to give an answer. You are given B, C and D's mean (or, depending on interpretation of "usual", median or mode), but that is not directly relevant. You need to know not what A$\_i$'s "usual" score is, but what the percentage of the exams they get 50% is. The only approach I can see is assuming that each student's scores have a binomial distribution with p = .8, .6, and .4, respectively. You could then calculate the P(X = 4) for each of those distributions. (Note that by symmetry, C and D should have the same probability of being the person who took the exam). You also need a prior distribution, and while "all priors are 1/3" is a reasonable assumption, it is not explicitly stated. Also note that in American English, to write an exam means to come up with the questions on the exam (and thus, the person who writes the exam is generally the instructor), not to take the exam.
30,043,245
How can I develop a Android App or Iphone app from Visual Studio Preferably the community edition of VS. Language of choice C# What costs are involved and how would I go about getting this onto my phone? Can I avoid putting it into the public app store?
2015/05/05
[ "https://Stackoverflow.com/questions/30043245", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4019642/" ]
The obvious answer to that is <http://xamarin.com/> You'll still need to have a Mac to debug iOS apps, but otherwise can code in Visual Studio on Windows. With Android you can distribute very easily, for example via email. For iOS you would have to sign up for the enterprise app program, which means you *can't* sell apps on the store, but can distribute your app to internal devices. <https://developer.apple.com/programs/ios/enterprise/> As for costs, they vary, just check the relevant web sites...
for android development i think eclipse is better choose. or you can use android studio. there are some plugins for visual studio that lets you write programs but it is not very efficient. eclipse is a standard environment for developing android apps.
3,439,090
There's [http://www.amazon.com/gp/product/0321278542/](https://rads.stackoverflow.com/amzn/click/com/0321278542) but it looks a bit dated. Specificaly, it talks about bits that are no longer in use (powerpc bootloader for example) on modern machines. So, my question really is: is there any other book, as comprehensive and detailed as this one? **EDIT**: There's a new book which seems to be relevant: [Mac OS X Internals - To The Apple's Core](http://www.newosxbook.com/).
2010/08/09
[ "https://Stackoverflow.com/questions/3439090", "https://Stackoverflow.com", "https://Stackoverflow.com/users/121182/" ]
No, but it's still a great book. The internal hasn't changed that much; once you get the broad idea by reading that book, you can directly go to <http://opensource.apple.com/> and read the latest kernel source code without problems.
There is also a new book coming out "OS X Internals", the designated sequel to Amit Singh's book: <http://blog.darkrainfall.org/2013/01/os-x-internals/> At the moment it is still in development, but hopefully the "late 2014" deadline will not be pushed back (too much) further!
8,638
Ok, if I want to buy something that is $8 in American dollars and use a Bitcoin that is worth an odd value in American dollars...like $17 for instance. Then what happens? I end up with a deciminal point version of a Bitcoin? How does an individual keep track of Bitcoin money when it translates into too many decimal point locations? Doesnt Bitcoin have 8 or 10 decimal places? What happens if you buy something from a country where money is worth very little? Could you have a bitcoin account with a long decimal point fractional value?
2013/03/23
[ "https://bitcoin.stackexchange.com/questions/8638", "https://bitcoin.stackexchange.com", "https://bitcoin.stackexchange.com/users/3534/" ]
Bitcoin can be split into smaller units which I believe are called "Satoshi's" but in practice things are not denominated in satoshi's but are instead just fractional amounts bitcoins. You can have (and send) bitcoins in fractional values with no consequence.
Yes, there is decimal values. For example, today: 1 BTC = $ 87.64 So 0.1 BTC = $ 8.76 //// 0.01 BTC = $ 0.87 //// 0.001 BTC = $ 0.08 //// And so on. The minimum value is called "Satoshi" and it is: 0.00000001
8,638
Ok, if I want to buy something that is $8 in American dollars and use a Bitcoin that is worth an odd value in American dollars...like $17 for instance. Then what happens? I end up with a deciminal point version of a Bitcoin? How does an individual keep track of Bitcoin money when it translates into too many decimal point locations? Doesnt Bitcoin have 8 or 10 decimal places? What happens if you buy something from a country where money is worth very little? Could you have a bitcoin account with a long decimal point fractional value?
2013/03/23
[ "https://bitcoin.stackexchange.com/questions/8638", "https://bitcoin.stackexchange.com", "https://bitcoin.stackexchange.com/users/3534/" ]
One Bitcoin is actually `10 000 000` units in a transaction record, meaning that a Bitcoin is divisible down to eight decimal places. `1` unit is called a **satoshi**, named for the creator of Bitcoin. Most world currencies don't go below two decimal places in daily usage, and only in financial systems do they go below four decimal places. When someone says "There's only 21 million Bitcoin!", they are unaware that while there is 21,000,000 BTC ever in the whole system, there are actually 2,100,000,000,000,000 units in the whole system. That's 2.1 quadrillion units. In the unlikely event that, several decades or centuries down the line, there is a shortage causing significant flow problems, it is possible to further increase divisibility.
Bitcoin can be split into smaller units which I believe are called "Satoshi's" but in practice things are not denominated in satoshi's but are instead just fractional amounts bitcoins. You can have (and send) bitcoins in fractional values with no consequence.
8,638
Ok, if I want to buy something that is $8 in American dollars and use a Bitcoin that is worth an odd value in American dollars...like $17 for instance. Then what happens? I end up with a deciminal point version of a Bitcoin? How does an individual keep track of Bitcoin money when it translates into too many decimal point locations? Doesnt Bitcoin have 8 or 10 decimal places? What happens if you buy something from a country where money is worth very little? Could you have a bitcoin account with a long decimal point fractional value?
2013/03/23
[ "https://bitcoin.stackexchange.com/questions/8638", "https://bitcoin.stackexchange.com", "https://bitcoin.stackexchange.com/users/3534/" ]
One Bitcoin is actually `10 000 000` units in a transaction record, meaning that a Bitcoin is divisible down to eight decimal places. `1` unit is called a **satoshi**, named for the creator of Bitcoin. Most world currencies don't go below two decimal places in daily usage, and only in financial systems do they go below four decimal places. When someone says "There's only 21 million Bitcoin!", they are unaware that while there is 21,000,000 BTC ever in the whole system, there are actually 2,100,000,000,000,000 units in the whole system. That's 2.1 quadrillion units. In the unlikely event that, several decades or centuries down the line, there is a shortage causing significant flow problems, it is possible to further increase divisibility.
Yes, there is decimal values. For example, today: 1 BTC = $ 87.64 So 0.1 BTC = $ 8.76 //// 0.01 BTC = $ 0.87 //// 0.001 BTC = $ 0.08 //// And so on. The minimum value is called "Satoshi" and it is: 0.00000001
216,432
I have tried hard to look for a solution to my problems, but I can't manage to find it on this site or with Google. I have tried: `minipage`, `multicol`, `longtable`, `tabu`. I've read the documentation on `glossaries` and I can not make head or tails from it. I've got a glossary, with linguistic gloss abbreviations in it. I just need the gloss entry abbreviation and the description. No need for a third part. To save paper, I would like the glossary to be in two columns (abbrev. descr. abbrev. descr.) and I want it not to be on a seperate page. My MWE: ``` \documentclass[openright,12pt,dutch]{report} \usepackage{longtable} \usepackage[nomain,nonumberlist,nogroupskip,nostyles]{glossaries} % voor de lijst met glossen. \usepackage{glossary-super} \usepackage{leipzig} % voor glossen \makeglossaries \newglossarystyle{myglosses}{ \renewenvironment{theglossary}{ \longtable{r l} }{ \endlongtable } \renewcommand*{\glossaryheader}{} \renewcommand*{\glsgroupheading}[1]{} \renewcommand*{\glsgroupskip}{} \renewcommand*{\glsclearpage}{} % set how each entry should appear: \renewcommand*{\glossentry}[2]{ \glstarget{##1}{\textsc{\glossentryname{##1}}} & \glossentrydesc{##1} \\ } \renewcommand*{\subglossentry}[3]{% \glossentry{##2}{##3} } } \begin{document} What does \Pl{} mean? My (\Fsg{}.\Poss{}) houses (house-\Pl{}). \Agr, \Antip, \Ben, \Caus, \Compl, \Comp, \Third, \Dem, \Erg, \Fut, \F, \Loc, \Irr, \Impf, \Inf, \Ind, \Indf, \Ins, \Neg, \N, \M, \Nmlz, \Obj, \Obl, \Parg, \Prf, \Prs, \Prog. \printglossary[style=myglosses,type=\leipzigtype,title=]. \end{document} ``` Remember to run `makeglossaries`. I'd really appreciate your help with my thesis.
2014/12/10
[ "https://tex.stackexchange.com/questions/216432", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/10367/" ]
something like this? ![enter image description here](https://i.stack.imgur.com/uBRfr.png) ``` \documentclass[openright,12pt,dutch]{report} \usepackage{multicol} \usepackage[nomain,nonumberlist,nogroupskip,nostyles]{glossaries} % voor de lijst met glossen. \usepackage{glossary-super} \usepackage{leipzig} % voor glossen \makeglossaries \newglossarystyle{myglosses}{% \renewenvironment{theglossary}% {\begin{multicols}{2}\raggedright} {\end{multicols}} \renewcommand*{\glossaryheader}{} \renewcommand*{\glsgroupheading}[1]{} \renewcommand*{\glsgroupskip}{} \renewcommand*{\glsclearpage}{} % set how each entry should appear: \renewcommand*{\glossentry}[2]{ \noindent\makebox[7em][l]{\glstarget{##1}{\textsc{\glossentryname{##1}}}} \glossentrydesc{##1} } \renewcommand*{\subglossentry}[3]{% \glossentry{##2}{##3} } } \renewcommand*{\glossarysection}[2][]{\section*{Glossary}} %\setglossarystyle{inline} \begin{document} What does \Pl{} mean? My (\Fsg{}.\Poss{}) houses (house-\Pl{}). \Agr, \Antip, \Ben, \Caus, \Compl, \Comp, \Third, \Dem, \Erg, \Fut, \F, \Loc, \Irr, \Impf, \Inf, \Ind, \Indf, \Ins, \Neg, \N, \M, \Nmlz, \Obj, \Obl, \Parg, \Prf, \Prs, \Prog. \printglossary[style=myglosses,type=\leipzigtype,title=]. \end{document} ```
Here is a way of using `multicol` with `\parbox` commands to format the glossary. The `section=section` package option is used to prevent a page break before the glossary by altering the sectioning level from the default chapter to section (which doesn't start a new page). ``` \documentclass[openright,12pt,dutch]{report} \usepackage[nomain,nonumberlist,nogroupskip,nostyles,section=section]{glossaries} % voor de lijst met glossen. \usepackage{leipzig} % voor glossen \usepackage{multicol} \makeglossaries \newglossarystyle{myglosses}{% \renewenvironment{theglossary}{% \setlength{\parindent}{0pt}% \begin{multicols}{2}% }{% \end{multicols}% }% \renewcommand*{\glossaryheader}{}% \renewcommand*{\glsgroupheading}[1]{}% \renewcommand*{\glsclearpage}{\columnbreak}% % set how each entry should appear: \renewcommand*{\glossentry}[2]{% \parbox{.3\linewidth}{\hskip \fill\glstarget{##1}{\textsc{\glossentryname{##1}}}}% \hspace{.1\linewidth}% \parbox{.6\linewidth}{\glossentrydesc{##1}\hskip \fill}\par% }% \renewcommand*{\subglossentry}[3]{% \glossentry{##2}{##3}% }% } \begin{document} What does \Pl{} mean? My (\Fsg{}.\Poss{}) houses (house-\Pl{}). \Agr, \Antip, \Ben, \Caus, \Compl, \Comp, \Third, \Dem, \Erg, \Fut, \F, \Loc, \Irr, \Impf, \Inf, \Ind, \Indf, \Ins, \Neg, \N, \M, \Nmlz, \Obj, \Obl, \Parg, \Prf, \Prs, \Prog. \printglossary[style=myglosses,type=\leipzigtype,title=] \end{document} ``` ![two columns of glossary entries](https://i.stack.imgur.com/4G5W1.png)
216,432
I have tried hard to look for a solution to my problems, but I can't manage to find it on this site or with Google. I have tried: `minipage`, `multicol`, `longtable`, `tabu`. I've read the documentation on `glossaries` and I can not make head or tails from it. I've got a glossary, with linguistic gloss abbreviations in it. I just need the gloss entry abbreviation and the description. No need for a third part. To save paper, I would like the glossary to be in two columns (abbrev. descr. abbrev. descr.) and I want it not to be on a seperate page. My MWE: ``` \documentclass[openright,12pt,dutch]{report} \usepackage{longtable} \usepackage[nomain,nonumberlist,nogroupskip,nostyles]{glossaries} % voor de lijst met glossen. \usepackage{glossary-super} \usepackage{leipzig} % voor glossen \makeglossaries \newglossarystyle{myglosses}{ \renewenvironment{theglossary}{ \longtable{r l} }{ \endlongtable } \renewcommand*{\glossaryheader}{} \renewcommand*{\glsgroupheading}[1]{} \renewcommand*{\glsgroupskip}{} \renewcommand*{\glsclearpage}{} % set how each entry should appear: \renewcommand*{\glossentry}[2]{ \glstarget{##1}{\textsc{\glossentryname{##1}}} & \glossentrydesc{##1} \\ } \renewcommand*{\subglossentry}[3]{% \glossentry{##2}{##3} } } \begin{document} What does \Pl{} mean? My (\Fsg{}.\Poss{}) houses (house-\Pl{}). \Agr, \Antip, \Ben, \Caus, \Compl, \Comp, \Third, \Dem, \Erg, \Fut, \F, \Loc, \Irr, \Impf, \Inf, \Ind, \Indf, \Ins, \Neg, \N, \M, \Nmlz, \Obj, \Obl, \Parg, \Prf, \Prs, \Prog. \printglossary[style=myglosses,type=\leipzigtype,title=]. \end{document} ``` Remember to run `makeglossaries`. I'd really appreciate your help with my thesis.
2014/12/10
[ "https://tex.stackexchange.com/questions/216432", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/10367/" ]
something like this? ![enter image description here](https://i.stack.imgur.com/uBRfr.png) ``` \documentclass[openright,12pt,dutch]{report} \usepackage{multicol} \usepackage[nomain,nonumberlist,nogroupskip,nostyles]{glossaries} % voor de lijst met glossen. \usepackage{glossary-super} \usepackage{leipzig} % voor glossen \makeglossaries \newglossarystyle{myglosses}{% \renewenvironment{theglossary}% {\begin{multicols}{2}\raggedright} {\end{multicols}} \renewcommand*{\glossaryheader}{} \renewcommand*{\glsgroupheading}[1]{} \renewcommand*{\glsgroupskip}{} \renewcommand*{\glsclearpage}{} % set how each entry should appear: \renewcommand*{\glossentry}[2]{ \noindent\makebox[7em][l]{\glstarget{##1}{\textsc{\glossentryname{##1}}}} \glossentrydesc{##1} } \renewcommand*{\subglossentry}[3]{% \glossentry{##2}{##3} } } \renewcommand*{\glossarysection}[2][]{\section*{Glossary}} %\setglossarystyle{inline} \begin{document} What does \Pl{} mean? My (\Fsg{}.\Poss{}) houses (house-\Pl{}). \Agr, \Antip, \Ben, \Caus, \Compl, \Comp, \Third, \Dem, \Erg, \Fut, \F, \Loc, \Irr, \Impf, \Inf, \Ind, \Indf, \Ins, \Neg, \N, \M, \Nmlz, \Obj, \Obl, \Parg, \Prf, \Prs, \Prog. \printglossary[style=myglosses,type=\leipzigtype,title=]. \end{document} ```
I'll add an answer for leipzig 2.0 (which has just been added to CTAN, 2017-06-16). It's too late for your thesis, but might help someone else. I have included a pre-defined multicolumn glossary style in this version of leipzig. After a lot of experimentation, I ultimately decided that any style based on a tabular format was no good, because they often do not break across pages nicely, and lists of gloss abbreviations are often multiple pages long. Instead, the predefined block styles are built on the `alttree` and `mcolalttree` styles of the glossaries package. The easiest way to set the style for the glossary of abbreviations is to use the package option [mcolblock]. All unknown package options for leipzig are passed to glossaries. Therefore, like @cfr, I used the [section] option to print the glossary name in a section header instead of a chapter header. If you really want no title, you can uncomment one line to redefine the glossary section to do nothing. MWE: ``` \documentclass[openright,12pt,dutch]{report} % leipzig 2.0 has a simpler preamble declaration! \usepackage[% mcolblock,% multicolumn block glossary section,% glossary begins with a section header (not chapter header) ]{leipzig} % voor glossen \makeglossaries % Uncomment if you want no chapter/section heading at all: %\renewcommand*{\glossarysection}[2][]{} \begin{document} What does \Pl{} mean? My (\Fsg{}.\Poss{}) houses (house-\Pl{}). \Agr, \Antip, \Ben, \Caus, \Compl, \Comp, \Third, \Dem, \Erg, \Fut, \F, \Loc, \Irr, %\Impf, % changed to \Ipfv! \Ipfv, \Inf, \Ind, \Indf, \Ins, \Neg, \N, \M, \Nmlz, \Obj, \Obl, \Parg, \Prf, \Prs, \Prog. \printglosses \end{document} ``` Output: [![enter image description here](https://i.stack.imgur.com/YSKzv.jpg)](https://i.stack.imgur.com/YSKzv.jpg) You can also see that leipzig 2.0 fixes some errors! No more PL.pluralpl.