Search is not available for this dataset
qid
int64
1
74.7M
question
stringlengths
1
70k
date
stringlengths
10
10
metadata
sequence
response_j
stringlengths
0
115k
response_k
stringlengths
0
60.5k
176,618
I wanted to delete my lom mod (lots of mobs mod) because it is crashing Minecraft, but I can't because it claims Minecraft is running. However, I do not see Minecraft on my screen. I want to delete my mod without restarting my computer, my restarting doesn't seem to properly work. So I want to close javaw.exe on my task manager but it seems I have alot of javaw.exe and has different type of numbers on it (my first time working with task manager) Which one do I close?
2014/07/12
[ "https://gaming.stackexchange.com/questions/176618", "https://gaming.stackexchange.com", "https://gaming.stackexchange.com/users/82418/" ]
Any program that uses Java will have a process called "javaw.exe". Try closing out of the other programs on your computer and the number of processes will go down. Some sample programs that use Java include web browsers, other games, some music players, et cetera. Your safest bet, unfortunately, is probably to save your work and restart your computer, thus killing all the Java programs at once. Then you should be able to remove the mod. The fact that Minecraft is still considered running despite not being visible on your screen indicates that something has gone wrong in the first place, and you might be seeing computer slowdowns and odd behavior which a restart would clear right up.
How are you trying to delete it? Minecraft doesn't enforce restrictions on deleting files as far as I know. The best solution to quitting things you can't see is rebooting the computer, what is your problem with that?
176,618
I wanted to delete my lom mod (lots of mobs mod) because it is crashing Minecraft, but I can't because it claims Minecraft is running. However, I do not see Minecraft on my screen. I want to delete my mod without restarting my computer, my restarting doesn't seem to properly work. So I want to close javaw.exe on my task manager but it seems I have alot of javaw.exe and has different type of numbers on it (my first time working with task manager) Which one do I close?
2014/07/12
[ "https://gaming.stackexchange.com/questions/176618", "https://gaming.stackexchange.com", "https://gaming.stackexchange.com/users/82418/" ]
Any program that uses Java will have a process called "javaw.exe". Try closing out of the other programs on your computer and the number of processes will go down. Some sample programs that use Java include web browsers, other games, some music players, et cetera. Your safest bet, unfortunately, is probably to save your work and restart your computer, thus killing all the Java programs at once. Then you should be able to remove the mod. The fact that Minecraft is still considered running despite not being visible on your screen indicates that something has gone wrong in the first place, and you might be seeing computer slowdowns and odd behavior which a restart would clear right up.
hey just here to help but go to task manager in the processes tab go under background processes and end any running java tasks. This will allow you to delete any mods, forge files or other unneeded files. :D
176,618
I wanted to delete my lom mod (lots of mobs mod) because it is crashing Minecraft, but I can't because it claims Minecraft is running. However, I do not see Minecraft on my screen. I want to delete my mod without restarting my computer, my restarting doesn't seem to properly work. So I want to close javaw.exe on my task manager but it seems I have alot of javaw.exe and has different type of numbers on it (my first time working with task manager) Which one do I close?
2014/07/12
[ "https://gaming.stackexchange.com/questions/176618", "https://gaming.stackexchange.com", "https://gaming.stackexchange.com/users/82418/" ]
How are you trying to delete it? Minecraft doesn't enforce restrictions on deleting files as far as I know. The best solution to quitting things you can't see is rebooting the computer, what is your problem with that?
hey just here to help but go to task manager in the processes tab go under background processes and end any running java tasks. This will allow you to delete any mods, forge files or other unneeded files. :D
53,190,392
How can I add a column from a select query but the value from the new column will be the row count of the select query for example. ``` select quantity from menu; ``` and returns like this ``` +--------+ |quantity| +--------+ | 50 | | 32 | | 23 | +--------+ ``` but I want somthing like this ``` +----------+--------+ |new column|quantity| +----------+--------+ | 1 | 50 | | 2 | 32 | | 3 | 23 | +----------+--------+ ``` the new column should start from 1 and end from row count of the select query statement. Any answer would help Thanks
2018/11/07
[ "https://Stackoverflow.com/questions/53190392", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7663474/" ]
Since [you can access the latest version of MySQL](https://stackoverflow.com/questions/53190392/add-a-column-from-a-select-query-with-index/53190422#comment93269574_53190392), we can simply use the [`Row_Number()`](https://dev.mysql.com/doc/refman/8.0/en/window-function-descriptions.html#function_row-number) functionality: ``` SELECT ROW_NUMBER() OVER () AS new_column, quantity FROM menu; ```
You can use: ``` select row_number() over (order by quantity desc) as col1, quantity from menu; ``` This assumes that you want the rows enumerated by quantity in descending order.
53,190,392
How can I add a column from a select query but the value from the new column will be the row count of the select query for example. ``` select quantity from menu; ``` and returns like this ``` +--------+ |quantity| +--------+ | 50 | | 32 | | 23 | +--------+ ``` but I want somthing like this ``` +----------+--------+ |new column|quantity| +----------+--------+ | 1 | 50 | | 2 | 32 | | 3 | 23 | +----------+--------+ ``` the new column should start from 1 and end from row count of the select query statement. Any answer would help Thanks
2018/11/07
[ "https://Stackoverflow.com/questions/53190392", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7663474/" ]
Since [you can access the latest version of MySQL](https://stackoverflow.com/questions/53190392/add-a-column-from-a-select-query-with-index/53190422#comment93269574_53190392), we can simply use the [`Row_Number()`](https://dev.mysql.com/doc/refman/8.0/en/window-function-descriptions.html#function_row-number) functionality: ``` SELECT ROW_NUMBER() OVER () AS new_column, quantity FROM menu; ```
See: <https://stackoverflow.com/a/6055852/3368558> For your example: ``` select @rownum:=@rownum+1 as rowNum, quantity from menu CROSS JOIN (SELECT @rownum:=0) AS user_init; ```
53,190,392
How can I add a column from a select query but the value from the new column will be the row count of the select query for example. ``` select quantity from menu; ``` and returns like this ``` +--------+ |quantity| +--------+ | 50 | | 32 | | 23 | +--------+ ``` but I want somthing like this ``` +----------+--------+ |new column|quantity| +----------+--------+ | 1 | 50 | | 2 | 32 | | 3 | 23 | +----------+--------+ ``` the new column should start from 1 and end from row count of the select query statement. Any answer would help Thanks
2018/11/07
[ "https://Stackoverflow.com/questions/53190392", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7663474/" ]
Since [you can access the latest version of MySQL](https://stackoverflow.com/questions/53190392/add-a-column-from-a-select-query-with-index/53190422#comment93269574_53190392), we can simply use the [`Row_Number()`](https://dev.mysql.com/doc/refman/8.0/en/window-function-descriptions.html#function_row-number) functionality: ``` SELECT ROW_NUMBER() OVER () AS new_column, quantity FROM menu; ```
What you need to do in this case is first to define the variable @inc using SET and you assign the default value of 0. Then you include @inc as part of your SELECT statement. You can even use AS to nickname the variable expression. Also as part of the SELECT you take care of incrementing the value in @inc. The Code will look something like this: ``` SET @inc :=0; SELECT @inc := @inc + 1 AS a, `some_field` FROM `some_table`; ``` Hope will help!
53,190,392
How can I add a column from a select query but the value from the new column will be the row count of the select query for example. ``` select quantity from menu; ``` and returns like this ``` +--------+ |quantity| +--------+ | 50 | | 32 | | 23 | +--------+ ``` but I want somthing like this ``` +----------+--------+ |new column|quantity| +----------+--------+ | 1 | 50 | | 2 | 32 | | 3 | 23 | +----------+--------+ ``` the new column should start from 1 and end from row count of the select query statement. Any answer would help Thanks
2018/11/07
[ "https://Stackoverflow.com/questions/53190392", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7663474/" ]
See: <https://stackoverflow.com/a/6055852/3368558> For your example: ``` select @rownum:=@rownum+1 as rowNum, quantity from menu CROSS JOIN (SELECT @rownum:=0) AS user_init; ```
You can use: ``` select row_number() over (order by quantity desc) as col1, quantity from menu; ``` This assumes that you want the rows enumerated by quantity in descending order.
53,190,392
How can I add a column from a select query but the value from the new column will be the row count of the select query for example. ``` select quantity from menu; ``` and returns like this ``` +--------+ |quantity| +--------+ | 50 | | 32 | | 23 | +--------+ ``` but I want somthing like this ``` +----------+--------+ |new column|quantity| +----------+--------+ | 1 | 50 | | 2 | 32 | | 3 | 23 | +----------+--------+ ``` the new column should start from 1 and end from row count of the select query statement. Any answer would help Thanks
2018/11/07
[ "https://Stackoverflow.com/questions/53190392", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7663474/" ]
See: <https://stackoverflow.com/a/6055852/3368558> For your example: ``` select @rownum:=@rownum+1 as rowNum, quantity from menu CROSS JOIN (SELECT @rownum:=0) AS user_init; ```
What you need to do in this case is first to define the variable @inc using SET and you assign the default value of 0. Then you include @inc as part of your SELECT statement. You can even use AS to nickname the variable expression. Also as part of the SELECT you take care of incrementing the value in @inc. The Code will look something like this: ``` SET @inc :=0; SELECT @inc := @inc + 1 AS a, `some_field` FROM `some_table`; ``` Hope will help!
47,313,371
I have widget that inherits from QTreeView, and I want to change the text color, but only for a specific column. Currently I set the stylesheet, so the entire row changes the text color to red when the item is selected. ``` QTreeView::item:selected {color: red} ``` I want to change only the color of the first column when the item is selected. I know how to change the colour for specific columns (using ForegroundRole on the model and checking the index column), but I don't know how to do check if the index is selected in the model.
2017/11/15
[ "https://Stackoverflow.com/questions/47313371", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2359027/" ]
You can use a delegate for that: ``` class MyDelegate : public QStyledItemDelegate { public: void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { if (option.state & QStyle::State_Selected) { QStyleOptionViewItem optCopy = option; optCopy.palette.setColor(QPalette::Foreground, Qt::red); } QStyledItemDelegate::paint(painter, optCopy, index); } } myTreeWidget->setItemDelegateForColumn(0, new MyDelegate); ```
So this is how I solved it. ``` class MyDelegate : public QStyledItemDelegate { public: void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { QString text_highlight; if (index.column() == 0)){ text_highlight = BLUE; } else{ text_highlight = RED; } QStyleOptionViewItem s = *qstyleoption_cast<const QStyleOptionViewItem*>(&option); s.palette.setColor(QPalette::HighlightedText, QColor(text_highlight)); QStyledItemDelegate::paint(painter, s, index); } } ```
382,753
**Question.** What do you recommend to have the arc(-arrow) start outside the node (b) and also stop outside the node (c) in [![enter image description here](https://i.stack.imgur.com/2lLjB.png)](https://i.stack.imgur.com/2lLjB.png) which was created with ``` \documentclass{amsart} \usepackage{tikz} \begin{document} \begin{tikzpicture} \node (a) at (0pt,0pt)[]{$a$}; \node (b) at (0pt,101pt)[]{$b$}; \draw[->] (a)--(b); \draw[->] (b) arc [start angle=0, end angle=74, x radius=25pt, y radius=25pt,line width=4pt] node (c) {$c$}; \end{tikzpicture} \end{document} ``` ? Do you agree that it is somewhat unsystematic of TikZ to not have the straight arrow *also* go from *center to center* by default? **Remarks.** I know more than one way to *somehow* do this, for example with the option "shorten", but none appears the right way to do this. For example, using functionality like (b.north) is not a good solution, since it does not *uniformly* work. One then has to keep track of where one should say "north", where "south", etc, especially when some degree of automation is used in a larger TikZ program.
2017/07/22
[ "https://tex.stackexchange.com/questions/382753", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/133810/" ]
I do not like to use arc, except when necessary, I prefer to use to [out = xx, in = xx]. It is also necessary that the node exists before joining it, otherwise, the coordinate is reached directly. ``` \documentclass{article} \usepackage{tikz} \begin{document} \begin{tikzpicture} \node (a) at (0pt,0pt){$a$}; \node (b) at (0pt,101pt){$b$}; \draw[->] (a)--(b); \path (b) arc (0:90:25pt) node (c) {$c$}; \draw[->] (b) to [out=90,in=0] (c); \end{tikzpicture} \end{document} ``` [![enter image description here](https://i.stack.imgur.com/NT64Q.jpg)](https://i.stack.imgur.com/NT64Q.jpg) another solution in 3 lines! All nodes are defined in a path It remains only to trace the arcs and segments with `[rounded corners]` ``` \documentclass{article} \usepackage{tikz} \begin{document} \begin{tikzpicture} \path node(a) {$a$} --++ (0,101pt)node(b){$b$} |-++ (-1,1) node (c) {$c$}; \draw[rounded corners=0.5cm,->] (a) -- (b) ; \draw[rounded corners=0.5cm,->] (b)|- (c); \end{tikzpicture} \end{document} ```
When you write ``` \draw (a) -- (b); ``` TikZ actually tries to help you by shortening the line such that you don't have the same problem with lines. But notice that it is trying to help. Unfortunately, this is not the case for arcs because arcs are geometrically constrained much more strictly and their start and end points are not available at the time of parsing. Hence, TikZ cannot offer the same help and just assumes the `center` anchor. Emphasis on *cannot offer* not a missing feature. For such use, TikZ offer `to` paths using Bezier curves with specifying in, out angles. For arcs that are specified with their start/end points you might want to use `\pgfpatharcto` or other arc variants specified in the manual. The other crossing of `c` is because you placed the node at the end of the path so it is not relevant to the problem stated above, just use any anchoring directions and it will be put away from the end point.
60,295,589
I have some address data that needs to be corrected. It is intending to show a range of addresses, but this will not work for geocoding. What is an effective way to to remove everything between the hyphen and the first space using regex in excel? Example: ``` 29-45 SICKLES ST 31-39 SHERMAN AV 36-44 ARDEN ST 118-22 NAGLE AV ``` Becomes ``` 29 SICKLES ST 31 SHERMAN AV 36 ARDEN ST 118 NAGLE AV ```
2020/02/19
[ "https://Stackoverflow.com/questions/60295589", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12817139/" ]
Since you have tagged `RegEx` you could use it like so within Excel's VBA: ``` Sub Test() Dim arr As Variant: arr = Array("29-45 SICKLES ST", "31-39 SHERMAN AV", "36-44 ARDEN ST", "118-22 NAGLE AV") With CreateObject("VBScript.RegExp") .Pattern = "-\d*\s*" For x = LBound(arr) To UBound(arr) arr(x) = .Replace(arr(x), " ") Next End With End Sub ```
You will create a new column by `= REGEXREPLACE(current_column,"-\d+ ","")`
8,971,000
How to request Android download manager to download multiple files at the same time. Also I would like to know each and every file download status.
2012/01/23
[ "https://Stackoverflow.com/questions/8971000", "https://Stackoverflow.com", "https://Stackoverflow.com/users/676625/" ]
Request the first one. Then, request the second one. Then, request the third one. Continue as needed. Whether they download "at the same time" is not your concern, nor do you have control over it. They will download when `DownloadManager` decides to download them, which may be simultaneously or not.
``` 1. Register listener for download complete IntentFilter intentFilter = new IntentFilter( DownloadManager.ACTION_DOWNLOAD_COMPLETE); registerReceiver(downloadReceiver, intentFilter); 2.Make request Uri downloadUri = Uri.parse(entry.getValue()); DownloadManager.Request request = new DownloadManager.Request( downloadUri); request.setDestinationUri(path_to _file_store))); downloadManager.enqueue(request); 3.Check status in listener private BroadcastReceiver downloadReceiver = new BroadcastReceiver() { @Override public void onReceive(Context arg0, Intent intent) { String action = intent.getAction(); if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) { long downloadId = intent.getLongExtra( DownloadManager.EXTRA_DOWNLOAD_ID, 0); System.out.println("download id=" + downloadId); CheckDwnloadStatus(downloadId); } } }; private void CheckDwnloadStatus(long id) { // TODO Auto-generated method stub DownloadManager.Query query = new DownloadManager.Query(); query.setFilterById(id); Cursor cursor = downloadManager.query(query); if (cursor.moveToFirst()) { int columnIndex = cursor .getColumnIndex(DownloadManager.COLUMN_STATUS); int status = cursor.getInt(columnIndex); int columnReason = cursor .getColumnIndex(DownloadManager.COLUMN_REASON); int reason = cursor.getInt(columnReason); switch (status) { case DownloadManager.STATUS_FAILED: String failedReason = ""; switch (reason) { case DownloadManager.ERROR_CANNOT_RESUME: failedReason = "ERROR_CANNOT_RESUME"; break; case DownloadManager.ERROR_DEVICE_NOT_FOUND: failedReason = "ERROR_DEVICE_NOT_FOUND"; break; case DownloadManager.ERROR_FILE_ALREADY_EXISTS: failedReason = "ERROR_FILE_ALREADY_EXISTS"; break; case DownloadManager.ERROR_FILE_ERROR: failedReason = "ERROR_FILE_ERROR"; break; case DownloadManager.ERROR_HTTP_DATA_ERROR: failedReason = "ERROR_HTTP_DATA_ERROR"; break; case DownloadManager.ERROR_INSUFFICIENT_SPACE: failedReason = "ERROR_INSUFFICIENT_SPACE"; break; case DownloadManager.ERROR_TOO_MANY_REDIRECTS: failedReason = "ERROR_TOO_MANY_REDIRECTS"; break; case DownloadManager.ERROR_UNHANDLED_HTTP_CODE: failedReason = "ERROR_UNHANDLED_HTTP_CODE"; break; case DownloadManager.ERROR_UNKNOWN: failedReason = "ERROR_UNKNOWN"; break; } Toast.makeText(this, "FAILED: " + failedReason, Toast.LENGTH_LONG).show(); break; case DownloadManager.STATUS_PAUSED: String pausedReason = ""; switch (reason) { case DownloadManager.PAUSED_QUEUED_FOR_WIFI: pausedReason = "PAUSED_QUEUED_FOR_WIFI"; break; case DownloadManager.PAUSED_UNKNOWN: pausedReason = "PAUSED_UNKNOWN"; break; case DownloadManager.PAUSED_WAITING_FOR_NETWORK: pausedReason = "PAUSED_WAITING_FOR_NETWORK"; break; case DownloadManager.PAUSED_WAITING_TO_RETRY: pausedReason = "PAUSED_WAITING_TO_RETRY"; break; } Toast.makeText(this, "PAUSED: " + pausedReason, Toast.LENGTH_LONG).show(); break; case DownloadManager.STATUS_PENDING: Toast.makeText(this, "PENDING", Toast.LENGTH_LONG).show(); break; case DownloadManager.STATUS_RUNNING: Toast.makeText(this, "RUNNING", Toast.LENGTH_LONG).show(); break; case DownloadManager.STATUS_SUCCESSFUL: caluclateLoadingData(); // Toast.makeText(this, "SUCCESSFUL", Toast.LENGTH_LONG).show(); // GetFile(); break; } } } ```
8,971,000
How to request Android download manager to download multiple files at the same time. Also I would like to know each and every file download status.
2012/01/23
[ "https://Stackoverflow.com/questions/8971000", "https://Stackoverflow.com", "https://Stackoverflow.com/users/676625/" ]
Request the first one. Then, request the second one. Then, request the third one. Continue as needed. Whether they download "at the same time" is not your concern, nor do you have control over it. They will download when `DownloadManager` decides to download them, which may be simultaneously or not.
public class DownloadManager { private static final String TAG = "DownloadManager"; ``` public final static String COLUMN_ID = BaseColumns._ID; public final static String COLUMN_TITLE = "title"; public final static String COLUMN_DESCRIPTION = "description"; public final static String COLUMN_URI = "uri"; public final static String COLUMN_MEDIA_TYPE = "media_type"; public final static String COLUMN_TOTAL_SIZE_BYTES = "total_size"; public final static String COLUMN_LOCAL_URI = "local_uri"; public final static String COLUMN_STATUS = "status"; public final static String COLUMN_REASON = "reason"; public final static String COLUMN_BYTES_DOWNLOADED_SO_FAR = "bytes_so_far"; public final static String COLUMN_LAST_MODIFIED_TIMESTAMP = "last_modified_timestamp"; public static final String COLUMN_MEDIAPROVIDER_URI = "mediaprovider_uri"; public final static int STATUS_PENDING = 1 << 0; public final static int STATUS_RUNNING = 1 << 1; public final static int STATUS_PAUSED = 1 << 2; public final static int STATUS_SUCCESSFUL = 1 << 3; public final static int STATUS_FAILED = 1 << 4; public final static int ERROR_UNKNOWN = 1000; public final static int ERROR_FILE_ERROR = 1001; public final static int ERROR_UNHANDLED_HTTP_CODE = 1002; public final static int ERROR_HTTP_DATA_ERROR = 1004; public final static int ERROR_TOO_MANY_REDIRECTS = 1005; public final static int ERROR_INSUFFICIENT_SPACE = 1006; public final static int ERROR_DEVICE_NOT_FOUND = 1007; public final static int ERROR_CANNOT_RESUME = 1008; public final static int ERROR_FILE_ALREADY_EXISTS = 1009; public final static int PAUSED_WAITING_TO_RETRY = 1; public final static int PAUSED_WAITING_FOR_NETWORK = 2; public final static int PAUSED_QUEUED_FOR_WIFI = 3; public final static int PAUSED_UNKNOWN = 4; public final static String ACTION_DOWNLOAD_COMPLETE = "android.intent.action.DOWNLOAD_COMPLETE"; public final static String ACTION_NOTIFICATION_CLICKED = "android.intent.action.DOWNLOAD_NOTIFICATION_CLICKED"; public final static String ACTION_VIEW_DOWNLOADS = "android.intent.action.VIEW_DOWNLOADS"; public static final String EXTRA_DOWNLOAD_ID = "extra_download_id"; // this array must contain all public columns private static final String[] COLUMNS = new String[] { COLUMN_ID, COLUMN_MEDIAPROVIDER_URI, COLUMN_TITLE, COLUMN_DESCRIPTION, COLUMN_URI, COLUMN_MEDIA_TYPE, COLUMN_TOTAL_SIZE_BYTES, COLUMN_LOCAL_URI, COLUMN_STATUS, COLUMN_REASON, COLUMN_BYTES_DOWNLOADED_SO_FAR, COLUMN_LAST_MODIFIED_TIMESTAMP }; // columns to request from DownloadProvider private static final String[] UNDERLYING_COLUMNS = new String[] { Downloads.Impl._ID, Downloads.Impl.COLUMN_MEDIAPROVIDER_URI, Downloads.COLUMN_TITLE, Downloads.COLUMN_DESCRIPTION, Downloads.COLUMN_URI, Downloads.COLUMN_MIME_TYPE, Downloads.COLUMN_TOTAL_BYTES, Downloads.COLUMN_STATUS, Downloads.COLUMN_CURRENT_BYTES, Downloads.COLUMN_LAST_MODIFICATION, Downloads.COLUMN_DESTINATION, Downloads.Impl.COLUMN_FILE_NAME_HINT, Downloads.Impl._DATA, }; private static final Set<String> LONG_COLUMNS = new HashSet<String>( Arrays.asList(COLUMN_ID, COLUMN_TOTAL_SIZE_BYTES, COLUMN_STATUS, COLUMN_REASON, COLUMN_BYTES_DOWNLOADED_SO_FAR, COLUMN_LAST_MODIFIED_TIMESTAMP)); public static class Request { public static final int NETWORK_MOBILE = 1 << 0; public static final int NETWORK_WIFI = 1 << 1; private Uri mUri; private Uri mDestinationUri; private List<Pair<String, String>> mRequestHeaders = new ArrayList<Pair<String, String>>(); private CharSequence mTitle; private CharSequence mDescription; private boolean mShowNotification = true; private String mMimeType; private boolean mRoamingAllowed = true; private int mAllowedNetworkTypes = ~0; // default to all network types // allowed private boolean mIsVisibleInDownloadsUi = true; /** * @param uri * the HTTP URI to download. */ public Request(Uri uri) { if (uri == null) { throw new NullPointerException(); } String scheme = uri.getScheme(); if (scheme == null || !(scheme.equals("http") || scheme.equals("https"))) { throw new IllegalArgumentException( "Can only download HTTP URIs: " + uri); } mUri = uri; } public Request setDestinationUri(Uri uri) { mDestinationUri = uri; return this; } public Request setDestinationInExternalFilesDir(Context context, String dirType, String subPath) { setDestinationFromBase(context.getExternalFilesDir(dirType), subPath); return this; } public Request setDestinationInExternalPublicDir(String dirType, String subPath) { setDestinationFromBase( Environment.getExternalStoragePublicDirectory(dirType), subPath); return this; } private void setDestinationFromBase(File base, String subPath) { if (subPath == null) { throw new NullPointerException("subPath cannot be null"); } mDestinationUri = Uri.withAppendedPath(Uri.fromFile(base), subPath); } public Request addRequestHeader(String header, String value) { if (header == null) { throw new NullPointerException("header cannot be null"); } if (header.contains(":")) { throw new IllegalArgumentException("header may not contain ':'"); } if (value == null) { value = ""; } mRequestHeaders.add(Pair.create(header, value)); return this; } public Request setTitle(CharSequence title) { mTitle = title; return this; } public Request setDescription(CharSequence description) { mDescription = description; return this; } public Request setMimeType(String mimeType) { mMimeType = mimeType; return this; } public Request setShowRunningNotification(boolean show) { mShowNotification = show; return this; } public Request setAllowedNetworkTypes(int flags) { mAllowedNetworkTypes = flags; return this; } public Request setAllowedOverRoaming(boolean allowed) { mRoamingAllowed = allowed; return this; } public Request setVisibleInDownloadsUi(boolean isVisible) { mIsVisibleInDownloadsUi = isVisible; return this; } /** * @return ContentValues to be passed to DownloadProvider.insert() */ ContentValues toContentValues(String packageName) { ContentValues values = new ContentValues(); assert mUri != null; values.put(Downloads.COLUMN_URI, mUri.toString()); values.put(Downloads.Impl.COLUMN_IS_PUBLIC_API, true); values.put(Downloads.COLUMN_NOTIFICATION_PACKAGE, packageName); if (mDestinationUri != null) { values.put(Downloads.COLUMN_DESTINATION, Downloads.Impl.DESTINATION_FILE_URI); values.put(Downloads.COLUMN_FILE_NAME_HINT, mDestinationUri.toString()); } else { values.put(Downloads.COLUMN_DESTINATION, Downloads.DESTINATION_CACHE_PARTITION_PURGEABLE); } if (!mRequestHeaders.isEmpty()) { encodeHttpHeaders(values); } putIfNonNull(values, Downloads.COLUMN_TITLE, mTitle); putIfNonNull(values, Downloads.COLUMN_DESCRIPTION, mDescription); putIfNonNull(values, Downloads.COLUMN_MIME_TYPE, mMimeType); values.put(Downloads.COLUMN_VISIBILITY, mShowNotification ? Downloads.VISIBILITY_VISIBLE : Downloads.VISIBILITY_HIDDEN); values.put(Downloads.Impl.COLUMN_ALLOWED_NETWORK_TYPES, mAllowedNetworkTypes); values.put(Downloads.Impl.COLUMN_ALLOW_ROAMING, mRoamingAllowed); values.put(Downloads.Impl.COLUMN_IS_VISIBLE_IN_DOWNLOADS_UI, mIsVisibleInDownloadsUi); return values; } private void encodeHttpHeaders(ContentValues values) { int index = 0; for (Pair<String, String> header : mRequestHeaders) { String headerString = header.first + ": " + header.second; values.put(Downloads.Impl.RequestHeaders.INSERT_KEY_PREFIX + index, headerString); index++; } } private void putIfNonNull(ContentValues contentValues, String key, Object value) { if (value != null) { contentValues.put(key, value.toString()); } } } /** * This class may be used to filter download manager queries. */ public static class Query { /** * Constant for use with {@link #orderBy} * * @hide */ public static final int ORDER_ASCENDING = 1; /** * Constant for use with {@link #orderBy} * * @hide */ public static final int ORDER_DESCENDING = 2; private long[] mIds = null; private Integer mStatusFlags = null; private String mOrderByColumn = Downloads.COLUMN_LAST_MODIFICATION; private int mOrderDirection = ORDER_DESCENDING; private boolean mOnlyIncludeVisibleInDownloadsUi = false; /** * Include only the downloads with the given IDs. * * @return this object */ public Query setFilterById(long... ids) { mIds = ids; return this; } /** * Include only downloads with status matching any the given status * flags. * * @param flags * any combination of the STATUS_* bit flags * @return this object */ public Query setFilterByStatus(int flags) { mStatusFlags = flags; return this; } /** * Controls whether this query includes downloads not visible in the * system's Downloads UI. * * @param value * if true, this query will only include downloads that * should be displayed in the system's Downloads UI; if false * (the default), this query will include both visible and * invisible downloads. * @return this object * @hide */ public Query setOnlyIncludeVisibleInDownloadsUi(boolean value) { mOnlyIncludeVisibleInDownloadsUi = value; return this; } /** * Change the sort order of the returned Cursor. * * @param column * one of the COLUMN_* constants; currently, only * {@link #COLUMN_LAST_MODIFIED_TIMESTAMP} and * {@link #COLUMN_TOTAL_SIZE_BYTES} are supported. * @param direction * either {@link #ORDER_ASCENDING} or * {@link #ORDER_DESCENDING} * @return this object * @hide */ public Query orderBy(String column, int direction) { if (direction != ORDER_ASCENDING && direction != ORDER_DESCENDING) { throw new IllegalArgumentException("Invalid direction: " + direction); } if (column.equals(COLUMN_LAST_MODIFIED_TIMESTAMP)) { mOrderByColumn = Downloads.COLUMN_LAST_MODIFICATION; } else if (column.equals(COLUMN_TOTAL_SIZE_BYTES)) { mOrderByColumn = Downloads.COLUMN_TOTAL_BYTES; } else { throw new IllegalArgumentException("Cannot order by " + column); } mOrderDirection = direction; return this; } /** * Run this query using the given ContentResolver. * * @param projection * the projection to pass to ContentResolver.query() * @return the Cursor returned by ContentResolver.query() */ Cursor runQuery(ContentResolver resolver, String[] projection, Uri baseUri) { Uri uri = baseUri; List<String> selectionParts = new ArrayList<String>(); String[] selectionArgs = null; if (mIds != null) { selectionParts.add(getWhereClauseForIds(mIds)); selectionArgs = getWhereArgsForIds(mIds); } if (mStatusFlags != null) { List<String> parts = new ArrayList<String>(); if ((mStatusFlags & STATUS_PENDING) != 0) { parts.add(statusClause("=", Downloads.STATUS_PENDING)); } if ((mStatusFlags & STATUS_RUNNING) != 0) { parts.add(statusClause("=", Downloads.STATUS_RUNNING)); } if ((mStatusFlags & STATUS_PAUSED) != 0) { parts.add(statusClause("=", Downloads.Impl.STATUS_PAUSED_BY_APP)); parts.add(statusClause("=", Downloads.Impl.STATUS_WAITING_TO_RETRY)); parts.add(statusClause("=", Downloads.Impl.STATUS_WAITING_FOR_NETWORK)); parts.add(statusClause("=", Downloads.Impl.STATUS_QUEUED_FOR_WIFI)); } if ((mStatusFlags & STATUS_SUCCESSFUL) != 0) { parts.add(statusClause("=", Downloads.STATUS_SUCCESS)); } if ((mStatusFlags & STATUS_FAILED) != 0) { parts.add("(" + statusClause(">=", 400) + " AND " + statusClause("<", 600) + ")"); } selectionParts.add(joinStrings(" OR ", parts)); } if (mOnlyIncludeVisibleInDownloadsUi) { selectionParts .add(Downloads.Impl.COLUMN_IS_VISIBLE_IN_DOWNLOADS_UI + " != '0'"); } // only return rows which are not marked 'deleted = 1' selectionParts.add(Downloads.Impl.COLUMN_DELETED + " != '1'"); String selection = joinStrings(" AND ", selectionParts); String orderDirection = (mOrderDirection == ORDER_ASCENDING ? "ASC" : "DESC"); String orderBy = mOrderByColumn + " " + orderDirection; return resolver.query(uri, projection, selection, selectionArgs, orderBy); } private String joinStrings(String joiner, Iterable<String> parts) { StringBuilder builder = new StringBuilder(); boolean first = true; for (String part : parts) { if (!first) { builder.append(joiner); } builder.append(part); first = false; } return builder.toString(); } private String statusClause(String operator, int value) { return Downloads.COLUMN_STATUS + operator + "'" + value + "'"; } } private ContentResolver mResolver; private String mPackageName; private Uri mBaseUri = Downloads.Impl.CONTENT_URI; /** * @hide */ public DownloadManager(ContentResolver resolver, String packageName) { mResolver = resolver; mPackageName = packageName; } /** * Makes this object access the download provider through /all_downloads * URIs rather than /my_downloads URIs, for clients that have permission to * do so. * * @hide */ public void setAccessAllDownloads(boolean accessAllDownloads) { if (accessAllDownloads) { mBaseUri = Downloads.Impl.ALL_DOWNLOADS_CONTENT_URI; } else { mBaseUri = Downloads.Impl.CONTENT_URI; } } public long enqueue(Request request) { ContentValues values = request.toContentValues(mPackageName); Uri downloadUri = mResolver.insert(Downloads.CONTENT_URI, values); long id = Long.parseLong(downloadUri.getLastPathSegment()); return id; } public int markRowDeleted(long... ids) { if (ids == null || ids.length == 0) { // called with nothing to remove! throw new IllegalArgumentException( "input param 'ids' can't be null"); } ContentValues values = new ContentValues(); values.put(Downloads.Impl.COLUMN_DELETED, 1); return mResolver.update(mBaseUri, values, getWhereClauseForIds(ids), getWhereArgsForIds(ids)); } public int remove(long... ids) { if (ids == null || ids.length == 0) { // called with nothing to remove! throw new IllegalArgumentException( "input param 'ids' can't be null"); } return mResolver.delete(mBaseUri, getWhereClauseForIds(ids), getWhereArgsForIds(ids)); } public Cursor query(Query query) { Cursor underlyingCursor = query.runQuery(mResolver, UNDERLYING_COLUMNS, mBaseUri); if (underlyingCursor == null) { return null; } return new CursorTranslator(underlyingCursor, mBaseUri); } public ParcelFileDescriptor openDownloadedFile(long id) throws FileNotFoundException { return mResolver.openFileDescriptor(getDownloadUri(id), "r"); } public void restartDownload(long... ids) { Cursor cursor = query(new Query().setFilterById(ids)); try { for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor .moveToNext()) { int status = cursor .getInt(cursor.getColumnIndex(COLUMN_STATUS)); if (status != STATUS_SUCCESSFUL && status != STATUS_FAILED) { throw new IllegalArgumentException( "Cannot restart incomplete download: " + cursor.getLong(cursor .getColumnIndex(COLUMN_ID))); } } } finally { cursor.close(); } ContentValues values = new ContentValues(); values.put(Downloads.Impl.COLUMN_CURRENT_BYTES, 0); values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, -1); values.putNull(Downloads.Impl._DATA); values.put(Downloads.Impl.COLUMN_STATUS, Downloads.Impl.STATUS_PENDING); mResolver.update(mBaseUri, values, getWhereClauseForIds(ids), getWhereArgsForIds(ids)); } /** * Get the DownloadProvider URI for the download with the given ID. */ Uri getDownloadUri(long id) { return ContentUris.withAppendedId(mBaseUri, id); } /** * Get a parameterized SQL WHERE clause to select a bunch of IDs. */ static String getWhereClauseForIds(long[] ids) { StringBuilder whereClause = new StringBuilder(); whereClause.append("("); for (int i = 0; i < ids.length; i++) { if (i > 0) { whereClause.append("OR "); } whereClause.append(Downloads.Impl._ID); whereClause.append(" = ? "); } whereClause.append(")"); return whereClause.toString(); } /** * Get the selection args for a clause returned by * {@link #getWhereClauseForIds(long[])}. */ static String[] getWhereArgsForIds(long[] ids) { String[] whereArgs = new String[ids.length]; for (int i = 0; i < ids.length; i++) { whereArgs[i] = Long.toString(ids[i]); } return whereArgs; } /** * This class wraps a cursor returned by DownloadProvider -- the * "underlying cursor" -- and presents a different set of columns, those * defined in the DownloadManager.COLUMN_* constants. Some columns * correspond directly to underlying values while others are computed from * underlying data. */ private static class CursorTranslator extends CursorWrapper { private Uri mBaseUri; public CursorTranslator(Cursor cursor, Uri baseUri) { super(cursor); mBaseUri = baseUri; } @Override public int getColumnIndex(String columnName) { return Arrays.asList(COLUMNS).indexOf(columnName); } @Override public int getColumnIndexOrThrow(String columnName) throws IllegalArgumentException { int index = getColumnIndex(columnName); if (index == -1) { throw new IllegalArgumentException("No such column: " + columnName); } return index; } @Override public String getColumnName(int columnIndex) { int numColumns = COLUMNS.length; if (columnIndex < 0 || columnIndex >= numColumns) { throw new IllegalArgumentException("Invalid column index " + columnIndex + ", " + numColumns + " columns exist"); } return COLUMNS[columnIndex]; } @Override public String[] getColumnNames() { String[] returnColumns = new String[COLUMNS.length]; System.arraycopy(COLUMNS, 0, returnColumns, 0, COLUMNS.length); return returnColumns; } @Override public int getColumnCount() { return COLUMNS.length; } @Override public byte[] getBlob(int columnIndex) { throw new UnsupportedOperationException(); } @Override public double getDouble(int columnIndex) { return getLong(columnIndex); } private boolean isLongColumn(String column) { return LONG_COLUMNS.contains(column); } @Override public float getFloat(int columnIndex) { return (float) getDouble(columnIndex); } @Override public int getInt(int columnIndex) { return (int) getLong(columnIndex); } @Override public long getLong(int columnIndex) { return translateLong(getColumnName(columnIndex)); } @Override public short getShort(int columnIndex) { return (short) getLong(columnIndex); } @Override public String getString(int columnIndex) { return translateString(getColumnName(columnIndex)); } private String translateString(String column) { if (isLongColumn(column)) { return Long.toString(translateLong(column)); } if (column.equals(COLUMN_TITLE)) { return getUnderlyingString(Downloads.COLUMN_TITLE); } if (column.equals(COLUMN_DESCRIPTION)) { return getUnderlyingString(Downloads.COLUMN_DESCRIPTION); } if (column.equals(COLUMN_URI)) { return getUnderlyingString(Downloads.COLUMN_URI); } if (column.equals(COLUMN_MEDIA_TYPE)) { return getUnderlyingString(Downloads.COLUMN_MIME_TYPE); } if (column.equals(COLUMN_MEDIAPROVIDER_URI)) { return getUnderlyingString(Downloads.Impl.COLUMN_MEDIAPROVIDER_URI); } assert column.equals(COLUMN_LOCAL_URI); return getLocalUri(); } private String getLocalUri() { long destinationType = getUnderlyingLong(Downloads.Impl.COLUMN_DESTINATION); if (destinationType == Downloads.Impl.DESTINATION_FILE_URI) { // return client-provided file URI for external download return getUnderlyingString(Downloads.Impl.COLUMN_FILE_NAME_HINT); } if (destinationType == Downloads.Impl.DESTINATION_EXTERNAL) { // return stored destination for legacy external download String localPath = getUnderlyingString(Downloads.Impl._DATA); if (localPath == null) { return null; } return Uri.fromFile(new File(localPath)).toString(); } // return content URI for cache download long downloadId = getUnderlyingLong(Downloads.Impl._ID); return ContentUris.withAppendedId(mBaseUri, downloadId).toString(); } private long translateLong(String column) { if (!isLongColumn(column)) { // mimic behavior of underlying cursor -- most likely, throw // NumberFormatException return Long.valueOf(translateString(column)); } if (column.equals(COLUMN_ID)) { return getUnderlyingLong(Downloads.Impl._ID); } if (column.equals(COLUMN_TOTAL_SIZE_BYTES)) { return getUnderlyingLong(Downloads.COLUMN_TOTAL_BYTES); } if (column.equals(COLUMN_STATUS)) { return translateStatus((int) getUnderlyingLong(Downloads.COLUMN_STATUS)); } if (column.equals(COLUMN_REASON)) { return getReason((int) getUnderlyingLong(Downloads.COLUMN_STATUS)); } if (column.equals(COLUMN_BYTES_DOWNLOADED_SO_FAR)) { return getUnderlyingLong(Downloads.COLUMN_CURRENT_BYTES); } assert column.equals(COLUMN_LAST_MODIFIED_TIMESTAMP); return getUnderlyingLong(Downloads.COLUMN_LAST_MODIFICATION); } private long getReason(int status) { switch (translateStatus(status)) { case STATUS_FAILED: return getErrorCode(status); case STATUS_PAUSED: return getPausedReason(status); default: return 0; // arbitrary value when status is not an error } } private long getPausedReason(int status) { switch (status) { case Downloads.Impl.STATUS_WAITING_TO_RETRY: return PAUSED_WAITING_TO_RETRY; case Downloads.Impl.STATUS_WAITING_FOR_NETWORK: return PAUSED_WAITING_FOR_NETWORK; case Downloads.Impl.STATUS_QUEUED_FOR_WIFI: return PAUSED_QUEUED_FOR_WIFI; default: return PAUSED_UNKNOWN; } } private long getErrorCode(int status) { if ((400 <= status && status < Downloads.Impl.MIN_ARTIFICIAL_ERROR_STATUS) || (500 <= status && status < 600)) { // HTTP status code return status; } switch (status) { case Downloads.STATUS_FILE_ERROR: return ERROR_FILE_ERROR; case Downloads.STATUS_UNHANDLED_HTTP_CODE: case Downloads.STATUS_UNHANDLED_REDIRECT: return ERROR_UNHANDLED_HTTP_CODE; case Downloads.STATUS_HTTP_DATA_ERROR: return ERROR_HTTP_DATA_ERROR; case Downloads.STATUS_TOO_MANY_REDIRECTS: return ERROR_TOO_MANY_REDIRECTS; case Downloads.STATUS_INSUFFICIENT_SPACE_ERROR: return ERROR_INSUFFICIENT_SPACE; case Downloads.STATUS_DEVICE_NOT_FOUND_ERROR: return ERROR_DEVICE_NOT_FOUND; case Downloads.Impl.STATUS_CANNOT_RESUME: return ERROR_CANNOT_RESUME; case Downloads.Impl.STATUS_FILE_ALREADY_EXISTS_ERROR: return ERROR_FILE_ALREADY_EXISTS; default: return ERROR_UNKNOWN; } } private long getUnderlyingLong(String column) { return super.getLong(super.getColumnIndex(column)); } private String getUnderlyingString(String column) { return super.getString(super.getColumnIndex(column)); } private int translateStatus(int status) { switch (status) { case Downloads.STATUS_PENDING: return STATUS_PENDING; case Downloads.STATUS_RUNNING: return STATUS_RUNNING; case Downloads.Impl.STATUS_PAUSED_BY_APP: case Downloads.Impl.STATUS_WAITING_TO_RETRY: case Downloads.Impl.STATUS_WAITING_FOR_NETWORK: case Downloads.Impl.STATUS_QUEUED_FOR_WIFI: return STATUS_PAUSED; case Downloads.STATUS_SUCCESS: return STATUS_SUCCESSFUL; default: assert Downloads.isStatusError(status); return STATUS_FAILED; } } } ``` }
8,971,000
How to request Android download manager to download multiple files at the same time. Also I would like to know each and every file download status.
2012/01/23
[ "https://Stackoverflow.com/questions/8971000", "https://Stackoverflow.com", "https://Stackoverflow.com/users/676625/" ]
Request the first one. Then, request the second one. Then, request the third one. Continue as needed. Whether they download "at the same time" is not your concern, nor do you have control over it. They will download when `DownloadManager` decides to download them, which may be simultaneously or not.
``` public final class Downloads { /** * @hide */ private Downloads() {} /** * The permission to access the download manager * @hide . */ public static final String PERMISSION_ACCESS = "android.permission.ACCESS_DOWNLOAD_MANAGER"; /** * The permission to access the download manager's advanced functions * @hide */ public static final String PERMISSION_ACCESS_ADVANCED = "android.permission.ACCESS_DOWNLOAD_MANAGER_ADVANCED"; /** * The permission to directly access the download manager's cache directory * @hide */ public static final String PERMISSION_CACHE = "android.permission.ACCESS_CACHE_FILESYSTEM"; /** * The permission to send broadcasts on download completion * @hide */ public static final String PERMISSION_SEND_INTENTS = "android.permission.SEND_DOWNLOAD_COMPLETED_INTENTS"; /** * The content:// URI for the data table in the provider * @hide */ public static final Uri CONTENT_URI = Uri.parse("content://downloads/my_downloads"); /** * Broadcast Action: this is sent by the download manager to the app * that had initiated a download when that download completes. The * download's content: uri is specified in the intent's data. * @hide */ public static final String ACTION_DOWNLOAD_COMPLETED = "android.intent.action.DOWNLOAD_COMPLETED"; /** * Broadcast Action: this is sent by the download manager to the app * that had initiated a download when the user selects the notification * associated with that download. The download's content: uri is specified * in the intent's data if the click is associated with a single download, * or Downloads.CONTENT_URI if the notification is associated with * multiple downloads. * Note: this is not currently sent for downloads that have completed * successfully. * @hide */ public static final String ACTION_NOTIFICATION_CLICKED = "android.intent.action.DOWNLOAD_NOTIFICATION_CLICKED"; /** * The name of the column containing the URI of the data being downloaded. * <P>Type: TEXT</P> * <P>Owner can Init/Read</P> * @hide */ public static final String COLUMN_URI = "uri"; public static final String COLUMN_APP_DATA = "entity"; public static final String COLUMN_NO_INTEGRITY = "no_integrity"; public static final String COLUMN_FILE_NAME_HINT = "hint"; public static final String _DATA = "_data"; public static final String COLUMN_MIME_TYPE = "mimetype"; public static final String COLUMN_DESTINATION = "destination"; public static final String COLUMN_VISIBILITY = "visibility"; public static final String COLUMN_CONTROL = "control"; public static final String COLUMN_STATUS = "status"; /** * The name of the column containing the date at which some interesting * status changed in the download. Stored as a System.currentTimeMillis() * value. * <P>Type: BIGINT</P> * <P>Owner can Read</P> * @hide */ public static final String COLUMN_LAST_MODIFICATION = "lastmod"; /** * The name of the column containing the package name of the application * that initiating the download. The download manager will send * notifications to a component in this package when the download completes. * <P>Type: TEXT</P> * <P>Owner can Init/Read</P> * @hide */ public static final String COLUMN_NOTIFICATION_PACKAGE = "notificationpackage"; public static final String COLUMN_NOTIFICATION_CLASS = "notificationclass"; public static final String COLUMN_NOTIFICATION_EXTRAS = "notificationextras"; public static final String COLUMN_COOKIE_DATA = "cookiedata"; public static final String COLUMN_USER_AGENT = "useragent"; public static final String COLUMN_REFERER = "referer"; public static final String COLUMN_TOTAL_BYTES = "total_bytes"; public static final String COLUMN_CURRENT_BYTES = "current_bytes"; public static final String COLUMN_OTHER_UID = "otheruid"; public static final String COLUMN_TITLE = "title"; public static final String COLUMN_DESCRIPTION = "description"; public static final String COLUMN_DELETED = "deleted"; public static final int DESTINATION_EXTERNAL = 0; public static final int DESTINATION_CACHE_PARTITION = 1; public static final int DESTINATION_CACHE_PARTITION_PURGEABLE = 2; public static final int DESTINATION_CACHE_PARTITION_NOROAMING = 3; public static final int CONTROL_RUN = 0; public static final int CONTROL_PAUSED = 1; /** * Returns whether the status is informational (i.e. 1xx). * @hide */ public static boolean isStatusInformational(int status) { return (status >= 100 && status < 200); } public static boolean isStatusSuccess(int status) { return (status >= 200 && status < 300); } public static boolean isStatusError(int status) { return (status >= 400 && status < 600); } public static boolean isStatusClientError(int status) { return (status >= 400 && status < 500); } public static boolean isStatusServerError(int status) { return (status >= 500 && status < 600); } public static boolean isStatusCompleted(int status) { return (status >= 200 && status < 300) || (status >= 400 && status < 600); } public static final int STATUS_PENDING = 190; public static final int STATUS_RUNNING = 192; public static final int STATUS_SUCCESS = 200; public static final int STATUS_BAD_REQUEST = 400; public static final int STATUS_NOT_ACCEPTABLE = 406; public static final int STATUS_LENGTH_REQUIRED = 411; public static final int STATUS_PRECONDITION_FAILED = 412; public static final int STATUS_CANCELED = 490; public static final int STATUS_UNKNOWN_ERROR = 491; public static final int STATUS_FILE_ERROR = 492; public static final int STATUS_UNHANDLED_REDIRECT = 493; public static final int STATUS_UNHANDLED_HTTP_CODE = 494; public static final int STATUS_HTTP_DATA_ERROR = 495; public static final int STATUS_HTTP_EXCEPTION = 496; public static final int STATUS_TOO_MANY_REDIRECTS = 497; public static final int STATUS_INSUFFICIENT_SPACE_ERROR = 498; public static final int STATUS_DEVICE_NOT_FOUND_ERROR = 499; public static final int VISIBILITY_VISIBLE = 0; public static final int VISIBILITY_VISIBLE_NOTIFY_COMPLETED = 1; public static final int VISIBILITY_HIDDEN = 2; public static final class Impl implements BaseColumns { private Impl() {} /** * The permission to access the download manager */ public static final String PERMISSION_ACCESS = "android.permission.ACCESS_DOWNLOAD_MANAGER"; /** * The permission to access the download manager's advanced functions */ public static final String PERMISSION_ACCESS_ADVANCED = "android.permission.ACCESS_DOWNLOAD_MANAGER_ADVANCED"; /** * The permission to access the all the downloads in the manager. */ public static final String PERMISSION_ACCESS_ALL = "android.permission.ACCESS_ALL_DOWNLOADS"; /** * The permission to directly access the download manager's cache * directory */ public static final String PERMISSION_CACHE = "android.permission.ACCESS_CACHE_FILESYSTEM"; /** * The permission to send broadcasts on download completion */ public static final String PERMISSION_SEND_INTENTS = "android.permission.SEND_DOWNLOAD_COMPLETED_INTENTS"; /** * The permission to download files to the cache partition that won't be automatically * purged when space is needed. */ public static final String PERMISSION_CACHE_NON_PURGEABLE = "android.permission.DOWNLOAD_CACHE_NON_PURGEABLE"; /** * The permission to download files without any system notification being shown. */ public static final String PERMISSION_NO_NOTIFICATION = "android.permission.DOWNLOAD_WITHOUT_NOTIFICATION"; /** * The content:// URI to access downloads owned by the caller's UID. */ public static final Uri CONTENT_URI = Uri.parse("content://downloads/my_downloads"); public static final Uri ALL_DOWNLOADS_CONTENT_URI = Uri.parse("content://downloads/all_downloads"); public static final String ACTION_DOWNLOAD_COMPLETED = "android.intent.action.DOWNLOAD_COMPLETED"; public static final String ACTION_NOTIFICATION_CLICKED = "android.intent.action.DOWNLOAD_NOTIFICATION_CLICKED"; public static final String COLUMN_URI = "uri"; public static final String COLUMN_APP_DATA = "entity"; public static final String COLUMN_NO_INTEGRITY = "no_integrity"; public static final String COLUMN_FILE_NAME_HINT = "hint"; public static final String _DATA = "_data"; public static final String COLUMN_MIME_TYPE = "mimetype"; public static final String COLUMN_DESTINATION = "destination"; public static final String COLUMN_VISIBILITY = "visibility"; public static final String COLUMN_CONTROL = "control"; public static final String COLUMN_STATUS = "status"; public static final String COLUMN_LAST_MODIFICATION = "lastmod"; public static final String COLUMN_NOTIFICATION_PACKAGE = "notificationpackage"; public static final String COLUMN_NOTIFICATION_CLASS = "notificationclass"; public static final String COLUMN_NOTIFICATION_EXTRAS = "notificationextras"; public static final String COLUMN_COOKIE_DATA = "cookiedata"; public static final String COLUMN_USER_AGENT = "useragent"; public static final String COLUMN_REFERER = "referer"; public static final String COLUMN_TOTAL_BYTES = "total_bytes"; public static final String COLUMN_CURRENT_BYTES = "current_bytes"; public static final String COLUMN_OTHER_UID = "otheruid"; public static final String COLUMN_TITLE = "title"; public static final String COLUMN_DESCRIPTION = "description"; public static final String COLUMN_IS_PUBLIC_API = "is_public_api"; public static final String COLUMN_ALLOW_ROAMING = "allow_roaming"; public static final String COLUMN_ALLOWED_NETWORK_TYPES = "allowed_network_types"; public static final String COLUMN_IS_VISIBLE_IN_DOWNLOADS_UI = "is_visible_in_downloads_ui"; public static final String COLUMN_BYPASS_RECOMMENDED_SIZE_LIMIT = "bypass_recommended_size_limit"; public static final String COLUMN_DELETED = "deleted"; public static final String COLUMN_MEDIAPROVIDER_URI = "mediaprovider_uri"; /* * Lists the destinations that an application can specify for a download. */ public static final int DESTINATION_EXTERNAL = 0; public static final int DESTINATION_CACHE_PARTITION = 1; public static final int DESTINATION_CACHE_PARTITION_PURGEABLE = 2; /** * This download will be saved to the download manager's private * partition, as with DESTINATION_CACHE_PARTITION, but the download * will not proceed if the user is on a roaming data connection. */ public static final int DESTINATION_CACHE_PARTITION_NOROAMING = 3; /** * This download will be saved to the location given by the file URI in * {@link #COLUMN_FILE_NAME_HINT}. */ public static final int DESTINATION_FILE_URI = 4; /** * This download is allowed to run. */ public static final int CONTROL_RUN = 0; /** * This download must pause at the first opportunity. */ public static final int CONTROL_PAUSED = 1; /** * Returns whether the status is informational (i.e. 1xx). */ public static boolean isStatusInformational(int status) { return (status >= 100 && status < 200); } /** * Returns whether the status is a success (i.e. 2xx). */ public static boolean isStatusSuccess(int status) { return (status >= 200 && status < 300); } /** * Returns whether the status is an error (i.e. 4xx or 5xx). */ public static boolean isStatusError(int status) { return (status >= 400 && status < 600); } /** * Returns whether the status is a client error (i.e. 4xx). */ public static boolean isStatusClientError(int status) { return (status >= 400 && status < 500); } /** * Returns whether the status is a server error (i.e. 5xx). */ public static boolean isStatusServerError(int status) { return (status >= 500 && status < 600); } /** * Returns whether the download has completed (either with success or * error). */ public static boolean isStatusCompleted(int status) { return (status >= 200 && status < 300) || (status >= 400 && status < 600); } /** * This download hasn't stated yet */ public static final int STATUS_PENDING = 190; /** * This download has started */ public static final int STATUS_RUNNING = 192; /** * This download has been paused by the owning app. */ public static final int STATUS_PAUSED_BY_APP = 193; /** * This download encountered some network error and is waiting before retrying the request. */ public static final int STATUS_WAITING_TO_RETRY = 194; /** * This download is waiting for network connectivity to proceed. */ public static final int STATUS_WAITING_FOR_NETWORK = 195; /** * This download exceeded a size limit for mobile networks and is waiting for a Wi-Fi * connection to proceed. */ public static final int STATUS_QUEUED_FOR_WIFI = 196; public static final int STATUS_SUCCESS = 200; public static final int STATUS_BAD_REQUEST = 400; /** * This download can't be performed because the content type cannot be * handled. */ public static final int STATUS_NOT_ACCEPTABLE = 406; public static final int STATUS_LENGTH_REQUIRED = 411; /** * This download was interrupted and cannot be resumed. * This is the code for the HTTP error "Precondition Failed", and it is * also used in situations where the client doesn't have an ETag at all. */ public static final int STATUS_PRECONDITION_FAILED = 412; /** * The lowest-valued error status that is not an actual HTTP status code. */ public static final int MIN_ARTIFICIAL_ERROR_STATUS = 488; /** * The requested destination file already exists. */ public static final int STATUS_FILE_ALREADY_EXISTS_ERROR = 488; /** * Some possibly transient error occurred, but we can't resume the download. */ public static final int STATUS_CANNOT_RESUME = 489; /** * This download was canceled */ public static final int STATUS_CANCELED = 490; public static final int STATUS_UNKNOWN_ERROR = 491; public static final int STATUS_FILE_ERROR = 492; /** * This download couldn't be completed because of an HTTP * redirect response that the download manager couldn't * handle. */ public static final int STATUS_UNHANDLED_REDIRECT = 493; /** * This download couldn't be completed because of an * unspecified unhandled HTTP code. */ public static final int STATUS_UNHANDLED_HTTP_CODE = 494; /** * This download couldn't be completed because of an * error receiving or processing data at the HTTP level. */ public static final int STATUS_HTTP_DATA_ERROR = 495; /** * This download couldn't be completed because of an * HttpException while setting up the request. */ public static final int STATUS_HTTP_EXCEPTION = 496; /** * This download couldn't be completed because there were * too many redirects. */ public static final int STATUS_TOO_MANY_REDIRECTS = 497; /** * This download couldn't be completed due to insufficient storage * space. Typically, this is because the SD card is full. */ public static final int STATUS_INSUFFICIENT_SPACE_ERROR = 498; /** * This download couldn't be completed because no external storage * device was found. Typically, this is because the SD card is not * mounted. */ public static final int STATUS_DEVICE_NOT_FOUND_ERROR = 499; /** * This download is visible but only shows in the notifications * while it's in progress. */ public static final int VISIBILITY_VISIBLE = 0; /** * This download is visible and shows in the notifications while * in progress and after completion. */ public static final int VISIBILITY_VISIBLE_NOTIFY_COMPLETED = 1; /** * This download doesn't show in the UI or in the notifications. */ public static final int VISIBILITY_HIDDEN = 2; /** * Constants related to HTTP request headers associated with each download. */ public static class RequestHeaders { public static final String HEADERS_DB_TABLE = "request_headers"; public static final String COLUMN_DOWNLOAD_ID = "download_id"; public static final String COLUMN_HEADER = "header"; public static final String COLUMN_VALUE = "value"; /** * Path segment to add to a download URI to retrieve request headers */ public static final String URI_SEGMENT = "headers"; /** * Prefix for ContentValues keys that contain HTTP header lines, to be passed to * DownloadProvider.insert(). */ public static final String INSERT_KEY_PREFIX = "http_header_"; } } } ```
8,971,000
How to request Android download manager to download multiple files at the same time. Also I would like to know each and every file download status.
2012/01/23
[ "https://Stackoverflow.com/questions/8971000", "https://Stackoverflow.com", "https://Stackoverflow.com/users/676625/" ]
``` 1. Register listener for download complete IntentFilter intentFilter = new IntentFilter( DownloadManager.ACTION_DOWNLOAD_COMPLETE); registerReceiver(downloadReceiver, intentFilter); 2.Make request Uri downloadUri = Uri.parse(entry.getValue()); DownloadManager.Request request = new DownloadManager.Request( downloadUri); request.setDestinationUri(path_to _file_store))); downloadManager.enqueue(request); 3.Check status in listener private BroadcastReceiver downloadReceiver = new BroadcastReceiver() { @Override public void onReceive(Context arg0, Intent intent) { String action = intent.getAction(); if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) { long downloadId = intent.getLongExtra( DownloadManager.EXTRA_DOWNLOAD_ID, 0); System.out.println("download id=" + downloadId); CheckDwnloadStatus(downloadId); } } }; private void CheckDwnloadStatus(long id) { // TODO Auto-generated method stub DownloadManager.Query query = new DownloadManager.Query(); query.setFilterById(id); Cursor cursor = downloadManager.query(query); if (cursor.moveToFirst()) { int columnIndex = cursor .getColumnIndex(DownloadManager.COLUMN_STATUS); int status = cursor.getInt(columnIndex); int columnReason = cursor .getColumnIndex(DownloadManager.COLUMN_REASON); int reason = cursor.getInt(columnReason); switch (status) { case DownloadManager.STATUS_FAILED: String failedReason = ""; switch (reason) { case DownloadManager.ERROR_CANNOT_RESUME: failedReason = "ERROR_CANNOT_RESUME"; break; case DownloadManager.ERROR_DEVICE_NOT_FOUND: failedReason = "ERROR_DEVICE_NOT_FOUND"; break; case DownloadManager.ERROR_FILE_ALREADY_EXISTS: failedReason = "ERROR_FILE_ALREADY_EXISTS"; break; case DownloadManager.ERROR_FILE_ERROR: failedReason = "ERROR_FILE_ERROR"; break; case DownloadManager.ERROR_HTTP_DATA_ERROR: failedReason = "ERROR_HTTP_DATA_ERROR"; break; case DownloadManager.ERROR_INSUFFICIENT_SPACE: failedReason = "ERROR_INSUFFICIENT_SPACE"; break; case DownloadManager.ERROR_TOO_MANY_REDIRECTS: failedReason = "ERROR_TOO_MANY_REDIRECTS"; break; case DownloadManager.ERROR_UNHANDLED_HTTP_CODE: failedReason = "ERROR_UNHANDLED_HTTP_CODE"; break; case DownloadManager.ERROR_UNKNOWN: failedReason = "ERROR_UNKNOWN"; break; } Toast.makeText(this, "FAILED: " + failedReason, Toast.LENGTH_LONG).show(); break; case DownloadManager.STATUS_PAUSED: String pausedReason = ""; switch (reason) { case DownloadManager.PAUSED_QUEUED_FOR_WIFI: pausedReason = "PAUSED_QUEUED_FOR_WIFI"; break; case DownloadManager.PAUSED_UNKNOWN: pausedReason = "PAUSED_UNKNOWN"; break; case DownloadManager.PAUSED_WAITING_FOR_NETWORK: pausedReason = "PAUSED_WAITING_FOR_NETWORK"; break; case DownloadManager.PAUSED_WAITING_TO_RETRY: pausedReason = "PAUSED_WAITING_TO_RETRY"; break; } Toast.makeText(this, "PAUSED: " + pausedReason, Toast.LENGTH_LONG).show(); break; case DownloadManager.STATUS_PENDING: Toast.makeText(this, "PENDING", Toast.LENGTH_LONG).show(); break; case DownloadManager.STATUS_RUNNING: Toast.makeText(this, "RUNNING", Toast.LENGTH_LONG).show(); break; case DownloadManager.STATUS_SUCCESSFUL: caluclateLoadingData(); // Toast.makeText(this, "SUCCESSFUL", Toast.LENGTH_LONG).show(); // GetFile(); break; } } } ```
public class DownloadManager { private static final String TAG = "DownloadManager"; ``` public final static String COLUMN_ID = BaseColumns._ID; public final static String COLUMN_TITLE = "title"; public final static String COLUMN_DESCRIPTION = "description"; public final static String COLUMN_URI = "uri"; public final static String COLUMN_MEDIA_TYPE = "media_type"; public final static String COLUMN_TOTAL_SIZE_BYTES = "total_size"; public final static String COLUMN_LOCAL_URI = "local_uri"; public final static String COLUMN_STATUS = "status"; public final static String COLUMN_REASON = "reason"; public final static String COLUMN_BYTES_DOWNLOADED_SO_FAR = "bytes_so_far"; public final static String COLUMN_LAST_MODIFIED_TIMESTAMP = "last_modified_timestamp"; public static final String COLUMN_MEDIAPROVIDER_URI = "mediaprovider_uri"; public final static int STATUS_PENDING = 1 << 0; public final static int STATUS_RUNNING = 1 << 1; public final static int STATUS_PAUSED = 1 << 2; public final static int STATUS_SUCCESSFUL = 1 << 3; public final static int STATUS_FAILED = 1 << 4; public final static int ERROR_UNKNOWN = 1000; public final static int ERROR_FILE_ERROR = 1001; public final static int ERROR_UNHANDLED_HTTP_CODE = 1002; public final static int ERROR_HTTP_DATA_ERROR = 1004; public final static int ERROR_TOO_MANY_REDIRECTS = 1005; public final static int ERROR_INSUFFICIENT_SPACE = 1006; public final static int ERROR_DEVICE_NOT_FOUND = 1007; public final static int ERROR_CANNOT_RESUME = 1008; public final static int ERROR_FILE_ALREADY_EXISTS = 1009; public final static int PAUSED_WAITING_TO_RETRY = 1; public final static int PAUSED_WAITING_FOR_NETWORK = 2; public final static int PAUSED_QUEUED_FOR_WIFI = 3; public final static int PAUSED_UNKNOWN = 4; public final static String ACTION_DOWNLOAD_COMPLETE = "android.intent.action.DOWNLOAD_COMPLETE"; public final static String ACTION_NOTIFICATION_CLICKED = "android.intent.action.DOWNLOAD_NOTIFICATION_CLICKED"; public final static String ACTION_VIEW_DOWNLOADS = "android.intent.action.VIEW_DOWNLOADS"; public static final String EXTRA_DOWNLOAD_ID = "extra_download_id"; // this array must contain all public columns private static final String[] COLUMNS = new String[] { COLUMN_ID, COLUMN_MEDIAPROVIDER_URI, COLUMN_TITLE, COLUMN_DESCRIPTION, COLUMN_URI, COLUMN_MEDIA_TYPE, COLUMN_TOTAL_SIZE_BYTES, COLUMN_LOCAL_URI, COLUMN_STATUS, COLUMN_REASON, COLUMN_BYTES_DOWNLOADED_SO_FAR, COLUMN_LAST_MODIFIED_TIMESTAMP }; // columns to request from DownloadProvider private static final String[] UNDERLYING_COLUMNS = new String[] { Downloads.Impl._ID, Downloads.Impl.COLUMN_MEDIAPROVIDER_URI, Downloads.COLUMN_TITLE, Downloads.COLUMN_DESCRIPTION, Downloads.COLUMN_URI, Downloads.COLUMN_MIME_TYPE, Downloads.COLUMN_TOTAL_BYTES, Downloads.COLUMN_STATUS, Downloads.COLUMN_CURRENT_BYTES, Downloads.COLUMN_LAST_MODIFICATION, Downloads.COLUMN_DESTINATION, Downloads.Impl.COLUMN_FILE_NAME_HINT, Downloads.Impl._DATA, }; private static final Set<String> LONG_COLUMNS = new HashSet<String>( Arrays.asList(COLUMN_ID, COLUMN_TOTAL_SIZE_BYTES, COLUMN_STATUS, COLUMN_REASON, COLUMN_BYTES_DOWNLOADED_SO_FAR, COLUMN_LAST_MODIFIED_TIMESTAMP)); public static class Request { public static final int NETWORK_MOBILE = 1 << 0; public static final int NETWORK_WIFI = 1 << 1; private Uri mUri; private Uri mDestinationUri; private List<Pair<String, String>> mRequestHeaders = new ArrayList<Pair<String, String>>(); private CharSequence mTitle; private CharSequence mDescription; private boolean mShowNotification = true; private String mMimeType; private boolean mRoamingAllowed = true; private int mAllowedNetworkTypes = ~0; // default to all network types // allowed private boolean mIsVisibleInDownloadsUi = true; /** * @param uri * the HTTP URI to download. */ public Request(Uri uri) { if (uri == null) { throw new NullPointerException(); } String scheme = uri.getScheme(); if (scheme == null || !(scheme.equals("http") || scheme.equals("https"))) { throw new IllegalArgumentException( "Can only download HTTP URIs: " + uri); } mUri = uri; } public Request setDestinationUri(Uri uri) { mDestinationUri = uri; return this; } public Request setDestinationInExternalFilesDir(Context context, String dirType, String subPath) { setDestinationFromBase(context.getExternalFilesDir(dirType), subPath); return this; } public Request setDestinationInExternalPublicDir(String dirType, String subPath) { setDestinationFromBase( Environment.getExternalStoragePublicDirectory(dirType), subPath); return this; } private void setDestinationFromBase(File base, String subPath) { if (subPath == null) { throw new NullPointerException("subPath cannot be null"); } mDestinationUri = Uri.withAppendedPath(Uri.fromFile(base), subPath); } public Request addRequestHeader(String header, String value) { if (header == null) { throw new NullPointerException("header cannot be null"); } if (header.contains(":")) { throw new IllegalArgumentException("header may not contain ':'"); } if (value == null) { value = ""; } mRequestHeaders.add(Pair.create(header, value)); return this; } public Request setTitle(CharSequence title) { mTitle = title; return this; } public Request setDescription(CharSequence description) { mDescription = description; return this; } public Request setMimeType(String mimeType) { mMimeType = mimeType; return this; } public Request setShowRunningNotification(boolean show) { mShowNotification = show; return this; } public Request setAllowedNetworkTypes(int flags) { mAllowedNetworkTypes = flags; return this; } public Request setAllowedOverRoaming(boolean allowed) { mRoamingAllowed = allowed; return this; } public Request setVisibleInDownloadsUi(boolean isVisible) { mIsVisibleInDownloadsUi = isVisible; return this; } /** * @return ContentValues to be passed to DownloadProvider.insert() */ ContentValues toContentValues(String packageName) { ContentValues values = new ContentValues(); assert mUri != null; values.put(Downloads.COLUMN_URI, mUri.toString()); values.put(Downloads.Impl.COLUMN_IS_PUBLIC_API, true); values.put(Downloads.COLUMN_NOTIFICATION_PACKAGE, packageName); if (mDestinationUri != null) { values.put(Downloads.COLUMN_DESTINATION, Downloads.Impl.DESTINATION_FILE_URI); values.put(Downloads.COLUMN_FILE_NAME_HINT, mDestinationUri.toString()); } else { values.put(Downloads.COLUMN_DESTINATION, Downloads.DESTINATION_CACHE_PARTITION_PURGEABLE); } if (!mRequestHeaders.isEmpty()) { encodeHttpHeaders(values); } putIfNonNull(values, Downloads.COLUMN_TITLE, mTitle); putIfNonNull(values, Downloads.COLUMN_DESCRIPTION, mDescription); putIfNonNull(values, Downloads.COLUMN_MIME_TYPE, mMimeType); values.put(Downloads.COLUMN_VISIBILITY, mShowNotification ? Downloads.VISIBILITY_VISIBLE : Downloads.VISIBILITY_HIDDEN); values.put(Downloads.Impl.COLUMN_ALLOWED_NETWORK_TYPES, mAllowedNetworkTypes); values.put(Downloads.Impl.COLUMN_ALLOW_ROAMING, mRoamingAllowed); values.put(Downloads.Impl.COLUMN_IS_VISIBLE_IN_DOWNLOADS_UI, mIsVisibleInDownloadsUi); return values; } private void encodeHttpHeaders(ContentValues values) { int index = 0; for (Pair<String, String> header : mRequestHeaders) { String headerString = header.first + ": " + header.second; values.put(Downloads.Impl.RequestHeaders.INSERT_KEY_PREFIX + index, headerString); index++; } } private void putIfNonNull(ContentValues contentValues, String key, Object value) { if (value != null) { contentValues.put(key, value.toString()); } } } /** * This class may be used to filter download manager queries. */ public static class Query { /** * Constant for use with {@link #orderBy} * * @hide */ public static final int ORDER_ASCENDING = 1; /** * Constant for use with {@link #orderBy} * * @hide */ public static final int ORDER_DESCENDING = 2; private long[] mIds = null; private Integer mStatusFlags = null; private String mOrderByColumn = Downloads.COLUMN_LAST_MODIFICATION; private int mOrderDirection = ORDER_DESCENDING; private boolean mOnlyIncludeVisibleInDownloadsUi = false; /** * Include only the downloads with the given IDs. * * @return this object */ public Query setFilterById(long... ids) { mIds = ids; return this; } /** * Include only downloads with status matching any the given status * flags. * * @param flags * any combination of the STATUS_* bit flags * @return this object */ public Query setFilterByStatus(int flags) { mStatusFlags = flags; return this; } /** * Controls whether this query includes downloads not visible in the * system's Downloads UI. * * @param value * if true, this query will only include downloads that * should be displayed in the system's Downloads UI; if false * (the default), this query will include both visible and * invisible downloads. * @return this object * @hide */ public Query setOnlyIncludeVisibleInDownloadsUi(boolean value) { mOnlyIncludeVisibleInDownloadsUi = value; return this; } /** * Change the sort order of the returned Cursor. * * @param column * one of the COLUMN_* constants; currently, only * {@link #COLUMN_LAST_MODIFIED_TIMESTAMP} and * {@link #COLUMN_TOTAL_SIZE_BYTES} are supported. * @param direction * either {@link #ORDER_ASCENDING} or * {@link #ORDER_DESCENDING} * @return this object * @hide */ public Query orderBy(String column, int direction) { if (direction != ORDER_ASCENDING && direction != ORDER_DESCENDING) { throw new IllegalArgumentException("Invalid direction: " + direction); } if (column.equals(COLUMN_LAST_MODIFIED_TIMESTAMP)) { mOrderByColumn = Downloads.COLUMN_LAST_MODIFICATION; } else if (column.equals(COLUMN_TOTAL_SIZE_BYTES)) { mOrderByColumn = Downloads.COLUMN_TOTAL_BYTES; } else { throw new IllegalArgumentException("Cannot order by " + column); } mOrderDirection = direction; return this; } /** * Run this query using the given ContentResolver. * * @param projection * the projection to pass to ContentResolver.query() * @return the Cursor returned by ContentResolver.query() */ Cursor runQuery(ContentResolver resolver, String[] projection, Uri baseUri) { Uri uri = baseUri; List<String> selectionParts = new ArrayList<String>(); String[] selectionArgs = null; if (mIds != null) { selectionParts.add(getWhereClauseForIds(mIds)); selectionArgs = getWhereArgsForIds(mIds); } if (mStatusFlags != null) { List<String> parts = new ArrayList<String>(); if ((mStatusFlags & STATUS_PENDING) != 0) { parts.add(statusClause("=", Downloads.STATUS_PENDING)); } if ((mStatusFlags & STATUS_RUNNING) != 0) { parts.add(statusClause("=", Downloads.STATUS_RUNNING)); } if ((mStatusFlags & STATUS_PAUSED) != 0) { parts.add(statusClause("=", Downloads.Impl.STATUS_PAUSED_BY_APP)); parts.add(statusClause("=", Downloads.Impl.STATUS_WAITING_TO_RETRY)); parts.add(statusClause("=", Downloads.Impl.STATUS_WAITING_FOR_NETWORK)); parts.add(statusClause("=", Downloads.Impl.STATUS_QUEUED_FOR_WIFI)); } if ((mStatusFlags & STATUS_SUCCESSFUL) != 0) { parts.add(statusClause("=", Downloads.STATUS_SUCCESS)); } if ((mStatusFlags & STATUS_FAILED) != 0) { parts.add("(" + statusClause(">=", 400) + " AND " + statusClause("<", 600) + ")"); } selectionParts.add(joinStrings(" OR ", parts)); } if (mOnlyIncludeVisibleInDownloadsUi) { selectionParts .add(Downloads.Impl.COLUMN_IS_VISIBLE_IN_DOWNLOADS_UI + " != '0'"); } // only return rows which are not marked 'deleted = 1' selectionParts.add(Downloads.Impl.COLUMN_DELETED + " != '1'"); String selection = joinStrings(" AND ", selectionParts); String orderDirection = (mOrderDirection == ORDER_ASCENDING ? "ASC" : "DESC"); String orderBy = mOrderByColumn + " " + orderDirection; return resolver.query(uri, projection, selection, selectionArgs, orderBy); } private String joinStrings(String joiner, Iterable<String> parts) { StringBuilder builder = new StringBuilder(); boolean first = true; for (String part : parts) { if (!first) { builder.append(joiner); } builder.append(part); first = false; } return builder.toString(); } private String statusClause(String operator, int value) { return Downloads.COLUMN_STATUS + operator + "'" + value + "'"; } } private ContentResolver mResolver; private String mPackageName; private Uri mBaseUri = Downloads.Impl.CONTENT_URI; /** * @hide */ public DownloadManager(ContentResolver resolver, String packageName) { mResolver = resolver; mPackageName = packageName; } /** * Makes this object access the download provider through /all_downloads * URIs rather than /my_downloads URIs, for clients that have permission to * do so. * * @hide */ public void setAccessAllDownloads(boolean accessAllDownloads) { if (accessAllDownloads) { mBaseUri = Downloads.Impl.ALL_DOWNLOADS_CONTENT_URI; } else { mBaseUri = Downloads.Impl.CONTENT_URI; } } public long enqueue(Request request) { ContentValues values = request.toContentValues(mPackageName); Uri downloadUri = mResolver.insert(Downloads.CONTENT_URI, values); long id = Long.parseLong(downloadUri.getLastPathSegment()); return id; } public int markRowDeleted(long... ids) { if (ids == null || ids.length == 0) { // called with nothing to remove! throw new IllegalArgumentException( "input param 'ids' can't be null"); } ContentValues values = new ContentValues(); values.put(Downloads.Impl.COLUMN_DELETED, 1); return mResolver.update(mBaseUri, values, getWhereClauseForIds(ids), getWhereArgsForIds(ids)); } public int remove(long... ids) { if (ids == null || ids.length == 0) { // called with nothing to remove! throw new IllegalArgumentException( "input param 'ids' can't be null"); } return mResolver.delete(mBaseUri, getWhereClauseForIds(ids), getWhereArgsForIds(ids)); } public Cursor query(Query query) { Cursor underlyingCursor = query.runQuery(mResolver, UNDERLYING_COLUMNS, mBaseUri); if (underlyingCursor == null) { return null; } return new CursorTranslator(underlyingCursor, mBaseUri); } public ParcelFileDescriptor openDownloadedFile(long id) throws FileNotFoundException { return mResolver.openFileDescriptor(getDownloadUri(id), "r"); } public void restartDownload(long... ids) { Cursor cursor = query(new Query().setFilterById(ids)); try { for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor .moveToNext()) { int status = cursor .getInt(cursor.getColumnIndex(COLUMN_STATUS)); if (status != STATUS_SUCCESSFUL && status != STATUS_FAILED) { throw new IllegalArgumentException( "Cannot restart incomplete download: " + cursor.getLong(cursor .getColumnIndex(COLUMN_ID))); } } } finally { cursor.close(); } ContentValues values = new ContentValues(); values.put(Downloads.Impl.COLUMN_CURRENT_BYTES, 0); values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, -1); values.putNull(Downloads.Impl._DATA); values.put(Downloads.Impl.COLUMN_STATUS, Downloads.Impl.STATUS_PENDING); mResolver.update(mBaseUri, values, getWhereClauseForIds(ids), getWhereArgsForIds(ids)); } /** * Get the DownloadProvider URI for the download with the given ID. */ Uri getDownloadUri(long id) { return ContentUris.withAppendedId(mBaseUri, id); } /** * Get a parameterized SQL WHERE clause to select a bunch of IDs. */ static String getWhereClauseForIds(long[] ids) { StringBuilder whereClause = new StringBuilder(); whereClause.append("("); for (int i = 0; i < ids.length; i++) { if (i > 0) { whereClause.append("OR "); } whereClause.append(Downloads.Impl._ID); whereClause.append(" = ? "); } whereClause.append(")"); return whereClause.toString(); } /** * Get the selection args for a clause returned by * {@link #getWhereClauseForIds(long[])}. */ static String[] getWhereArgsForIds(long[] ids) { String[] whereArgs = new String[ids.length]; for (int i = 0; i < ids.length; i++) { whereArgs[i] = Long.toString(ids[i]); } return whereArgs; } /** * This class wraps a cursor returned by DownloadProvider -- the * "underlying cursor" -- and presents a different set of columns, those * defined in the DownloadManager.COLUMN_* constants. Some columns * correspond directly to underlying values while others are computed from * underlying data. */ private static class CursorTranslator extends CursorWrapper { private Uri mBaseUri; public CursorTranslator(Cursor cursor, Uri baseUri) { super(cursor); mBaseUri = baseUri; } @Override public int getColumnIndex(String columnName) { return Arrays.asList(COLUMNS).indexOf(columnName); } @Override public int getColumnIndexOrThrow(String columnName) throws IllegalArgumentException { int index = getColumnIndex(columnName); if (index == -1) { throw new IllegalArgumentException("No such column: " + columnName); } return index; } @Override public String getColumnName(int columnIndex) { int numColumns = COLUMNS.length; if (columnIndex < 0 || columnIndex >= numColumns) { throw new IllegalArgumentException("Invalid column index " + columnIndex + ", " + numColumns + " columns exist"); } return COLUMNS[columnIndex]; } @Override public String[] getColumnNames() { String[] returnColumns = new String[COLUMNS.length]; System.arraycopy(COLUMNS, 0, returnColumns, 0, COLUMNS.length); return returnColumns; } @Override public int getColumnCount() { return COLUMNS.length; } @Override public byte[] getBlob(int columnIndex) { throw new UnsupportedOperationException(); } @Override public double getDouble(int columnIndex) { return getLong(columnIndex); } private boolean isLongColumn(String column) { return LONG_COLUMNS.contains(column); } @Override public float getFloat(int columnIndex) { return (float) getDouble(columnIndex); } @Override public int getInt(int columnIndex) { return (int) getLong(columnIndex); } @Override public long getLong(int columnIndex) { return translateLong(getColumnName(columnIndex)); } @Override public short getShort(int columnIndex) { return (short) getLong(columnIndex); } @Override public String getString(int columnIndex) { return translateString(getColumnName(columnIndex)); } private String translateString(String column) { if (isLongColumn(column)) { return Long.toString(translateLong(column)); } if (column.equals(COLUMN_TITLE)) { return getUnderlyingString(Downloads.COLUMN_TITLE); } if (column.equals(COLUMN_DESCRIPTION)) { return getUnderlyingString(Downloads.COLUMN_DESCRIPTION); } if (column.equals(COLUMN_URI)) { return getUnderlyingString(Downloads.COLUMN_URI); } if (column.equals(COLUMN_MEDIA_TYPE)) { return getUnderlyingString(Downloads.COLUMN_MIME_TYPE); } if (column.equals(COLUMN_MEDIAPROVIDER_URI)) { return getUnderlyingString(Downloads.Impl.COLUMN_MEDIAPROVIDER_URI); } assert column.equals(COLUMN_LOCAL_URI); return getLocalUri(); } private String getLocalUri() { long destinationType = getUnderlyingLong(Downloads.Impl.COLUMN_DESTINATION); if (destinationType == Downloads.Impl.DESTINATION_FILE_URI) { // return client-provided file URI for external download return getUnderlyingString(Downloads.Impl.COLUMN_FILE_NAME_HINT); } if (destinationType == Downloads.Impl.DESTINATION_EXTERNAL) { // return stored destination for legacy external download String localPath = getUnderlyingString(Downloads.Impl._DATA); if (localPath == null) { return null; } return Uri.fromFile(new File(localPath)).toString(); } // return content URI for cache download long downloadId = getUnderlyingLong(Downloads.Impl._ID); return ContentUris.withAppendedId(mBaseUri, downloadId).toString(); } private long translateLong(String column) { if (!isLongColumn(column)) { // mimic behavior of underlying cursor -- most likely, throw // NumberFormatException return Long.valueOf(translateString(column)); } if (column.equals(COLUMN_ID)) { return getUnderlyingLong(Downloads.Impl._ID); } if (column.equals(COLUMN_TOTAL_SIZE_BYTES)) { return getUnderlyingLong(Downloads.COLUMN_TOTAL_BYTES); } if (column.equals(COLUMN_STATUS)) { return translateStatus((int) getUnderlyingLong(Downloads.COLUMN_STATUS)); } if (column.equals(COLUMN_REASON)) { return getReason((int) getUnderlyingLong(Downloads.COLUMN_STATUS)); } if (column.equals(COLUMN_BYTES_DOWNLOADED_SO_FAR)) { return getUnderlyingLong(Downloads.COLUMN_CURRENT_BYTES); } assert column.equals(COLUMN_LAST_MODIFIED_TIMESTAMP); return getUnderlyingLong(Downloads.COLUMN_LAST_MODIFICATION); } private long getReason(int status) { switch (translateStatus(status)) { case STATUS_FAILED: return getErrorCode(status); case STATUS_PAUSED: return getPausedReason(status); default: return 0; // arbitrary value when status is not an error } } private long getPausedReason(int status) { switch (status) { case Downloads.Impl.STATUS_WAITING_TO_RETRY: return PAUSED_WAITING_TO_RETRY; case Downloads.Impl.STATUS_WAITING_FOR_NETWORK: return PAUSED_WAITING_FOR_NETWORK; case Downloads.Impl.STATUS_QUEUED_FOR_WIFI: return PAUSED_QUEUED_FOR_WIFI; default: return PAUSED_UNKNOWN; } } private long getErrorCode(int status) { if ((400 <= status && status < Downloads.Impl.MIN_ARTIFICIAL_ERROR_STATUS) || (500 <= status && status < 600)) { // HTTP status code return status; } switch (status) { case Downloads.STATUS_FILE_ERROR: return ERROR_FILE_ERROR; case Downloads.STATUS_UNHANDLED_HTTP_CODE: case Downloads.STATUS_UNHANDLED_REDIRECT: return ERROR_UNHANDLED_HTTP_CODE; case Downloads.STATUS_HTTP_DATA_ERROR: return ERROR_HTTP_DATA_ERROR; case Downloads.STATUS_TOO_MANY_REDIRECTS: return ERROR_TOO_MANY_REDIRECTS; case Downloads.STATUS_INSUFFICIENT_SPACE_ERROR: return ERROR_INSUFFICIENT_SPACE; case Downloads.STATUS_DEVICE_NOT_FOUND_ERROR: return ERROR_DEVICE_NOT_FOUND; case Downloads.Impl.STATUS_CANNOT_RESUME: return ERROR_CANNOT_RESUME; case Downloads.Impl.STATUS_FILE_ALREADY_EXISTS_ERROR: return ERROR_FILE_ALREADY_EXISTS; default: return ERROR_UNKNOWN; } } private long getUnderlyingLong(String column) { return super.getLong(super.getColumnIndex(column)); } private String getUnderlyingString(String column) { return super.getString(super.getColumnIndex(column)); } private int translateStatus(int status) { switch (status) { case Downloads.STATUS_PENDING: return STATUS_PENDING; case Downloads.STATUS_RUNNING: return STATUS_RUNNING; case Downloads.Impl.STATUS_PAUSED_BY_APP: case Downloads.Impl.STATUS_WAITING_TO_RETRY: case Downloads.Impl.STATUS_WAITING_FOR_NETWORK: case Downloads.Impl.STATUS_QUEUED_FOR_WIFI: return STATUS_PAUSED; case Downloads.STATUS_SUCCESS: return STATUS_SUCCESSFUL; default: assert Downloads.isStatusError(status); return STATUS_FAILED; } } } ``` }
8,971,000
How to request Android download manager to download multiple files at the same time. Also I would like to know each and every file download status.
2012/01/23
[ "https://Stackoverflow.com/questions/8971000", "https://Stackoverflow.com", "https://Stackoverflow.com/users/676625/" ]
``` 1. Register listener for download complete IntentFilter intentFilter = new IntentFilter( DownloadManager.ACTION_DOWNLOAD_COMPLETE); registerReceiver(downloadReceiver, intentFilter); 2.Make request Uri downloadUri = Uri.parse(entry.getValue()); DownloadManager.Request request = new DownloadManager.Request( downloadUri); request.setDestinationUri(path_to _file_store))); downloadManager.enqueue(request); 3.Check status in listener private BroadcastReceiver downloadReceiver = new BroadcastReceiver() { @Override public void onReceive(Context arg0, Intent intent) { String action = intent.getAction(); if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) { long downloadId = intent.getLongExtra( DownloadManager.EXTRA_DOWNLOAD_ID, 0); System.out.println("download id=" + downloadId); CheckDwnloadStatus(downloadId); } } }; private void CheckDwnloadStatus(long id) { // TODO Auto-generated method stub DownloadManager.Query query = new DownloadManager.Query(); query.setFilterById(id); Cursor cursor = downloadManager.query(query); if (cursor.moveToFirst()) { int columnIndex = cursor .getColumnIndex(DownloadManager.COLUMN_STATUS); int status = cursor.getInt(columnIndex); int columnReason = cursor .getColumnIndex(DownloadManager.COLUMN_REASON); int reason = cursor.getInt(columnReason); switch (status) { case DownloadManager.STATUS_FAILED: String failedReason = ""; switch (reason) { case DownloadManager.ERROR_CANNOT_RESUME: failedReason = "ERROR_CANNOT_RESUME"; break; case DownloadManager.ERROR_DEVICE_NOT_FOUND: failedReason = "ERROR_DEVICE_NOT_FOUND"; break; case DownloadManager.ERROR_FILE_ALREADY_EXISTS: failedReason = "ERROR_FILE_ALREADY_EXISTS"; break; case DownloadManager.ERROR_FILE_ERROR: failedReason = "ERROR_FILE_ERROR"; break; case DownloadManager.ERROR_HTTP_DATA_ERROR: failedReason = "ERROR_HTTP_DATA_ERROR"; break; case DownloadManager.ERROR_INSUFFICIENT_SPACE: failedReason = "ERROR_INSUFFICIENT_SPACE"; break; case DownloadManager.ERROR_TOO_MANY_REDIRECTS: failedReason = "ERROR_TOO_MANY_REDIRECTS"; break; case DownloadManager.ERROR_UNHANDLED_HTTP_CODE: failedReason = "ERROR_UNHANDLED_HTTP_CODE"; break; case DownloadManager.ERROR_UNKNOWN: failedReason = "ERROR_UNKNOWN"; break; } Toast.makeText(this, "FAILED: " + failedReason, Toast.LENGTH_LONG).show(); break; case DownloadManager.STATUS_PAUSED: String pausedReason = ""; switch (reason) { case DownloadManager.PAUSED_QUEUED_FOR_WIFI: pausedReason = "PAUSED_QUEUED_FOR_WIFI"; break; case DownloadManager.PAUSED_UNKNOWN: pausedReason = "PAUSED_UNKNOWN"; break; case DownloadManager.PAUSED_WAITING_FOR_NETWORK: pausedReason = "PAUSED_WAITING_FOR_NETWORK"; break; case DownloadManager.PAUSED_WAITING_TO_RETRY: pausedReason = "PAUSED_WAITING_TO_RETRY"; break; } Toast.makeText(this, "PAUSED: " + pausedReason, Toast.LENGTH_LONG).show(); break; case DownloadManager.STATUS_PENDING: Toast.makeText(this, "PENDING", Toast.LENGTH_LONG).show(); break; case DownloadManager.STATUS_RUNNING: Toast.makeText(this, "RUNNING", Toast.LENGTH_LONG).show(); break; case DownloadManager.STATUS_SUCCESSFUL: caluclateLoadingData(); // Toast.makeText(this, "SUCCESSFUL", Toast.LENGTH_LONG).show(); // GetFile(); break; } } } ```
``` public final class Downloads { /** * @hide */ private Downloads() {} /** * The permission to access the download manager * @hide . */ public static final String PERMISSION_ACCESS = "android.permission.ACCESS_DOWNLOAD_MANAGER"; /** * The permission to access the download manager's advanced functions * @hide */ public static final String PERMISSION_ACCESS_ADVANCED = "android.permission.ACCESS_DOWNLOAD_MANAGER_ADVANCED"; /** * The permission to directly access the download manager's cache directory * @hide */ public static final String PERMISSION_CACHE = "android.permission.ACCESS_CACHE_FILESYSTEM"; /** * The permission to send broadcasts on download completion * @hide */ public static final String PERMISSION_SEND_INTENTS = "android.permission.SEND_DOWNLOAD_COMPLETED_INTENTS"; /** * The content:// URI for the data table in the provider * @hide */ public static final Uri CONTENT_URI = Uri.parse("content://downloads/my_downloads"); /** * Broadcast Action: this is sent by the download manager to the app * that had initiated a download when that download completes. The * download's content: uri is specified in the intent's data. * @hide */ public static final String ACTION_DOWNLOAD_COMPLETED = "android.intent.action.DOWNLOAD_COMPLETED"; /** * Broadcast Action: this is sent by the download manager to the app * that had initiated a download when the user selects the notification * associated with that download. The download's content: uri is specified * in the intent's data if the click is associated with a single download, * or Downloads.CONTENT_URI if the notification is associated with * multiple downloads. * Note: this is not currently sent for downloads that have completed * successfully. * @hide */ public static final String ACTION_NOTIFICATION_CLICKED = "android.intent.action.DOWNLOAD_NOTIFICATION_CLICKED"; /** * The name of the column containing the URI of the data being downloaded. * <P>Type: TEXT</P> * <P>Owner can Init/Read</P> * @hide */ public static final String COLUMN_URI = "uri"; public static final String COLUMN_APP_DATA = "entity"; public static final String COLUMN_NO_INTEGRITY = "no_integrity"; public static final String COLUMN_FILE_NAME_HINT = "hint"; public static final String _DATA = "_data"; public static final String COLUMN_MIME_TYPE = "mimetype"; public static final String COLUMN_DESTINATION = "destination"; public static final String COLUMN_VISIBILITY = "visibility"; public static final String COLUMN_CONTROL = "control"; public static final String COLUMN_STATUS = "status"; /** * The name of the column containing the date at which some interesting * status changed in the download. Stored as a System.currentTimeMillis() * value. * <P>Type: BIGINT</P> * <P>Owner can Read</P> * @hide */ public static final String COLUMN_LAST_MODIFICATION = "lastmod"; /** * The name of the column containing the package name of the application * that initiating the download. The download manager will send * notifications to a component in this package when the download completes. * <P>Type: TEXT</P> * <P>Owner can Init/Read</P> * @hide */ public static final String COLUMN_NOTIFICATION_PACKAGE = "notificationpackage"; public static final String COLUMN_NOTIFICATION_CLASS = "notificationclass"; public static final String COLUMN_NOTIFICATION_EXTRAS = "notificationextras"; public static final String COLUMN_COOKIE_DATA = "cookiedata"; public static final String COLUMN_USER_AGENT = "useragent"; public static final String COLUMN_REFERER = "referer"; public static final String COLUMN_TOTAL_BYTES = "total_bytes"; public static final String COLUMN_CURRENT_BYTES = "current_bytes"; public static final String COLUMN_OTHER_UID = "otheruid"; public static final String COLUMN_TITLE = "title"; public static final String COLUMN_DESCRIPTION = "description"; public static final String COLUMN_DELETED = "deleted"; public static final int DESTINATION_EXTERNAL = 0; public static final int DESTINATION_CACHE_PARTITION = 1; public static final int DESTINATION_CACHE_PARTITION_PURGEABLE = 2; public static final int DESTINATION_CACHE_PARTITION_NOROAMING = 3; public static final int CONTROL_RUN = 0; public static final int CONTROL_PAUSED = 1; /** * Returns whether the status is informational (i.e. 1xx). * @hide */ public static boolean isStatusInformational(int status) { return (status >= 100 && status < 200); } public static boolean isStatusSuccess(int status) { return (status >= 200 && status < 300); } public static boolean isStatusError(int status) { return (status >= 400 && status < 600); } public static boolean isStatusClientError(int status) { return (status >= 400 && status < 500); } public static boolean isStatusServerError(int status) { return (status >= 500 && status < 600); } public static boolean isStatusCompleted(int status) { return (status >= 200 && status < 300) || (status >= 400 && status < 600); } public static final int STATUS_PENDING = 190; public static final int STATUS_RUNNING = 192; public static final int STATUS_SUCCESS = 200; public static final int STATUS_BAD_REQUEST = 400; public static final int STATUS_NOT_ACCEPTABLE = 406; public static final int STATUS_LENGTH_REQUIRED = 411; public static final int STATUS_PRECONDITION_FAILED = 412; public static final int STATUS_CANCELED = 490; public static final int STATUS_UNKNOWN_ERROR = 491; public static final int STATUS_FILE_ERROR = 492; public static final int STATUS_UNHANDLED_REDIRECT = 493; public static final int STATUS_UNHANDLED_HTTP_CODE = 494; public static final int STATUS_HTTP_DATA_ERROR = 495; public static final int STATUS_HTTP_EXCEPTION = 496; public static final int STATUS_TOO_MANY_REDIRECTS = 497; public static final int STATUS_INSUFFICIENT_SPACE_ERROR = 498; public static final int STATUS_DEVICE_NOT_FOUND_ERROR = 499; public static final int VISIBILITY_VISIBLE = 0; public static final int VISIBILITY_VISIBLE_NOTIFY_COMPLETED = 1; public static final int VISIBILITY_HIDDEN = 2; public static final class Impl implements BaseColumns { private Impl() {} /** * The permission to access the download manager */ public static final String PERMISSION_ACCESS = "android.permission.ACCESS_DOWNLOAD_MANAGER"; /** * The permission to access the download manager's advanced functions */ public static final String PERMISSION_ACCESS_ADVANCED = "android.permission.ACCESS_DOWNLOAD_MANAGER_ADVANCED"; /** * The permission to access the all the downloads in the manager. */ public static final String PERMISSION_ACCESS_ALL = "android.permission.ACCESS_ALL_DOWNLOADS"; /** * The permission to directly access the download manager's cache * directory */ public static final String PERMISSION_CACHE = "android.permission.ACCESS_CACHE_FILESYSTEM"; /** * The permission to send broadcasts on download completion */ public static final String PERMISSION_SEND_INTENTS = "android.permission.SEND_DOWNLOAD_COMPLETED_INTENTS"; /** * The permission to download files to the cache partition that won't be automatically * purged when space is needed. */ public static final String PERMISSION_CACHE_NON_PURGEABLE = "android.permission.DOWNLOAD_CACHE_NON_PURGEABLE"; /** * The permission to download files without any system notification being shown. */ public static final String PERMISSION_NO_NOTIFICATION = "android.permission.DOWNLOAD_WITHOUT_NOTIFICATION"; /** * The content:// URI to access downloads owned by the caller's UID. */ public static final Uri CONTENT_URI = Uri.parse("content://downloads/my_downloads"); public static final Uri ALL_DOWNLOADS_CONTENT_URI = Uri.parse("content://downloads/all_downloads"); public static final String ACTION_DOWNLOAD_COMPLETED = "android.intent.action.DOWNLOAD_COMPLETED"; public static final String ACTION_NOTIFICATION_CLICKED = "android.intent.action.DOWNLOAD_NOTIFICATION_CLICKED"; public static final String COLUMN_URI = "uri"; public static final String COLUMN_APP_DATA = "entity"; public static final String COLUMN_NO_INTEGRITY = "no_integrity"; public static final String COLUMN_FILE_NAME_HINT = "hint"; public static final String _DATA = "_data"; public static final String COLUMN_MIME_TYPE = "mimetype"; public static final String COLUMN_DESTINATION = "destination"; public static final String COLUMN_VISIBILITY = "visibility"; public static final String COLUMN_CONTROL = "control"; public static final String COLUMN_STATUS = "status"; public static final String COLUMN_LAST_MODIFICATION = "lastmod"; public static final String COLUMN_NOTIFICATION_PACKAGE = "notificationpackage"; public static final String COLUMN_NOTIFICATION_CLASS = "notificationclass"; public static final String COLUMN_NOTIFICATION_EXTRAS = "notificationextras"; public static final String COLUMN_COOKIE_DATA = "cookiedata"; public static final String COLUMN_USER_AGENT = "useragent"; public static final String COLUMN_REFERER = "referer"; public static final String COLUMN_TOTAL_BYTES = "total_bytes"; public static final String COLUMN_CURRENT_BYTES = "current_bytes"; public static final String COLUMN_OTHER_UID = "otheruid"; public static final String COLUMN_TITLE = "title"; public static final String COLUMN_DESCRIPTION = "description"; public static final String COLUMN_IS_PUBLIC_API = "is_public_api"; public static final String COLUMN_ALLOW_ROAMING = "allow_roaming"; public static final String COLUMN_ALLOWED_NETWORK_TYPES = "allowed_network_types"; public static final String COLUMN_IS_VISIBLE_IN_DOWNLOADS_UI = "is_visible_in_downloads_ui"; public static final String COLUMN_BYPASS_RECOMMENDED_SIZE_LIMIT = "bypass_recommended_size_limit"; public static final String COLUMN_DELETED = "deleted"; public static final String COLUMN_MEDIAPROVIDER_URI = "mediaprovider_uri"; /* * Lists the destinations that an application can specify for a download. */ public static final int DESTINATION_EXTERNAL = 0; public static final int DESTINATION_CACHE_PARTITION = 1; public static final int DESTINATION_CACHE_PARTITION_PURGEABLE = 2; /** * This download will be saved to the download manager's private * partition, as with DESTINATION_CACHE_PARTITION, but the download * will not proceed if the user is on a roaming data connection. */ public static final int DESTINATION_CACHE_PARTITION_NOROAMING = 3; /** * This download will be saved to the location given by the file URI in * {@link #COLUMN_FILE_NAME_HINT}. */ public static final int DESTINATION_FILE_URI = 4; /** * This download is allowed to run. */ public static final int CONTROL_RUN = 0; /** * This download must pause at the first opportunity. */ public static final int CONTROL_PAUSED = 1; /** * Returns whether the status is informational (i.e. 1xx). */ public static boolean isStatusInformational(int status) { return (status >= 100 && status < 200); } /** * Returns whether the status is a success (i.e. 2xx). */ public static boolean isStatusSuccess(int status) { return (status >= 200 && status < 300); } /** * Returns whether the status is an error (i.e. 4xx or 5xx). */ public static boolean isStatusError(int status) { return (status >= 400 && status < 600); } /** * Returns whether the status is a client error (i.e. 4xx). */ public static boolean isStatusClientError(int status) { return (status >= 400 && status < 500); } /** * Returns whether the status is a server error (i.e. 5xx). */ public static boolean isStatusServerError(int status) { return (status >= 500 && status < 600); } /** * Returns whether the download has completed (either with success or * error). */ public static boolean isStatusCompleted(int status) { return (status >= 200 && status < 300) || (status >= 400 && status < 600); } /** * This download hasn't stated yet */ public static final int STATUS_PENDING = 190; /** * This download has started */ public static final int STATUS_RUNNING = 192; /** * This download has been paused by the owning app. */ public static final int STATUS_PAUSED_BY_APP = 193; /** * This download encountered some network error and is waiting before retrying the request. */ public static final int STATUS_WAITING_TO_RETRY = 194; /** * This download is waiting for network connectivity to proceed. */ public static final int STATUS_WAITING_FOR_NETWORK = 195; /** * This download exceeded a size limit for mobile networks and is waiting for a Wi-Fi * connection to proceed. */ public static final int STATUS_QUEUED_FOR_WIFI = 196; public static final int STATUS_SUCCESS = 200; public static final int STATUS_BAD_REQUEST = 400; /** * This download can't be performed because the content type cannot be * handled. */ public static final int STATUS_NOT_ACCEPTABLE = 406; public static final int STATUS_LENGTH_REQUIRED = 411; /** * This download was interrupted and cannot be resumed. * This is the code for the HTTP error "Precondition Failed", and it is * also used in situations where the client doesn't have an ETag at all. */ public static final int STATUS_PRECONDITION_FAILED = 412; /** * The lowest-valued error status that is not an actual HTTP status code. */ public static final int MIN_ARTIFICIAL_ERROR_STATUS = 488; /** * The requested destination file already exists. */ public static final int STATUS_FILE_ALREADY_EXISTS_ERROR = 488; /** * Some possibly transient error occurred, but we can't resume the download. */ public static final int STATUS_CANNOT_RESUME = 489; /** * This download was canceled */ public static final int STATUS_CANCELED = 490; public static final int STATUS_UNKNOWN_ERROR = 491; public static final int STATUS_FILE_ERROR = 492; /** * This download couldn't be completed because of an HTTP * redirect response that the download manager couldn't * handle. */ public static final int STATUS_UNHANDLED_REDIRECT = 493; /** * This download couldn't be completed because of an * unspecified unhandled HTTP code. */ public static final int STATUS_UNHANDLED_HTTP_CODE = 494; /** * This download couldn't be completed because of an * error receiving or processing data at the HTTP level. */ public static final int STATUS_HTTP_DATA_ERROR = 495; /** * This download couldn't be completed because of an * HttpException while setting up the request. */ public static final int STATUS_HTTP_EXCEPTION = 496; /** * This download couldn't be completed because there were * too many redirects. */ public static final int STATUS_TOO_MANY_REDIRECTS = 497; /** * This download couldn't be completed due to insufficient storage * space. Typically, this is because the SD card is full. */ public static final int STATUS_INSUFFICIENT_SPACE_ERROR = 498; /** * This download couldn't be completed because no external storage * device was found. Typically, this is because the SD card is not * mounted. */ public static final int STATUS_DEVICE_NOT_FOUND_ERROR = 499; /** * This download is visible but only shows in the notifications * while it's in progress. */ public static final int VISIBILITY_VISIBLE = 0; /** * This download is visible and shows in the notifications while * in progress and after completion. */ public static final int VISIBILITY_VISIBLE_NOTIFY_COMPLETED = 1; /** * This download doesn't show in the UI or in the notifications. */ public static final int VISIBILITY_HIDDEN = 2; /** * Constants related to HTTP request headers associated with each download. */ public static class RequestHeaders { public static final String HEADERS_DB_TABLE = "request_headers"; public static final String COLUMN_DOWNLOAD_ID = "download_id"; public static final String COLUMN_HEADER = "header"; public static final String COLUMN_VALUE = "value"; /** * Path segment to add to a download URI to retrieve request headers */ public static final String URI_SEGMENT = "headers"; /** * Prefix for ContentValues keys that contain HTTP header lines, to be passed to * DownloadProvider.insert(). */ public static final String INSERT_KEY_PREFIX = "http_header_"; } } } ```
8,971,000
How to request Android download manager to download multiple files at the same time. Also I would like to know each and every file download status.
2012/01/23
[ "https://Stackoverflow.com/questions/8971000", "https://Stackoverflow.com", "https://Stackoverflow.com/users/676625/" ]
``` public final class Downloads { /** * @hide */ private Downloads() {} /** * The permission to access the download manager * @hide . */ public static final String PERMISSION_ACCESS = "android.permission.ACCESS_DOWNLOAD_MANAGER"; /** * The permission to access the download manager's advanced functions * @hide */ public static final String PERMISSION_ACCESS_ADVANCED = "android.permission.ACCESS_DOWNLOAD_MANAGER_ADVANCED"; /** * The permission to directly access the download manager's cache directory * @hide */ public static final String PERMISSION_CACHE = "android.permission.ACCESS_CACHE_FILESYSTEM"; /** * The permission to send broadcasts on download completion * @hide */ public static final String PERMISSION_SEND_INTENTS = "android.permission.SEND_DOWNLOAD_COMPLETED_INTENTS"; /** * The content:// URI for the data table in the provider * @hide */ public static final Uri CONTENT_URI = Uri.parse("content://downloads/my_downloads"); /** * Broadcast Action: this is sent by the download manager to the app * that had initiated a download when that download completes. The * download's content: uri is specified in the intent's data. * @hide */ public static final String ACTION_DOWNLOAD_COMPLETED = "android.intent.action.DOWNLOAD_COMPLETED"; /** * Broadcast Action: this is sent by the download manager to the app * that had initiated a download when the user selects the notification * associated with that download. The download's content: uri is specified * in the intent's data if the click is associated with a single download, * or Downloads.CONTENT_URI if the notification is associated with * multiple downloads. * Note: this is not currently sent for downloads that have completed * successfully. * @hide */ public static final String ACTION_NOTIFICATION_CLICKED = "android.intent.action.DOWNLOAD_NOTIFICATION_CLICKED"; /** * The name of the column containing the URI of the data being downloaded. * <P>Type: TEXT</P> * <P>Owner can Init/Read</P> * @hide */ public static final String COLUMN_URI = "uri"; public static final String COLUMN_APP_DATA = "entity"; public static final String COLUMN_NO_INTEGRITY = "no_integrity"; public static final String COLUMN_FILE_NAME_HINT = "hint"; public static final String _DATA = "_data"; public static final String COLUMN_MIME_TYPE = "mimetype"; public static final String COLUMN_DESTINATION = "destination"; public static final String COLUMN_VISIBILITY = "visibility"; public static final String COLUMN_CONTROL = "control"; public static final String COLUMN_STATUS = "status"; /** * The name of the column containing the date at which some interesting * status changed in the download. Stored as a System.currentTimeMillis() * value. * <P>Type: BIGINT</P> * <P>Owner can Read</P> * @hide */ public static final String COLUMN_LAST_MODIFICATION = "lastmod"; /** * The name of the column containing the package name of the application * that initiating the download. The download manager will send * notifications to a component in this package when the download completes. * <P>Type: TEXT</P> * <P>Owner can Init/Read</P> * @hide */ public static final String COLUMN_NOTIFICATION_PACKAGE = "notificationpackage"; public static final String COLUMN_NOTIFICATION_CLASS = "notificationclass"; public static final String COLUMN_NOTIFICATION_EXTRAS = "notificationextras"; public static final String COLUMN_COOKIE_DATA = "cookiedata"; public static final String COLUMN_USER_AGENT = "useragent"; public static final String COLUMN_REFERER = "referer"; public static final String COLUMN_TOTAL_BYTES = "total_bytes"; public static final String COLUMN_CURRENT_BYTES = "current_bytes"; public static final String COLUMN_OTHER_UID = "otheruid"; public static final String COLUMN_TITLE = "title"; public static final String COLUMN_DESCRIPTION = "description"; public static final String COLUMN_DELETED = "deleted"; public static final int DESTINATION_EXTERNAL = 0; public static final int DESTINATION_CACHE_PARTITION = 1; public static final int DESTINATION_CACHE_PARTITION_PURGEABLE = 2; public static final int DESTINATION_CACHE_PARTITION_NOROAMING = 3; public static final int CONTROL_RUN = 0; public static final int CONTROL_PAUSED = 1; /** * Returns whether the status is informational (i.e. 1xx). * @hide */ public static boolean isStatusInformational(int status) { return (status >= 100 && status < 200); } public static boolean isStatusSuccess(int status) { return (status >= 200 && status < 300); } public static boolean isStatusError(int status) { return (status >= 400 && status < 600); } public static boolean isStatusClientError(int status) { return (status >= 400 && status < 500); } public static boolean isStatusServerError(int status) { return (status >= 500 && status < 600); } public static boolean isStatusCompleted(int status) { return (status >= 200 && status < 300) || (status >= 400 && status < 600); } public static final int STATUS_PENDING = 190; public static final int STATUS_RUNNING = 192; public static final int STATUS_SUCCESS = 200; public static final int STATUS_BAD_REQUEST = 400; public static final int STATUS_NOT_ACCEPTABLE = 406; public static final int STATUS_LENGTH_REQUIRED = 411; public static final int STATUS_PRECONDITION_FAILED = 412; public static final int STATUS_CANCELED = 490; public static final int STATUS_UNKNOWN_ERROR = 491; public static final int STATUS_FILE_ERROR = 492; public static final int STATUS_UNHANDLED_REDIRECT = 493; public static final int STATUS_UNHANDLED_HTTP_CODE = 494; public static final int STATUS_HTTP_DATA_ERROR = 495; public static final int STATUS_HTTP_EXCEPTION = 496; public static final int STATUS_TOO_MANY_REDIRECTS = 497; public static final int STATUS_INSUFFICIENT_SPACE_ERROR = 498; public static final int STATUS_DEVICE_NOT_FOUND_ERROR = 499; public static final int VISIBILITY_VISIBLE = 0; public static final int VISIBILITY_VISIBLE_NOTIFY_COMPLETED = 1; public static final int VISIBILITY_HIDDEN = 2; public static final class Impl implements BaseColumns { private Impl() {} /** * The permission to access the download manager */ public static final String PERMISSION_ACCESS = "android.permission.ACCESS_DOWNLOAD_MANAGER"; /** * The permission to access the download manager's advanced functions */ public static final String PERMISSION_ACCESS_ADVANCED = "android.permission.ACCESS_DOWNLOAD_MANAGER_ADVANCED"; /** * The permission to access the all the downloads in the manager. */ public static final String PERMISSION_ACCESS_ALL = "android.permission.ACCESS_ALL_DOWNLOADS"; /** * The permission to directly access the download manager's cache * directory */ public static final String PERMISSION_CACHE = "android.permission.ACCESS_CACHE_FILESYSTEM"; /** * The permission to send broadcasts on download completion */ public static final String PERMISSION_SEND_INTENTS = "android.permission.SEND_DOWNLOAD_COMPLETED_INTENTS"; /** * The permission to download files to the cache partition that won't be automatically * purged when space is needed. */ public static final String PERMISSION_CACHE_NON_PURGEABLE = "android.permission.DOWNLOAD_CACHE_NON_PURGEABLE"; /** * The permission to download files without any system notification being shown. */ public static final String PERMISSION_NO_NOTIFICATION = "android.permission.DOWNLOAD_WITHOUT_NOTIFICATION"; /** * The content:// URI to access downloads owned by the caller's UID. */ public static final Uri CONTENT_URI = Uri.parse("content://downloads/my_downloads"); public static final Uri ALL_DOWNLOADS_CONTENT_URI = Uri.parse("content://downloads/all_downloads"); public static final String ACTION_DOWNLOAD_COMPLETED = "android.intent.action.DOWNLOAD_COMPLETED"; public static final String ACTION_NOTIFICATION_CLICKED = "android.intent.action.DOWNLOAD_NOTIFICATION_CLICKED"; public static final String COLUMN_URI = "uri"; public static final String COLUMN_APP_DATA = "entity"; public static final String COLUMN_NO_INTEGRITY = "no_integrity"; public static final String COLUMN_FILE_NAME_HINT = "hint"; public static final String _DATA = "_data"; public static final String COLUMN_MIME_TYPE = "mimetype"; public static final String COLUMN_DESTINATION = "destination"; public static final String COLUMN_VISIBILITY = "visibility"; public static final String COLUMN_CONTROL = "control"; public static final String COLUMN_STATUS = "status"; public static final String COLUMN_LAST_MODIFICATION = "lastmod"; public static final String COLUMN_NOTIFICATION_PACKAGE = "notificationpackage"; public static final String COLUMN_NOTIFICATION_CLASS = "notificationclass"; public static final String COLUMN_NOTIFICATION_EXTRAS = "notificationextras"; public static final String COLUMN_COOKIE_DATA = "cookiedata"; public static final String COLUMN_USER_AGENT = "useragent"; public static final String COLUMN_REFERER = "referer"; public static final String COLUMN_TOTAL_BYTES = "total_bytes"; public static final String COLUMN_CURRENT_BYTES = "current_bytes"; public static final String COLUMN_OTHER_UID = "otheruid"; public static final String COLUMN_TITLE = "title"; public static final String COLUMN_DESCRIPTION = "description"; public static final String COLUMN_IS_PUBLIC_API = "is_public_api"; public static final String COLUMN_ALLOW_ROAMING = "allow_roaming"; public static final String COLUMN_ALLOWED_NETWORK_TYPES = "allowed_network_types"; public static final String COLUMN_IS_VISIBLE_IN_DOWNLOADS_UI = "is_visible_in_downloads_ui"; public static final String COLUMN_BYPASS_RECOMMENDED_SIZE_LIMIT = "bypass_recommended_size_limit"; public static final String COLUMN_DELETED = "deleted"; public static final String COLUMN_MEDIAPROVIDER_URI = "mediaprovider_uri"; /* * Lists the destinations that an application can specify for a download. */ public static final int DESTINATION_EXTERNAL = 0; public static final int DESTINATION_CACHE_PARTITION = 1; public static final int DESTINATION_CACHE_PARTITION_PURGEABLE = 2; /** * This download will be saved to the download manager's private * partition, as with DESTINATION_CACHE_PARTITION, but the download * will not proceed if the user is on a roaming data connection. */ public static final int DESTINATION_CACHE_PARTITION_NOROAMING = 3; /** * This download will be saved to the location given by the file URI in * {@link #COLUMN_FILE_NAME_HINT}. */ public static final int DESTINATION_FILE_URI = 4; /** * This download is allowed to run. */ public static final int CONTROL_RUN = 0; /** * This download must pause at the first opportunity. */ public static final int CONTROL_PAUSED = 1; /** * Returns whether the status is informational (i.e. 1xx). */ public static boolean isStatusInformational(int status) { return (status >= 100 && status < 200); } /** * Returns whether the status is a success (i.e. 2xx). */ public static boolean isStatusSuccess(int status) { return (status >= 200 && status < 300); } /** * Returns whether the status is an error (i.e. 4xx or 5xx). */ public static boolean isStatusError(int status) { return (status >= 400 && status < 600); } /** * Returns whether the status is a client error (i.e. 4xx). */ public static boolean isStatusClientError(int status) { return (status >= 400 && status < 500); } /** * Returns whether the status is a server error (i.e. 5xx). */ public static boolean isStatusServerError(int status) { return (status >= 500 && status < 600); } /** * Returns whether the download has completed (either with success or * error). */ public static boolean isStatusCompleted(int status) { return (status >= 200 && status < 300) || (status >= 400 && status < 600); } /** * This download hasn't stated yet */ public static final int STATUS_PENDING = 190; /** * This download has started */ public static final int STATUS_RUNNING = 192; /** * This download has been paused by the owning app. */ public static final int STATUS_PAUSED_BY_APP = 193; /** * This download encountered some network error and is waiting before retrying the request. */ public static final int STATUS_WAITING_TO_RETRY = 194; /** * This download is waiting for network connectivity to proceed. */ public static final int STATUS_WAITING_FOR_NETWORK = 195; /** * This download exceeded a size limit for mobile networks and is waiting for a Wi-Fi * connection to proceed. */ public static final int STATUS_QUEUED_FOR_WIFI = 196; public static final int STATUS_SUCCESS = 200; public static final int STATUS_BAD_REQUEST = 400; /** * This download can't be performed because the content type cannot be * handled. */ public static final int STATUS_NOT_ACCEPTABLE = 406; public static final int STATUS_LENGTH_REQUIRED = 411; /** * This download was interrupted and cannot be resumed. * This is the code for the HTTP error "Precondition Failed", and it is * also used in situations where the client doesn't have an ETag at all. */ public static final int STATUS_PRECONDITION_FAILED = 412; /** * The lowest-valued error status that is not an actual HTTP status code. */ public static final int MIN_ARTIFICIAL_ERROR_STATUS = 488; /** * The requested destination file already exists. */ public static final int STATUS_FILE_ALREADY_EXISTS_ERROR = 488; /** * Some possibly transient error occurred, but we can't resume the download. */ public static final int STATUS_CANNOT_RESUME = 489; /** * This download was canceled */ public static final int STATUS_CANCELED = 490; public static final int STATUS_UNKNOWN_ERROR = 491; public static final int STATUS_FILE_ERROR = 492; /** * This download couldn't be completed because of an HTTP * redirect response that the download manager couldn't * handle. */ public static final int STATUS_UNHANDLED_REDIRECT = 493; /** * This download couldn't be completed because of an * unspecified unhandled HTTP code. */ public static final int STATUS_UNHANDLED_HTTP_CODE = 494; /** * This download couldn't be completed because of an * error receiving or processing data at the HTTP level. */ public static final int STATUS_HTTP_DATA_ERROR = 495; /** * This download couldn't be completed because of an * HttpException while setting up the request. */ public static final int STATUS_HTTP_EXCEPTION = 496; /** * This download couldn't be completed because there were * too many redirects. */ public static final int STATUS_TOO_MANY_REDIRECTS = 497; /** * This download couldn't be completed due to insufficient storage * space. Typically, this is because the SD card is full. */ public static final int STATUS_INSUFFICIENT_SPACE_ERROR = 498; /** * This download couldn't be completed because no external storage * device was found. Typically, this is because the SD card is not * mounted. */ public static final int STATUS_DEVICE_NOT_FOUND_ERROR = 499; /** * This download is visible but only shows in the notifications * while it's in progress. */ public static final int VISIBILITY_VISIBLE = 0; /** * This download is visible and shows in the notifications while * in progress and after completion. */ public static final int VISIBILITY_VISIBLE_NOTIFY_COMPLETED = 1; /** * This download doesn't show in the UI or in the notifications. */ public static final int VISIBILITY_HIDDEN = 2; /** * Constants related to HTTP request headers associated with each download. */ public static class RequestHeaders { public static final String HEADERS_DB_TABLE = "request_headers"; public static final String COLUMN_DOWNLOAD_ID = "download_id"; public static final String COLUMN_HEADER = "header"; public static final String COLUMN_VALUE = "value"; /** * Path segment to add to a download URI to retrieve request headers */ public static final String URI_SEGMENT = "headers"; /** * Prefix for ContentValues keys that contain HTTP header lines, to be passed to * DownloadProvider.insert(). */ public static final String INSERT_KEY_PREFIX = "http_header_"; } } } ```
public class DownloadManager { private static final String TAG = "DownloadManager"; ``` public final static String COLUMN_ID = BaseColumns._ID; public final static String COLUMN_TITLE = "title"; public final static String COLUMN_DESCRIPTION = "description"; public final static String COLUMN_URI = "uri"; public final static String COLUMN_MEDIA_TYPE = "media_type"; public final static String COLUMN_TOTAL_SIZE_BYTES = "total_size"; public final static String COLUMN_LOCAL_URI = "local_uri"; public final static String COLUMN_STATUS = "status"; public final static String COLUMN_REASON = "reason"; public final static String COLUMN_BYTES_DOWNLOADED_SO_FAR = "bytes_so_far"; public final static String COLUMN_LAST_MODIFIED_TIMESTAMP = "last_modified_timestamp"; public static final String COLUMN_MEDIAPROVIDER_URI = "mediaprovider_uri"; public final static int STATUS_PENDING = 1 << 0; public final static int STATUS_RUNNING = 1 << 1; public final static int STATUS_PAUSED = 1 << 2; public final static int STATUS_SUCCESSFUL = 1 << 3; public final static int STATUS_FAILED = 1 << 4; public final static int ERROR_UNKNOWN = 1000; public final static int ERROR_FILE_ERROR = 1001; public final static int ERROR_UNHANDLED_HTTP_CODE = 1002; public final static int ERROR_HTTP_DATA_ERROR = 1004; public final static int ERROR_TOO_MANY_REDIRECTS = 1005; public final static int ERROR_INSUFFICIENT_SPACE = 1006; public final static int ERROR_DEVICE_NOT_FOUND = 1007; public final static int ERROR_CANNOT_RESUME = 1008; public final static int ERROR_FILE_ALREADY_EXISTS = 1009; public final static int PAUSED_WAITING_TO_RETRY = 1; public final static int PAUSED_WAITING_FOR_NETWORK = 2; public final static int PAUSED_QUEUED_FOR_WIFI = 3; public final static int PAUSED_UNKNOWN = 4; public final static String ACTION_DOWNLOAD_COMPLETE = "android.intent.action.DOWNLOAD_COMPLETE"; public final static String ACTION_NOTIFICATION_CLICKED = "android.intent.action.DOWNLOAD_NOTIFICATION_CLICKED"; public final static String ACTION_VIEW_DOWNLOADS = "android.intent.action.VIEW_DOWNLOADS"; public static final String EXTRA_DOWNLOAD_ID = "extra_download_id"; // this array must contain all public columns private static final String[] COLUMNS = new String[] { COLUMN_ID, COLUMN_MEDIAPROVIDER_URI, COLUMN_TITLE, COLUMN_DESCRIPTION, COLUMN_URI, COLUMN_MEDIA_TYPE, COLUMN_TOTAL_SIZE_BYTES, COLUMN_LOCAL_URI, COLUMN_STATUS, COLUMN_REASON, COLUMN_BYTES_DOWNLOADED_SO_FAR, COLUMN_LAST_MODIFIED_TIMESTAMP }; // columns to request from DownloadProvider private static final String[] UNDERLYING_COLUMNS = new String[] { Downloads.Impl._ID, Downloads.Impl.COLUMN_MEDIAPROVIDER_URI, Downloads.COLUMN_TITLE, Downloads.COLUMN_DESCRIPTION, Downloads.COLUMN_URI, Downloads.COLUMN_MIME_TYPE, Downloads.COLUMN_TOTAL_BYTES, Downloads.COLUMN_STATUS, Downloads.COLUMN_CURRENT_BYTES, Downloads.COLUMN_LAST_MODIFICATION, Downloads.COLUMN_DESTINATION, Downloads.Impl.COLUMN_FILE_NAME_HINT, Downloads.Impl._DATA, }; private static final Set<String> LONG_COLUMNS = new HashSet<String>( Arrays.asList(COLUMN_ID, COLUMN_TOTAL_SIZE_BYTES, COLUMN_STATUS, COLUMN_REASON, COLUMN_BYTES_DOWNLOADED_SO_FAR, COLUMN_LAST_MODIFIED_TIMESTAMP)); public static class Request { public static final int NETWORK_MOBILE = 1 << 0; public static final int NETWORK_WIFI = 1 << 1; private Uri mUri; private Uri mDestinationUri; private List<Pair<String, String>> mRequestHeaders = new ArrayList<Pair<String, String>>(); private CharSequence mTitle; private CharSequence mDescription; private boolean mShowNotification = true; private String mMimeType; private boolean mRoamingAllowed = true; private int mAllowedNetworkTypes = ~0; // default to all network types // allowed private boolean mIsVisibleInDownloadsUi = true; /** * @param uri * the HTTP URI to download. */ public Request(Uri uri) { if (uri == null) { throw new NullPointerException(); } String scheme = uri.getScheme(); if (scheme == null || !(scheme.equals("http") || scheme.equals("https"))) { throw new IllegalArgumentException( "Can only download HTTP URIs: " + uri); } mUri = uri; } public Request setDestinationUri(Uri uri) { mDestinationUri = uri; return this; } public Request setDestinationInExternalFilesDir(Context context, String dirType, String subPath) { setDestinationFromBase(context.getExternalFilesDir(dirType), subPath); return this; } public Request setDestinationInExternalPublicDir(String dirType, String subPath) { setDestinationFromBase( Environment.getExternalStoragePublicDirectory(dirType), subPath); return this; } private void setDestinationFromBase(File base, String subPath) { if (subPath == null) { throw new NullPointerException("subPath cannot be null"); } mDestinationUri = Uri.withAppendedPath(Uri.fromFile(base), subPath); } public Request addRequestHeader(String header, String value) { if (header == null) { throw new NullPointerException("header cannot be null"); } if (header.contains(":")) { throw new IllegalArgumentException("header may not contain ':'"); } if (value == null) { value = ""; } mRequestHeaders.add(Pair.create(header, value)); return this; } public Request setTitle(CharSequence title) { mTitle = title; return this; } public Request setDescription(CharSequence description) { mDescription = description; return this; } public Request setMimeType(String mimeType) { mMimeType = mimeType; return this; } public Request setShowRunningNotification(boolean show) { mShowNotification = show; return this; } public Request setAllowedNetworkTypes(int flags) { mAllowedNetworkTypes = flags; return this; } public Request setAllowedOverRoaming(boolean allowed) { mRoamingAllowed = allowed; return this; } public Request setVisibleInDownloadsUi(boolean isVisible) { mIsVisibleInDownloadsUi = isVisible; return this; } /** * @return ContentValues to be passed to DownloadProvider.insert() */ ContentValues toContentValues(String packageName) { ContentValues values = new ContentValues(); assert mUri != null; values.put(Downloads.COLUMN_URI, mUri.toString()); values.put(Downloads.Impl.COLUMN_IS_PUBLIC_API, true); values.put(Downloads.COLUMN_NOTIFICATION_PACKAGE, packageName); if (mDestinationUri != null) { values.put(Downloads.COLUMN_DESTINATION, Downloads.Impl.DESTINATION_FILE_URI); values.put(Downloads.COLUMN_FILE_NAME_HINT, mDestinationUri.toString()); } else { values.put(Downloads.COLUMN_DESTINATION, Downloads.DESTINATION_CACHE_PARTITION_PURGEABLE); } if (!mRequestHeaders.isEmpty()) { encodeHttpHeaders(values); } putIfNonNull(values, Downloads.COLUMN_TITLE, mTitle); putIfNonNull(values, Downloads.COLUMN_DESCRIPTION, mDescription); putIfNonNull(values, Downloads.COLUMN_MIME_TYPE, mMimeType); values.put(Downloads.COLUMN_VISIBILITY, mShowNotification ? Downloads.VISIBILITY_VISIBLE : Downloads.VISIBILITY_HIDDEN); values.put(Downloads.Impl.COLUMN_ALLOWED_NETWORK_TYPES, mAllowedNetworkTypes); values.put(Downloads.Impl.COLUMN_ALLOW_ROAMING, mRoamingAllowed); values.put(Downloads.Impl.COLUMN_IS_VISIBLE_IN_DOWNLOADS_UI, mIsVisibleInDownloadsUi); return values; } private void encodeHttpHeaders(ContentValues values) { int index = 0; for (Pair<String, String> header : mRequestHeaders) { String headerString = header.first + ": " + header.second; values.put(Downloads.Impl.RequestHeaders.INSERT_KEY_PREFIX + index, headerString); index++; } } private void putIfNonNull(ContentValues contentValues, String key, Object value) { if (value != null) { contentValues.put(key, value.toString()); } } } /** * This class may be used to filter download manager queries. */ public static class Query { /** * Constant for use with {@link #orderBy} * * @hide */ public static final int ORDER_ASCENDING = 1; /** * Constant for use with {@link #orderBy} * * @hide */ public static final int ORDER_DESCENDING = 2; private long[] mIds = null; private Integer mStatusFlags = null; private String mOrderByColumn = Downloads.COLUMN_LAST_MODIFICATION; private int mOrderDirection = ORDER_DESCENDING; private boolean mOnlyIncludeVisibleInDownloadsUi = false; /** * Include only the downloads with the given IDs. * * @return this object */ public Query setFilterById(long... ids) { mIds = ids; return this; } /** * Include only downloads with status matching any the given status * flags. * * @param flags * any combination of the STATUS_* bit flags * @return this object */ public Query setFilterByStatus(int flags) { mStatusFlags = flags; return this; } /** * Controls whether this query includes downloads not visible in the * system's Downloads UI. * * @param value * if true, this query will only include downloads that * should be displayed in the system's Downloads UI; if false * (the default), this query will include both visible and * invisible downloads. * @return this object * @hide */ public Query setOnlyIncludeVisibleInDownloadsUi(boolean value) { mOnlyIncludeVisibleInDownloadsUi = value; return this; } /** * Change the sort order of the returned Cursor. * * @param column * one of the COLUMN_* constants; currently, only * {@link #COLUMN_LAST_MODIFIED_TIMESTAMP} and * {@link #COLUMN_TOTAL_SIZE_BYTES} are supported. * @param direction * either {@link #ORDER_ASCENDING} or * {@link #ORDER_DESCENDING} * @return this object * @hide */ public Query orderBy(String column, int direction) { if (direction != ORDER_ASCENDING && direction != ORDER_DESCENDING) { throw new IllegalArgumentException("Invalid direction: " + direction); } if (column.equals(COLUMN_LAST_MODIFIED_TIMESTAMP)) { mOrderByColumn = Downloads.COLUMN_LAST_MODIFICATION; } else if (column.equals(COLUMN_TOTAL_SIZE_BYTES)) { mOrderByColumn = Downloads.COLUMN_TOTAL_BYTES; } else { throw new IllegalArgumentException("Cannot order by " + column); } mOrderDirection = direction; return this; } /** * Run this query using the given ContentResolver. * * @param projection * the projection to pass to ContentResolver.query() * @return the Cursor returned by ContentResolver.query() */ Cursor runQuery(ContentResolver resolver, String[] projection, Uri baseUri) { Uri uri = baseUri; List<String> selectionParts = new ArrayList<String>(); String[] selectionArgs = null; if (mIds != null) { selectionParts.add(getWhereClauseForIds(mIds)); selectionArgs = getWhereArgsForIds(mIds); } if (mStatusFlags != null) { List<String> parts = new ArrayList<String>(); if ((mStatusFlags & STATUS_PENDING) != 0) { parts.add(statusClause("=", Downloads.STATUS_PENDING)); } if ((mStatusFlags & STATUS_RUNNING) != 0) { parts.add(statusClause("=", Downloads.STATUS_RUNNING)); } if ((mStatusFlags & STATUS_PAUSED) != 0) { parts.add(statusClause("=", Downloads.Impl.STATUS_PAUSED_BY_APP)); parts.add(statusClause("=", Downloads.Impl.STATUS_WAITING_TO_RETRY)); parts.add(statusClause("=", Downloads.Impl.STATUS_WAITING_FOR_NETWORK)); parts.add(statusClause("=", Downloads.Impl.STATUS_QUEUED_FOR_WIFI)); } if ((mStatusFlags & STATUS_SUCCESSFUL) != 0) { parts.add(statusClause("=", Downloads.STATUS_SUCCESS)); } if ((mStatusFlags & STATUS_FAILED) != 0) { parts.add("(" + statusClause(">=", 400) + " AND " + statusClause("<", 600) + ")"); } selectionParts.add(joinStrings(" OR ", parts)); } if (mOnlyIncludeVisibleInDownloadsUi) { selectionParts .add(Downloads.Impl.COLUMN_IS_VISIBLE_IN_DOWNLOADS_UI + " != '0'"); } // only return rows which are not marked 'deleted = 1' selectionParts.add(Downloads.Impl.COLUMN_DELETED + " != '1'"); String selection = joinStrings(" AND ", selectionParts); String orderDirection = (mOrderDirection == ORDER_ASCENDING ? "ASC" : "DESC"); String orderBy = mOrderByColumn + " " + orderDirection; return resolver.query(uri, projection, selection, selectionArgs, orderBy); } private String joinStrings(String joiner, Iterable<String> parts) { StringBuilder builder = new StringBuilder(); boolean first = true; for (String part : parts) { if (!first) { builder.append(joiner); } builder.append(part); first = false; } return builder.toString(); } private String statusClause(String operator, int value) { return Downloads.COLUMN_STATUS + operator + "'" + value + "'"; } } private ContentResolver mResolver; private String mPackageName; private Uri mBaseUri = Downloads.Impl.CONTENT_URI; /** * @hide */ public DownloadManager(ContentResolver resolver, String packageName) { mResolver = resolver; mPackageName = packageName; } /** * Makes this object access the download provider through /all_downloads * URIs rather than /my_downloads URIs, for clients that have permission to * do so. * * @hide */ public void setAccessAllDownloads(boolean accessAllDownloads) { if (accessAllDownloads) { mBaseUri = Downloads.Impl.ALL_DOWNLOADS_CONTENT_URI; } else { mBaseUri = Downloads.Impl.CONTENT_URI; } } public long enqueue(Request request) { ContentValues values = request.toContentValues(mPackageName); Uri downloadUri = mResolver.insert(Downloads.CONTENT_URI, values); long id = Long.parseLong(downloadUri.getLastPathSegment()); return id; } public int markRowDeleted(long... ids) { if (ids == null || ids.length == 0) { // called with nothing to remove! throw new IllegalArgumentException( "input param 'ids' can't be null"); } ContentValues values = new ContentValues(); values.put(Downloads.Impl.COLUMN_DELETED, 1); return mResolver.update(mBaseUri, values, getWhereClauseForIds(ids), getWhereArgsForIds(ids)); } public int remove(long... ids) { if (ids == null || ids.length == 0) { // called with nothing to remove! throw new IllegalArgumentException( "input param 'ids' can't be null"); } return mResolver.delete(mBaseUri, getWhereClauseForIds(ids), getWhereArgsForIds(ids)); } public Cursor query(Query query) { Cursor underlyingCursor = query.runQuery(mResolver, UNDERLYING_COLUMNS, mBaseUri); if (underlyingCursor == null) { return null; } return new CursorTranslator(underlyingCursor, mBaseUri); } public ParcelFileDescriptor openDownloadedFile(long id) throws FileNotFoundException { return mResolver.openFileDescriptor(getDownloadUri(id), "r"); } public void restartDownload(long... ids) { Cursor cursor = query(new Query().setFilterById(ids)); try { for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor .moveToNext()) { int status = cursor .getInt(cursor.getColumnIndex(COLUMN_STATUS)); if (status != STATUS_SUCCESSFUL && status != STATUS_FAILED) { throw new IllegalArgumentException( "Cannot restart incomplete download: " + cursor.getLong(cursor .getColumnIndex(COLUMN_ID))); } } } finally { cursor.close(); } ContentValues values = new ContentValues(); values.put(Downloads.Impl.COLUMN_CURRENT_BYTES, 0); values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, -1); values.putNull(Downloads.Impl._DATA); values.put(Downloads.Impl.COLUMN_STATUS, Downloads.Impl.STATUS_PENDING); mResolver.update(mBaseUri, values, getWhereClauseForIds(ids), getWhereArgsForIds(ids)); } /** * Get the DownloadProvider URI for the download with the given ID. */ Uri getDownloadUri(long id) { return ContentUris.withAppendedId(mBaseUri, id); } /** * Get a parameterized SQL WHERE clause to select a bunch of IDs. */ static String getWhereClauseForIds(long[] ids) { StringBuilder whereClause = new StringBuilder(); whereClause.append("("); for (int i = 0; i < ids.length; i++) { if (i > 0) { whereClause.append("OR "); } whereClause.append(Downloads.Impl._ID); whereClause.append(" = ? "); } whereClause.append(")"); return whereClause.toString(); } /** * Get the selection args for a clause returned by * {@link #getWhereClauseForIds(long[])}. */ static String[] getWhereArgsForIds(long[] ids) { String[] whereArgs = new String[ids.length]; for (int i = 0; i < ids.length; i++) { whereArgs[i] = Long.toString(ids[i]); } return whereArgs; } /** * This class wraps a cursor returned by DownloadProvider -- the * "underlying cursor" -- and presents a different set of columns, those * defined in the DownloadManager.COLUMN_* constants. Some columns * correspond directly to underlying values while others are computed from * underlying data. */ private static class CursorTranslator extends CursorWrapper { private Uri mBaseUri; public CursorTranslator(Cursor cursor, Uri baseUri) { super(cursor); mBaseUri = baseUri; } @Override public int getColumnIndex(String columnName) { return Arrays.asList(COLUMNS).indexOf(columnName); } @Override public int getColumnIndexOrThrow(String columnName) throws IllegalArgumentException { int index = getColumnIndex(columnName); if (index == -1) { throw new IllegalArgumentException("No such column: " + columnName); } return index; } @Override public String getColumnName(int columnIndex) { int numColumns = COLUMNS.length; if (columnIndex < 0 || columnIndex >= numColumns) { throw new IllegalArgumentException("Invalid column index " + columnIndex + ", " + numColumns + " columns exist"); } return COLUMNS[columnIndex]; } @Override public String[] getColumnNames() { String[] returnColumns = new String[COLUMNS.length]; System.arraycopy(COLUMNS, 0, returnColumns, 0, COLUMNS.length); return returnColumns; } @Override public int getColumnCount() { return COLUMNS.length; } @Override public byte[] getBlob(int columnIndex) { throw new UnsupportedOperationException(); } @Override public double getDouble(int columnIndex) { return getLong(columnIndex); } private boolean isLongColumn(String column) { return LONG_COLUMNS.contains(column); } @Override public float getFloat(int columnIndex) { return (float) getDouble(columnIndex); } @Override public int getInt(int columnIndex) { return (int) getLong(columnIndex); } @Override public long getLong(int columnIndex) { return translateLong(getColumnName(columnIndex)); } @Override public short getShort(int columnIndex) { return (short) getLong(columnIndex); } @Override public String getString(int columnIndex) { return translateString(getColumnName(columnIndex)); } private String translateString(String column) { if (isLongColumn(column)) { return Long.toString(translateLong(column)); } if (column.equals(COLUMN_TITLE)) { return getUnderlyingString(Downloads.COLUMN_TITLE); } if (column.equals(COLUMN_DESCRIPTION)) { return getUnderlyingString(Downloads.COLUMN_DESCRIPTION); } if (column.equals(COLUMN_URI)) { return getUnderlyingString(Downloads.COLUMN_URI); } if (column.equals(COLUMN_MEDIA_TYPE)) { return getUnderlyingString(Downloads.COLUMN_MIME_TYPE); } if (column.equals(COLUMN_MEDIAPROVIDER_URI)) { return getUnderlyingString(Downloads.Impl.COLUMN_MEDIAPROVIDER_URI); } assert column.equals(COLUMN_LOCAL_URI); return getLocalUri(); } private String getLocalUri() { long destinationType = getUnderlyingLong(Downloads.Impl.COLUMN_DESTINATION); if (destinationType == Downloads.Impl.DESTINATION_FILE_URI) { // return client-provided file URI for external download return getUnderlyingString(Downloads.Impl.COLUMN_FILE_NAME_HINT); } if (destinationType == Downloads.Impl.DESTINATION_EXTERNAL) { // return stored destination for legacy external download String localPath = getUnderlyingString(Downloads.Impl._DATA); if (localPath == null) { return null; } return Uri.fromFile(new File(localPath)).toString(); } // return content URI for cache download long downloadId = getUnderlyingLong(Downloads.Impl._ID); return ContentUris.withAppendedId(mBaseUri, downloadId).toString(); } private long translateLong(String column) { if (!isLongColumn(column)) { // mimic behavior of underlying cursor -- most likely, throw // NumberFormatException return Long.valueOf(translateString(column)); } if (column.equals(COLUMN_ID)) { return getUnderlyingLong(Downloads.Impl._ID); } if (column.equals(COLUMN_TOTAL_SIZE_BYTES)) { return getUnderlyingLong(Downloads.COLUMN_TOTAL_BYTES); } if (column.equals(COLUMN_STATUS)) { return translateStatus((int) getUnderlyingLong(Downloads.COLUMN_STATUS)); } if (column.equals(COLUMN_REASON)) { return getReason((int) getUnderlyingLong(Downloads.COLUMN_STATUS)); } if (column.equals(COLUMN_BYTES_DOWNLOADED_SO_FAR)) { return getUnderlyingLong(Downloads.COLUMN_CURRENT_BYTES); } assert column.equals(COLUMN_LAST_MODIFIED_TIMESTAMP); return getUnderlyingLong(Downloads.COLUMN_LAST_MODIFICATION); } private long getReason(int status) { switch (translateStatus(status)) { case STATUS_FAILED: return getErrorCode(status); case STATUS_PAUSED: return getPausedReason(status); default: return 0; // arbitrary value when status is not an error } } private long getPausedReason(int status) { switch (status) { case Downloads.Impl.STATUS_WAITING_TO_RETRY: return PAUSED_WAITING_TO_RETRY; case Downloads.Impl.STATUS_WAITING_FOR_NETWORK: return PAUSED_WAITING_FOR_NETWORK; case Downloads.Impl.STATUS_QUEUED_FOR_WIFI: return PAUSED_QUEUED_FOR_WIFI; default: return PAUSED_UNKNOWN; } } private long getErrorCode(int status) { if ((400 <= status && status < Downloads.Impl.MIN_ARTIFICIAL_ERROR_STATUS) || (500 <= status && status < 600)) { // HTTP status code return status; } switch (status) { case Downloads.STATUS_FILE_ERROR: return ERROR_FILE_ERROR; case Downloads.STATUS_UNHANDLED_HTTP_CODE: case Downloads.STATUS_UNHANDLED_REDIRECT: return ERROR_UNHANDLED_HTTP_CODE; case Downloads.STATUS_HTTP_DATA_ERROR: return ERROR_HTTP_DATA_ERROR; case Downloads.STATUS_TOO_MANY_REDIRECTS: return ERROR_TOO_MANY_REDIRECTS; case Downloads.STATUS_INSUFFICIENT_SPACE_ERROR: return ERROR_INSUFFICIENT_SPACE; case Downloads.STATUS_DEVICE_NOT_FOUND_ERROR: return ERROR_DEVICE_NOT_FOUND; case Downloads.Impl.STATUS_CANNOT_RESUME: return ERROR_CANNOT_RESUME; case Downloads.Impl.STATUS_FILE_ALREADY_EXISTS_ERROR: return ERROR_FILE_ALREADY_EXISTS; default: return ERROR_UNKNOWN; } } private long getUnderlyingLong(String column) { return super.getLong(super.getColumnIndex(column)); } private String getUnderlyingString(String column) { return super.getString(super.getColumnIndex(column)); } private int translateStatus(int status) { switch (status) { case Downloads.STATUS_PENDING: return STATUS_PENDING; case Downloads.STATUS_RUNNING: return STATUS_RUNNING; case Downloads.Impl.STATUS_PAUSED_BY_APP: case Downloads.Impl.STATUS_WAITING_TO_RETRY: case Downloads.Impl.STATUS_WAITING_FOR_NETWORK: case Downloads.Impl.STATUS_QUEUED_FOR_WIFI: return STATUS_PAUSED; case Downloads.STATUS_SUCCESS: return STATUS_SUCCESSFUL; default: assert Downloads.isStatusError(status); return STATUS_FAILED; } } } ``` }
279,991
Please tell me how can save a string with special characters to DB.Special characters may contatin single `quotes/double quotes` etc.. I am using ASP.NET with C#
2008/11/11
[ "https://Stackoverflow.com/questions/279991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Use parameterized queries. <http://aspnet101.com/aspnet101/tutorials.aspx?id=1> When rendering to the client, you should also use Server.HtmlEncode() to convert characters which have special meaning in HTML to numeric character references.
Hard to answer without much details. But usually the best bet is parametrized queries.
279,991
Please tell me how can save a string with special characters to DB.Special characters may contatin single `quotes/double quotes` etc.. I am using ASP.NET with C#
2008/11/11
[ "https://Stackoverflow.com/questions/279991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Use parameterized queries. <http://aspnet101.com/aspnet101/tutorials.aspx?id=1> When rendering to the client, you should also use Server.HtmlEncode() to convert characters which have special meaning in HTML to numeric character references.
Ok.Eventhough i saved in the DB.I need to display this back to a text box.Then the page is breaking. Ex: I have saved Student name as Ani"s and when i am displayin gthis How to get rid of this problem ?
279,991
Please tell me how can save a string with special characters to DB.Special characters may contatin single `quotes/double quotes` etc.. I am using ASP.NET with C#
2008/11/11
[ "https://Stackoverflow.com/questions/279991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Use parameterized queries. <http://aspnet101.com/aspnet101/tutorials.aspx?id=1> When rendering to the client, you should also use Server.HtmlEncode() to convert characters which have special meaning in HTML to numeric character references.
Are you encoding the value when you write it out? (Server.HtmlEncode(value))
279,991
Please tell me how can save a string with special characters to DB.Special characters may contatin single `quotes/double quotes` etc.. I am using ASP.NET with C#
2008/11/11
[ "https://Stackoverflow.com/questions/279991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Use parameterized queries. <http://aspnet101.com/aspnet101/tutorials.aspx?id=1> When rendering to the client, you should also use Server.HtmlEncode() to convert characters which have special meaning in HTML to numeric character references.
``` Using (SqlConnection conn = new SqlConnection(connstr)) { Using (SqlCommand command = new SqlCommand("INSERT INTO FOO (col) VALUES (@arg)")) { command.Connection = conn; command.Parameters.AddWithValue("@arg",SpecialCharsString); command.ExecuteNonQuery(); } } ``` Reading it out should not be breaking your output at all, if it is, its not the database code doing it.
279,991
Please tell me how can save a string with special characters to DB.Special characters may contatin single `quotes/double quotes` etc.. I am using ASP.NET with C#
2008/11/11
[ "https://Stackoverflow.com/questions/279991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Use parameterized queries. <http://aspnet101.com/aspnet101/tutorials.aspx?id=1> When rendering to the client, you should also use Server.HtmlEncode() to convert characters which have special meaning in HTML to numeric character references.
(Server.HtmlEncode(value)) worked !
20,630,552
I have a simple c program that consists of `main.c` and `selection_sort.c`. I am compiling with `gcc -Wall -Wextra main.c selection_sort.c` I get no errors of warnings, but when executed it immediately terminates without any `printf` or `system quot`. I am using Linux OS. ``` //main.c #include <stdio.h> #include <stdlib.h> #include <time.h> void selection_sort(); int main(void) { printf("Program started...\n"); selection_sort(); printf("Selection_sort has finished...\n"); return 0; } //selection_sort.c #include <stdio.h> #include <stdlib.h> #define size 10000 void selection_sort() { int i,j, array[size]; for(i = 0; i < size; i++) { int num = rand() % size; array[i] = num; printf("%d ", num); } for(i = 0; i < size; i++){ int max_index = i; for(j = 0; j < size; j++) { if(array[j] > max_index) { max_index = array[j]; } } int tmp = array[i]; array[i] = array[max_index]; array[max_index] = tmp; } printf("\n"); for(i = 0; i < size;i++){ printf("%d", array[i]); } } ```
2013/12/17
[ "https://Stackoverflow.com/questions/20630552", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3008098/" ]
For anything below Honeycomb (API Level 11) you'll have to use setLayoutParams(...). you can dynamically set the position of view in Android. for example if you have an ImageView in LinearLayout of your xml file.So you can set its position through LayoutParams.But make sure to take LayoutParams according to the layout taken in your xml file.There are different LayoutParams according to the layout taken. Here is the code to set: ``` FrameLayout.LayoutParams layoutParams=new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT); layoutParams.setMargins(int left, int top, int right, int bottom); imageView.setLayoutParams(layoutParams); ```
From android documentations: [doc](http://developer.android.com/reference/android/view/View.html#setTop%28int%29) > > Sets the top position of this view relative to its parent. This method is meant to be called by the layout system and should not generally be called otherwise, because the property may be changed at any time by the layout. > > > This method shouldn't be called directly, mainly because different ViewGroups have different approach to layout which makes this method not consistent (framelayout). as @nitesh goel suggested, use Margin or padding to set the spacing between a child view and its original position in the ViewGroup. [doc](http://developer.android.com/reference/android/view/View.html) > > Size, padding and margins > The size of a view is expressed with a width and a height. A view actually possess two >pairs of width and height values. > > > The first pair is known as measured width and measured height. These dimensions define how big a view wants to be within its parent (see Layout for more details.) The measured dimensions can be obtained by calling getMeasuredWidth() and getMeasuredHeight(). > > > The second pair is simply known as width and height, or sometimes drawing width and drawing height. These dimensions define the actual size of the view on screen, at drawing time and after layout. These values may, but do not have to, be different from the measured width and height. The width and height can be obtained by calling getWidth() and getHeight(). > > > To measure its dimensions, a view takes into account its padding. The padding is expressed in pixels for the left, top, right and bottom parts of the view. Padding can be used to offset the content of the view by a specific amount of pixels. For instance, a left padding of 2 will push the view's content by 2 pixels to the right of the left edge. Padding can be set using the setPadding(int, int, int, int) or setPaddingRelative(int, int, int, int) method and queried by calling getPaddingLeft(), getPaddingTop(), getPaddingRight(), getPaddingBottom(), getPaddingStart(), getPaddingEnd(). > > > Even though a view can define a padding, it does not provide any support for margins. However, view groups provide such a support. Refer to ViewGroup and ViewGroup.MarginLayoutParams for further information. > > >
56,779,996
I need to show all the letters in uppercase while the user is writing. I'm using this: `android:inputType="textCapCharacters"` But, when I push shift it turns to lowercase. I need something permanent.
2019/06/26
[ "https://Stackoverflow.com/questions/56779996", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10561060/" ]
Functions will look into the module level scope i.e. global scope automatically when some name does not exist in the local scope. So, rather than checking in the `globals` dict, you can *ask for forgiveness*: ``` def _get_client(): try: return api_client except NameError: return some_api.Client() ```
Just to offer a different idea, assuming your API client is never falsy, you might consider just initializing the global to `None`. Then you could do something like ``` api_client = None def _get_client(): return api_client or whatever_default ```
61,423,714
I'm looping through a array filled with objects, and when i certain condition is met i want to make a copy of the current item and change a value **only** for the duplicated item. Something like: ``` while (j--) { if (value[j].extended.subcategories[0] === "lorem") { value.push(value[j]); value[DUPLICATED_ITEM].extended.subcategories[0] = "ipsum"; } } ``` I was playing around in jsfiddle and i also tried something like: ``` while (j--) { if (value[j].extended.subcategories[0] === "lorem") { value[value.length] = value[j]; value[value.length].extended.subcategories[0] = "ipsum"; } } ``` This does add a duplicate but when trying to change a value in the object it's (still) undefined. --- Small sidenote: while playing with the fiddle, i found another weird interaction that i don't really get. If you do this: <https://jsfiddle.net/luffyyyyy/bs1h0qLz/13/>. Both array[0] and array[3] get a value of 8 while i just specify array[3] = 8;
2020/04/25
[ "https://Stackoverflow.com/questions/61423714", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2851791/" ]
Using Javascript / jQuery the following will remove all "hovered" action buttons, for a specific user role, on the subscriptions admin dashboard from the status column: ``` add_action( 'admin_footer', 'admin_dashboard_subscriptions_filter_callback' ); function admin_dashboard_subscriptions_filter_callback() { global $pagenow, $post_type; $targeted_user_role = 'va_support'; // <== Your defined user role slug // Targeting subscriptions admin dashboard for specific user role if( $pagenow === 'edit.php' && $post_type === 'shop_subscription' && current_user_can( $targeted_user_role ) ) : ?> <script> jQuery(function($){ $('td.column-status > div.row-actions').each(function() { $(this).remove(); }); }); </script> <?php endif; } ``` Code goes in functions.php file of your active child theme (or active theme). Tested and works.
As of now, there is no filter where handling this action trigger. You may add a filter on your own for handling this. /woocommerce-subscriptions/includes/admin/class-wcs-admin-post-types.php inside this function around Line# 330 - `public function parse_bulk_actions()` ``` /* * Use below hook for handling custom user role permission for action from subscription listing page */ $can_change_status = apply_filters('wcs_can_change_subscription_status', true, $subscription_ids); if(!$can_change_status){ return; } ``` In theme, you can check the current user has the role then return true/false accordingly. You may be aware that when updating the plugin, the changes will be lost. But as far as checking the code, there is no filter just before triggering these functions. ``` add_filter( 'wcs_can_change_subscription_status', 'alter_can_change_subscription_status' ); function alter_can_change_subscription_status( $can_change_status ) { $user = wp_get_current_user(); if ( in_array( 'va_support', (array) $user->roles ) ) { //The user has the "va_support" role return false; } return $can_change_status; } ```
14,322
Ma recherche initiale sur l'étymologie de [« désormais » (adv. de temps)](http://www.littre.org/definition/d%C3%A9sormais) m'a dévoilé une définition de **mais** comme « davantage », voir ci-dessous. > > **Dès**,        **or** ou **ore**, heure (voy. OR),      et      **mais** [=] davantage : > > > mot à mot, dès l'heure en avant. > > > Ensuite, je me lance dans [l'étymologie de « mais »](https://fr.wiktionary.org/wiki/mais#.C3.89tymologie) : > > [1.] (Xe siècle) Du latin [magis](https://fr.wiktionary.org/wiki/magis#la) (« plus, plutôt ») [[Plus, davantage.]](https://fr.wiktionary.org/wiki/magis#la) > > > La connotation de « magis », et de **mais** dans « désormais », me semble neutre. 2. Pourtant, en français moderne, « mais » peut servir [« à marquer opposition, restriction, différence » (cf la définition 3)](http://www.littre.org/definition/mais). Donc, le sens de « mais », comment a-t-il évolué de 1 à 2 ? Est-il devenu opposé? J'ai tenté de lire [l'étymologie du TLF sur « mais »](http://www.cnrtl.fr/etymologie/mais/1), dont la longueur et le manque de formatage m'ont rebuté.
2015/07/06
[ "https://french.stackexchange.com/questions/14322", "https://french.stackexchange.com", "https://french.stackexchange.com/users/-1/" ]
Je ne sais pas si ceci répondra à votre question, et je ne suis pas spécialiste de l'étymologie (et le TLF m'est aussi difficile à lire qu'à vous, même reformaté), mais il me semble qu'on peut affirmer en résumé : * Le **sens originel** de *mais* est celui de *magis* en latin : « plus, davantage ». Il me semble que c'est bien ce sens qui est à l'origine de *désormais*. * Pour obtenir un effet d'opposition ou de restriction, il fallait originellement y ajouter la **particule de négation** (*ne*, *non*). On retrouve ces constructions dans les exemples du TLF, ou dans certaines expressions figées, comme « n'en pouvoir mais ». > > « Il les assura même de la bénédiction pourtant hypothétique de sa > mère et de la pensée affectueuse de Dabek Sariéloubal qui **n'en pouvait** > **mais**. » (René Fallet, *Le triporteur*, 1951) > > > * Au cours des siècles, la particule de négation a de plus en plus fréquemment été omise, le sens négatif restant dominant dans l'usage et l'idée d'opposition passant donc au mot *mais* lui-même. (C'est le même phénomène qui explique l'existence simultanée des sens négatif et positif de *plus*.) * Finalement, le sens originel s'est perdu et le sens d'opposition est resté dans l'usage.
> > Étymol. et Hist. > > > ***I - Adverbe*. > > A. Temporel** > > > 1. 2e moitié xes. ja non... mais «jamais plus ... ne»; ca 1130 ja mais «à partir de maintenant et dans l'avenir», v. jamais; > 2. a) fin xes. magis [+ imparfait du subj.]«à un moment, un jour (dans le passé)» (Passion, éd. D'Arco Silvio Avalle, 88); ca 1100 mais [+ fut.] «à l'avenir, désormais» (Roland, éd. J. Bédier, 543); > 3. b) ca 1050 mais ... ne, ne ... mais «ne plus jamais, ne plus» (St Alexis, éd. Chr. Storey, 36: Quant veit li pedre que mais n'avrat amfant; 187: ,,Certes`dist il, ,,n'i ai mais ad ester`); > 4. ca 1100 unkes mais ne [+ parfait] «jamais, jamais encore (durée indéfinie dans le passé)» (Roland, 2223); > 5. 1130-40 desormais (Wace, Conception N.-D., éd. W.R. Ashford, 1302, v. aussi désormais); > 6. ca 1165 hui mais, mais hui «à partir de maintenant, désormais» (Benoît de Ste-Maure, Troie, 2108 [+ fut.], 2275 [+ ind. prés.] ds T.-L.); id. ne ... hui mais [+ fut.] «ne ... plus» (id. 7943, ibid.); > 7. id. toz jorz ... mais [+ fut.] «toujours (durée indéfinie)» (id., 2269, ibid.). > > > **B. Quantitatif** > > > fin xes. mais «davantage» (Passion, 498); ca 1160 ne poöir mais «ne rien y pouvoir» (Eneas, 4390 ds T.-L., s.v. poöir); ca 1165 n'en poöir mais (Benoît de Ste-Maure, op. cit., 13164, ibid.). > > > ***II - Conjonction.* > > A. Adversative** > > > 1. marque une opposition > > > 1.a) 2emoitié xes. introduit une idée contraire à celle déjà exprimée (St Léger, éd. J.Linskill, 58 apr. une phrase négative; 113 apr. une phrase positive); > > > 1.b) ca 1200 marque une préférence (Jean Bodel, St Nicolas, éd. A. Henry, 801: Pinchedé, hocherons as crois? − Mais a le mine, entre nous trois); > > > 1.c) ca 1160 marque une précision, une rectification, un renchérissement apr. une interr. dir. (Eneas, 1754 ds T.-L.); ca 1200 (Jean Bodel, op. cit., 294: Soit pour un parti: a pais faire − Pour un? Mais pour canques tu dois); > > > 2. marque une transition ca 1050 dans un récit «et voici que ...» (St Alexis, 213); ca 1100 (Roland, 1154); > 3. dans un entretien assez vif, renforce une affirmation, une interr., un doute précédemment exprimés : > > > 3.a) ca 1135 précède le verbe d'une prop. impér. (Couronnement de Louis, éd. E. Langlois, 2120: De quei le dotez vos? Mais chevalchiez et poignez tresqu'al pont); > > > 3.b) 1176-84 [ms. fin xiiies.] introduit une intervention répondant à une mise en doute, un étonnement (Gautier d'Arras, Ille et Galeron, éd. A. G. Cowper, 3797, var. ms. P: Oïstes me vos ainc requerre se vostre pere ot rice tere U s'il ert besogneus d'avoir? − Mais voel je vostre pere avoir U vos amer por vostre pere?); > > > 3.c) 1178 introduit la réponse à une interr. précise (Renart, éd. M. Roques, 13257: ,,Avroie ge poisons assez Tant que seroie respassez De cest mal qui m'a confondu?`Et Renart li [Ysengrin] a respondu ,,Mais tant con vos porrez mangier`). > > > **B. Restrictive** > > > 1. mais que «à l'exception de» fin xes. apr. une phrase positive (Passion, 99); ca 1050 apr. une phrase négative (St Alexis, 37); > 2. ne mais que «id.» ca 1100 apr. une phrase négative (Roland, 1934); apr. une phrase positive (ibid., 217). > > > **C. Hypothétique,** exprimant la supposition, la condition ca 1100 mais que + subj. «pourvu que, à condition que» (ibid., 234). > > > **D. Concessive** ca 1165 mais bien + subj. «bien que, même si» (Benoît de Ste-Maure, Troie, 8621 ds T.-L.); ca 1170 mes que bien + subj. (Chrétien de Troyes, Erec, éd. M. Roques, 4684). > De l'adv. lat. magis «plus, davantage» employé notamment pour exprimer le compar. (en remplacement des formes synthétiques pour les adj. en -eus, -ius, -uus; dès l'époque pré-class. pour marquer une oppos., une mise en relief de l'adj. [cf. disertus magis quam sapiens, Cic., Att., 10, 1, 4], le tour périphrastique devenant de plus en plus fréquent à basse époque sans valeur expressive particulière), d'où mais adv. quantitatif (I A), et, appliqué à une quantité de temps, adv. temporel, le plus souvent combiné à d'autres adv. de temps (I B). Du sens secondaire «plutôt», notamment dans les tours non ... sed magis, ac magis, magis autem (TLL, s.v., 68, 1 sqq.), est issu l'emploi adversatif [cf., d'abord dans la langue poétique Catulle, 68, 30: id. ... non est turpe magis miserum est; en prose dep. Salluste, Jug., 96, 2: ab nullo repetere [sc. beneficia] magis id laborare ut...] (II A), ses représentants rom. (FEW t. 6, 1, p. 31b) montrant que magis avait dès l'époque prérom. assumé les emplois de sed (oppos. forte) et de autem (oppos. faible); pour sa part, à partir du m.fr., mais empiétera de plus en plus sur ainz (employé surtout dans les antithèses dont le premier terme est négatif, pour énoncer le second sous une forme positive, Ph. Ménard, Synt. de l'a.fr., § 309, 3orem.; G. Moignet, Gramm. de l'a. fr., p. 335) qu'il finit par supplanter. > L'emploi restrictif (II B) semble issu du tour compar. «pas plus ... que» [non magis ... quam], d'où «seulement; rien, si ce n'est que» [ne ... mais que; mais que], v. Lat. Gramm. t. 2, Syntax und Stilistik, p. 497, § 268 Zusatz > > > 2. De l'emploi restrictif seraient issus l'emploi hypothétique (II C): «seulement, excepté, mis à part» d'où «sous la réserve que, à condition que, pourvu que» − et l'emploi concessif: «mis à part le fait que», d'où «sans tenir compte du fait que, bien que», v. Ph. Ménard, op. cit., §§ 263 C, 270 c, 273; v. aussi FEW, loc. cit., p. 32a et b. > > > --- Si vous copiez/collez la page du TLF dans une page LibreOffice, vous pouvez garder la typographie originelle, la formater et même souligner les différentes acceptions de *mais* et suivre leur évolution. Il en ressort que le contexte détermine le sens. Le *§ D* devrait répondre à votre question.
138,043
I want to create a new net.tcp://localhost:x/Service endpoint for a WCF service call, with a dynamically assigned new open TCP port. I know that TcpClient will assign a new client side port when I open a connection to a given server. Is there a simple way to find the next open TCP port in .NET? I need the actual number, so that I can build the string above. 0 does not work, since I need to pass that string to another process, so that I can call back on that new channel.
2008/09/26
[ "https://Stackoverflow.com/questions/138043", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4829/" ]
Here is what I was looking for: ``` static int FreeTcpPort() { TcpListener l = new TcpListener(IPAddress.Loopback, 0); l.Start(); int port = ((IPEndPoint)l.LocalEndpoint).Port; l.Stop(); return port; } ```
Use a port number of 0. The TCP stack will allocate the next free one.
138,043
I want to create a new net.tcp://localhost:x/Service endpoint for a WCF service call, with a dynamically assigned new open TCP port. I know that TcpClient will assign a new client side port when I open a connection to a given server. Is there a simple way to find the next open TCP port in .NET? I need the actual number, so that I can build the string above. 0 does not work, since I need to pass that string to another process, so that I can call back on that new channel.
2008/09/26
[ "https://Stackoverflow.com/questions/138043", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4829/" ]
It's a solution comparable to the accepted answer of TheSeeker. Though I think it's more readable: ``` using System; using System.Net; using System.Net.Sockets; private static readonly IPEndPoint DefaultLoopbackEndpoint = new IPEndPoint(IPAddress.Loopback, port: 0); public static int GetAvailablePort() { using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { socket.Bind(DefaultLoopbackEndpoint); return ((IPEndPoint)socket.LocalEndPoint).Port; } } ```
Here's a more abbreviated way to implement this if you want to find the next available TCP port within a given range: ```cs private int GetNextUnusedPort(int min, int max) { if (max < min) throw new ArgumentException("Max cannot be less than min."); var ipProperties = IPGlobalProperties.GetIPGlobalProperties(); var usedPorts = ipProperties.GetActiveTcpConnections() .Where(connection => connection.State != TcpState.Closed) .Select(connection => connection.LocalEndPoint) .Concat(ipProperties.GetActiveTcpListeners()) .Concat(ipProperties.GetActiveUdpListeners()) .Select(endpoint => endpoint.Port) .ToArray(); var firstUnused = Enumerable.Range(min, max - min) .Where(port => !usedPorts.Contains(port)) .Select(port => new int?(port)) .FirstOrDefault(); if (!firstUnused.HasValue) throw new Exception($"All local TCP ports between {min} and {max} are currently in use."); return firstUnused.Value; } ```
138,043
I want to create a new net.tcp://localhost:x/Service endpoint for a WCF service call, with a dynamically assigned new open TCP port. I know that TcpClient will assign a new client side port when I open a connection to a given server. Is there a simple way to find the next open TCP port in .NET? I need the actual number, so that I can build the string above. 0 does not work, since I need to pass that string to another process, so that I can call back on that new channel.
2008/09/26
[ "https://Stackoverflow.com/questions/138043", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4829/" ]
Use a port number of 0. The TCP stack will allocate the next free one.
Here's a more abbreviated way to implement this if you want to find the next available TCP port within a given range: ```cs private int GetNextUnusedPort(int min, int max) { if (max < min) throw new ArgumentException("Max cannot be less than min."); var ipProperties = IPGlobalProperties.GetIPGlobalProperties(); var usedPorts = ipProperties.GetActiveTcpConnections() .Where(connection => connection.State != TcpState.Closed) .Select(connection => connection.LocalEndPoint) .Concat(ipProperties.GetActiveTcpListeners()) .Concat(ipProperties.GetActiveUdpListeners()) .Select(endpoint => endpoint.Port) .ToArray(); var firstUnused = Enumerable.Range(min, max - min) .Where(port => !usedPorts.Contains(port)) .Select(port => new int?(port)) .FirstOrDefault(); if (!firstUnused.HasValue) throw new Exception($"All local TCP ports between {min} and {max} are currently in use."); return firstUnused.Value; } ```
138,043
I want to create a new net.tcp://localhost:x/Service endpoint for a WCF service call, with a dynamically assigned new open TCP port. I know that TcpClient will assign a new client side port when I open a connection to a given server. Is there a simple way to find the next open TCP port in .NET? I need the actual number, so that I can build the string above. 0 does not work, since I need to pass that string to another process, so that I can call back on that new channel.
2008/09/26
[ "https://Stackoverflow.com/questions/138043", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4829/" ]
It's a solution comparable to the accepted answer of TheSeeker. Though I think it's more readable: ``` using System; using System.Net; using System.Net.Sockets; private static readonly IPEndPoint DefaultLoopbackEndpoint = new IPEndPoint(IPAddress.Loopback, port: 0); public static int GetAvailablePort() { using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { socket.Bind(DefaultLoopbackEndpoint); return ((IPEndPoint)socket.LocalEndPoint).Port; } } ```
First open the port, then give the correct port number to the other process. Otherwise it is still possible that some other process opens the port first and you still have a different one.
138,043
I want to create a new net.tcp://localhost:x/Service endpoint for a WCF service call, with a dynamically assigned new open TCP port. I know that TcpClient will assign a new client side port when I open a connection to a given server. Is there a simple way to find the next open TCP port in .NET? I need the actual number, so that I can build the string above. 0 does not work, since I need to pass that string to another process, so that I can call back on that new channel.
2008/09/26
[ "https://Stackoverflow.com/questions/138043", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4829/" ]
Use a port number of 0. The TCP stack will allocate the next free one.
It's a solution comparable to the accepted answer of TheSeeker. Though I think it's more readable: ``` using System; using System.Net; using System.Net.Sockets; private static readonly IPEndPoint DefaultLoopbackEndpoint = new IPEndPoint(IPAddress.Loopback, port: 0); public static int GetAvailablePort() { using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { socket.Bind(DefaultLoopbackEndpoint); return ((IPEndPoint)socket.LocalEndPoint).Port; } } ```
138,043
I want to create a new net.tcp://localhost:x/Service endpoint for a WCF service call, with a dynamically assigned new open TCP port. I know that TcpClient will assign a new client side port when I open a connection to a given server. Is there a simple way to find the next open TCP port in .NET? I need the actual number, so that I can build the string above. 0 does not work, since I need to pass that string to another process, so that I can call back on that new channel.
2008/09/26
[ "https://Stackoverflow.com/questions/138043", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4829/" ]
Here is what I was looking for: ``` static int FreeTcpPort() { TcpListener l = new TcpListener(IPAddress.Loopback, 0); l.Start(); int port = ((IPEndPoint)l.LocalEndpoint).Port; l.Stop(); return port; } ```
First open the port, then give the correct port number to the other process. Otherwise it is still possible that some other process opens the port first and you still have a different one.
138,043
I want to create a new net.tcp://localhost:x/Service endpoint for a WCF service call, with a dynamically assigned new open TCP port. I know that TcpClient will assign a new client side port when I open a connection to a given server. Is there a simple way to find the next open TCP port in .NET? I need the actual number, so that I can build the string above. 0 does not work, since I need to pass that string to another process, so that I can call back on that new channel.
2008/09/26
[ "https://Stackoverflow.com/questions/138043", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4829/" ]
First open the port, then give the correct port number to the other process. Otherwise it is still possible that some other process opens the port first and you still have a different one.
If you want to get a free port in a specific range in order to use it as local port / end point: ``` private int GetFreePortInRange(int PortStartIndex, int PortEndIndex) { DevUtils.LogDebugMessage(string.Format("GetFreePortInRange, PortStartIndex: {0} PortEndIndex: {1}", PortStartIndex, PortEndIndex)); try { IPGlobalProperties ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties(); IPEndPoint[] tcpEndPoints = ipGlobalProperties.GetActiveTcpListeners(); List<int> usedServerTCpPorts = tcpEndPoints.Select(p => p.Port).ToList<int>(); IPEndPoint[] udpEndPoints = ipGlobalProperties.GetActiveUdpListeners(); List<int> usedServerUdpPorts = udpEndPoints.Select(p => p.Port).ToList<int>(); TcpConnectionInformation[] tcpConnInfoArray = ipGlobalProperties.GetActiveTcpConnections(); List<int> usedPorts = tcpConnInfoArray.Where(p=> p.State != TcpState.Closed).Select(p => p.LocalEndPoint.Port).ToList<int>(); usedPorts.AddRange(usedServerTCpPorts.ToArray()); usedPorts.AddRange(usedServerUdpPorts.ToArray()); int unusedPort = 0; for (int port = PortStartIndex; port < PortEndIndex; port++) { if (!usedPorts.Contains(port)) { unusedPort = port; break; } } DevUtils.LogDebugMessage(string.Format("Local unused Port:{0}", unusedPort.ToString())); if (unusedPort == 0) { DevUtils.LogErrorMessage("Out of ports"); throw new ApplicationException("GetFreePortInRange, Out of ports"); } return unusedPort; } catch (Exception ex) { string errorMessage = ex.Message; DevUtils.LogErrorMessage(errorMessage); throw; } } private int GetLocalFreePort() { int hemoStartLocalPort = int.Parse(DBConfig.GetField("Site.Config.hemoStartLocalPort")); int hemoEndLocalPort = int.Parse(DBConfig.GetField("Site.Config.hemoEndLocalPort")); int localPort = GetFreePortInRange(hemoStartLocalPort, hemoEndLocalPort); DevUtils.LogDebugMessage(string.Format("Local Free Port:{0}", localPort.ToString())); return localPort; } public void Connect(string host, int port) { try { // Create socket Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); var localPort = GetLocalFreePort(); // Create an endpoint for the specified IP on any port IPEndPoint bindEndPoint = new IPEndPoint(IPAddress.Any, localPort); // Bind the socket to the endpoint socket.Bind(bindEndPoint); // Connect to host socket.Connect(IPAddress.Parse(host), port); socket.Dispose(); } catch (SocketException ex) { // Get the error message string errorMessage = ex.Message; DevUtils.LogErrorMessage(errorMessage); } } public void Connect2(string host, int port) { try { // Create socket var localPort = GetLocalFreePort(); // Create an endpoint for the specified IP on any port IPEndPoint bindEndPoint = new IPEndPoint(IPAddress.Any, localPort); var client = new TcpClient(bindEndPoint); //client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); //will release port when done // Connect to the host client.Connect(IPAddress.Parse(host), port); client.Close(); } catch (SocketException ex) { // Get the error message string errorMessage = ex.Message; DevUtils.LogErrorMessage(errorMessage); } } ```
138,043
I want to create a new net.tcp://localhost:x/Service endpoint for a WCF service call, with a dynamically assigned new open TCP port. I know that TcpClient will assign a new client side port when I open a connection to a given server. Is there a simple way to find the next open TCP port in .NET? I need the actual number, so that I can build the string above. 0 does not work, since I need to pass that string to another process, so that I can call back on that new channel.
2008/09/26
[ "https://Stackoverflow.com/questions/138043", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4829/" ]
Here is what I was looking for: ``` static int FreeTcpPort() { TcpListener l = new TcpListener(IPAddress.Loopback, 0); l.Start(); int port = ((IPEndPoint)l.LocalEndpoint).Port; l.Stop(); return port; } ```
I found the following code from **Selenium.WebDriver DLL** **Namespace**: OpenQA.Selenium.Internal **Class**: PortUtility ``` public static int FindFreePort() { int port = 0; Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { IPEndPoint localEP = new IPEndPoint(IPAddress.Any, 0); socket.Bind(localEP); localEP = (IPEndPoint)socket.LocalEndPoint; port = localEP.Port; } finally { socket.Close(); } return port; } ```
138,043
I want to create a new net.tcp://localhost:x/Service endpoint for a WCF service call, with a dynamically assigned new open TCP port. I know that TcpClient will assign a new client side port when I open a connection to a given server. Is there a simple way to find the next open TCP port in .NET? I need the actual number, so that I can build the string above. 0 does not work, since I need to pass that string to another process, so that I can call back on that new channel.
2008/09/26
[ "https://Stackoverflow.com/questions/138043", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4829/" ]
It's a solution comparable to the accepted answer of TheSeeker. Though I think it's more readable: ``` using System; using System.Net; using System.Net.Sockets; private static readonly IPEndPoint DefaultLoopbackEndpoint = new IPEndPoint(IPAddress.Loopback, port: 0); public static int GetAvailablePort() { using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { socket.Bind(DefaultLoopbackEndpoint); return ((IPEndPoint)socket.LocalEndPoint).Port; } } ```
If you want to get a free port in a specific range in order to use it as local port / end point: ``` private int GetFreePortInRange(int PortStartIndex, int PortEndIndex) { DevUtils.LogDebugMessage(string.Format("GetFreePortInRange, PortStartIndex: {0} PortEndIndex: {1}", PortStartIndex, PortEndIndex)); try { IPGlobalProperties ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties(); IPEndPoint[] tcpEndPoints = ipGlobalProperties.GetActiveTcpListeners(); List<int> usedServerTCpPorts = tcpEndPoints.Select(p => p.Port).ToList<int>(); IPEndPoint[] udpEndPoints = ipGlobalProperties.GetActiveUdpListeners(); List<int> usedServerUdpPorts = udpEndPoints.Select(p => p.Port).ToList<int>(); TcpConnectionInformation[] tcpConnInfoArray = ipGlobalProperties.GetActiveTcpConnections(); List<int> usedPorts = tcpConnInfoArray.Where(p=> p.State != TcpState.Closed).Select(p => p.LocalEndPoint.Port).ToList<int>(); usedPorts.AddRange(usedServerTCpPorts.ToArray()); usedPorts.AddRange(usedServerUdpPorts.ToArray()); int unusedPort = 0; for (int port = PortStartIndex; port < PortEndIndex; port++) { if (!usedPorts.Contains(port)) { unusedPort = port; break; } } DevUtils.LogDebugMessage(string.Format("Local unused Port:{0}", unusedPort.ToString())); if (unusedPort == 0) { DevUtils.LogErrorMessage("Out of ports"); throw new ApplicationException("GetFreePortInRange, Out of ports"); } return unusedPort; } catch (Exception ex) { string errorMessage = ex.Message; DevUtils.LogErrorMessage(errorMessage); throw; } } private int GetLocalFreePort() { int hemoStartLocalPort = int.Parse(DBConfig.GetField("Site.Config.hemoStartLocalPort")); int hemoEndLocalPort = int.Parse(DBConfig.GetField("Site.Config.hemoEndLocalPort")); int localPort = GetFreePortInRange(hemoStartLocalPort, hemoEndLocalPort); DevUtils.LogDebugMessage(string.Format("Local Free Port:{0}", localPort.ToString())); return localPort; } public void Connect(string host, int port) { try { // Create socket Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); var localPort = GetLocalFreePort(); // Create an endpoint for the specified IP on any port IPEndPoint bindEndPoint = new IPEndPoint(IPAddress.Any, localPort); // Bind the socket to the endpoint socket.Bind(bindEndPoint); // Connect to host socket.Connect(IPAddress.Parse(host), port); socket.Dispose(); } catch (SocketException ex) { // Get the error message string errorMessage = ex.Message; DevUtils.LogErrorMessage(errorMessage); } } public void Connect2(string host, int port) { try { // Create socket var localPort = GetLocalFreePort(); // Create an endpoint for the specified IP on any port IPEndPoint bindEndPoint = new IPEndPoint(IPAddress.Any, localPort); var client = new TcpClient(bindEndPoint); //client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); //will release port when done // Connect to the host client.Connect(IPAddress.Parse(host), port); client.Close(); } catch (SocketException ex) { // Get the error message string errorMessage = ex.Message; DevUtils.LogErrorMessage(errorMessage); } } ```
138,043
I want to create a new net.tcp://localhost:x/Service endpoint for a WCF service call, with a dynamically assigned new open TCP port. I know that TcpClient will assign a new client side port when I open a connection to a given server. Is there a simple way to find the next open TCP port in .NET? I need the actual number, so that I can build the string above. 0 does not work, since I need to pass that string to another process, so that I can call back on that new channel.
2008/09/26
[ "https://Stackoverflow.com/questions/138043", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4829/" ]
Use a port number of 0. The TCP stack will allocate the next free one.
I found the following code from **Selenium.WebDriver DLL** **Namespace**: OpenQA.Selenium.Internal **Class**: PortUtility ``` public static int FindFreePort() { int port = 0; Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { IPEndPoint localEP = new IPEndPoint(IPAddress.Any, 0); socket.Bind(localEP); localEP = (IPEndPoint)socket.LocalEndPoint; port = localEP.Port; } finally { socket.Close(); } return port; } ```
73,394,646
In a webapp implemented as a Jetty container, we have a custom `javax.ws.rs.ext.MessageBodyWriter<T>` annotated with ``` @Singleton @Provider @Produces( "application/rss+xml" ) ``` We also have a resource which works just fine. The `get()` method is annotated with ``` @Produces( "application/vnd.api+json" ) ``` Visiting that endpoint returns the expected json response. Adding `.rss` to the endpoint causes a 406 response to be returned. What could be the reason it is not finding the `MessageBodyWriter` for returning the RSS response? The full stacktrace is: ``` javax.ws.rs.NotAcceptableException: HTTP 406 Not Acceptable at org.glassfish.jersey.server.internal.routing.MethodSelectingRouter.getMethodRouter(MethodSelectingRouter.java:472) at org.glassfish.jersey.server.internal.routing.MethodSelectingRouter.access$000(MethodSelectingRouter.java:73) at org.glassfish.jersey.server.internal.routing.MethodSelectingRouter$4.apply(MethodSelectingRouter.java:674) at org.glassfish.jersey.server.internal.routing.MethodSelectingRouter.apply(MethodSelectingRouter.java:305) at org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:86) at org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:89) at org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:89) at org.glassfish.jersey.server.internal.routing.RoutingStage.apply(RoutingStage.java:69) at org.glassfish.jersey.server.internal.routing.RoutingStage.apply(RoutingStage.java:38) at org.glassfish.jersey.process.internal.Stages.process(Stages.java:173) at org.glassfish.jersey.server.ServerRuntime$1.run(ServerRuntime.java:247) at org.glassfish.jersey.internal.Errors$1.call(Errors.java:248) at org.glassfish.jersey.internal.Errors$1.call(Errors.java:244) at org.glassfish.jersey.internal.Errors.process(Errors.java:292) at org.glassfish.jersey.internal.Errors.process(Errors.java:274) at org.glassfish.jersey.internal.Errors.process(Errors.java:244) at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:265) at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:234) at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:684) at <our package>.Jetty94HttpContainer.handle(Jetty94HttpContainer.java:167) // Jetty94HttpContainer extends AbstractHandler implements Container at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:127) at com.codahale.metrics.jetty9.InstrumentedHandler.handle(InstrumentedHandler.java:284) at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:127) at org.eclipse.jetty.server.Server.handle(Server.java:516) at org.eclipse.jetty.server.HttpChannel.lambda$handle$1(HttpChannel.java:487) at org.eclipse.jetty.server.HttpChannel.dispatch(HttpChannel.java:732) at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:479) at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:277) at org.eclipse.jetty.io.AbstractConnection$ReadCallback.succeeded(AbstractConnection.java:311) at org.eclipse.jetty.io.FillInterest.fillable(FillInterest.java:105) at org.eclipse.jetty.io.ChannelEndPoint$1.run(ChannelEndPoint.java:104) at org.eclipse.jetty.util.thread.strategy.EatWhatYouKill.runTask(EatWhatYouKill.java:338) at org.eclipse.jetty.util.thread.strategy.EatWhatYouKill.doProduce(EatWhatYouKill.java:315) at org.eclipse.jetty.util.thread.strategy.EatWhatYouKill.tryProduce(EatWhatYouKill.java:173) at org.eclipse.jetty.util.thread.strategy.EatWhatYouKill.run(EatWhatYouKill.java:131) at org.eclipse.jetty.util.thread.ReservedThreadExecutor$ReservedThread.run(ReservedThreadExecutor.java:409) at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:883) at org.eclipse.jetty.util.thread.QueuedThreadPool$Runner.run(QueuedThreadPool.java:1034) at java.base/java.lang.Thread.run(Thread.java:829) ```
2022/08/17
[ "https://Stackoverflow.com/questions/73394646", "https://Stackoverflow.com", "https://Stackoverflow.com/users/167745/" ]
The resource methods annotated with a request method should declare the supported request media types equals to the entity providers that supply mapping services between representations and their associated Java types. Adding: ``` @Produces( "application/vnd.api+json", "application/rss+xml" ) ``` to the `get()` method should do the trick.
*(Posted an answer from the question author in order to move it to the answer space)*. Thanks to [Lety](https://stackoverflow.com/users/3819421/lety) I was able to find the problem. It's one of those which are super-obvious once you realise it, but which no amount of staring at the code alone would reveal! [This answer also helped](https://stackoverflow.com/questions/38488903/jersey-multiple-produces) If you want to switch a resource output between different output types depending on the `Accept` request header, the resource method needs `@Produces` to cover all the desired output types, as well as having a `MessageBodyWriter` configured for that output. In other words, I changed the `get()` method of the resource to read ... ``` @Produces( "application/vnd.api+json", "application/rss+xml" ) ``` ... and this is what made it work.
5,720,386
I have a small chat implementation, which uses a `Message` model underneath. In the `index` action, I am showing all the messages in a "chat-area" form. The thing is, I would like to start a background task which will poll the server for new messages every X seconds. How can I do that and have my JS unobtrusive? I wouldn't like to have inline JS in my `index.html.erb`, and I wouldn't like to have the polling code getting evaluated on every page I am on.
2011/04/19
[ "https://Stackoverflow.com/questions/5720386", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31610/" ]
This would be easiest using a library like mootools or jquery. On `domready`/`document.ready`, you should check for a given class, like "chat-area-container". If it is found, you can build a new `<script>` tag and inject it into DOM in order to include the javascript specific for the chat area. That way, it isn't loaded on every page. The "chat-area-container" can be structured so that it is hidden or shows a loading message, which the script can remove once it is initialized. On the dynamically created `<script>` tag, you add an onLoad event. When the script is finished loading, you can call any initialization functions from within the onLoad event. Using this method, you can progressively enhance your page - users without javascript will either see a non-functioning chat area with a loading message (since it won't work without js anyway), or if you hide it initially, they'll be none-the-wiser that there is a chat area at all. Also, by using a dynamic script tag, the onLoad event "pseudo-threads" the initialization off the main javascript procedural stack.
To set up a poll on a fixed interval use setInterval or setTimeout. Here is an example, using jQuery and making some guesses about what your server's ajax interface might look like: ``` $(function() { // Look for the chat area by its element id. var chat = $('#chat-area'); var lastPoll = 0; function poll() { $.getJSON('/messages', { since: lastPoll }, function(data) { // Imagining that data is a list of message objects... $.each(data, function(i, message) { // Create a paragraph element to display each message. var m = $('<p/>', { 'class': 'chat-message', text: message.author +': '+ message.text; }); chat.append(m); }); }); // Schedules the function to run again in 1000 milliseconds. setTimeout(poll, 1000); lastPoll = (new Date()).getTime(); } // Starts the polling process if the chat area exists. if (chat.length > 0) { poll(); } }); ```
23,943,895
Is it possible to get an Excel VLOOKUP to pick out the most recent date where it finds multiple lookup values: e.g. this is what I have at the moment: ``` =IFERROR(VLOOKUP(A$1:A$5635,'RSA Report'!A:V,21,FALSE),"") ``` it would currently pick (User1 acting as the value that is being looked up) ``` Col A (1) Col U (21) User1 22/10/2013 ``` from ``` Col A (1) Col U (21) User1 22/10/2013 User1 28/03/2014 User1 22/10/2013 User1 28/03/2014 ``` whereas I want it to pick ``` Col A (1) Col U (21) User1 28/03/2014 ```
2014/05/29
[ "https://Stackoverflow.com/questions/23943895", "https://Stackoverflow.com", "https://Stackoverflow.com/users/436493/" ]
VLookup is designed to look for a single match for a specific value (either using an exact or approximate comparison). It doesn't check for any other matching values. I can think of 2 options which might help: * If you can sort the data, sort Column U in descending order. The most recent date will then be returned as the first match. * If you can't sort the data, you could consider using the [DMax](http://office.microsoft.com/en-us/excel-help/dmax-HP005209061.aspx) function. This allows you to specify criteria and then return the maximum value for a specific field. It does require you to put the criteria in a table format rather than specifying directly within the formula, so it's not ideal in all situations. Here's an example showing DMAX: Formula: `=DMAX(B3:C7,"Date",E3:E4)` This assumes that your table of data is in range B3:B7, you want to find the maximum value in a field called "Date" and your criteria is in range E3:E4 (where E3 contains the field name you are filtering on, and E4 contains the value you are looking for). One of the benefits of DMax is that you can use multiple sets of criteria.
You should work sort your data before the vlookup. Sort by the column A and add one more level sorting by column U (ordering by the most recent date) Then you can do the Vlookup and it will return the first match, that will be the most recent date!
23,943,895
Is it possible to get an Excel VLOOKUP to pick out the most recent date where it finds multiple lookup values: e.g. this is what I have at the moment: ``` =IFERROR(VLOOKUP(A$1:A$5635,'RSA Report'!A:V,21,FALSE),"") ``` it would currently pick (User1 acting as the value that is being looked up) ``` Col A (1) Col U (21) User1 22/10/2013 ``` from ``` Col A (1) Col U (21) User1 22/10/2013 User1 28/03/2014 User1 22/10/2013 User1 28/03/2014 ``` whereas I want it to pick ``` Col A (1) Col U (21) User1 28/03/2014 ```
2014/05/29
[ "https://Stackoverflow.com/questions/23943895", "https://Stackoverflow.com", "https://Stackoverflow.com/users/436493/" ]
VLookup is designed to look for a single match for a specific value (either using an exact or approximate comparison). It doesn't check for any other matching values. I can think of 2 options which might help: * If you can sort the data, sort Column U in descending order. The most recent date will then be returned as the first match. * If you can't sort the data, you could consider using the [DMax](http://office.microsoft.com/en-us/excel-help/dmax-HP005209061.aspx) function. This allows you to specify criteria and then return the maximum value for a specific field. It does require you to put the criteria in a table format rather than specifying directly within the formula, so it's not ideal in all situations. Here's an example showing DMAX: Formula: `=DMAX(B3:C7,"Date",E3:E4)` This assumes that your table of data is in range B3:B7, you want to find the maximum value in a field called "Date" and your criteria is in range E3:E4 (where E3 contains the field name you are filtering on, and E4 contains the value you are looking for). One of the benefits of DMax is that you can use multiple sets of criteria.
``` =Max(if(sheet2$A:$A=sheet1A1,Sheet2$B:$B)) ``` Where `sheet2` is data sheet and `sheet1` is where you want to do lookup. End formula with `ctrl` + `shift` + `enter`.
15,250,942
I need to animate a relative-positioned div, where the animation goes from `display:none;` to `display:block;`. I need to "scale" it, starting from the bottom-right corner towards the top-left corner. Are there any ways of doing this? (Preferably in jQuery, but anything that works is good)
2013/03/06
[ "https://Stackoverflow.com/questions/15250942", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2140478/" ]
I am not sure that you want to fade in or change the size of the element. It sounds like you want need to bring it out of hiding. Since HTML layout is all done from the top and the left, getting something to animate from the bottom right to the top left is tricky to say the least. By carefully combining `slideUp` and `slideDown` with position fixed or absolute, [you can get an element to show from the bottom up.](http://www.bennadel.com/blog/1827-Using-jQuery-s-SlideUp-and-SlideDown-Methods-With-Bottom-Positioned-Elements.htm) But I have not heard of a way to slide right to left without using some [very advanced jQuery with bleeding edge includes.](https://stackoverflow.com/questions/521291/jquery-slide-left-and-show) So I offer this solution: Since the div you are trying to show is positioned relative you probably have some kind of wrapper, or an easily place one. With a wrapper in place you can set it's `overflow` rules to hidden and then place the 'hiding' div out side of its bounds. [Now with a simple jQuery animate](http://jsfiddle.net/q8w9d/2/) you can bring 'show' it by re-positioning it inside the bounds of the wrapper Here is an example: HTML: ``` <div class='wrapper'> <div class='growIt'>Text for div</div> </div> <input type='button' id='showHide' value='Show / Hide'/> ``` CSS: ``` .wrapper{ background:blue; position:relative; width:200px; height:200px; overflow:hidden; } .growIt{ background: red; position:relative; width:200px; height:200px; top:200px; left:200px; display:block; } ``` jQuery: ``` $(function(){ var hiding = true; $('#showHide').click(function(){ if(hiding == true){ hiding = false; $('.growIt').animate({top:'0px',left:'0px'},2000); }else{ hiding = true; $('.growIt').animate({top:'200px',left:'200px'},2000); } }); }); ``` When you click the button it will either hide or show the red div. If your requirement of animating it from `display:none` to `display:block` is because you need it to push other form elements out of the way when it comes into view, [I would suggest adding another wrapper with `position:relative` and then making the wrapper slide 'down' from the bottom.](http://jsfiddle.net/KftqU/2/)
Is this what you are looking for? <http://jqueryui.com/resizable/> <http://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_eff_animate> <http://jqueryui.com/effect/>
60,322,576
Hello guys i have json data from firestore and i want to display these data in html table. This is my customer-list.component.html ``` <body> <div class="container"> <div class="title"> <h3>Customer Table</h3> </div> <div class="row"> <div class="col-md-12"> </div> <div class="col-lg-8 col-md-10 ml-auto mr-auto"> <div class="table-responsive"> <table class="table"> <thead> <tr> <th class="text-center">#</th> <th>Name</th> <th>Age</th> <th>Active</th> </tr> </thead> <tbody> <div *ngFor="let customer of customers" style="width: 300px;"> <app-customer-details [customer]='customer'></app-customer-details> </div> <div style="margin-top:20px;"> <button type="button" class="button btn-danger" (click)='deleteCustomers()'>Delete All</button> </div> </tbody> </table> </div> </div> ``` Seems like there is nothing wrong in there. This is my customer-details.component.html ``` <div *ngIf="customer"> <tr> <td> <label>First Name: </label> {{customer.name}} </td> <td> <label>Age: </label> {{customer.age}} </td> <td> <label>Active: </label> {{customer.active}} </td> <span class="button is-small btn-primary" *ngIf='customer.active' (click)='updateActive(false)'>Inactive</span> <span class="button is-small btn-primary" *ngIf='!customer.active' (click)='updateActive(true)'>Active</span> <span class="button is-small btn-danger" (click)='deleteCustomer()'>Delete</span> </tr> </div> ``` But my table output is : [![table](https://i.stack.imgur.com/AlMO4.jpg)](https://i.stack.imgur.com/AlMO4.jpg) Thanks for answers.
2020/02/20
[ "https://Stackoverflow.com/questions/60322576", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7244857/" ]
When you look at the DOM tree you will find out that `<tr><app-customer-details>...</app-customer-details</td>` This will not result in the component rendering inside the table as a but will cram the entire component HTML template inside one column. By adding an attribute selector to the component i.e. selector: 'app-customer-details, [app-customer-details]', you can add the selector directly to the element like so and now the elements inside the component HTML template will render correctly inside the table. Look at this [link](https://stackoverflow.com/questions/51972286/child-component-loses-parent-table-formatting); The correct code is as follows: Customer-list.component.html ``` <div class="container"> <div class="title"> <h3>Customer Table</h3> </div> <div class="row"> <div class="col-md-12"> </div> <div class="col-lg-8 col-md-10 ml-auto mr-auto"> <div class="table-responsive"> <table class="table"> <thead> <tr> <!-- <th class="text-center">#</th> --> <th>Name</th> <th>Age</th> <th>Active</th> </tr> </thead> <tbody> <tr *ngFor="let customer of customers" [customerDetails]="customer"> </tr> <div style="margin-top:20px;"> <button type="button" class="button btn-danger" (click)='deleteCustomers()'>Delete All</button> </div> </tbody> </table> </div> </div> </div> </div> ``` Customer-details.component.html ``` <td> {{customerDetails.name}} </td> <td> {{customerDetails.age}} </td> <td> {{customerDetails.active}} </td> ``` Customer-details.component.ts ``` import { Component, OnInit, Input } from '@angular/core'; @Component({ selector: 'customerDetails, [customerDetails]', templateUrl: './customer-details.component.html', styleUrls: ['./customer-details.component.css'] }) export class CustomerDetailsComponent implements OnInit { @Input() customerDetails: object = {}; constructor() { } ngOnInit() { } } ```
Don´t limit the width of a customer´s component to 300px, like you did here: ``` <div *ngFor="let customer of customers" style="width: 300px;"> ```
60,322,576
Hello guys i have json data from firestore and i want to display these data in html table. This is my customer-list.component.html ``` <body> <div class="container"> <div class="title"> <h3>Customer Table</h3> </div> <div class="row"> <div class="col-md-12"> </div> <div class="col-lg-8 col-md-10 ml-auto mr-auto"> <div class="table-responsive"> <table class="table"> <thead> <tr> <th class="text-center">#</th> <th>Name</th> <th>Age</th> <th>Active</th> </tr> </thead> <tbody> <div *ngFor="let customer of customers" style="width: 300px;"> <app-customer-details [customer]='customer'></app-customer-details> </div> <div style="margin-top:20px;"> <button type="button" class="button btn-danger" (click)='deleteCustomers()'>Delete All</button> </div> </tbody> </table> </div> </div> ``` Seems like there is nothing wrong in there. This is my customer-details.component.html ``` <div *ngIf="customer"> <tr> <td> <label>First Name: </label> {{customer.name}} </td> <td> <label>Age: </label> {{customer.age}} </td> <td> <label>Active: </label> {{customer.active}} </td> <span class="button is-small btn-primary" *ngIf='customer.active' (click)='updateActive(false)'>Inactive</span> <span class="button is-small btn-primary" *ngIf='!customer.active' (click)='updateActive(true)'>Active</span> <span class="button is-small btn-danger" (click)='deleteCustomer()'>Delete</span> </tr> </div> ``` But my table output is : [![table](https://i.stack.imgur.com/AlMO4.jpg)](https://i.stack.imgur.com/AlMO4.jpg) Thanks for answers.
2020/02/20
[ "https://Stackoverflow.com/questions/60322576", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7244857/" ]
When you look at the DOM tree you will find out that `<tr><app-customer-details>...</app-customer-details</td>` This will not result in the component rendering inside the table as a but will cram the entire component HTML template inside one column. By adding an attribute selector to the component i.e. selector: 'app-customer-details, [app-customer-details]', you can add the selector directly to the element like so and now the elements inside the component HTML template will render correctly inside the table. Look at this [link](https://stackoverflow.com/questions/51972286/child-component-loses-parent-table-formatting); The correct code is as follows: Customer-list.component.html ``` <div class="container"> <div class="title"> <h3>Customer Table</h3> </div> <div class="row"> <div class="col-md-12"> </div> <div class="col-lg-8 col-md-10 ml-auto mr-auto"> <div class="table-responsive"> <table class="table"> <thead> <tr> <!-- <th class="text-center">#</th> --> <th>Name</th> <th>Age</th> <th>Active</th> </tr> </thead> <tbody> <tr *ngFor="let customer of customers" [customerDetails]="customer"> </tr> <div style="margin-top:20px;"> <button type="button" class="button btn-danger" (click)='deleteCustomers()'>Delete All</button> </div> </tbody> </table> </div> </div> </div> </div> ``` Customer-details.component.html ``` <td> {{customerDetails.name}} </td> <td> {{customerDetails.age}} </td> <td> {{customerDetails.active}} </td> ``` Customer-details.component.ts ``` import { Component, OnInit, Input } from '@angular/core'; @Component({ selector: 'customerDetails, [customerDetails]', templateUrl: './customer-details.component.html', styleUrls: ['./customer-details.component.css'] }) export class CustomerDetailsComponent implements OnInit { @Input() customerDetails: object = {}; constructor() { } ngOnInit() { } } ```
You have many things which will not render your table properly: ``` <tbody> <div *ngFor="let customer of customers" style="width: 300px;"> <app-customer-details [customer]='customer'> </app-customer-details> </div> .... </tbody> ``` This will render like this: ``` <tbody> <div ...> <app-customer-details> <div> <tr>.....</tr></div> </app-customer-details> </div> .... </tbody> ``` Which is not correct HTML. Change you detail component to use `ng-template`: ``` <ng-template > <tr *ngIf="customer"> <td><label>First Name: </label> {{customer.name}}</td> <td><label>Age: </label> {{customer.age}}</td> <td><label>Active: </label> {{customer.active}}</td> <td> Note: All spans should also be inside a TD tag </td> </tr> </ng-template> ```
27,266,402
How to get color picker in IE11 I am getting just text box in ie11 when I type ``` <input type="color" name="clr1" value=""/> ``` The above code is working fine in chrome but in IE it is shwoing just textbox.
2014/12/03
[ "https://Stackoverflow.com/questions/27266402", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4307008/" ]
Try this: ``` <![if !IE]> <input type="color" name="clr1" value=""/> <![endif]> <!--[if IE]> <input type="text" name="clr1" value="" style="display:none"/> <button onclick="var s = Dlg.ChooseColorDlg(clr1.value); window.event.srcElement.style.color = s; clr1.value = s">&#9608;&#9608;&#9608;&#9608;&#9608;</button> <object id="Dlg" classid="CLSID:3050F819-98B5-11CF-BB82-00AA00BDCE0B" width="0" height="0"></object> <![endif]--> ```
You can try Native Color Picker Polyfill for the HTML5's "color" input type on Internet Explorer. See : [nativeColorPicker](https://github.com/dciccale/nativeColorPicker) **HTML Code** ``` <!doctype html> <title>Demo - Native Color Picker</title> <style>body{font-family:verdana;background-color:#ebebeb;padding:30px}h1{font-family:'Trebuchet MS';font-weight:700;font-size:30px;margin-bottom:20px}#content{background-color:#fff;border:3px solid #ccc;padding:20px}p{margin:20px 0}input{position:relative;top:10px}label{cursor:pointer;font-size:14px}</style> <h1>Native Color Picker</h1> <div id="content"> <p> <label>Choose a color: <input type="color" id="color"></label> <button id="btn_color">get value</button> </p> <p> <label>Choose another color: <input type="color" id="color2"></label> <button id="btn_color2">get value</button> </p> </div> <!-- fork me on Github --> <a href="http://github.com/dciccale/nativeColorPicker"><img style="position: absolute; top: 0; right: 0; border: 0" src="http://s3.amazonaws.com/github/ribbons/forkme_right_darkblue_121621.png" alt="Fork me on GitHub"></a> <!-- include the plugin --> <script src="nativeColorPicker.js"></script> <script> (function () { // init the plugin window.nativeColorPicker.init('color'); window.nativeColorPicker.init('color2'); // demo buttons.. move along var $=function(id){return document.getElementById(id)},alertColor=function(){alert($(this.id.split('_')[1]).value);}; $('btn_color').onclick = alertColor; $('btn_color2').onclick = alertColor; }()); </script> ``` \*\* Javascript code \*\* ``` (function (window) { var document = window.document, nativeColorPicker = { // initialized flag started: false, // start color color: '#000000', // inputs where plugin was initialized inputs: {}, // flag to know if color input is supported hasNativeColorSupport: false, // inits the plugin on specified input init: function (inputId) { // start the plugin this.start(); if (this.hasNativeColorSupport) { return; } if (typeof inputId !== 'string') { throw 'inputId have to be a string id selector'; } // set the input this.input = (this.inputs[inputId] = this.inputs[inputId]) || document.getElementById(inputId); if (!this.input) { throw 'There was no input found with id: "' + inputId + '"'; } // input defaults this.input.value = this.color; this.input.unselectable = 'on'; this.css(this.input, { backgroundColor: this.color, borderWidth: '0.4em 0.3em', width: '3em', cursor: 'default' }); // register input event this.input.onfocus = function () { nativeColorPicker.onFocus(this.id); }; }, // initialize once start: function () { // is already started if (this.started) { return; } // test if browser has native support for color input try { this.hasNativeColorSupport = !!(document.createElement('input').type = 'color'); } catch (e) {}; // no native support... if (!this.hasNativeColorSupport) { // create object element var object_element = document.createElement('object'); object_element.classid = 'clsid:3050f819-98b5-11cf-bb82-00aa00bdce0b'; // set attributes object_element.id = 'colorHelperObj'; this.css(object_element, { width: '0', height: '0' }); document.body.appendChild(object_element); } // mark as started this.started = true; }, // destroys the plugin destroy: function (inputId) { var i; // destroy one input or all the plugin if no input id if (typeof inputId === 'string') { this.off(this.inputs[inputId]); } else { // remove helper object document.body.removeChild(document.getElementById('colorHelperObj')); // remove input events and styles for (i in this.inputs) { this.off(this.inputs[i]); } // mark not started this.started = false; } }, off: function (input) { input.onfocus = null; this.css(input, { backgroundColor: '', borderWidth: '', width: '', cursor: '' }); }, // input focus function onFocus: function (inputId) { this.input = this.inputs[inputId]; this.color = this.getColor(); this.input.value = this.color; nativeColorPicker.css(this.input, { backgroundColor: this.color, color: this.color }); this.input.blur(); }, // gets the color from the object // and normalize it getColor: function () { // get decimal color, (passing the previous one) // and change to hex var hex = colorHelperObj.ChooseColorDlg(this.color.replace(/#/, '')).toString(16); // add extra zeroes if hex number is less than 6 digits if (hex.length < 6) { var tmpstr = '000000'.substring(0, 6 - hex.length); hex = tmpstr.concat(hex); } return '#' + hex; }, // set css properties css: function (el, props) { for (var prop in props) { el.style[prop] = props[prop]; } } }; // expose to global window.nativeColorPicker = nativeColorPicker; }(window)); ``` Demo : [denis.io](http://denis.io/nativeColorPicker/)
27,266,402
How to get color picker in IE11 I am getting just text box in ie11 when I type ``` <input type="color" name="clr1" value=""/> ``` The above code is working fine in chrome but in IE it is shwoing just textbox.
2014/12/03
[ "https://Stackoverflow.com/questions/27266402", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4307008/" ]
Try this: ``` <![if !IE]> <input type="color" name="clr1" value=""/> <![endif]> <!--[if IE]> <input type="text" name="clr1" value="" style="display:none"/> <button onclick="var s = Dlg.ChooseColorDlg(clr1.value); window.event.srcElement.style.color = s; clr1.value = s">&#9608;&#9608;&#9608;&#9608;&#9608;</button> <object id="Dlg" classid="CLSID:3050F819-98B5-11CF-BB82-00AA00BDCE0B" width="0" height="0"></object> <![endif]--> ```
Try this : **HTML :** ```html <!--Colorpicker --> <input class="paletacolor" type="text" id="paletacolor" value="#f1040f"/> <!--about Colorpicker js --> <script src="jquery-3.4.1.slim.min.js"></script> <script src="jquery.drawrpalette-min.js" defer></script> <script> $(function(){ $("#paletacolor").drawrpalette() }); </script> ``` **jquery.drawrpalette-min.js and jquery.drawrpalette-min.js** FILES : <https://drive.google.com/drive/folders/1pcfPEVmgz6UG8M1mAI8blFyPAsvKBzgi?usp=sharing> Demo : <https://qvgukvb6oklnucssvrtcvq-on.drv.tw/public/colorpicker/> Source : <https://www.jqueryscript.net>
55,687,688
i have table Collection: ``` id orderId productId 1 201 1 2 202 2 3 205 3 4 206 1 5 207 1 6 208 1 7 311 2 ``` OrderId and ProductId is relations to Collection table. And I need to check if exist record where eg. productId = 1 AND orderId[205, 206, 207, 208]. How i should built my query to find what i want? The array of orderId is not static, it's dynamic and depends of situation, can have diffrent number of elements. I tried to make it like this: ``` $ordersCollection = [various id objects of orders ]; $productId = just productId createQueryBuilder('p') ->andWhere('p.product = :productId') ->andWhere('p.order in :ordersCollection') ->setParameters(['productId' => $productId, 'ordersCollection' => $ordersCollection]) ->getQuery() ->getResult(); ``` But it doesn't work
2019/04/15
[ "https://Stackoverflow.com/questions/55687688", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10925079/" ]
Couple of things - don't use `forEach()`, and use `map()` in your `myFunction`: ```js myDiv = Array.from(document.getElementsByClassName('myDiv')); function myFunction(){ const number = myDiv.map(d => d.dataset["number"]); console.log(number); } ``` ```html <div class="myDiv" data-name="MrMr" data-number="1"> THIS IS A TEXT </div> <div class="myDiv" data-number="2"> another text. </div> <div class="myDiv" data-number="3"> another text. </div> <div class="myDiv" data-number="4"> another text. </div> <p id="demo"></p> <button onclick="myFunction();">Button</button> ```
Why not something like so: ```js var myFancyButton = document.querySelector('.myFancyButton'); // get the button via querySelector("className") myFancyButton.addEventListener('click', function() { // add a click event listener to the button var myDivs = document.querySelectorAll('.myDiv'); // query for alle elements with a class name = "myDiv" myDivs.forEach(function(myDiv) { // now use forEach on all those divs const number = myDiv.dataset["number"]; console.log(number); }); }); ``` ```html <div class="myDiv" data-name="MrMr" data-number="1"> THIS IS A TEXT </div> <div class="myDiv" data-number="2"> another text. </div> <div class="myDiv" data-number="3"> another text. </div> <div class="myDiv" data-number="4"> another text. </div> <p id="demo"></p> <button class="myFancyButton">Button</button> ```
55,687,688
i have table Collection: ``` id orderId productId 1 201 1 2 202 2 3 205 3 4 206 1 5 207 1 6 208 1 7 311 2 ``` OrderId and ProductId is relations to Collection table. And I need to check if exist record where eg. productId = 1 AND orderId[205, 206, 207, 208]. How i should built my query to find what i want? The array of orderId is not static, it's dynamic and depends of situation, can have diffrent number of elements. I tried to make it like this: ``` $ordersCollection = [various id objects of orders ]; $productId = just productId createQueryBuilder('p') ->andWhere('p.product = :productId') ->andWhere('p.order in :ordersCollection') ->setParameters(['productId' => $productId, 'ordersCollection' => $ordersCollection]) ->getQuery() ->getResult(); ``` But it doesn't work
2019/04/15
[ "https://Stackoverflow.com/questions/55687688", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10925079/" ]
Couple of things - don't use `forEach()`, and use `map()` in your `myFunction`: ```js myDiv = Array.from(document.getElementsByClassName('myDiv')); function myFunction(){ const number = myDiv.map(d => d.dataset["number"]); console.log(number); } ``` ```html <div class="myDiv" data-name="MrMr" data-number="1"> THIS IS A TEXT </div> <div class="myDiv" data-number="2"> another text. </div> <div class="myDiv" data-number="3"> another text. </div> <div class="myDiv" data-number="4"> another text. </div> <p id="demo"></p> <button onclick="myFunction();">Button</button> ```
First - the function you want array.forEach() to execute needs an element to process. In your case these are the individual DIV elements. So you're function needs a parameter that 'links' to that particular element. This can be done like: ``` function myFunction(element); ``` The attribute you want to query is called **data-number**, so I'd recommend using it. If you want to get a specific property of a DOM element, you can use `element.getAttribute(attribute);` Here's a complete example: ```js myDiv = Array.from(document.getElementsByClassName('myDiv')); function myFunction(element) { var theNumber = element.getAttribute("data-number"); console.log(theNumber); } myDiv.forEach(myFunction); ``` ```html <div class="myDiv" data-name="MrMr" data-number="1"> THIS IS A TEXT </div> <div class="myDiv" data-number="2"> another text. </div> <div class="myDiv" data-number="3"> another text. </div> <div class="myDiv" data-number="4"> another text. </div> ```
44,710,509
In order to configure spring batch admin UI to use db2 database, I referred the Admin UI documentation which says **"launch the application with a system property -DENVIRONMENT=[type]."** I understand that **"-DENVIRONMENT=db2**" should be kept in some file. I tried by keeping in **batch-default.properties** file, but that did not work. Since I am using WLP(liberty server), tried by keeping in server.xml file, no help. Still in the console I see env-context.xml file from batch admin is still loading batch-hsql.properties file(default configuration).
2017/06/22
[ "https://Stackoverflow.com/questions/44710509", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5964695/" ]
I finally found a fix. I used 'qs' to stringify 'options' with {arrayFormat : 'brackets'} and then concatinated to url ended with '?' as follows: ``` var request = require('request'); var qs1 = require('qs'); var getLibs = function() { var options = qs1.stringify({ packages: ['example1', 'example2', 'example3'], os: 'linux', pack_type: 'npm' },{ arrayFormat : 'brackets' }); request({url:'http://localhost:3000/package?' + options}, function (error , response, body) { if (! error && response.statusCode == 200) { console.log(body); } else if (error) { console.log(error); } else{ console.log(response.statusCode); } }); }(); ``` Note: I tried to avoid concatenation to url, but all responses had code 400
If the array need to be received as it is, you can set `useQuerystring` as `true`: UPDATE: `list` key in the following code example has been changed to `'list[]'`, so that OP's ruby backend can successfully parse the array. Here is example code: ``` const request = require('request'); let data = { 'name': 'John', 'list[]': ['XXX', 'YYY', 'ZZZ'] }; request({ url: 'https://requestb.in/1fg1v0i1', qs: data, useQuerystring: true }, function(err, res, body) { // ... }); ``` In this way, when the HTTP `GET` request is sent, the query parameters would be: ``` ?name=John&list[]=XXX&list[]=YYY&list[]=ZZZ ``` and the `list` field would be parsed as `['XXX', 'YYY', 'ZZZ']` --- Without `useQuerystring` (default value as `false`), the query parameters would be: ``` ?name=John&list[][0]=XXX&list[][1]=YYY&list[][2]=ZZZ ```
44,710,509
In order to configure spring batch admin UI to use db2 database, I referred the Admin UI documentation which says **"launch the application with a system property -DENVIRONMENT=[type]."** I understand that **"-DENVIRONMENT=db2**" should be kept in some file. I tried by keeping in **batch-default.properties** file, but that did not work. Since I am using WLP(liberty server), tried by keeping in server.xml file, no help. Still in the console I see env-context.xml file from batch admin is still loading batch-hsql.properties file(default configuration).
2017/06/22
[ "https://Stackoverflow.com/questions/44710509", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5964695/" ]
If the array need to be received as it is, you can set `useQuerystring` as `true`: UPDATE: `list` key in the following code example has been changed to `'list[]'`, so that OP's ruby backend can successfully parse the array. Here is example code: ``` const request = require('request'); let data = { 'name': 'John', 'list[]': ['XXX', 'YYY', 'ZZZ'] }; request({ url: 'https://requestb.in/1fg1v0i1', qs: data, useQuerystring: true }, function(err, res, body) { // ... }); ``` In this way, when the HTTP `GET` request is sent, the query parameters would be: ``` ?name=John&list[]=XXX&list[]=YYY&list[]=ZZZ ``` and the `list` field would be parsed as `['XXX', 'YYY', 'ZZZ']` --- Without `useQuerystring` (default value as `false`), the query parameters would be: ``` ?name=John&list[][0]=XXX&list[][1]=YYY&list[][2]=ZZZ ```
This problem can be solved using Request library itself. Request internally uses qs.stringify. You can pass q option to request which it will use to parse array params. You don't need to append to url which leaves reader in question why that would have been done. Reference: <https://github.com/request/request#requestoptions-callback> > > > ``` > const options = { > method: 'GET', > uri: 'http://localhost:3000/package', > qs: { > packages: ['example1', 'example2', 'example3'], > os: 'linux', > pack_type: 'npm' > }, > qsStringifyOptions: { > arrayFormat: 'repeat' // You could use one of indices|brackets|repeat > }, > json: true > }; > > ``` > >
44,710,509
In order to configure spring batch admin UI to use db2 database, I referred the Admin UI documentation which says **"launch the application with a system property -DENVIRONMENT=[type]."** I understand that **"-DENVIRONMENT=db2**" should be kept in some file. I tried by keeping in **batch-default.properties** file, but that did not work. Since I am using WLP(liberty server), tried by keeping in server.xml file, no help. Still in the console I see env-context.xml file from batch admin is still loading batch-hsql.properties file(default configuration).
2017/06/22
[ "https://Stackoverflow.com/questions/44710509", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5964695/" ]
I finally found a fix. I used 'qs' to stringify 'options' with {arrayFormat : 'brackets'} and then concatinated to url ended with '?' as follows: ``` var request = require('request'); var qs1 = require('qs'); var getLibs = function() { var options = qs1.stringify({ packages: ['example1', 'example2', 'example3'], os: 'linux', pack_type: 'npm' },{ arrayFormat : 'brackets' }); request({url:'http://localhost:3000/package?' + options}, function (error , response, body) { if (! error && response.statusCode == 200) { console.log(body); } else if (error) { console.log(error); } else{ console.log(response.statusCode); } }); }(); ``` Note: I tried to avoid concatenation to url, but all responses had code 400
This problem can be solved using Request library itself. Request internally uses qs.stringify. You can pass q option to request which it will use to parse array params. You don't need to append to url which leaves reader in question why that would have been done. Reference: <https://github.com/request/request#requestoptions-callback> > > > ``` > const options = { > method: 'GET', > uri: 'http://localhost:3000/package', > qs: { > packages: ['example1', 'example2', 'example3'], > os: 'linux', > pack_type: 'npm' > }, > qsStringifyOptions: { > arrayFormat: 'repeat' // You could use one of indices|brackets|repeat > }, > json: true > }; > > ``` > >
26,501,936
To expire a timer in 5 seconds, is there any practical difference between these two? Is any one preferable(performance, resource, etc.) to the other for this case? [Option 1] **`deadline_timer`**: ``` boost::asio::deadline_timer timer(io_service); timer.expires_from_now(boost::posix_time::seconds(5)); ``` [Option 2] **`waitable_timer`**(`system_timer` or `steady_timer`): ``` boost::asio::system_timer timer(io_service); timer.expires_from_now(std::chrono::seconds(5)); ``` *PS: Please concentrate on comparing `deadline_timer` vs. `system_timer`, rather than `system_timer` vs. `steady_timer`.*
2014/10/22
[ "https://Stackoverflow.com/questions/26501936", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3687475/" ]
The only difference is between clock types used. As of Boost 1.56, both `basic_deadline_timer` and `basic_waitable_timer` use `detail::deadline_timer_service` inside. There's no difference in how it performs waiting, the only difference is in how it performs time calculation. In its `wait()` method it uses `Time_Traits::now()` to check if it needs to wait more. For `system_timer` it's `std::chrono::system_clock::now()`, and for `deadline_timer` it's `boost::posix_time::microsec_clock::universal_time()` or `boost::posix_time::second_clock::universal_time()` depending on the presence of high precision clock (see [time\_traits.hpp](http://www.boost.org/doc/libs/1_56_0/boost/asio/time_traits.hpp)). `std::chrono::system_clock` implementation is provided by a compiler/standard library vendor, whereas `boost::posix_time::*clock` is implemented by Boost using available system functions. These implementations of course may have different performance and/or precision depending on the platform and the compiler.
There is excellent responce to similar problem here: <https://stackoverflow.com/a/16364002/3491378> Basically, the main difference is that if you expect any external changes to the system clock, you should rather use steady\_timer - deadline\_timer delay will be affected by those changes
28,732,250
I don't want to use smart pointers. Her'es my code. ``` CCOLFile *pCOLFile = CCOLManager::getInstance()->parseFile(strCOLPath); // returns instance of CCOLFile // ... pCOLFile->unload(); // hoping to comment this out, and use destructor instead. delete pCOLFile; struct CCOLFile { std::string m_strFilePath; std::vector<CCOLEntry*> m_vecEntries; }; void CCOLFile::unload(void) { for (auto pCOLEntry : m_vecEntries) { delete pCOLEntry; } m_vecEntries.clear(); } ``` Is it safe in c++ to comment my call to CCOLFile::unload, and then move the code from the CCOLFile::unload method to the CCOLFile destructor?
2015/02/26
[ "https://Stackoverflow.com/questions/28732250", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4539315/" ]
Yes - see [C++ Super-FAQ section on Destructors](http://isocpp.org/wiki/faq/dtors). However if you do move that code to the dtor, or have the dtor call unload(), you need to make sure your 'delete pCOLEntry' doesn't throw exceptions. Reason: if it did, and if your CCOLFile dtor got called because of stack-unwinding, you will end up with an exception within an exception; bang; do not do that. Another problem if 'delete pCOLEntry' can throw an exception: your unload() method will end up with gobbledegook in your CCOLFile object. In particular, only some of the pCOLEntry pointers will have been deleted and they will now point to the carcass of what was once a CCOLEntry object but is now just a ghost. I called that a "Ghost Pointer" in the C++ FAQ. It's a bad thing since you will perhaps in the future use that Ghost Pointer, then you'll end up with a "Wild Pointer." Badness ensues. Lots of other issues with your code: since you have avoided using a smart-pointer (why?) you really ought to wrap your usage in a try/catch block, or at least put BIG FAT UGLY COMMENTS in your code to make sure no one ever does anything that might throw an exception. Basically if anything throws an exception before control-flow reaches your unload() or 'delete' call, all the CCOLEntry objects will leak and perhaps more significantly any desirable side effects in their dtor will not happen - closing files, unlocking locks, whatever. Note: I'm not asking you whether your code can CURRENTLY throw an exception in that area - that is only a small part of the concern. The concern is not just the present but the future. Someone else (likely at 3am) will add some code somewhere in there and that code will be able to throw an exception. Smart pointers make that innocuous, or a BIG FAT UGLY COMMENT at least makes it slightly less likely. Another consideration: you need to be concerned with 'ownership' and the copy-constructor and assignment-operator. The [Rule of Three (which I coined in 1991, but which has been more recently been replaced by the Rule of Five or even better the Rule of Zero)](http://en.wikipedia.org/wiki/Rule_of_three_(C%2B%2B_programming)) tells you you will need all of them if you explicitly define one of them, in this case the dtor. Here again a smart-pointer would likely help. Another thing: your use of (void), e.g., in the definition of CCOLFile::unload(void)) is considered by at least some as an abomination :-) :-) :-)
Yes === The whole point of the destructor is to allow you to clean up your object before its memory is freed. So all members are accessible just as they would be in a normal method. Just be wary not to throw an exception from the destructor, and be careful about getting the memory semantics (copy constructors, assignment, etc.) right in all cases so that nothing is leaked or double-freed.
31,239,897
How can I get the total number of table elements having ID inside a DIV tag using Selenium Webdriver and C#? Expected Output: I need output as "Number of Table ID = 2 " ``` <form id="form1"> <div class="sec_container_pop"> <div class="sec_header_pop"> Item Details </div> <table class="subheader"> <div class="spacerdiv"/> <div style="width: 900px; height: 400px; overflow-x: auto; position: relative; overflow-y: auto;"> <table class="reportscontent_pop" style="width: 880px"> <table id="tItemDetails0" class="reportscontent_pop" style="width: 880px; display: none;"> <table class="reportscontent_pop" style="width: 880px"> <table id="tItemDetails1" class="reportscontent_pop" style="width: 880px; display: none;"> </div> </form> ```
2015/07/06
[ "https://Stackoverflow.com/questions/31239897", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4985758/" ]
Try like this: ``` WebElement webElement = driver.findElement(By.xpath("//form[@id='form1']/div[4]")); //Get list of table elements using tagName List<WebElement> list = webElement.findElements(By.tagName("table")); ```
XPath: ``` IList<IWebElement> tableIDs = driver.FindElements(By.XPath("//div/table[@id]")); Console.WriteLine("Number of Table ID = {0}", tableIDs.Count); ``` Css: ``` IList<IWebElement> tableIDs = driver.FindElement(By.CssSelector("div>table[id]")); Console.WriteLine("Number of Table ID = {0}", tableIDs.Count); ```
8,506,986
i am using this ``` SELECT TOP (100) PERCENT CONVERT(char(10), [Reg Date1], 103) AS [Reg Date], Regs FROM (SELECT CAST(SetupDateTime AS datetime) AS [Reg Date1], COUNT(DISTINCT ID) AS Regs FROM dbo.tbl_User WHERE (CAST(SetupDateTime AS datetime) BETWEEN CAST(DATEADD(dd, - 7, GETDATE()) AS datetime) AND CAST(DATEADD(dd, - 1, GETDATE()) AS datetime)) GROUP BY CAST(SetupDateTime AS datetime)) AS a ORDER BY [Reg Date1] ``` which then produces ``` Reg Date Regs 07/12/2011 1 07/12/2011 1 07/12/2011 1 08/12/2011 1 08/12/2011 1 09/12/2011 1 09/12/2011 1 10/12/2011 1 10/12/2011 1 10/12/2011 1 ``` but i want it to do ``` Reg Date Regs 07/12/2011 10 08/12/2011 12 09/12/2011 15 10/12/2011 11 11/12/2011 10 12/12/2011 17 ``` i cant seem to get it to group in this way
2011/12/14
[ "https://Stackoverflow.com/questions/8506986", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1097453/" ]
Try this: ``` SELECT TOP (100) PERCENT CONVERT(char(10), [Reg Date1], 103) AS [Reg Date], Sum(Regs) FROM (SELECT CAST(SetupDateTime AS datetime) AS [Reg Date1], COUNT(DISTINCT ID) AS Regs FROM dbo.tbl_User WHERE (CAST(SetupDateTime AS datetime) BETWEEN CAST(DATEADD(dd, - 7, CAST(convert(varchar, GETDATE(), 112) AS datetime)) AS datetime) AND CAST(convert(varchar, GETDATE(), 112) AS datetime)) GROUP BY CAST(SetupDateTime AS datetime)) AS a group by CONVERT(char(10), [Reg Date1], 103) ORDER BY CONVERT(char(10), [Reg Date1], 103) ```
Try this: `SELECT TOP (100) PERCENT CONVERT(char(10), [Reg Date1], 103) AS [Reg Date], COUNT(Regs)` Note the use of `COUNT` which is I suspect what you are trying to do.
13,244
I know the $|1\rangle$ state can relax spontaneously to the $|0\rangle$ state, but can the opposite also happen?
2020/08/10
[ "https://quantumcomputing.stackexchange.com/questions/13244", "https://quantumcomputing.stackexchange.com", "https://quantumcomputing.stackexchange.com/users/12906/" ]
As a first note: the (uncontrolled) transition of $|1\rangle$ to $|0\rangle$ is generally not referred to as *dephasing* but as *relaxation*. The noise-process that involves (spontaneous) relaxation is also called the *amplitude damping* channel. Now, if you have a system which has a finite temperature, meaning that there is some energy in the system, the reverse might spontaneously happen as well - the $|0\rangle$ state spontaneously transitions to the $|1\rangle$ state, something we call (spontaneous) *excitation*. So yeah, if there is any energy in the system (i.e. de facto **every** conceivable system), the reverse is also possible. If you're familiar with the math, you might want to check out the *generalized amplitude damping* channel, for instance as introduced [here](https://arxiv.org/abs/1902.00967). It formalizes the above idea that, in addition of a small relaxation probability, there is also a (small) probability of a spontaneous excitation.
[Spontaneous emission](https://en.wikipedia.org/wiki/Spontaneous_emission) from an excited state $|1\rangle$ to ground state $|0\rangle$ is a well known phenomenon, but spontaneous excitation is not discussed as often, although [there has been discussion about spontaneous excitation for accelerating qubits](https://arxiv.org/abs/gr-qc/9408019), along with its relation to the [Unruh effect](https://en.wikipedia.org/wiki/Unruh_effect) which comes up when relativity is considered. As JSdJ said in their answer, if the temperature is high, we can expect ground state systems to absorb photons or phonons or some form of energy which takes them from $|0\rangle$ to $|1\rangle$ without outside control of the situation (i.e. shining a laser on the system to force the excitation). In the absence of a laser, this excitation could be considered spontaneous excitation. Keep in mind also that Wolfgang Ketterle's group has observed [negative temperature](https://en.wikipedia.org/wiki/Negative_temperature) at his lab, which means the opposite is true: $|1\rangle$ is the preferred state and you would need to provide external energy to force the system to go from $|1\rangle$ to $|0\rangle$ except in the case of spontaneous emission, which at negative temperature would be the equivalent of spontaneous excitation.
13,244
I know the $|1\rangle$ state can relax spontaneously to the $|0\rangle$ state, but can the opposite also happen?
2020/08/10
[ "https://quantumcomputing.stackexchange.com/questions/13244", "https://quantumcomputing.stackexchange.com", "https://quantumcomputing.stackexchange.com/users/12906/" ]
As a first note: the (uncontrolled) transition of $|1\rangle$ to $|0\rangle$ is generally not referred to as *dephasing* but as *relaxation*. The noise-process that involves (spontaneous) relaxation is also called the *amplitude damping* channel. Now, if you have a system which has a finite temperature, meaning that there is some energy in the system, the reverse might spontaneously happen as well - the $|0\rangle$ state spontaneously transitions to the $|1\rangle$ state, something we call (spontaneous) *excitation*. So yeah, if there is any energy in the system (i.e. de facto **every** conceivable system), the reverse is also possible. If you're familiar with the math, you might want to check out the *generalized amplitude damping* channel, for instance as introduced [here](https://arxiv.org/abs/1902.00967). It formalizes the above idea that, in addition of a small relaxation probability, there is also a (small) probability of a spontaneous excitation.
I tried to prepare a two simple circuits on IBM Q (1 qubit Armonk processor). First one was composed only of $X$ gate. So, when the gate was applied on state $|0\rangle$, it changed to $|1\rangle$. As you can see from the figure below, after measurement there is non-zero probability that the qubit is in state $|0\rangle$. This is a spontaneous relaxation. [![relaxation](https://i.stack.imgur.com/CHdrh.png)](https://i.stack.imgur.com/CHdrh.png) When you replaced gate $X$ with $I$ (or there is no gate at all), the qubit remains in state $|0\rangle$. However, after measurement, there is also non-zero probability that the qubit is in state $|1\rangle$. This is a spontaneous excitation. [![excitation](https://i.stack.imgur.com/TTZqh.png)](https://i.stack.imgur.com/TTZqh.png) As you can see, the spontaneous excitation does not occur as often as the relaxation. *Note that these results can be also influenced by read-out errors and imperfect gates.*
38,503,229
Learning React & chrome extensions the hard way, so my `this.url` has one of 2 values: `null` or `www.sample.com` I'm getting the url value from an async call using `chrome.storage.local.get(...)` so once I get the response from the storage I set the value to this.url and want to use such value to display a component using a ternary operator like so: ``` export default React.createClass({ url: '', componentDidMount: function(){ this.observeResource(); }, observeResource(){ var self = this function getValue(callback){ chrome.storage.local.get('xxxx', callback); } getValue(function (url) { this.url = url.xxxx; return this.url; }); }, /* RENDER */ render: function(){ return ( <div className="app"> <AppHeader /> {this.url != null ? <VideoFoundOverlay /> : null} {this.url == null ? <VideoNotFoundOverlay /> : null } </div> ) } }); ``` I can not get the value of `this.url` outside of the `observeResource` function. Where am I going wrong?
2016/07/21
[ "https://Stackoverflow.com/questions/38503229", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4183602/" ]
You need to use [**this.setState()**](https://facebook.github.io/react/docs/component-api.html#setstate) ``` constructor(props) { super(props) this.state = { url: '' } } componentDidMount() { setTimeout(() => { this.setState({ url: 'www.sample.com' }) }, 1000) } render() { return <div>this.state.url</div> } ``` Look at working example in [JSFiddle](https://jsfiddle.net/SergeyBaranyuk/Lg6m8m6t/3/)
I would go by and do it like this: ``` export default React.createClass({ getInitialState: function(){ return { url: null } }, componentDidMount: function(){ this.observeResource(); }, observeResource(){ var self = this function getValue(callback){ chrome.storage.local.get('newswireStoryUrl', callback); } getValue(function (url) { //here you are seting the state of the react component using the 'self' object self.setState({url: url.newswireStoryUrl}) //not sure if the 'return this.url' is needed here. //here the 'this' object is not refering to the react component but //the window object. return this.url; }); }, videoNotFound: function(){ return ( <div className="app"> <AppHeader /> <VideoNotFoundOverlay /> </div ) }, /* RENDER */ render: function(){ if(this.state.url == null){ return this.videoNotFound() } return ( <div className="app"> <AppHeader /> <VideoFoundOverlay /> </div> ) } }); ```
38,503,229
Learning React & chrome extensions the hard way, so my `this.url` has one of 2 values: `null` or `www.sample.com` I'm getting the url value from an async call using `chrome.storage.local.get(...)` so once I get the response from the storage I set the value to this.url and want to use such value to display a component using a ternary operator like so: ``` export default React.createClass({ url: '', componentDidMount: function(){ this.observeResource(); }, observeResource(){ var self = this function getValue(callback){ chrome.storage.local.get('xxxx', callback); } getValue(function (url) { this.url = url.xxxx; return this.url; }); }, /* RENDER */ render: function(){ return ( <div className="app"> <AppHeader /> {this.url != null ? <VideoFoundOverlay /> : null} {this.url == null ? <VideoNotFoundOverlay /> : null } </div> ) } }); ``` I can not get the value of `this.url` outside of the `observeResource` function. Where am I going wrong?
2016/07/21
[ "https://Stackoverflow.com/questions/38503229", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4183602/" ]
1. The `this` inside the following call points to `window` rather than the component itself, since the callback is invocated as a function, the `window` is actually the "owner" of the function. ``` getValue(function (url) { this.url = url.newswireStoryUrl; return this.url; }); ``` To avoid this error, you could use `self.url` instead, since you have explicitly assign `this` to `self`. Or you could use [`Arrow Function`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions#Lexical_this) instead of `function(...)`. 2. To render the component, you should declare `url` as a state, because only state changes will cause the `render` function to be called. ``` export default React.createClass({ getInitialState: function() { return { url: '' }; }, componentDidMount: function(){ this.observeResource(); }, observeResource(){ var self = this; function getValue(callback){ chrome.storage.local.get('newswireStoryUrl', callback); } getValue(function (url) { self.setState({ url: url.newswireStoryUrl }); return self.state.url; }); }, /* RENDER */ render: function(){ return ( <div className="app"> <AppHeader /> {this.state.url !== null ? <VideoFoundOverlay /> : null} {this.state.url === null ? <VideoNotFoundOverlay /> : null } </div> ); } }); ```
I would go by and do it like this: ``` export default React.createClass({ getInitialState: function(){ return { url: null } }, componentDidMount: function(){ this.observeResource(); }, observeResource(){ var self = this function getValue(callback){ chrome.storage.local.get('newswireStoryUrl', callback); } getValue(function (url) { //here you are seting the state of the react component using the 'self' object self.setState({url: url.newswireStoryUrl}) //not sure if the 'return this.url' is needed here. //here the 'this' object is not refering to the react component but //the window object. return this.url; }); }, videoNotFound: function(){ return ( <div className="app"> <AppHeader /> <VideoNotFoundOverlay /> </div ) }, /* RENDER */ render: function(){ if(this.state.url == null){ return this.videoNotFound() } return ( <div className="app"> <AppHeader /> <VideoFoundOverlay /> </div> ) } }); ```
60,125,337
The ANTLR4 lexer pattern [\p{Emoji}]+ is matching numbers. See screenshot. Note that it correctly rejects alpha chars. Is there an issue with the pattern? [![enter image description here](https://i.stack.imgur.com/QkkX2.png)](https://i.stack.imgur.com/QkkX2.png)
2020/02/08
[ "https://Stackoverflow.com/questions/60125337", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9668824/" ]
`\p{Emoji}` matches everything that has the Unicode Emoji property. Numbers do have that property, so `\p{Emoji}` is correct in matching them. Why though? The Unicode standard defines any codepoint to have the Emoji property if it can appear as part of an Emoji. Numbers can appear as parts of emojis (for example I think shapes with numbers on them, which for them reason count as emojis, consist of a shape, followed by a join, followed by the number), so they have that property. If you only want to match codepoints that are emojis by themselves, you can just use the `Emoji_Presentation` property instead. This will fail to match combined emojis though. If you want to match any sequence that creates an emoji, I think you'll want to match something like "`Emoji_Presentation`, followed by zero or more of '(`Join_Control` or `Variation_Selector`) followed by `Emoji`'" (here you want `Emoji` instead of `Emoji_Presentation` because that's where numbers are allowed). --- However, for the purpose of allowing emojis in identifiers (as opposed to a lexer rule to match emojis and nothing else), you don't actually have to worry about whether a number is part of an emoji or not, just that it doesn't appear as the first character of the identifier. So you could simply define your fragment for the starting character to only include `Emoji_Presentation` and then the fragment for continuing characters to include `Emoji` as well as `Join_Control` and `Variation_Selector`. So something like this would work: ``` fragment IdStart : [_\p{Alpha}\p{General_Category=Other_Letter}\p{Emoji_Presentation}] ; fragment IdContinue : IdStart // The `\p{Number}` might be redundant, I'm not sure. I don't know // whether there are any (non-ascii) numeric codepoints that don't // also have the `Emoji` property. | [\p{Number}\p{Emoji}\p{Join_Control}\p{Variation_Selector}] ; Identifier: IdStart IdContinue*; ``` Of course that's assuming you actually want to allow characters besides emojis. The definition in your question only included emojis (or was meant to anyway), but since it was called `Identifier`, I'm assuming you just removed the other allowed categories to simplify it.
Looking at [the code](https://github.com/antlr/antlr4/blob/98dc2c0f0249a67b797b151da3adf4ffbc1fd6a1/tool/src/org/antlr/v4/unicode/UnicodeDataTemplateController.java) that seems to define emoji code points: ```java UnicodeSet emojiRKUnicodeSet = new UnicodeSet("[\\p{GCB=Regional_Indicator}\\*#0-9\\u00a9\\u00ae\\u2122\\u3030\\u303d]"); ``` it looks to be including digits (~~why, I don't know~~, checkout sepp2k's excellent explanation). ~~You can always [raise an issue](https://github.com/antlr/antlr4/issues) if you think something is wrong.~~ You could also just use a character class like this instead: ``` Identifier : [\u00a9\u00ae\u2000-\u3300\ud83c\ud000-\udfff\ud83d\ud000-\udfff\ud83e\ud000-\udfff]+ ; ```
67,406,088
We have a requirement where our Users can hide/Unhide and move around Excel Columns. Once the user clicks on generate CSV button, we want the columns to be in a particular sequence. For example, Col1, Col2, Col3 are the column headings in the Excel first row A,B,C Columns. User moved the column Col2 to the end and did hide Col2: A,B,C columns are now having headings: Col1, Col3, Col2(hidden) Our CSV file should be generated as: Col1, Col2, Col3. Using below code, we are unable to see Col2 and even if we manage to unhide, how can we know that the user has moved the Col2 at the end? ``` Public Sub ExportWorksheetAndSaveAsCSV() Dim csvFilePath As String Dim fileNo As Integer Dim fileName As String Dim oneLine As String Dim lastRow, lastCol As Long Dim idxRow, idxCol As Long Dim dt As String dt = Format(CStr(Now), "_yyyymmdd_hhmmss") ' --- get this file name (without extension) fileName = Left(ThisWorkbook.Name, InStrRev(ThisWorkbook.Name, ".", -1, vbTextCompare) - 1) ' --- create file name of CSV file (with full path) csvFilePath = ThisWorkbook.Path & "\" & fileName & dt & ".csv" ' --- get last row and last column lastRow = Cells(Rows.Count, 1).End(xlUp).Row lastCol = Cells(1, Columns.Count).End(xlToLeft).Column ' --- open CSC file fileNo = FreeFile Open csvFilePath For Output As #fileNo ' --- row loop For idxRow = 1 To lastRow If idxRow = 2 Then GoTo ContinueForLoop End If oneLine = "" ' --- column loop: concatenate oneLine For idxCol = 1 To lastCol If (idxCol = 1) Then oneLine = Cells(idxRow, idxCol).Value Else oneLine = oneLine & "," & Cells(idxRow, idxCol).Value End If Next ' --- write oneLine > CSV file Print #fileNo, oneLine ' -- Print: no quotation (output oneLine as it is) ContinueForLoop: Next ' --- close file Close #fileNo End Sub ```
2021/05/05
[ "https://Stackoverflow.com/questions/67406088", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11772301/" ]
If the header names are fixed (and only the position varies) then you'd loop over the headers looking for the ones you want, and note their positions: then use that information to write the cells' values to the output file. ```vb Public Sub ExportWorksheetAndSaveAsCSV() Dim csvFilePath As String Dim fileNo As Integer Dim fileName As String Dim oneLine As String Dim lastRow As Long Dim idxRow, idxCol As Long Dim dt As String, ws As Worksheet, hdr, arrCols, arrPos, i As Long, f As Range, sep Set ws = ActiveSheet 'or whatever lastRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row 'find all required columns arrCols = Array("Col1", "Col2", "Col3") ReDim arrPos(LBound(arrCols) To UBound(arrCols)) For i = LBound(arrCols) To UBound(arrCols) 'Note: lookin:=xlFormulas finds hidden cells but lookin:=xlValues does not... Set f = ws.Rows(1).Find(arrCols(i), lookat:=xlWhole, LookIn:=xlFormulas) If Not f Is Nothing Then arrPos(i) = f.Column Else MsgBox "Required column '" & arrCols(i) & "' not found!", _ vbCritical, "Missing column header" Exit Sub End If Next i 'done finding columns fileName = Left(ThisWorkbook.Name, InStrRev(ThisWorkbook.Name, ".", -1, vbTextCompare) - 1) dt = Format(CStr(Now), "_yyyymmdd_hhmmss") csvFilePath = ThisWorkbook.Path & "\" & fileName & dt & ".csv" fileNo = FreeFile Open csvFilePath For Output As #fileNo For idxRow = 1 To lastRow If idxRow <> 2 Then oneLine = "" sep = "" 'loop over the located column positions For idxCol = LBound(arrPos) To UBound(arrPos) oneLine = oneLine & sep & ws.Cells(idxRow, arrPos(idxCol)).Value sep = "," Next Print #fileNo, oneLine End If Next Close #fileNo ' --- close file End Sub ```
Export to CSV with Given Column Order ------------------------------------- * It is assumed that the table (first row are headers) is contiguous (no empty rows or columns) and starts in cell `A1`. ```vb Option Explicit Sub exportToCSV() Const wsName As String = "Sheet1" Const TimePattern As String = "_yyyymmdd_hhmmss" Dim hCols As Variant: hCols = VBA.Array("Col1", "Col2", "Col3", "Col4") Dim wb As Workbook: Set wb = ThisWorkbook Dim ws As Worksheet: Set ws = wb.Worksheets(wsName) ' If the data is not contiguous, you might need something different here. Dim rg As Range: Set rg = ws.Range("A1").CurrentRegion Dim Data As Variant: Data = rg.Value Dim hData As Variant: hData = rg.Rows(1).Value ' For 'Application.Match' Dim rCount As Long: rCount = UBound(Data, 1) Dim cHeader As Variant Dim dHeader As Variant Dim cIndex As Variant Dim Temp As Variant Dim r As Long, c As Long For c = 0 To UBound(hCols) cHeader = hCols(c) dHeader = Data(1, c + 1) If cHeader <> dHeader Then cIndex = Application.Match(cHeader, hData, 0) If IsNumeric(cIndex) Then For r = 1 To rCount Temp = Data(r, c + 1) Data(r, c + 1) = Data(r, cIndex) Data(r, cIndex) = Temp Next r End If End If Next c Dim TimeStamp As String TimeStamp = Format(CStr(Now), TimePattern) Dim BaseName As String BaseName = Left(wb.Name, InStrRev(wb.Name, ".") - 1) Dim FilePath As String FilePath = wb.Path & "\" & BaseName & TimeStamp & ".csv" Application.ScreenUpdating = False With Workbooks.Add .Worksheets(1).Range("A1").Resize(rCount, UBound(Data, 2)).Value = Data .SaveAs Filename:=FilePath, FileFormat:=xlCSV ' 'Semicolon users' might need this instead: '.SaveAs Filename:=FilePath, FileFormat:=xlCSV, Local:=True .Close End With ' Test the result in the worksheet: 'ws.Range("F1").Resize(rCount, UBound(Data, 2)).Value = Data Application.ScreenUpdating = True End Sub ```
43,274,643
I have this code and i want to stop animate between loops for ex 5sec, I was googled and found just rotate (no delay) ```css .line-1{ border-left: 2px solid rgba(255,255,255,.75); white-space: nowrap; overflow: hidden; direction:ltr; } /* Animation */ .anim-typewriter{ animation: typewriter 4s steps(44) 1s infinite normal both, blinkTextCursor 500ms steps(44) infinite normal; } @keyframes typewriter{ from{width: 0;} to{width: 24em;} } @keyframes blinkTextCursor{ from{border-left-color: rgba(255,255,255,.75);} to{border-left-color: transparent;} } ``` ```html <p class="line-1 anim-typewriter" style="margin-left:auto;margin-right:auto;">Good News: You Won :)<a href="Awards/"> Get Award </a></p> ```
2017/04/07
[ "https://Stackoverflow.com/questions/43274643", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7613282/" ]
I believe this is what you are looking for? ``` -- Generate a sequence of dates from 2010-01-01 to 2010-12-31 select toDate('2010-01-01') + number as d FROM numbers(365); ``` <https://clickhouse.tech/docs/en/sql-reference/table-functions/numbers/>
Clickhouse don't support sequences like a postgresql or other RDBMS what is your use case? you need insert data with incremented sequence ? what for? or you need sequenceMatch and sequenceCount functions for funnel analyze? may be it's url will helfull <https://clickhouse.yandex/reference_en.html#sequenceMatch(pattern)(time,+cond1,+cond2,+...)>
4,835,739
Is there a straight forward way to "brut force" the network connection (cellular and WIFI) off and back on on an iphone? I'm working on an application that syncs through dropbox and would like to test & debug my error recovery code from lost connections. UPDATE: I should have been a bit more specific, I want to turn this off in sw. For example after launching a request to dropbox, I want to simulate a failed download by turning off the network.
2011/01/29
[ "https://Stackoverflow.com/questions/4835739", "https://Stackoverflow.com", "https://Stackoverflow.com/users/512447/" ]
Instead of doing a JOIN to retrieve both the article and the user data in a single query, why not do two separate queries, one to retrieve the articles and the second to retrieve the user data who's relevant to the articles? It is surely simpler and is probably more efficient.
It is no a good practice to use this method in PDO class. PDO works with DB and should returns structured data. You can write your own function, that will do manipulations with returned array.
98,363
We use `sha1sum` to calculate SHA-1 hash value of our packages. **Clarification about the usage:** We distribute some software packages, and we want users to be able to check that what they downloaded is the correct package, down to the last bit. The SHA-1 cryptographic hash algorithm has been replaced by SHA-2 since SHA-1 is known to be considerably weaker. Can we still use `sha1sum`? Or should we replace it with `sha256sum`, or `sha512sum`?
2015/09/02
[ "https://security.stackexchange.com/questions/98363", "https://security.stackexchange.com", "https://security.stackexchange.com/users/24842/" ]
Even if you are not doing work for the federal government, the link to the document below is a good reference to how long people should use hash key lengths until future dates for specific tasks like authenticating a signature. For package authentication, I would also include a size which makes it much harder to create a collision (Changed package that matches the same hash). Why would you not use both SHA1 and SHA512 (if the compute time is not so burdensome)? Also take into account the asymmetric key length used to sign the hash given. While it is great that you are thinking about this, there are probably other integrity issues that are more pressing like how to ensure that a person does not receive a falsified hash for comparison and the source of all of your included libraries that would be more of a risk. P.S. If you are thinking about certificates for a browser both Chrome and IE are going to or have set UI about sunsetting the use of SHA1. If you are storing passwords, look to salted (and possibly peppered) hashes with PBKDF2. <http://csrc.nist.gov/publications/nistpubs/800-131A/sp800-131A.pdf> <http://googleonlinesecurity.blogspot.com/2014/09/gradually-sunsetting-sha-1.html> <https://en.wikipedia.org/wiki/PBKDF2>
There are better choices than SHA2. Blake2, for example, is a finalist of SHA3 competition, and blake2-256 is as fast as SHA1 and much faster as SHA2. It can be used as the checksum algorithm in Winrar 5. Like MD5 and SHA1, SHA2 is based on Merkle-Damgard structure and has possibly similar vulnerabilities. SHA3 is not vulnerable, but SHA3-224 is ca. 8 times slower than SHA1.
98,363
We use `sha1sum` to calculate SHA-1 hash value of our packages. **Clarification about the usage:** We distribute some software packages, and we want users to be able to check that what they downloaded is the correct package, down to the last bit. The SHA-1 cryptographic hash algorithm has been replaced by SHA-2 since SHA-1 is known to be considerably weaker. Can we still use `sha1sum`? Or should we replace it with `sha256sum`, or `sha512sum`?
2015/09/02
[ "https://security.stackexchange.com/questions/98363", "https://security.stackexchange.com", "https://security.stackexchange.com/users/24842/" ]
You should use SHA-256 or SHA-512. If you are only signing packages you have created yourself, then technically SHA-1 is still secure for that purpose. The property that is now weakened is "collision resistance" which you are not strictly relying on. However, the security of SHA-1 is only going to get worse with time, so it makes sense to move on now.
Even if you are not doing work for the federal government, the link to the document below is a good reference to how long people should use hash key lengths until future dates for specific tasks like authenticating a signature. For package authentication, I would also include a size which makes it much harder to create a collision (Changed package that matches the same hash). Why would you not use both SHA1 and SHA512 (if the compute time is not so burdensome)? Also take into account the asymmetric key length used to sign the hash given. While it is great that you are thinking about this, there are probably other integrity issues that are more pressing like how to ensure that a person does not receive a falsified hash for comparison and the source of all of your included libraries that would be more of a risk. P.S. If you are thinking about certificates for a browser both Chrome and IE are going to or have set UI about sunsetting the use of SHA1. If you are storing passwords, look to salted (and possibly peppered) hashes with PBKDF2. <http://csrc.nist.gov/publications/nistpubs/800-131A/sp800-131A.pdf> <http://googleonlinesecurity.blogspot.com/2014/09/gradually-sunsetting-sha-1.html> <https://en.wikipedia.org/wiki/PBKDF2>
98,363
We use `sha1sum` to calculate SHA-1 hash value of our packages. **Clarification about the usage:** We distribute some software packages, and we want users to be able to check that what they downloaded is the correct package, down to the last bit. The SHA-1 cryptographic hash algorithm has been replaced by SHA-2 since SHA-1 is known to be considerably weaker. Can we still use `sha1sum`? Or should we replace it with `sha256sum`, or `sha512sum`?
2015/09/02
[ "https://security.stackexchange.com/questions/98363", "https://security.stackexchange.com", "https://security.stackexchange.com/users/24842/" ]
I suppose you "use `sha1sum`" in the following context: you distribute some software packages, and you want users to be able to check that what they downloaded is the correct package, down to the last bit. This assumes that you have a way to convey the hash value (computed with SHA-1) in an "unalterable" way (e.g. as part of a Web page which is served over HTTPS). I also suppose that we are talking about *attacks* here, i.e. some malicious individual who can somehow alter the package as it is downloaded, and will want to inject some modification that will go undetected. The security property that the used hash function should offer here is **resistance to second-preimages**. Most importantly, this is *not* the same as resistance to collisions. A collision is when the attacker can craft two distinct messages *m* and *m'* that hash to the same value; a second-preimage is when the attacker is given a fixed *m* and challenged with finding a distinct *m'* that hashes to the same value. Second-preimages are a lot harder to obtain than collisions. For a "perfect" hash function with output size *n* bits, the computational effort for finding a collision is about 2*n*/2 invocations of the hash function; for a second-preimage, this is 2*n*. Moreover, structural weaknesses that allow for a faster collision attack do not necessarily apply to a second-preimage attack. This is true, in particular, for the known weaknesses of SHA-1: right now (September 2015), there are some known theoretical weaknesses of SHA-1 that should allow the computation of a collision in less than the ideal 280 effort (this is still a huge effort, about 261, so it has not been actually demonstrated yet); but these weaknesses are differential paths that intrinsically require the attacker to craft both *m* and *m'*, therefore they do not carry over second-preimages. For the time being, there is no known second-preimage attack on SHA-1 that would be even theoretically or academically faster than the generic attack, with a 2160 cost that is way beyond technological feasibility, by a [long shot](https://security.stackexchange.com/questions/6141/amount-of-simple-operations-that-is-safely-out-of-reach-for-all-humanity/6149#6149). **Bottom-line:** within the context of what you are trying to do, SHA-1 is safe, and likely to remain safe for some time (even MD5 would still be appropriate). Another reason for using `sha1sum` is the availability of client-side tools: in particular, the command-line hashing tool provided by Microsoft for Windows (called [FCIV](https://support.microsoft.com/en-us/kb/841290)) knows MD5 and SHA-1, but not SHA-256 (at least so says the documentation)(\*). Windows 7 and later also contain a command-line tool called "certutil" that can compute SHA-256 hashes with the "-hashfile" sub-command. This is not widely known, but it can be convenient at times. --- That being said, a powerful reason *against* using SHA-1 is that of **image**: it is currently highly trendy to boo and mock any use of SHA-1; the crowds clamour for its removal, anathema, arrest and public execution. By using SHA-1 you are telling the world that you are, definitely, not a hipster. From a business point of view, it rarely makes any good not to yield to the fashion *du jour*, so you should use one of the SHA-2 functions, e.g. SHA-256 or SHA-512. There is no strong reason to prefer SHA-256 over SHA-512 or the other way round; some small, 32-bit only architectures are more comfortable with SHA-256, but this rarely matters in practice (even a 32-bit implementation of SHA-512 will still be able to hash several dozens of megabytes of data per second on an anemic laptop, and even in 32-bit mode, a not-too-old x86 CPU has some abilities at 64-bit computations with SSE2, which give a good boost for SHA-512). Any marketing expert would tell you to use SHA-512 on the sole basis that 512 is greater than 256, so "it must be better" in some (magical) way.
Tom Leak has a [beautiful answer](https://security.stackexchange.com/a/98376/40258) (which is why it is accepted). It is concerned with the mathematically provable facts behind the use of SHA-1. There is a second approach which is less fact based but may provide valuable heuristic information. I learned this approach from reading Bruce Schneier's opinions, but I cannot find the links off hand, so Bruce will have to deal with my namedropping. In theory an algorithm is not broken until it's broken. Until someone has found a way to do X, where X is something that should be computationally infeasible, it is not considered "broken."1 However, that proves to be of limited value in its practical application in cryptography. Cryptographers would *really* rather get a little notice before their products fall apart, not after. What has been found, historically, is that algorithms are rarely broken in one big step. Yes, it can happen, and a cryptographer has to plan for that, but what has been found empirically is that they are typically whittled away over time, paper after paper. It has been found that watching the difficulty of generating a collision is a reasonably good metric for guesstimating when the algorithm will actually be broken. So when Tom points out that the collision should take 280 operations and now takes 261, it is very valid to point out, as he did, that the 261 operations is theoretical, because it is still too large to warrant an attempt. However, it is also valid to think of it as "the algorithm has experienced a reduction in strength of 19 bits of power," and use that as a poor man's rule of thumb to project forward and estimate when that will become an issue. This kind of thinking is why there is now a SHA-3, even though theoretically SHA-1 is still not fully broken. The cryptographers involved in SHA-3's development and testing know that it is going to take quite a while to develop confidence in SHA-3, and they want to make sure that confidence is there before SHA-1 breaks, not after. 1. I am aware that the most technically strict definition of a "broken" hash merely one where an attacker can do better than brute force, as opposed to when it actually becomes computationally feasible. However, this latter definition is more typically used when discussing the practical side of hashing.
98,363
We use `sha1sum` to calculate SHA-1 hash value of our packages. **Clarification about the usage:** We distribute some software packages, and we want users to be able to check that what they downloaded is the correct package, down to the last bit. The SHA-1 cryptographic hash algorithm has been replaced by SHA-2 since SHA-1 is known to be considerably weaker. Can we still use `sha1sum`? Or should we replace it with `sha256sum`, or `sha512sum`?
2015/09/02
[ "https://security.stackexchange.com/questions/98363", "https://security.stackexchange.com", "https://security.stackexchange.com/users/24842/" ]
I suppose you "use `sha1sum`" in the following context: you distribute some software packages, and you want users to be able to check that what they downloaded is the correct package, down to the last bit. This assumes that you have a way to convey the hash value (computed with SHA-1) in an "unalterable" way (e.g. as part of a Web page which is served over HTTPS). I also suppose that we are talking about *attacks* here, i.e. some malicious individual who can somehow alter the package as it is downloaded, and will want to inject some modification that will go undetected. The security property that the used hash function should offer here is **resistance to second-preimages**. Most importantly, this is *not* the same as resistance to collisions. A collision is when the attacker can craft two distinct messages *m* and *m'* that hash to the same value; a second-preimage is when the attacker is given a fixed *m* and challenged with finding a distinct *m'* that hashes to the same value. Second-preimages are a lot harder to obtain than collisions. For a "perfect" hash function with output size *n* bits, the computational effort for finding a collision is about 2*n*/2 invocations of the hash function; for a second-preimage, this is 2*n*. Moreover, structural weaknesses that allow for a faster collision attack do not necessarily apply to a second-preimage attack. This is true, in particular, for the known weaknesses of SHA-1: right now (September 2015), there are some known theoretical weaknesses of SHA-1 that should allow the computation of a collision in less than the ideal 280 effort (this is still a huge effort, about 261, so it has not been actually demonstrated yet); but these weaknesses are differential paths that intrinsically require the attacker to craft both *m* and *m'*, therefore they do not carry over second-preimages. For the time being, there is no known second-preimage attack on SHA-1 that would be even theoretically or academically faster than the generic attack, with a 2160 cost that is way beyond technological feasibility, by a [long shot](https://security.stackexchange.com/questions/6141/amount-of-simple-operations-that-is-safely-out-of-reach-for-all-humanity/6149#6149). **Bottom-line:** within the context of what you are trying to do, SHA-1 is safe, and likely to remain safe for some time (even MD5 would still be appropriate). Another reason for using `sha1sum` is the availability of client-side tools: in particular, the command-line hashing tool provided by Microsoft for Windows (called [FCIV](https://support.microsoft.com/en-us/kb/841290)) knows MD5 and SHA-1, but not SHA-256 (at least so says the documentation)(\*). Windows 7 and later also contain a command-line tool called "certutil" that can compute SHA-256 hashes with the "-hashfile" sub-command. This is not widely known, but it can be convenient at times. --- That being said, a powerful reason *against* using SHA-1 is that of **image**: it is currently highly trendy to boo and mock any use of SHA-1; the crowds clamour for its removal, anathema, arrest and public execution. By using SHA-1 you are telling the world that you are, definitely, not a hipster. From a business point of view, it rarely makes any good not to yield to the fashion *du jour*, so you should use one of the SHA-2 functions, e.g. SHA-256 or SHA-512. There is no strong reason to prefer SHA-256 over SHA-512 or the other way round; some small, 32-bit only architectures are more comfortable with SHA-256, but this rarely matters in practice (even a 32-bit implementation of SHA-512 will still be able to hash several dozens of megabytes of data per second on an anemic laptop, and even in 32-bit mode, a not-too-old x86 CPU has some abilities at 64-bit computations with SSE2, which give a good boost for SHA-512). Any marketing expert would tell you to use SHA-512 on the sole basis that 512 is greater than 256, so "it must be better" in some (magical) way.
There are better choices than SHA2. Blake2, for example, is a finalist of SHA3 competition, and blake2-256 is as fast as SHA1 and much faster as SHA2. It can be used as the checksum algorithm in Winrar 5. Like MD5 and SHA1, SHA2 is based on Merkle-Damgard structure and has possibly similar vulnerabilities. SHA3 is not vulnerable, but SHA3-224 is ca. 8 times slower than SHA1.
98,363
We use `sha1sum` to calculate SHA-1 hash value of our packages. **Clarification about the usage:** We distribute some software packages, and we want users to be able to check that what they downloaded is the correct package, down to the last bit. The SHA-1 cryptographic hash algorithm has been replaced by SHA-2 since SHA-1 is known to be considerably weaker. Can we still use `sha1sum`? Or should we replace it with `sha256sum`, or `sha512sum`?
2015/09/02
[ "https://security.stackexchange.com/questions/98363", "https://security.stackexchange.com", "https://security.stackexchange.com/users/24842/" ]
For the intended purpose, the practical answer is "Yes, of course", although for reasons of prestige you should also publish a more recent hash (such as SHA-3). If it didn't have so much "stench", you could in principle still use MD5 (apart from people yelling at you, even MD5 will work fine for this application). Using SHA-1 to verify downloads has never been "secure" and is primarily not intended to be. The main purpose of providing a hash (of any kind) is to detect bit errors, partial downloads, or accidentially downloading the wrong executable (clicking on the row above or below in the list and not noticing). Malicious modifications are an issue that is not very well addressed with a hash, since an attacker who has sufficient access to the server so he can replace the binary can usually also replace the hash. Arguably, you **do** gain some security if you use a CDN, since someone who gains access to a node in the CDN cannot successfully replace the binary on that node without the user (who downloads the hash from the server that *only you* control) noticing. If, however, you need something that must be "secure" and resilient to malicious modification, you should most definitively digitally sign your executables and include for example a GPG signature. A hash will not do.
There are better choices than SHA2. Blake2, for example, is a finalist of SHA3 competition, and blake2-256 is as fast as SHA1 and much faster as SHA2. It can be used as the checksum algorithm in Winrar 5. Like MD5 and SHA1, SHA2 is based on Merkle-Damgard structure and has possibly similar vulnerabilities. SHA3 is not vulnerable, but SHA3-224 is ca. 8 times slower than SHA1.
98,363
We use `sha1sum` to calculate SHA-1 hash value of our packages. **Clarification about the usage:** We distribute some software packages, and we want users to be able to check that what they downloaded is the correct package, down to the last bit. The SHA-1 cryptographic hash algorithm has been replaced by SHA-2 since SHA-1 is known to be considerably weaker. Can we still use `sha1sum`? Or should we replace it with `sha256sum`, or `sha512sum`?
2015/09/02
[ "https://security.stackexchange.com/questions/98363", "https://security.stackexchange.com", "https://security.stackexchange.com/users/24842/" ]
You should use SHA-256 or SHA-512. If you are only signing packages you have created yourself, then technically SHA-1 is still secure for that purpose. The property that is now weakened is "collision resistance" which you are not strictly relying on. However, the security of SHA-1 is only going to get worse with time, so it makes sense to move on now.
For the intended purpose, the practical answer is "Yes, of course", although for reasons of prestige you should also publish a more recent hash (such as SHA-3). If it didn't have so much "stench", you could in principle still use MD5 (apart from people yelling at you, even MD5 will work fine for this application). Using SHA-1 to verify downloads has never been "secure" and is primarily not intended to be. The main purpose of providing a hash (of any kind) is to detect bit errors, partial downloads, or accidentially downloading the wrong executable (clicking on the row above or below in the list and not noticing). Malicious modifications are an issue that is not very well addressed with a hash, since an attacker who has sufficient access to the server so he can replace the binary can usually also replace the hash. Arguably, you **do** gain some security if you use a CDN, since someone who gains access to a node in the CDN cannot successfully replace the binary on that node without the user (who downloads the hash from the server that *only you* control) noticing. If, however, you need something that must be "secure" and resilient to malicious modification, you should most definitively digitally sign your executables and include for example a GPG signature. A hash will not do.
98,363
We use `sha1sum` to calculate SHA-1 hash value of our packages. **Clarification about the usage:** We distribute some software packages, and we want users to be able to check that what they downloaded is the correct package, down to the last bit. The SHA-1 cryptographic hash algorithm has been replaced by SHA-2 since SHA-1 is known to be considerably weaker. Can we still use `sha1sum`? Or should we replace it with `sha256sum`, or `sha512sum`?
2015/09/02
[ "https://security.stackexchange.com/questions/98363", "https://security.stackexchange.com", "https://security.stackexchange.com/users/24842/" ]
Even if you are not doing work for the federal government, the link to the document below is a good reference to how long people should use hash key lengths until future dates for specific tasks like authenticating a signature. For package authentication, I would also include a size which makes it much harder to create a collision (Changed package that matches the same hash). Why would you not use both SHA1 and SHA512 (if the compute time is not so burdensome)? Also take into account the asymmetric key length used to sign the hash given. While it is great that you are thinking about this, there are probably other integrity issues that are more pressing like how to ensure that a person does not receive a falsified hash for comparison and the source of all of your included libraries that would be more of a risk. P.S. If you are thinking about certificates for a browser both Chrome and IE are going to or have set UI about sunsetting the use of SHA1. If you are storing passwords, look to salted (and possibly peppered) hashes with PBKDF2. <http://csrc.nist.gov/publications/nistpubs/800-131A/sp800-131A.pdf> <http://googleonlinesecurity.blogspot.com/2014/09/gradually-sunsetting-sha-1.html> <https://en.wikipedia.org/wiki/PBKDF2>
Can you still use it?..Yes you can, but sha-1 is vulnerable to collision attacks and has been deprecated by a number of browsers. If the question was should you still use it, then I would say no you shouldn't, you should move to sha-2 and sha256sum type program.
98,363
We use `sha1sum` to calculate SHA-1 hash value of our packages. **Clarification about the usage:** We distribute some software packages, and we want users to be able to check that what they downloaded is the correct package, down to the last bit. The SHA-1 cryptographic hash algorithm has been replaced by SHA-2 since SHA-1 is known to be considerably weaker. Can we still use `sha1sum`? Or should we replace it with `sha256sum`, or `sha512sum`?
2015/09/02
[ "https://security.stackexchange.com/questions/98363", "https://security.stackexchange.com", "https://security.stackexchange.com/users/24842/" ]
I suppose you "use `sha1sum`" in the following context: you distribute some software packages, and you want users to be able to check that what they downloaded is the correct package, down to the last bit. This assumes that you have a way to convey the hash value (computed with SHA-1) in an "unalterable" way (e.g. as part of a Web page which is served over HTTPS). I also suppose that we are talking about *attacks* here, i.e. some malicious individual who can somehow alter the package as it is downloaded, and will want to inject some modification that will go undetected. The security property that the used hash function should offer here is **resistance to second-preimages**. Most importantly, this is *not* the same as resistance to collisions. A collision is when the attacker can craft two distinct messages *m* and *m'* that hash to the same value; a second-preimage is when the attacker is given a fixed *m* and challenged with finding a distinct *m'* that hashes to the same value. Second-preimages are a lot harder to obtain than collisions. For a "perfect" hash function with output size *n* bits, the computational effort for finding a collision is about 2*n*/2 invocations of the hash function; for a second-preimage, this is 2*n*. Moreover, structural weaknesses that allow for a faster collision attack do not necessarily apply to a second-preimage attack. This is true, in particular, for the known weaknesses of SHA-1: right now (September 2015), there are some known theoretical weaknesses of SHA-1 that should allow the computation of a collision in less than the ideal 280 effort (this is still a huge effort, about 261, so it has not been actually demonstrated yet); but these weaknesses are differential paths that intrinsically require the attacker to craft both *m* and *m'*, therefore they do not carry over second-preimages. For the time being, there is no known second-preimage attack on SHA-1 that would be even theoretically or academically faster than the generic attack, with a 2160 cost that is way beyond technological feasibility, by a [long shot](https://security.stackexchange.com/questions/6141/amount-of-simple-operations-that-is-safely-out-of-reach-for-all-humanity/6149#6149). **Bottom-line:** within the context of what you are trying to do, SHA-1 is safe, and likely to remain safe for some time (even MD5 would still be appropriate). Another reason for using `sha1sum` is the availability of client-side tools: in particular, the command-line hashing tool provided by Microsoft for Windows (called [FCIV](https://support.microsoft.com/en-us/kb/841290)) knows MD5 and SHA-1, but not SHA-256 (at least so says the documentation)(\*). Windows 7 and later also contain a command-line tool called "certutil" that can compute SHA-256 hashes with the "-hashfile" sub-command. This is not widely known, but it can be convenient at times. --- That being said, a powerful reason *against* using SHA-1 is that of **image**: it is currently highly trendy to boo and mock any use of SHA-1; the crowds clamour for its removal, anathema, arrest and public execution. By using SHA-1 you are telling the world that you are, definitely, not a hipster. From a business point of view, it rarely makes any good not to yield to the fashion *du jour*, so you should use one of the SHA-2 functions, e.g. SHA-256 or SHA-512. There is no strong reason to prefer SHA-256 over SHA-512 or the other way round; some small, 32-bit only architectures are more comfortable with SHA-256, but this rarely matters in practice (even a 32-bit implementation of SHA-512 will still be able to hash several dozens of megabytes of data per second on an anemic laptop, and even in 32-bit mode, a not-too-old x86 CPU has some abilities at 64-bit computations with SSE2, which give a good boost for SHA-512). Any marketing expert would tell you to use SHA-512 on the sole basis that 512 is greater than 256, so "it must be better" in some (magical) way.
For the intended purpose, the practical answer is "Yes, of course", although for reasons of prestige you should also publish a more recent hash (such as SHA-3). If it didn't have so much "stench", you could in principle still use MD5 (apart from people yelling at you, even MD5 will work fine for this application). Using SHA-1 to verify downloads has never been "secure" and is primarily not intended to be. The main purpose of providing a hash (of any kind) is to detect bit errors, partial downloads, or accidentially downloading the wrong executable (clicking on the row above or below in the list and not noticing). Malicious modifications are an issue that is not very well addressed with a hash, since an attacker who has sufficient access to the server so he can replace the binary can usually also replace the hash. Arguably, you **do** gain some security if you use a CDN, since someone who gains access to a node in the CDN cannot successfully replace the binary on that node without the user (who downloads the hash from the server that *only you* control) noticing. If, however, you need something that must be "secure" and resilient to malicious modification, you should most definitively digitally sign your executables and include for example a GPG signature. A hash will not do.
98,363
We use `sha1sum` to calculate SHA-1 hash value of our packages. **Clarification about the usage:** We distribute some software packages, and we want users to be able to check that what they downloaded is the correct package, down to the last bit. The SHA-1 cryptographic hash algorithm has been replaced by SHA-2 since SHA-1 is known to be considerably weaker. Can we still use `sha1sum`? Or should we replace it with `sha256sum`, or `sha512sum`?
2015/09/02
[ "https://security.stackexchange.com/questions/98363", "https://security.stackexchange.com", "https://security.stackexchange.com/users/24842/" ]
Tom Leak has a [beautiful answer](https://security.stackexchange.com/a/98376/40258) (which is why it is accepted). It is concerned with the mathematically provable facts behind the use of SHA-1. There is a second approach which is less fact based but may provide valuable heuristic information. I learned this approach from reading Bruce Schneier's opinions, but I cannot find the links off hand, so Bruce will have to deal with my namedropping. In theory an algorithm is not broken until it's broken. Until someone has found a way to do X, where X is something that should be computationally infeasible, it is not considered "broken."1 However, that proves to be of limited value in its practical application in cryptography. Cryptographers would *really* rather get a little notice before their products fall apart, not after. What has been found, historically, is that algorithms are rarely broken in one big step. Yes, it can happen, and a cryptographer has to plan for that, but what has been found empirically is that they are typically whittled away over time, paper after paper. It has been found that watching the difficulty of generating a collision is a reasonably good metric for guesstimating when the algorithm will actually be broken. So when Tom points out that the collision should take 280 operations and now takes 261, it is very valid to point out, as he did, that the 261 operations is theoretical, because it is still too large to warrant an attempt. However, it is also valid to think of it as "the algorithm has experienced a reduction in strength of 19 bits of power," and use that as a poor man's rule of thumb to project forward and estimate when that will become an issue. This kind of thinking is why there is now a SHA-3, even though theoretically SHA-1 is still not fully broken. The cryptographers involved in SHA-3's development and testing know that it is going to take quite a while to develop confidence in SHA-3, and they want to make sure that confidence is there before SHA-1 breaks, not after. 1. I am aware that the most technically strict definition of a "broken" hash merely one where an attacker can do better than brute force, as opposed to when it actually becomes computationally feasible. However, this latter definition is more typically used when discussing the practical side of hashing.
Can you still use it?..Yes you can, but sha-1 is vulnerable to collision attacks and has been deprecated by a number of browsers. If the question was should you still use it, then I would say no you shouldn't, you should move to sha-2 and sha256sum type program.
98,363
We use `sha1sum` to calculate SHA-1 hash value of our packages. **Clarification about the usage:** We distribute some software packages, and we want users to be able to check that what they downloaded is the correct package, down to the last bit. The SHA-1 cryptographic hash algorithm has been replaced by SHA-2 since SHA-1 is known to be considerably weaker. Can we still use `sha1sum`? Or should we replace it with `sha256sum`, or `sha512sum`?
2015/09/02
[ "https://security.stackexchange.com/questions/98363", "https://security.stackexchange.com", "https://security.stackexchange.com/users/24842/" ]
I suppose you "use `sha1sum`" in the following context: you distribute some software packages, and you want users to be able to check that what they downloaded is the correct package, down to the last bit. This assumes that you have a way to convey the hash value (computed with SHA-1) in an "unalterable" way (e.g. as part of a Web page which is served over HTTPS). I also suppose that we are talking about *attacks* here, i.e. some malicious individual who can somehow alter the package as it is downloaded, and will want to inject some modification that will go undetected. The security property that the used hash function should offer here is **resistance to second-preimages**. Most importantly, this is *not* the same as resistance to collisions. A collision is when the attacker can craft two distinct messages *m* and *m'* that hash to the same value; a second-preimage is when the attacker is given a fixed *m* and challenged with finding a distinct *m'* that hashes to the same value. Second-preimages are a lot harder to obtain than collisions. For a "perfect" hash function with output size *n* bits, the computational effort for finding a collision is about 2*n*/2 invocations of the hash function; for a second-preimage, this is 2*n*. Moreover, structural weaknesses that allow for a faster collision attack do not necessarily apply to a second-preimage attack. This is true, in particular, for the known weaknesses of SHA-1: right now (September 2015), there are some known theoretical weaknesses of SHA-1 that should allow the computation of a collision in less than the ideal 280 effort (this is still a huge effort, about 261, so it has not been actually demonstrated yet); but these weaknesses are differential paths that intrinsically require the attacker to craft both *m* and *m'*, therefore they do not carry over second-preimages. For the time being, there is no known second-preimage attack on SHA-1 that would be even theoretically or academically faster than the generic attack, with a 2160 cost that is way beyond technological feasibility, by a [long shot](https://security.stackexchange.com/questions/6141/amount-of-simple-operations-that-is-safely-out-of-reach-for-all-humanity/6149#6149). **Bottom-line:** within the context of what you are trying to do, SHA-1 is safe, and likely to remain safe for some time (even MD5 would still be appropriate). Another reason for using `sha1sum` is the availability of client-side tools: in particular, the command-line hashing tool provided by Microsoft for Windows (called [FCIV](https://support.microsoft.com/en-us/kb/841290)) knows MD5 and SHA-1, but not SHA-256 (at least so says the documentation)(\*). Windows 7 and later also contain a command-line tool called "certutil" that can compute SHA-256 hashes with the "-hashfile" sub-command. This is not widely known, but it can be convenient at times. --- That being said, a powerful reason *against* using SHA-1 is that of **image**: it is currently highly trendy to boo and mock any use of SHA-1; the crowds clamour for its removal, anathema, arrest and public execution. By using SHA-1 you are telling the world that you are, definitely, not a hipster. From a business point of view, it rarely makes any good not to yield to the fashion *du jour*, so you should use one of the SHA-2 functions, e.g. SHA-256 or SHA-512. There is no strong reason to prefer SHA-256 over SHA-512 or the other way round; some small, 32-bit only architectures are more comfortable with SHA-256, but this rarely matters in practice (even a 32-bit implementation of SHA-512 will still be able to hash several dozens of megabytes of data per second on an anemic laptop, and even in 32-bit mode, a not-too-old x86 CPU has some abilities at 64-bit computations with SSE2, which give a good boost for SHA-512). Any marketing expert would tell you to use SHA-512 on the sole basis that 512 is greater than 256, so "it must be better" in some (magical) way.
Can you still use it?..Yes you can, but sha-1 is vulnerable to collision attacks and has been deprecated by a number of browsers. If the question was should you still use it, then I would say no you shouldn't, you should move to sha-2 and sha256sum type program.
34,934,717
I'm writing my own HTTP server. I'm using `Java Socket` for it. I read request from `InputStream` next way ``` val input = BufferedReader(InputStreamReader(socket.inputStream, "UTF-8")) ``` When I receive requests from `curl` or browser all is good. But when I receive request from `Postman` I get something like this: ``` ��g�������#���=��g�������#���, ��9� ��3���5�/�=��9� ��3���5�/�, ``` I tried to use others encodings for `InputStreamReader` such as `UTF-16` and `ASCII`. Which encoding is used for Postman requests and how I can read it on my server? ***UPDATE:*** Sorry, this is my failure. I used HTTPS when making requests.
2016/01/21
[ "https://Stackoverflow.com/questions/34934717", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3830108/" ]
If the first two bytes received are ASCII 31 (0x1F) and 139 (0x8B) you are receiving a GZIP stream and for some reason convinced the client that you supported GZIP `Content-Encoding` (not the same thing as the charset encoding). The data looks more binary than character encoding. Gzip, deflate, SSL, or other reason for binary data is what should be looked at. You may not be doing content negotiation correctly and therefore receiving binary gzip or deflate. Or using HTTPS vs. HTTP. Or uploading an image. Something but not text.
***NOTE:*** my other answer is more direct, this is related HTTP server libraries for use in Kotlin, in case others read this question and want to know alternatives. Not sure if this is an [XY problem](http://xyproblem.info/) and if the author is not aware of other options. Other ways if you do not want to build an HTTP library, but instead use one: **Raw HTTP frameworks:** * Anything written for Java, and specifically: * [Undertow.io](http://undertow.io/) * [Vert.x 3](http://vertx.io/docs/) with [Vert.x-web](http://vertx.io/docs/vertx-web/java/) * [Netty](http://netty.io/) - very low level **Somewhat more than raw HTTP, but not a MVC or REST framework:** * [Wasabi](https://github.com/hhariri/wasabi) - Kotlin specific **And for fuller REST or Web frameworks:** * [KTOR](https://github.com/Kotlin/ktor) - Kotlin specific * [Kovert](https://github.com/kohesive/kovert) - Kotlin specific, REST but adding views (*Disclaimer: I'm the author*) * [Spark Java](http://sparkjava.com/) - Java, works nicely in Kotlin * [Vert.x Nubes](https://github.com/aesteve/nubes) - Java, to work on top of Vert.x * [Kikaha](http://kikaha.skullabs.io/) - Java, to work on top of Undertow
34,393,450
One of the rule defined in the PMD rule set is: **"Avoid using Volatile"** which explains that **"Use of modifier volatile is not recommended"**. This rule is mentioned under the **Controversial Rule Set** of PMD. In my team, we have Sonar configured on various modules which indirectly has the rule set from PMD and hence any use of **volatile** pops as a critical warning. **Question is why are we using volatile?** The volatile keyword is used for boolean variables to control the state of the external session. This state is accessed across various threads and hence to know if the state is UP or DOWN, it is maintained as a boolean volatile variable, so that visibility is shared across multiple threads. **My question is how to fix this sonar warning?** One solution is to remove the rule from the rule set, which is not allowed because: firstly it is not recommended as these rules form the basic guidelines defined from PMD rule set and secondly the SONAR server in my organisation is a central server being used by all the teams. Hence is not allowed. Another solution is to ignore the sonar warning by use of some annotation, which is again not recommended on basic rule set. Can anyone suggest how can we fix this sonar warning in code? Thanks in advance.
2015/12/21
[ "https://Stackoverflow.com/questions/34393450", "https://Stackoverflow.com", "https://Stackoverflow.com/users/988206/" ]
First off, this rule does not indicate a general problem in the code - `volatile` is a perfectly fine keyword, and there is nothing wrong with it. That's why it's a [controversial rule](http://pmd.sourceforge.net/pmd-4.3.0/rules/controversial.html#AvoidUsingVolatile). On the other hand, using it is indeed a bit of an advanced technique that requires you to know what you are doing. Situations exist where you would know that, let's say, the people who will maintain your code will not have sufficient Java knowledge. In such cases, the rule *may* make sense. To satisfy the rule in your case, use [AtomicBoolean](https://docs.oracle.com/javase/8/docs/api/index.html?java/util/concurrent/atomic/AtomicBoolean.html).
Why not suppress the warning with an annotation? ``` @SuppressWarnings("PMD.AvoidUsingVolatile") ```
87,904
Is there a formula for the size of Symplectic group defined over a finite ring $Z/p^k Z$?
2012/02/08
[ "https://mathoverflow.net/questions/87904", "https://mathoverflow.net", "https://mathoverflow.net/users/21237/" ]
From L. C. Grove's *Classical Groups and Geometric Algebra,* page 27: $$|\operatorname{SP}(2n,\mathbb{F}\_q)|=q^{n^2}\prod\_{i=1}^n(q^{2i}-1),$$ for some $q=p^k$. This works in the case of $\mathbb{F}\_p\cong\mathbb{Z}/p\mathbb{Z}$, but I don't think it's helpful for the general case $\mathbb{Z}/q\mathbb{Z}$.
Hi. EDIT: As Joe Silverman pointed out, this approach doesn't work as simple as I imagined it. Sorry for that. I leave the attempted proof here in case someone has an idea how to fix it. Yes, there is such a formula. It works for in a similar fashion all of the classical algebraic group. Consider the projection $\mathbb{Z}/p^k\to\mathbb{Z}/p$. It induces a surjection $Sp\_{2n}(\mathbb{Z}/p^k)\to Sp\_{2n}(\mathbb{Z}/p)$ because every transvection has a preimage and the transvections generate $Sp\_{2n}(F)$ for every field $F$. The kernel of the homomorphism consists obviously of those matrices $M$ with $M-I \in (p\mathbb{Z}/p^k\mathbb{Z})^{n\times n}$. There are $p^{(k-1)n^2}$ such matrices. Therefore $|Sp\_{2n}(\mathbb{Z}/p^k)| = p^{(k-1)n^2} |Sp\_{2n}(\mathbb{Z}/p)|$. The order of the symplectic group over $\mathbb{Z}/p$ is known.
87,904
Is there a formula for the size of Symplectic group defined over a finite ring $Z/p^k Z$?
2012/02/08
[ "https://mathoverflow.net/questions/87904", "https://mathoverflow.net", "https://mathoverflow.net/users/21237/" ]
From Christopher Perez's answer, we have $|Sp\_{2n}(\mathbb{Z}/p\mathbb{Z})| = p^{n^2} \prod\_{i=1}^n (p^{2i}-1)$. Following Johannes Hahn, we wish to determine the size of the kernel of the homomorphism $Sp\_{2n}(\mathbb{Z}/p^k\mathbb{Z}) \to Sp\_{2n}(\mathbb{Z}/p\mathbb{Z})$. To compute this, we may induct on $k$: For $k \geq 1$, elements in the kernel of the homomorphism $Sp\_{2n}(\mathbb{Z}/p^{k+1}\mathbb{Z}) \to Sp\_{2n}(\mathbb{Z}/p^k\mathbb{Z})$ have the form $I + p^k A$ for a matrix $A = \left( \begin{smallmatrix} E & F \\ G & H \end{smallmatrix} \right)$ with values in $\mathbb{Z}/p\mathbb{Z}$. The symplectic condition (given in [Wikipedia](http://en.wikipedia.org/wiki/Symplectic_matrix)) is equivalent to the conditions that $F^t = F$, $G^t = G$, and $E^t + H = 0$. $F$ and $G$ are therefore symmetric matrices, while $H$ and $E$ determine each other, with no further conditions. The kernel of one-step reduction therefore has size $p^{n(n+1)/2} \cdot p^{n(n+1)/2} \cdot p^{n^2}$, or $p^{2n^2 + n}$. The final answer is therefore: $|Sp\_{2n}(\mathbb{Z}/p^k\mathbb{Z})| = p^{(2k-1)n^2 + (k-1)n} \prod\_{i=1}^n (p^{2i}-1)$ **Edit:** To address kassabov's complaint, I'll explain the calculation in a bit more detail. The symplectic condition on $I + p^k A$ is that $(I + p^k A)^t \Omega (I + p^k A) \equiv \Omega \pmod {p^{k+1}}$, where $\Omega = \left( \begin{smallmatrix} 0 & I\_n \\ -I\_n & 0 \end{smallmatrix} \right)$. Because $k \geq 1$, we may eliminate the $p^{2k} A^t \Omega A$ term when expanding, to get $$ \Omega + p^k A^t \Omega + p^k \Omega A \equiv \Omega \pmod {p^{k+1}}$$ By subtracting $\Omega$ from both sides, we get the conditions I mentioned on the blocks in $A$. As you mentioned, this coincides with the symplectic Lie algebra condition. George McNinch gave an elegant explanation in the comments, but a possibly more pedestrian reason is that $(p^k)$ is a square zero ideal in $\mathbb{Z}/p^{k+1}\mathbb{Z}$, so one has a canonical isomorphism between the kernel of reduction and the Lie algebra tensored with the quotient ring.
From L. C. Grove's *Classical Groups and Geometric Algebra,* page 27: $$|\operatorname{SP}(2n,\mathbb{F}\_q)|=q^{n^2}\prod\_{i=1}^n(q^{2i}-1),$$ for some $q=p^k$. This works in the case of $\mathbb{F}\_p\cong\mathbb{Z}/p\mathbb{Z}$, but I don't think it's helpful for the general case $\mathbb{Z}/q\mathbb{Z}$.
87,904
Is there a formula for the size of Symplectic group defined over a finite ring $Z/p^k Z$?
2012/02/08
[ "https://mathoverflow.net/questions/87904", "https://mathoverflow.net", "https://mathoverflow.net/users/21237/" ]
From Christopher Perez's answer, we have $|Sp\_{2n}(\mathbb{Z}/p\mathbb{Z})| = p^{n^2} \prod\_{i=1}^n (p^{2i}-1)$. Following Johannes Hahn, we wish to determine the size of the kernel of the homomorphism $Sp\_{2n}(\mathbb{Z}/p^k\mathbb{Z}) \to Sp\_{2n}(\mathbb{Z}/p\mathbb{Z})$. To compute this, we may induct on $k$: For $k \geq 1$, elements in the kernel of the homomorphism $Sp\_{2n}(\mathbb{Z}/p^{k+1}\mathbb{Z}) \to Sp\_{2n}(\mathbb{Z}/p^k\mathbb{Z})$ have the form $I + p^k A$ for a matrix $A = \left( \begin{smallmatrix} E & F \\ G & H \end{smallmatrix} \right)$ with values in $\mathbb{Z}/p\mathbb{Z}$. The symplectic condition (given in [Wikipedia](http://en.wikipedia.org/wiki/Symplectic_matrix)) is equivalent to the conditions that $F^t = F$, $G^t = G$, and $E^t + H = 0$. $F$ and $G$ are therefore symmetric matrices, while $H$ and $E$ determine each other, with no further conditions. The kernel of one-step reduction therefore has size $p^{n(n+1)/2} \cdot p^{n(n+1)/2} \cdot p^{n^2}$, or $p^{2n^2 + n}$. The final answer is therefore: $|Sp\_{2n}(\mathbb{Z}/p^k\mathbb{Z})| = p^{(2k-1)n^2 + (k-1)n} \prod\_{i=1}^n (p^{2i}-1)$ **Edit:** To address kassabov's complaint, I'll explain the calculation in a bit more detail. The symplectic condition on $I + p^k A$ is that $(I + p^k A)^t \Omega (I + p^k A) \equiv \Omega \pmod {p^{k+1}}$, where $\Omega = \left( \begin{smallmatrix} 0 & I\_n \\ -I\_n & 0 \end{smallmatrix} \right)$. Because $k \geq 1$, we may eliminate the $p^{2k} A^t \Omega A$ term when expanding, to get $$ \Omega + p^k A^t \Omega + p^k \Omega A \equiv \Omega \pmod {p^{k+1}}$$ By subtracting $\Omega$ from both sides, we get the conditions I mentioned on the blocks in $A$. As you mentioned, this coincides with the symplectic Lie algebra condition. George McNinch gave an elegant explanation in the comments, but a possibly more pedestrian reason is that $(p^k)$ is a square zero ideal in $\mathbb{Z}/p^{k+1}\mathbb{Z}$, so one has a canonical isomorphism between the kernel of reduction and the Lie algebra tensored with the quotient ring.
Hi. EDIT: As Joe Silverman pointed out, this approach doesn't work as simple as I imagined it. Sorry for that. I leave the attempted proof here in case someone has an idea how to fix it. Yes, there is such a formula. It works for in a similar fashion all of the classical algebraic group. Consider the projection $\mathbb{Z}/p^k\to\mathbb{Z}/p$. It induces a surjection $Sp\_{2n}(\mathbb{Z}/p^k)\to Sp\_{2n}(\mathbb{Z}/p)$ because every transvection has a preimage and the transvections generate $Sp\_{2n}(F)$ for every field $F$. The kernel of the homomorphism consists obviously of those matrices $M$ with $M-I \in (p\mathbb{Z}/p^k\mathbb{Z})^{n\times n}$. There are $p^{(k-1)n^2}$ such matrices. Therefore $|Sp\_{2n}(\mathbb{Z}/p^k)| = p^{(k-1)n^2} |Sp\_{2n}(\mathbb{Z}/p)|$. The order of the symplectic group over $\mathbb{Z}/p$ is known.
1,887,374
Let's say we have an arbitrary complex number $z \in \mathbb{C}$ , $z = x+iy$ Then the absolute value (or magnitude/norm of $z$) is defined as follows. $$|z| \stackrel{\text{def}}{=} \sqrt{x^2 + y^2}$$ But to me it seems a bit hand wavy as that is exactly the magnitude of a vector in $\mathbb{R^2}$ e.g $||\vec{a}|| = \sqrt{(a\_1, a\_2) \bullet (a\_1, a\_2)} = \sqrt{a\_{1}^{2} + a\_2^2}$ I asked a question earlier if it was possible to write a complex number as a vector in $\mathbb{R}^2$ : [Writing Complex Numbers as a Vector in $\mathbb{R^2}$](https://math.stackexchange.com/questions/1886864/writing-complex-numbers-as-a-vector-in-mathbbr2), and the answer was yes, as $\mathbb{C}$ is isomorphic to $\mathbb{R^2}$, however one has to be careful with how you choose to write it. Am I correct in saying that you can describe a point in the complex plane as a 2-tuple $(x, iy)$ over $\mathbb{R^2}$ but only as a one tuple, a scalar $x+ iy$ over $\mathbb{C}$. i.e. $\mathbb{C}$ is one-dimensional with respect to itself, but two-dimensional with respect to $\mathbb{R}$. I ask this as there may be a misinterpretation on my part. I've included this image here to illustrate my point. [![enter image description here](https://i.stack.imgur.com/Ypgld.png)](https://i.stack.imgur.com/Ypgld.png) To find the absolute value (the magnitude) of $|z|$, **if** $z = (x, iy)$ (a 2-tuple over $\mathbb{R}$, or a point in $\mathbb{R^2}$), then wouldn't the absolute value be, by the Theorem of Pythagoras (or via the square root of the dot-product with itself) $$|z| \stackrel{\text{def}}{=} \sqrt{x^2 + i^2y^2} \implies |z| \stackrel{\text{def}}{=} \sqrt{x^2 - y^2}$$ Now this can't be right, so my question boils down to: **Why is the $i$ just dropped in the definition of the absolute value of $|z|$?** We certainly can't use the Theorem of Pythagoras over $\mathbb{C}$ as $\mathbb{C}$ is one-dimensional with respect to itself, so we must be using the Theorem of Pythagoras over $\mathbb{R^2}$, and in that case one of the basis vectors must be $(0, i)$, correct? (i.e it must contain the Imaginary Axis for $\mathbb{R^2} = \mathbb{C}$) If I'm totally off the ball here, please tell me as it seems I'm having trouble making the connection between $\mathbb{R^2}$ and $\mathbb{C}$. I've included extra information in my question so that you can see where I'm coming from when I make the arguments I'm trying to make.
2016/08/09
[ "https://math.stackexchange.com/questions/1887374", "https://math.stackexchange.com", "https://math.stackexchange.com/users/266135/" ]
The standard inner product of two complex numbers $z\_1,z\_2 \in \mathbb{C}$ is defined to be $z\_1\bar{z\_2}$, so the norm it induces will be $||z\_1||:=\sqrt{z\_1z\_1}=\sqrt{z\_1\bar{z\_1}}=\sqrt{(a+bi)(a-bi)}=\sqrt{a^2+b^2}$. As a vector space over $\mathbb{R}$ (which it is almost never considered to be in practice), $\mathbb{C}$ has dimension two and thus is isomorphic to $\mathbb{R}^2$, the standard basis might be chosen to be $\{(1,0), (0,i)\}$ where we represent a number $z=a+bi$. The canonical isomorphic then sends $(1,0) \to (1,0)$ and $(0,i) \to (0,1)$, thus if you take a vector in $\mathbb{C}$, say $z=a+bi$, and "transport" it to $\mathbb{R^2}$ to investigate its norm in that inner product space (where the inner product is defined to be $(x\_1,y\_1)(x\_2,y\_2)=x\_1x\_2+y\_1y\_2$), we have $z=a+bi=a(1,0)+b(0,i)$, apply the canonical isomorphism and we get $a+bi$ is transported to $(a,b)$, (and *not* (a,bi)!), so the inner product here is different, there being no conjugation in the second coordinate, but that's fine because we're dropped the $i$ anyways by moving to $\mathbb{R^2}$. Pythagoras is fine. One further comment: viewing $\mathbb{C}$ as a two-dimensional vector space over $\mathbb{R}$ is convenient merely for visualizing the complex plane, not for investigating its properties as a vector space, consider the following excerpt from Rudin's *Functional Analysis*: [![enter image description here](https://i.stack.imgur.com/xh8xf.png)](https://i.stack.imgur.com/xh8xf.png)
Complex numbers $z=x+i\*y$ are viewed as "a 2-tuple over $\mathbb{R}$" as you put but you made a mistake there which carried throughout your post. You say $z=(x,iy)$ but this is not a tuple over $\mathbb{R}$ because $i$ is not a real number. The correct way would be to say that $z=x+iy=(x,y)$. To answer your bolded question, why $i$ is dropped in the definition of $|z|$, is because $y$ is the length in the "imaginary" direction. If we look at the nice image that you posted, think about those 2 vectors in the image as vectors from the origin to the point $(x,y)=x+iy=z$ and to the point $(x,-y)=x-iy =\bar{z}$. Then the magnitude of a vector from the point $(0,0)$ to the point $(x,y)$ is defined by the Pythagorean Theorem as you mentioned, which would be $\sqrt{x^2+y^2}=|z|$.
1,887,374
Let's say we have an arbitrary complex number $z \in \mathbb{C}$ , $z = x+iy$ Then the absolute value (or magnitude/norm of $z$) is defined as follows. $$|z| \stackrel{\text{def}}{=} \sqrt{x^2 + y^2}$$ But to me it seems a bit hand wavy as that is exactly the magnitude of a vector in $\mathbb{R^2}$ e.g $||\vec{a}|| = \sqrt{(a\_1, a\_2) \bullet (a\_1, a\_2)} = \sqrt{a\_{1}^{2} + a\_2^2}$ I asked a question earlier if it was possible to write a complex number as a vector in $\mathbb{R}^2$ : [Writing Complex Numbers as a Vector in $\mathbb{R^2}$](https://math.stackexchange.com/questions/1886864/writing-complex-numbers-as-a-vector-in-mathbbr2), and the answer was yes, as $\mathbb{C}$ is isomorphic to $\mathbb{R^2}$, however one has to be careful with how you choose to write it. Am I correct in saying that you can describe a point in the complex plane as a 2-tuple $(x, iy)$ over $\mathbb{R^2}$ but only as a one tuple, a scalar $x+ iy$ over $\mathbb{C}$. i.e. $\mathbb{C}$ is one-dimensional with respect to itself, but two-dimensional with respect to $\mathbb{R}$. I ask this as there may be a misinterpretation on my part. I've included this image here to illustrate my point. [![enter image description here](https://i.stack.imgur.com/Ypgld.png)](https://i.stack.imgur.com/Ypgld.png) To find the absolute value (the magnitude) of $|z|$, **if** $z = (x, iy)$ (a 2-tuple over $\mathbb{R}$, or a point in $\mathbb{R^2}$), then wouldn't the absolute value be, by the Theorem of Pythagoras (or via the square root of the dot-product with itself) $$|z| \stackrel{\text{def}}{=} \sqrt{x^2 + i^2y^2} \implies |z| \stackrel{\text{def}}{=} \sqrt{x^2 - y^2}$$ Now this can't be right, so my question boils down to: **Why is the $i$ just dropped in the definition of the absolute value of $|z|$?** We certainly can't use the Theorem of Pythagoras over $\mathbb{C}$ as $\mathbb{C}$ is one-dimensional with respect to itself, so we must be using the Theorem of Pythagoras over $\mathbb{R^2}$, and in that case one of the basis vectors must be $(0, i)$, correct? (i.e it must contain the Imaginary Axis for $\mathbb{R^2} = \mathbb{C}$) If I'm totally off the ball here, please tell me as it seems I'm having trouble making the connection between $\mathbb{R^2}$ and $\mathbb{C}$. I've included extra information in my question so that you can see where I'm coming from when I make the arguments I'm trying to make.
2016/08/09
[ "https://math.stackexchange.com/questions/1887374", "https://math.stackexchange.com", "https://math.stackexchange.com/users/266135/" ]
Complex numbers $z=x+i\*y$ are viewed as "a 2-tuple over $\mathbb{R}$" as you put but you made a mistake there which carried throughout your post. You say $z=(x,iy)$ but this is not a tuple over $\mathbb{R}$ because $i$ is not a real number. The correct way would be to say that $z=x+iy=(x,y)$. To answer your bolded question, why $i$ is dropped in the definition of $|z|$, is because $y$ is the length in the "imaginary" direction. If we look at the nice image that you posted, think about those 2 vectors in the image as vectors from the origin to the point $(x,y)=x+iy=z$ and to the point $(x,-y)=x-iy =\bar{z}$. Then the magnitude of a vector from the point $(0,0)$ to the point $(x,y)$ is defined by the Pythagorean Theorem as you mentioned, which would be $\sqrt{x^2+y^2}=|z|$.
When $\mathbb{C}$ is identified with $\mathbb{R}^2$, we usually identify the number $1$ in $\mathbb{C}$ with the vector $(1, 0)$ in $\mathbb{R}^2$, and the number $i$ in $\mathbb{C}$ with the vector $(0, 1)$ in $\mathbb{R}^2$. Then, $x + yi = (x, y) = x(1, 0) + y(0, 1)$, so the coordinates of $x + yi$ w.r.t. the standard basis $\{(1, 0), (0, 1)\}$ of $\mathbb{R}^2$ are $(x, y)$ - and not $(x, iy)$, as you wrote, which would be impossible anyway because coordinates of a vector in $\mathbb{R}^2$ must be real.
1,887,374
Let's say we have an arbitrary complex number $z \in \mathbb{C}$ , $z = x+iy$ Then the absolute value (or magnitude/norm of $z$) is defined as follows. $$|z| \stackrel{\text{def}}{=} \sqrt{x^2 + y^2}$$ But to me it seems a bit hand wavy as that is exactly the magnitude of a vector in $\mathbb{R^2}$ e.g $||\vec{a}|| = \sqrt{(a\_1, a\_2) \bullet (a\_1, a\_2)} = \sqrt{a\_{1}^{2} + a\_2^2}$ I asked a question earlier if it was possible to write a complex number as a vector in $\mathbb{R}^2$ : [Writing Complex Numbers as a Vector in $\mathbb{R^2}$](https://math.stackexchange.com/questions/1886864/writing-complex-numbers-as-a-vector-in-mathbbr2), and the answer was yes, as $\mathbb{C}$ is isomorphic to $\mathbb{R^2}$, however one has to be careful with how you choose to write it. Am I correct in saying that you can describe a point in the complex plane as a 2-tuple $(x, iy)$ over $\mathbb{R^2}$ but only as a one tuple, a scalar $x+ iy$ over $\mathbb{C}$. i.e. $\mathbb{C}$ is one-dimensional with respect to itself, but two-dimensional with respect to $\mathbb{R}$. I ask this as there may be a misinterpretation on my part. I've included this image here to illustrate my point. [![enter image description here](https://i.stack.imgur.com/Ypgld.png)](https://i.stack.imgur.com/Ypgld.png) To find the absolute value (the magnitude) of $|z|$, **if** $z = (x, iy)$ (a 2-tuple over $\mathbb{R}$, or a point in $\mathbb{R^2}$), then wouldn't the absolute value be, by the Theorem of Pythagoras (or via the square root of the dot-product with itself) $$|z| \stackrel{\text{def}}{=} \sqrt{x^2 + i^2y^2} \implies |z| \stackrel{\text{def}}{=} \sqrt{x^2 - y^2}$$ Now this can't be right, so my question boils down to: **Why is the $i$ just dropped in the definition of the absolute value of $|z|$?** We certainly can't use the Theorem of Pythagoras over $\mathbb{C}$ as $\mathbb{C}$ is one-dimensional with respect to itself, so we must be using the Theorem of Pythagoras over $\mathbb{R^2}$, and in that case one of the basis vectors must be $(0, i)$, correct? (i.e it must contain the Imaginary Axis for $\mathbb{R^2} = \mathbb{C}$) If I'm totally off the ball here, please tell me as it seems I'm having trouble making the connection between $\mathbb{R^2}$ and $\mathbb{C}$. I've included extra information in my question so that you can see where I'm coming from when I make the arguments I'm trying to make.
2016/08/09
[ "https://math.stackexchange.com/questions/1887374", "https://math.stackexchange.com", "https://math.stackexchange.com/users/266135/" ]
The standard inner product of two complex numbers $z\_1,z\_2 \in \mathbb{C}$ is defined to be $z\_1\bar{z\_2}$, so the norm it induces will be $||z\_1||:=\sqrt{z\_1z\_1}=\sqrt{z\_1\bar{z\_1}}=\sqrt{(a+bi)(a-bi)}=\sqrt{a^2+b^2}$. As a vector space over $\mathbb{R}$ (which it is almost never considered to be in practice), $\mathbb{C}$ has dimension two and thus is isomorphic to $\mathbb{R}^2$, the standard basis might be chosen to be $\{(1,0), (0,i)\}$ where we represent a number $z=a+bi$. The canonical isomorphic then sends $(1,0) \to (1,0)$ and $(0,i) \to (0,1)$, thus if you take a vector in $\mathbb{C}$, say $z=a+bi$, and "transport" it to $\mathbb{R^2}$ to investigate its norm in that inner product space (where the inner product is defined to be $(x\_1,y\_1)(x\_2,y\_2)=x\_1x\_2+y\_1y\_2$), we have $z=a+bi=a(1,0)+b(0,i)$, apply the canonical isomorphism and we get $a+bi$ is transported to $(a,b)$, (and *not* (a,bi)!), so the inner product here is different, there being no conjugation in the second coordinate, but that's fine because we're dropped the $i$ anyways by moving to $\mathbb{R^2}$. Pythagoras is fine. One further comment: viewing $\mathbb{C}$ as a two-dimensional vector space over $\mathbb{R}$ is convenient merely for visualizing the complex plane, not for investigating its properties as a vector space, consider the following excerpt from Rudin's *Functional Analysis*: [![enter image description here](https://i.stack.imgur.com/xh8xf.png)](https://i.stack.imgur.com/xh8xf.png)
When $\mathbb{C}$ is identified with $\mathbb{R}^2$, we usually identify the number $1$ in $\mathbb{C}$ with the vector $(1, 0)$ in $\mathbb{R}^2$, and the number $i$ in $\mathbb{C}$ with the vector $(0, 1)$ in $\mathbb{R}^2$. Then, $x + yi = (x, y) = x(1, 0) + y(0, 1)$, so the coordinates of $x + yi$ w.r.t. the standard basis $\{(1, 0), (0, 1)\}$ of $\mathbb{R}^2$ are $(x, y)$ - and not $(x, iy)$, as you wrote, which would be impossible anyway because coordinates of a vector in $\mathbb{R}^2$ must be real.
23,145,872
having trouble implementing this bxslider slider. first things first, the images are all visible? how do i make this look like an actual slider? you can see the issue live here; <http://danielmdesigns.com/windermere/index.html> otherwise, i've done exactly what the website told me to =/ JS Script ``` <!-- jQuery library (served from Google) --> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script> <!-- bxSlider Javascript file --> <script src="/js/jquery.bxslider.min.js"></script> <!-- bxSlider CSS file --> <link href="/lib/jquery.bxslider.css" rel="stylesheet" /> <script src="bxslider.js" type="text/javascript"></script> ``` HTML ``` <ul class="bxslider"> <li><img src="images/Couple%20on%20Lounge%20Chair_Towneclub.jpg" /></li> <li><img src="images/Man%20on%20Bench_Towneclub.jpg" /></li> <li><img src="images/Picnic%20Couple_Towneclub.jpg" /></li> <li><img src="images/Small%20Golf_Towneclub.jpg" /></li> </ul> ``` CSS ``` .bxslider{ height:600px; width:auto; background-color:#c41230; /*background-image: url(images/imagescroll_1.png);*/ background-size:cover; position:relative; top:95px; } ``` JS file ``` $(document).ready(function(){ $('.bxslider').bxSlider(); }); ``` I am an amateur, but all help is very appreciated. Thanks in advance.
2014/04/18
[ "https://Stackoverflow.com/questions/23145872", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3475867/" ]
The exact complexity of this algorithm is O(⌊sqrt(num)⌋-1) This is number of checks ((num % ArrayOfPrimes[i]) == 0) condition. In case number 19 this algorithm will 3 checks: 2, 3, 4
The get the exact complexity, you have to know the number of entrys in `ArrayOfPrimes` that are smaller than `sqrt(num)`. The worst case is, that you have to check all of them. So if `pi(sqrt(num))` is the [number of primes](http://en.wikipedia.org/wiki/Prime_number_theorem#Statement_of_the_theorem) lower than `sqrt(num)` the complexity is ``` O(pi(sqrt(num))) = O(sqrt(num) / log(num)) ```
37,240,904
I changed my php version into `5.6` but when i run `composer update` it still thinks I am using 5.4 version. The version of my server is `5.4` but I changed my project directory php version in to `5.6`. I changed that one via cpanel php configuration. Here's the screenshot: [![enter image description here](https://i.stack.imgur.com/ad3pp.png)](https://i.stack.imgur.com/ad3pp.png) As you can see i changed my project directory php version in to 5.6, but when i run composer update, it still thinks that i am using 5.4 version. I also tried adding this in my composer.json: ``` "platform": { "php": "5.5.9" } ``` And when I run composer update, it installs some dependencies except for the last one..it is giving me this error: ``` Generating autoload files > Illuminate\Foundation\ComposerScripts::postUpdate Parse error: syntax error, unexpected 'class' (T_CLASS), expecting identifier (T_STRING) or variable (T_VARIABLE) or '{' or '$' in /home3/idmadm/public_html/app/vendor/laravel/framework/src/Illuminate/Foundation/helpers.php on line 146 ``` When I checked line 146 of helpers.php, this is the code: ``` function auth($guard = null) { if (is_null($guard)) { return app(AuthFactory::class); //THIS IS THE CODE!! } else { return app(AuthFactory::class)->guard($guard); } } ``` I researched about that error and some said it's because of my PHP Version. I guess Laravel still think that my PHP Version is 5.4 where in fact, i changed it into 5.6. How can i let Laravel know that I am using PHP Version 5.6. Any help please! Your help will be greatly appreciated and rewarded! Thanks! :) PS: The reason why I am changing PHP version in the directory because some websites that are hosted in my server do not support PHP 5.5+.
2016/05/15
[ "https://Stackoverflow.com/questions/37240904", "https://Stackoverflow.com", "https://Stackoverflow.com/users/822465/" ]
You are declaring a "no match" too soon: you need to walk the whole list before adding a new subject. Your program tries the first subject, and if ut does not match, it adds a subject, and moves on. Unfortunately, it does not break, so it keeps adding the same subject for each existing one that does not match. In order to fix this problem make a boolean variable called "found", set it to false before the loop, and search for matches. Once a match is found, set the variable to true, and break. After the loop check your variable. If it's true, do not add, and say that you found a duplicate. Otherwise, add the new subject.
in your case, you can not check for 'contains' you have to manually check every entry if its the same. override the equal() function of your Subject: ``` public boolean equal(Object o){ Subject b = (Subject) o; return (this.name.equal(b.name) && this.code.equal(b.code)); } ``` then in your loop: ``` boolean found = false; for(Subject s : subjectList){ if(s.equal(newSubject)){ found = true; break; } } if(!found) //add new entry ```
37,240,904
I changed my php version into `5.6` but when i run `composer update` it still thinks I am using 5.4 version. The version of my server is `5.4` but I changed my project directory php version in to `5.6`. I changed that one via cpanel php configuration. Here's the screenshot: [![enter image description here](https://i.stack.imgur.com/ad3pp.png)](https://i.stack.imgur.com/ad3pp.png) As you can see i changed my project directory php version in to 5.6, but when i run composer update, it still thinks that i am using 5.4 version. I also tried adding this in my composer.json: ``` "platform": { "php": "5.5.9" } ``` And when I run composer update, it installs some dependencies except for the last one..it is giving me this error: ``` Generating autoload files > Illuminate\Foundation\ComposerScripts::postUpdate Parse error: syntax error, unexpected 'class' (T_CLASS), expecting identifier (T_STRING) or variable (T_VARIABLE) or '{' or '$' in /home3/idmadm/public_html/app/vendor/laravel/framework/src/Illuminate/Foundation/helpers.php on line 146 ``` When I checked line 146 of helpers.php, this is the code: ``` function auth($guard = null) { if (is_null($guard)) { return app(AuthFactory::class); //THIS IS THE CODE!! } else { return app(AuthFactory::class)->guard($guard); } } ``` I researched about that error and some said it's because of my PHP Version. I guess Laravel still think that my PHP Version is 5.4 where in fact, i changed it into 5.6. How can i let Laravel know that I am using PHP Version 5.6. Any help please! Your help will be greatly appreciated and rewarded! Thanks! :) PS: The reason why I am changing PHP version in the directory because some websites that are hosted in my server do not support PHP 5.5+.
2016/05/15
[ "https://Stackoverflow.com/questions/37240904", "https://Stackoverflow.com", "https://Stackoverflow.com/users/822465/" ]
You are declaring a "no match" too soon: you need to walk the whole list before adding a new subject. Your program tries the first subject, and if ut does not match, it adds a subject, and moves on. Unfortunately, it does not break, so it keeps adding the same subject for each existing one that does not match. In order to fix this problem make a boolean variable called "found", set it to false before the loop, and search for matches. Once a match is found, set the variable to true, and break. After the loop check your variable. If it's true, do not add, and say that you found a duplicate. Otherwise, add the new subject.
If `Subject` implements `equals()`, then create the object and call `subjectList.contains(subject)`. Better yet, implement `hashCode()` too and change the `ArrayList` to a `HashSet` (or `LinkedHashSet` if order is important) for better performance. Otherwise, search like this (using `equals()`, not `contains()`, for string comparison): ``` boolean found = false; for (Subject subject : subjectList) if (subject.getName().equals(newGetName) && subject.getSubjectCode().equals(newSubjectCode)) { found = true; break; } if (found) System.out.println("We have a match "); else subjectList.add(new Subject(newGetName, newSubjectCode)); ```
13,596,449
Good day, I'm currently new in working with databases. I downloaded an application called MySql Worckbench 5.2 CE because I saw that it has an easy way of creating and accessing databases. I'm now in the process of exporting the .sql. Whenever I go to the export tab which looks like this: ![enter image description here](https://i.stack.imgur.com/QmKDS.png) After I click on Start Export, it gives me this error: ![enter image description here](https://i.stack.imgur.com/DToSu.png) I'm not sure what the error is cause I'm not familiar with MySql dump.. is there a way to resolve this? or use an alternative way. I'm also not familiar with using mysql from cmd (Windows) but if there is any suggestion or steps I can follow, it would be a great help.
2012/11/28
[ "https://Stackoverflow.com/questions/13596449", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1557464/" ]
A couple of tips to help make routing less confusing. It can be a bit unnerving to get used to. **Routing Rule #1** Always check the output of `rake routes` to be sure how to call your various routing methods. You might *think* you know how your routes will play out by looking at `routes.rb` but you won't *know* until you look at the compiled routes table. In your case you're expecting a route with the format: ``` /projects/:project_id/lists/:list_id/tasks/:id ``` Be sure that's the case. If it is, your call should look like: ``` project_list_task_path(@project, @list, task) ``` Note that the arguments here are `:project_id`, `:list_id` and `:id`, so all three are required in this case. Any in brackets in the path specification can be ignored, like `:format` usually is. **Routing Rule #2** Use the `_path` methods unless you strictly require the full URL. They're shorter and the output is easier to read and debug. They also don't inadvertently flip the URL in the browser and cause session problems if you don't properly differentiate between `www.mysite.com` and `site.com`. **Routing Rule #3** Don't forget there's a *huge* difference between `@project` and `@project.id` when it's supplied to a routing path method. The router will always call the `to_param` method if it's available and this can be over-ridden in your model to produce pretty or friendly URLs. `id` is for your database and your database alone. `to_param` is for routing but you shouldn't be calling it manually unless you're doing something exceptionally irregular.
You generally should not nest resources [more than one level deep](http://weblog.jamisbuck.org/2007/2/5/nesting-resources), but putting that aside, the `link_to` format should be: ``` link_to task.description, project_list_task_path(@project, @list, task) ``` i.e. `project_link_tasks_url` should be `project_link_task_url`, and you have to pass the `@project` as the first argument (I'm assuming that your project is named `@project`). I've switched `_url` to `_path` so you can just pass the objects themselves as arguments rather than their ids. See the [documentation on creating paths and URLs from objects](http://guides.rubyonrails.org/routing.html#nested-resources#creating-paths-and-urls-from-objects) for details.
60,728,260
I know, that using gets() is a very bad idea as it may lead to buffer overflow. But I have some queries. Suppose a c program has the following code- ``` char word[6]; gets(word); puts(word); ``` If I input for example - `HELLO WORLD`, is it correct to assume that `gets()` reads it as `[H] [E] [L] [L] [O] [ ]`, and the rest goes into the input buffer ? If that happens than, how does `puts()` get the data to display the complete string ?
2020/03/17
[ "https://Stackoverflow.com/questions/60728260", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11687739/" ]
This is the exact problem with `gets`; it *will not* stop once it reads 6 characters, it will keep reading until it sees a newline character and assign those characters to the memory immediately following the end of the `word` buffer. This is what a buffer overflow *is*. If there isn't anything *important* for several bytes after the `word` buffer (like the return address for the stack frame, or another local variable), then overwriting that memory doesn't cause *obvious* problems, and `puts` will do pretty much the same thing - read from `word` *and the memory following it* until it sees the string terminator.
No, it is not correct to assume it just stops when it runs out space; it doesn't know how much space is available. `gets` just keeps reading in characters and writing into neighboring memory, invoking undefined behavior. You may get lucky, and that neighboring memory isn't used (before or after the `gets`), and `puts` "just works". Or it may overwrite your stack pointer, and everything explodes. Or it may write the buffer correctly, but bits of the buffer get overwritten before `puts` gets there. Or anything else; it's undefined behavior. Don't do this. Never use `gets`.
60,728,260
I know, that using gets() is a very bad idea as it may lead to buffer overflow. But I have some queries. Suppose a c program has the following code- ``` char word[6]; gets(word); puts(word); ``` If I input for example - `HELLO WORLD`, is it correct to assume that `gets()` reads it as `[H] [E] [L] [L] [O] [ ]`, and the rest goes into the input buffer ? If that happens than, how does `puts()` get the data to display the complete string ?
2020/03/17
[ "https://Stackoverflow.com/questions/60728260", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11687739/" ]
This is the exact problem with `gets`; it *will not* stop once it reads 6 characters, it will keep reading until it sees a newline character and assign those characters to the memory immediately following the end of the `word` buffer. This is what a buffer overflow *is*. If there isn't anything *important* for several bytes after the `word` buffer (like the return address for the stack frame, or another local variable), then overwriting that memory doesn't cause *obvious* problems, and `puts` will do pretty much the same thing - read from `word` *and the memory following it* until it sees the string terminator.
The `gets` function reads a full line at a time. So in your example it would attempt to read "HELLO WORLD" which is 11 characters into a buffer that is only 6 characters wide. This overflows the buffer causing [undefined behavior](https://en.wikipedia.org/wiki/Undefined_behavior). And because `gets` has no way to limit how many characters it can read, this makes it dangerous which is why it was removed from the C11 standard.
60,728,260
I know, that using gets() is a very bad idea as it may lead to buffer overflow. But I have some queries. Suppose a c program has the following code- ``` char word[6]; gets(word); puts(word); ``` If I input for example - `HELLO WORLD`, is it correct to assume that `gets()` reads it as `[H] [E] [L] [L] [O] [ ]`, and the rest goes into the input buffer ? If that happens than, how does `puts()` get the data to display the complete string ?
2020/03/17
[ "https://Stackoverflow.com/questions/60728260", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11687739/" ]
This is the exact problem with `gets`; it *will not* stop once it reads 6 characters, it will keep reading until it sees a newline character and assign those characters to the memory immediately following the end of the `word` buffer. This is what a buffer overflow *is*. If there isn't anything *important* for several bytes after the `word` buffer (like the return address for the stack frame, or another local variable), then overwriting that memory doesn't cause *obvious* problems, and `puts` will do pretty much the same thing - read from `word` *and the memory following it* until it sees the string terminator.
> > is it correct to assume that gets() reads it as [H] [E] [L] [L] [O] [ ], and the rest goes into the input buffer ? > > > No. It is *undefined behavior* to attempt to overfill the buffer `word[]`. Anything may happen. Rest of code is irrelevant. Nothing is specified about the contents of the buffer when this happens.
60,728,260
I know, that using gets() is a very bad idea as it may lead to buffer overflow. But I have some queries. Suppose a c program has the following code- ``` char word[6]; gets(word); puts(word); ``` If I input for example - `HELLO WORLD`, is it correct to assume that `gets()` reads it as `[H] [E] [L] [L] [O] [ ]`, and the rest goes into the input buffer ? If that happens than, how does `puts()` get the data to display the complete string ?
2020/03/17
[ "https://Stackoverflow.com/questions/60728260", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11687739/" ]
This is the exact problem with `gets`; it *will not* stop once it reads 6 characters, it will keep reading until it sees a newline character and assign those characters to the memory immediately following the end of the `word` buffer. This is what a buffer overflow *is*. If there isn't anything *important* for several bytes after the `word` buffer (like the return address for the stack frame, or another local variable), then overwriting that memory doesn't cause *obvious* problems, and `puts` will do pretty much the same thing - read from `word` *and the memory following it* until it sees the string terminator.
Your question suggests you think `gets` might somehow know that `word` is only 6 characters long, so it fills it with just 6 characters and leaves the rest in the buffer associated with the input stream. That is not the case. The call `gets(word)` passes **only** the start address of `word` to `gets`. That is all it receives—a starting location. It does not receive any information about length. `gets` reads from the input stream until a new-line character is read or an end-of-file is encountered or an error occurs. If you entered “HELLO WORLD”, and the program printed that, it is because `gets` read the data and wrote it into memory, exceeding the bounds of `word`. There is not any fancy buffering or interaction occurring—gets just wrote over memory that was not assigned for that purpose. It could have broken something in your program. But it appears you got “lucky” in that the error did not immediately break your program, and the data sat there until `puts` could read it from memory and write it to output. However, you should never expect that behavior. One reason that worked the way it did is you have a very simple program that did not do anything else with memory. In more complicated programs, where there are many objects and activities, it is more likely that overrunning a buffer will break the program in a variety of ways.
44,953,922
I am trying to do a search on my MySQL database to get the row that contains the most similar value to the one searched for. Even if the closest result is very different, I'd still like to return it (Later on I do a string comparison and add the 'unknown' into the learning pool) I would like to search my table 'responses' via the 'msg1' column and get one result, the one with the lowest levenshtein score, as in the one that is the most similar out of the whole column. This sort of thing: ``` SELECT * FROM people WHERE levenshtein('$message', 'msg1') ORDER BY ??? LIMIT 1 ``` I don't quite grasp the concept of levenshtein here, as you can see I am searching the whole table, sorting it by ??? (the function's score?) and then limiting it to one result. I'd then like to set $reply to the value in column "reply" from this singular row that I get. Help would be greatly appreciated, I can't find many examples of what I'm looking for. I may be doing this completely wrong, I'm not sure. Thank you!
2017/07/06
[ "https://Stackoverflow.com/questions/44953922", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7286275/" ]
You would do: ``` SELECT p.* FROM people p ORDER BY levenshtein('$message', msg1) ASC LIMIT 1; ``` If you want a threshold (to limit the number of rows for sorting, then use a `WHERE` clause. Otherwise, you just need `ORDER BY`.
Try this ``` SELECT * FROM people WHERE levenshtein('$message', 'msg1') <= 0 ```
75,998
Ok, here's the story. I have a server running FTP 'out there' I can connect to it using the admin account, browse files, download files. When I try to upload files, I get 550 Access Denied. I have tried through FileZilla and command line. I have windows firewall turned off (on my machine) I can UPLOAD files from another machine (using the same admin account) on our local network (that means, same public IP) what is the problem? I am running Windows 7, Build 7100 and the other machine on the network is running XP SP3 The thing that gets me though, is that this worked for the last probably 4 months, without a problem, I get back in the office after a weekend today and it won't work...
2009/10/19
[ "https://serverfault.com/questions/75998", "https://serverfault.com", "https://serverfault.com/users/-1/" ]
A common problem I have had with Windows boxes and FTP access, is that the local account I set up to log in via FTP on the target box does not have the "do not expire" checkbox checked. So basically it has expired the FTP account password, and wants it to be changed - but that can only be done manually, not through FTP. That is the default state for new accounts created on the system and it must be changed manually (even the command line option /noexpire does not work on MS Server 2003 and below). That might be your problem. To fix it, someone with admin access on the FTP target server has to login and check the "do not expire" checkbox for your FTP login account. Ron
Looks like you don't have write permission. You may need to contact your system admin. See [this page](http://support.ipswitch.com/kb/WS-20000817-DM02.htm) for a brief explanation.
75,998
Ok, here's the story. I have a server running FTP 'out there' I can connect to it using the admin account, browse files, download files. When I try to upload files, I get 550 Access Denied. I have tried through FileZilla and command line. I have windows firewall turned off (on my machine) I can UPLOAD files from another machine (using the same admin account) on our local network (that means, same public IP) what is the problem? I am running Windows 7, Build 7100 and the other machine on the network is running XP SP3 The thing that gets me though, is that this worked for the last probably 4 months, without a problem, I get back in the office after a weekend today and it won't work...
2009/10/19
[ "https://serverfault.com/questions/75998", "https://serverfault.com", "https://serverfault.com/users/-1/" ]
A common problem I have had with Windows boxes and FTP access, is that the local account I set up to log in via FTP on the target box does not have the "do not expire" checkbox checked. So basically it has expired the FTP account password, and wants it to be changed - but that can only be done manually, not through FTP. That is the default state for new accounts created on the system and it must be changed manually (even the command line option /noexpire does not work on MS Server 2003 and below). That might be your problem. To fix it, someone with admin access on the FTP target server has to login and check the "do not expire" checkbox for your FTP login account. Ron
Sometimes some FTP clients change the default chmod before any uploading. If it's not working from that specific computer BUT with the cliens, that means, it's related to the computer's settings. Try to check the log of the computer, and make sure the firewall is turned off (check that throuh services.msc for instance)
75,998
Ok, here's the story. I have a server running FTP 'out there' I can connect to it using the admin account, browse files, download files. When I try to upload files, I get 550 Access Denied. I have tried through FileZilla and command line. I have windows firewall turned off (on my machine) I can UPLOAD files from another machine (using the same admin account) on our local network (that means, same public IP) what is the problem? I am running Windows 7, Build 7100 and the other machine on the network is running XP SP3 The thing that gets me though, is that this worked for the last probably 4 months, without a problem, I get back in the office after a weekend today and it won't work...
2009/10/19
[ "https://serverfault.com/questions/75998", "https://serverfault.com", "https://serverfault.com/users/-1/" ]
I have experienced a similar problem before like this before, my colleague set me up an account on his FTP server. He could access and upload the FTP server using his laptop and his account from our work ext IP, when I tried using my computer with my account and the same ext IP it wouldn't upload. He tried my account on his laptop and it worked fine. I played about with alot of the settings but I believe that when I changed my network location in Windows 7 to Home as it was set to Public that's when it started working again for me. Again not the exactly the same problem but it obviously has something do with Windows 7
Looks like you don't have write permission. You may need to contact your system admin. See [this page](http://support.ipswitch.com/kb/WS-20000817-DM02.htm) for a brief explanation.
75,998
Ok, here's the story. I have a server running FTP 'out there' I can connect to it using the admin account, browse files, download files. When I try to upload files, I get 550 Access Denied. I have tried through FileZilla and command line. I have windows firewall turned off (on my machine) I can UPLOAD files from another machine (using the same admin account) on our local network (that means, same public IP) what is the problem? I am running Windows 7, Build 7100 and the other machine on the network is running XP SP3 The thing that gets me though, is that this worked for the last probably 4 months, without a problem, I get back in the office after a weekend today and it won't work...
2009/10/19
[ "https://serverfault.com/questions/75998", "https://serverfault.com", "https://serverfault.com/users/-1/" ]
Windows 7 blocks access to active ftp by default. Please check if these steps take care of the issue. Open Services.msc Find Application Layer Gateway Service Select Automatic and start the service. Try accessing the ftp server.
Looks like you don't have write permission. You may need to contact your system admin. See [this page](http://support.ipswitch.com/kb/WS-20000817-DM02.htm) for a brief explanation.
75,998
Ok, here's the story. I have a server running FTP 'out there' I can connect to it using the admin account, browse files, download files. When I try to upload files, I get 550 Access Denied. I have tried through FileZilla and command line. I have windows firewall turned off (on my machine) I can UPLOAD files from another machine (using the same admin account) on our local network (that means, same public IP) what is the problem? I am running Windows 7, Build 7100 and the other machine on the network is running XP SP3 The thing that gets me though, is that this worked for the last probably 4 months, without a problem, I get back in the office after a weekend today and it won't work...
2009/10/19
[ "https://serverfault.com/questions/75998", "https://serverfault.com", "https://serverfault.com/users/-1/" ]
I have experienced a similar problem before like this before, my colleague set me up an account on his FTP server. He could access and upload the FTP server using his laptop and his account from our work ext IP, when I tried using my computer with my account and the same ext IP it wouldn't upload. He tried my account on his laptop and it worked fine. I played about with alot of the settings but I believe that when I changed my network location in Windows 7 to Home as it was set to Public that's when it started working again for me. Again not the exactly the same problem but it obviously has something do with Windows 7
Sometimes some FTP clients change the default chmod before any uploading. If it's not working from that specific computer BUT with the cliens, that means, it's related to the computer's settings. Try to check the log of the computer, and make sure the firewall is turned off (check that throuh services.msc for instance)
75,998
Ok, here's the story. I have a server running FTP 'out there' I can connect to it using the admin account, browse files, download files. When I try to upload files, I get 550 Access Denied. I have tried through FileZilla and command line. I have windows firewall turned off (on my machine) I can UPLOAD files from another machine (using the same admin account) on our local network (that means, same public IP) what is the problem? I am running Windows 7, Build 7100 and the other machine on the network is running XP SP3 The thing that gets me though, is that this worked for the last probably 4 months, without a problem, I get back in the office after a weekend today and it won't work...
2009/10/19
[ "https://serverfault.com/questions/75998", "https://serverfault.com", "https://serverfault.com/users/-1/" ]
Windows 7 blocks access to active ftp by default. Please check if these steps take care of the issue. Open Services.msc Find Application Layer Gateway Service Select Automatic and start the service. Try accessing the ftp server.
Sometimes some FTP clients change the default chmod before any uploading. If it's not working from that specific computer BUT with the cliens, that means, it's related to the computer's settings. Try to check the log of the computer, and make sure the firewall is turned off (check that throuh services.msc for instance)
17,737,104
Hey, it's all about Jquery. I am using two Div and a button, at a time only one div is shown. Suppose these are div: ``` <div id="first"></div> <div id="second"></div> ``` And button is: ``` <input type="button" value="show first" onClick="called a javascript();"/> ``` Only single div is shown i.e. `first` ``` <script> $(document).ready( function() { $("#second").hide(); }); </script> ``` Now on clicking button, I want to hide first div, show second and the `value` of button is changed to show second and if clicked again it revert back to previous state. Thanks in advance
2013/07/19
[ "https://Stackoverflow.com/questions/17737104", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2585973/" ]
Heres' the **[FIDDLE](http://jsfiddle.net/vonDy2791/vN88X/)**. Hope it helps. html ``` <div id="first" style="display:none;">first</div> <div id="second">second</div> <input id="btn" type="button" value="show first" /> ``` script ``` $('#btn').on('click', function () { var $this = $(this); if ($this.val() === 'show first') { $('#first').show(); $('#second').hide(); $this.val('show second'); } else { $('#first').hide(); $('#second').show(); $this.val('show first'); } }); ```
What you are looking for is the [toggle](http://api.jquery.com/toggle/) function from jquery Here's an example on [fiddle](http://jsfiddle.net/gY7Rc/) ``` $(".toggleMe").click(function() { $(".toggleMe").toggle(); }); ```
32,667,075
Is this correct? ``` var headers = new Headers(); headers.append('Accept', 'application/json, application/pdf') ``` I want to accept both json and pdf files.
2015/09/19
[ "https://Stackoverflow.com/questions/32667075", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3949281/" ]
Yes, [it is correct](http://www.w3.org/Protocols/HTTP/HTRQ_Headers.html). Example form w3c: ``` Accept: text/plain, text/html ```
More generally, multiple value headers must be expressable as a comma-separated list, so expressing the values this way is valid. Also valid would be to include multiple `Accept` headers, which the server might optionally compress back into a comma-separated list. From an HTTP RFC: <https://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html> > > Multiple message-header fields with the same field-name MAY be present in a message if and only if the entire field-value for that header field is defined as a comma-separated list [i.e., #(values)]. It MUST be possible to combine the multiple header fields into one "field-name: field-value" pair, without changing the semantics of the message, by appending each subsequent field-value to the first, each separated by a comma. The order in which header fields with the same field-name are received is therefore significant to the interpretation of the combined field value, and thus a proxy MUST NOT change the order of these field values when a message is forwarded. > > >
30,459,682
I would like to implement an Amazon SNS topic which first delivers messages to a SQS queue that is a subscriber on the topic, and then executes an AWS Lambda function that is also a subscriber on the same topic. The Lambda function can then read messages from the SQS queue and process several of them in parallel (hundreds). My question is whether there is any way to guarantee that messages sent to the SNS topic would first be delivered to the SQS queue, and only then to the Lambda function? The purpose of this is to scale to a large number of messages without having to execute the Lambda function separately for every single message.
2015/05/26
[ "https://Stackoverflow.com/questions/30459682", "https://Stackoverflow.com", "https://Stackoverflow.com/users/445202/" ]
What you're looking for is currently not possible with one `SNS Topic`. If you subscribe your `Lambda` to a `SNS Topic` that particular `Lambda` gets executed each time that `SNS Topic` receives a message, in parallel. Solution might be to have two `SNS Topics` and publish messages to the first one and have your `SQS` subscribe to it. After successful submission of messages to this first topic you could send a message to the second `SNS Topic` to execute your `Lambda` to process messages the first `SNS Topic` stored to `SQS`. Another possible solution might be the above, you could just send some periodic message to the second topic to run the subscribed `Lambda`. This would allow you to scale your `Lambda SQS Workers`.
Subscribing both an SQS queue and a Lambda function to an SNS topic is a good way to have your Lambda function process SNS messages with low latency. I've tested this process just now. With every attempt the lambda function is invoked after the SQS message is inserted. I wouldn't expect this to always be the case, but it fixes the latency problem as best I am willing to measure. It's not guaranteed and you will need a CloudWatch scheduled event to pick up any missed messages.
30,459,682
I would like to implement an Amazon SNS topic which first delivers messages to a SQS queue that is a subscriber on the topic, and then executes an AWS Lambda function that is also a subscriber on the same topic. The Lambda function can then read messages from the SQS queue and process several of them in parallel (hundreds). My question is whether there is any way to guarantee that messages sent to the SNS topic would first be delivered to the SQS queue, and only then to the Lambda function? The purpose of this is to scale to a large number of messages without having to execute the Lambda function separately for every single message.
2015/05/26
[ "https://Stackoverflow.com/questions/30459682", "https://Stackoverflow.com", "https://Stackoverflow.com/users/445202/" ]
For this purpose, triggering the lambda could be better and efficient if used from a cloud watch alert. With the cloud watch alert set at a buffer limit on the SQS, that could fire the lambda to start and process the full queue.
Subscribing both an SQS queue and a Lambda function to an SNS topic is a good way to have your Lambda function process SNS messages with low latency. I've tested this process just now. With every attempt the lambda function is invoked after the SQS message is inserted. I wouldn't expect this to always be the case, but it fixes the latency problem as best I am willing to measure. It's not guaranteed and you will need a CloudWatch scheduled event to pick up any missed messages.
6,794,998
Hi I am New to android programming and currently developing an application that uses location manager to get user location and place a marker on a map. i am attempting to use AsyncTask to run the LocationListener and Constantly update the marker when the user location has changed. this is the class i am working on... ``` public class IncidentActivity extends MapActivity{ public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); this.setContentView(R.layout.incidentactivity); mapView = (MapView)findViewById(R.id.mapView); mapView.setBuiltInZoomControls(true); mapView.setTraffic(true); mapController = mapView.getController(); String coordinates[] = {"-26.167004","27.965505"}; double lat = Double.parseDouble(coordinates[0]); double lng = Double.parseDouble(coordinates[1]); geoPoint = new GeoPoint((int)(lat*1E6), (int)(lng*1E6)); mapController.animateTo(geoPoint); mapController.setZoom(16); mapView.invalidate(); new MyLocationAsyncTask().execute(); } private class MyLocationAsyncTask extends AsyncTask<Void, Location, Void> implements LocationListener{ private double latLocation; private Location l; //location management variables to track and maintain user location protected LocationManager locationManager; protected LocationListener locationListener; @Override protected Void doInBackground(Void... arg0) { Looper.prepare(); locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 1, locationListener); this.publishProgress(l); return null; } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); } @Override protected void onProgressUpdate(Location... values) { super.onProgressUpdate(values); } //this method is never executed i dont know why...? public void onLocationChanged(Location location) { if (location != null){ latLocation = location.getLatitude(); Toast.makeText(getBaseContext(), " Your latLocation :" + latLocation, Toast.LENGTH_LONG).show(); //Log.d("Your Location", ""+latLocation); } } public void onProviderDisabled(String provider) { } public void onProviderEnabled(String provider) { // TODO Auto-generated method stub } public void onStatusChanged(String provider, int status, Bundle extras) { // TODO Auto-generated method stub } } } ```
2011/07/22
[ "https://Stackoverflow.com/questions/6794998", "https://Stackoverflow.com", "https://Stackoverflow.com/users/858528/" ]
I've just implemented such `AsyncTask`: ``` class GetPositionTask extends AsyncTask<Void, Void, Location> implements LocationListener { final long TWO_MINUTES = 2*60*1000; private Location location; private LocationManager lm; protected void onPreExecute() { // Configure location manager - I'm using just the network provider in this example lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE); lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, this); nearProgress.setVisibility(View.VISIBLE); } protected Location doInBackground(Void... params) { // Try to use the last known position Location lastLocation = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); // If it's too old, get a new one by location manager if (System.currentTimeMillis() - lastLocation.getTime() > TWO_MINUTES) { while (location == null) try { Thread.sleep(100); } catch (Exception ex) {} return location; } return lastLocation; } protected void onPostExecute(Location location) { nearProgress.setVisibility(View.GONE); lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE); lm.removeUpdates(this); // HERE USE THE LOCATION } @Override public void onLocationChanged(Location newLocation) { location = newLocation; } public void onProviderDisabled(String provider) {} public void onProviderEnabled(String provider) {} public void onStatusChanged(String provider, int status, Bundle extras) {} } ```
From what I have read and tried, you cannot use a looper (which is needed by the locationlistener), inside an ASyncTask. [Click Here](http://www.mail-archive.com/[email protected]/msg62797.html) > > Actually it mean the two threading models are not compatible, so you can't > use these together. Looper expects to to own the thread that you associate > it with, while AsyncTask owns the thread it creates for you to run in the > background. They thus conflict with each other, and can't be used together. > > > Dianne Hackborn suggested using a HandlerThread, but I succeeded in getting mine to work inside of an IntentService. I will admit that my code is still a bit of a hack.