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
28,510,878
On Android, when the selector is touched, the keyboard input appears. I suspect this is because the generated input is of type="text". **How can I prevent this from happening? If the user is choosing from a drop-down list, it does not make sense for the keyboard to appear.** I'm implementing selectize as an Angular module [angular-selectize](https://github.com/machineboy2045/angular-selectize), but I checked with the developer and the issue is not specific to the angular wrapper. Here is my code: ``` <selectize ng-model="filters.min_bedrooms" options="[ {title:'0', id:0}, {title:'1', id:1}, {title:'2', id:2}, ]"> </selectize> ``` Which generates this markup: ``` <input type="text" autocomplete="off" tabindex="" style="width: 4px; opacity: 0; position: absolute; left: -10000px;"> ```
2015/02/14
[ "https://Stackoverflow.com/questions/28510878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1141918/" ]
I had the same issue, where I want the user to select a value but not enter any new values, and the keyboard always shows up when you tap on the dropdown on an iPad. I've solved it by this: ``` $('#myDropDownId').selectize({ create: true, sortField: 'date' }); $(".selectize-input input").attr('readonly','readonly'); ``` Basically what happens is, the input gets focus when you click/tap on the dropdown, and that is what shows the keyboard. By setting readonly to false, the input no longer gets focus. I've tested this on an iPad Mini 2 in Safari and Chrome.
Quoting <http://brianreavis.github.io/selectize.js/>: > > **Selectize** is the hybrid of a textbox and `<select>` box. > > > It is not a pure `<select>` UI widget equivalent; it is not a dropdown-only widget. If you want to use it as such, you will need to disable/hide the `<input>` element while keeping the whole directive working.
28,510,878
On Android, when the selector is touched, the keyboard input appears. I suspect this is because the generated input is of type="text". **How can I prevent this from happening? If the user is choosing from a drop-down list, it does not make sense for the keyboard to appear.** I'm implementing selectize as an Angular module [angular-selectize](https://github.com/machineboy2045/angular-selectize), but I checked with the developer and the issue is not specific to the angular wrapper. Here is my code: ``` <selectize ng-model="filters.min_bedrooms" options="[ {title:'0', id:0}, {title:'1', id:1}, {title:'2', id:2}, ]"> </selectize> ``` Which generates this markup: ``` <input type="text" autocomplete="off" tabindex="" style="width: 4px; opacity: 0; position: absolute; left: -10000px;"> ```
2015/02/14
[ "https://Stackoverflow.com/questions/28510878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1141918/" ]
This worked for me: ``` $(".selectize-input input").attr('readonly','readonly'); ``` Also worked: ``` $(".selectize-input input").prop('readonly','readonly'); ```
Quoting <http://brianreavis.github.io/selectize.js/>: > > **Selectize** is the hybrid of a textbox and `<select>` box. > > > It is not a pure `<select>` UI widget equivalent; it is not a dropdown-only widget. If you want to use it as such, you will need to disable/hide the `<input>` element while keeping the whole directive working.
28,510,878
On Android, when the selector is touched, the keyboard input appears. I suspect this is because the generated input is of type="text". **How can I prevent this from happening? If the user is choosing from a drop-down list, it does not make sense for the keyboard to appear.** I'm implementing selectize as an Angular module [angular-selectize](https://github.com/machineboy2045/angular-selectize), but I checked with the developer and the issue is not specific to the angular wrapper. Here is my code: ``` <selectize ng-model="filters.min_bedrooms" options="[ {title:'0', id:0}, {title:'1', id:1}, {title:'2', id:2}, ]"> </selectize> ``` Which generates this markup: ``` <input type="text" autocomplete="off" tabindex="" style="width: 4px; opacity: 0; position: absolute; left: -10000px;"> ```
2015/02/14
[ "https://Stackoverflow.com/questions/28510878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1141918/" ]
I had the same issue, where I want the user to select a value but not enter any new values, and the keyboard always shows up when you tap on the dropdown on an iPad. I've solved it by this: ``` $('#myDropDownId').selectize({ create: true, sortField: 'date' }); $(".selectize-input input").attr('readonly','readonly'); ``` Basically what happens is, the input gets focus when you click/tap on the dropdown, and that is what shows the keyboard. By setting readonly to false, the input no longer gets focus. I've tested this on an iPad Mini 2 in Safari and Chrome.
If I understand correctly, you want to prevent the user can type in this `text` field... (ergo, no keyboard on focus, but still will be able to select one of the dropdown options) So, as you said this is exactly what you want, and as far as I know this is not possible to do it with default options, it occurs to me to do this disabling the input field (readonly) on `focus event`, and turn it back again when loose focus (`blur event`). With this, the user is able to select another tag after the first one. Check out this example... ```js var tags = [{ id: '1', value: 'first' }, { id: '2', value: 'second' }, { id: '3', value: 'third' }, ]; // initialize the selectize control var $select = jQuery('#test').selectize({ create: true, closeAfterSelect: true, options: tags, valueField: 'id', labelField: 'value' }); var selectize = $select[0].selectize; selectize.on('focus', function () { jQuery('.readonly').find('input').attr('readonly', true); }); selectize.on('change', function () { selectize.blur(); }); selectize.on('blur', function () { jQuery('.readonly').find('input').attr('readonly', false); }); ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.12.0/js/standalone/selectize.js"></script> <link href="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.12.0/css/selectize.css" rel="stylesheet"/> <label>test <input class="readonly" name="test" id="test" /> </label> ``` It's an approach, but I think this could be enough depending on your needs. (or at least, point you in the right direction) *[JSFiddle file](http://jsfiddle.net/gmolop/3m57zru4/) in case the embed snippet don't work as expected.*
28,510,878
On Android, when the selector is touched, the keyboard input appears. I suspect this is because the generated input is of type="text". **How can I prevent this from happening? If the user is choosing from a drop-down list, it does not make sense for the keyboard to appear.** I'm implementing selectize as an Angular module [angular-selectize](https://github.com/machineboy2045/angular-selectize), but I checked with the developer and the issue is not specific to the angular wrapper. Here is my code: ``` <selectize ng-model="filters.min_bedrooms" options="[ {title:'0', id:0}, {title:'1', id:1}, {title:'2', id:2}, ]"> </selectize> ``` Which generates this markup: ``` <input type="text" autocomplete="off" tabindex="" style="width: 4px; opacity: 0; position: absolute; left: -10000px;"> ```
2015/02/14
[ "https://Stackoverflow.com/questions/28510878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1141918/" ]
This worked for me: ``` $(".selectize-input input").attr('readonly','readonly'); ``` Also worked: ``` $(".selectize-input input").prop('readonly','readonly'); ```
If I understand correctly, you want to prevent the user can type in this `text` field... (ergo, no keyboard on focus, but still will be able to select one of the dropdown options) So, as you said this is exactly what you want, and as far as I know this is not possible to do it with default options, it occurs to me to do this disabling the input field (readonly) on `focus event`, and turn it back again when loose focus (`blur event`). With this, the user is able to select another tag after the first one. Check out this example... ```js var tags = [{ id: '1', value: 'first' }, { id: '2', value: 'second' }, { id: '3', value: 'third' }, ]; // initialize the selectize control var $select = jQuery('#test').selectize({ create: true, closeAfterSelect: true, options: tags, valueField: 'id', labelField: 'value' }); var selectize = $select[0].selectize; selectize.on('focus', function () { jQuery('.readonly').find('input').attr('readonly', true); }); selectize.on('change', function () { selectize.blur(); }); selectize.on('blur', function () { jQuery('.readonly').find('input').attr('readonly', false); }); ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.12.0/js/standalone/selectize.js"></script> <link href="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.12.0/css/selectize.css" rel="stylesheet"/> <label>test <input class="readonly" name="test" id="test" /> </label> ``` It's an approach, but I think this could be enough depending on your needs. (or at least, point you in the right direction) *[JSFiddle file](http://jsfiddle.net/gmolop/3m57zru4/) in case the embed snippet don't work as expected.*
28,510,878
On Android, when the selector is touched, the keyboard input appears. I suspect this is because the generated input is of type="text". **How can I prevent this from happening? If the user is choosing from a drop-down list, it does not make sense for the keyboard to appear.** I'm implementing selectize as an Angular module [angular-selectize](https://github.com/machineboy2045/angular-selectize), but I checked with the developer and the issue is not specific to the angular wrapper. Here is my code: ``` <selectize ng-model="filters.min_bedrooms" options="[ {title:'0', id:0}, {title:'1', id:1}, {title:'2', id:2}, ]"> </selectize> ``` Which generates this markup: ``` <input type="text" autocomplete="off" tabindex="" style="width: 4px; opacity: 0; position: absolute; left: -10000px;"> ```
2015/02/14
[ "https://Stackoverflow.com/questions/28510878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1141918/" ]
I had the same issue, where I want the user to select a value but not enter any new values, and the keyboard always shows up when you tap on the dropdown on an iPad. I've solved it by this: ``` $('#myDropDownId').selectize({ create: true, sortField: 'date' }); $(".selectize-input input").attr('readonly','readonly'); ``` Basically what happens is, the input gets focus when you click/tap on the dropdown, and that is what shows the keyboard. By setting readonly to false, the input no longer gets focus. I've tested this on an iPad Mini 2 in Safari and Chrome.
This worked for me: ``` $(".selectize-input input").attr('readonly','readonly'); ``` Also worked: ``` $(".selectize-input input").prop('readonly','readonly'); ```
1,163,030
I can't narrow down this bug, *however* I seem to have the following problem: * `saveState()` of a `horizontalHeader()` * restart app * modify model so that it has one less column * `restoreState()` * Now, for some reason, the state of the headerview is totally messed up. I cannot show or hide any new columns, nor can I ever get a reasonable state back I know, this is not very descriptive but I'm hoping others have had this problem before.
2009/07/22
[ "https://Stackoverflow.com/questions/1163030", "https://Stackoverflow.com", "https://Stackoverflow.com/users/122933/" ]
I personally never use `saveState()`/`restoreState()` in any Qt widget, since they just return a binary blob anyway. I want my config files to be human-readable, with simple types. That also gets rid of these kind of problems. In addition, `QHeaderView` has the naughty problem that `restoreState()` (or equivalents) only ever worked for me when the model has already been set, and then some time. I ended up connecting to the `QHeaderView::sectionCountChanged()` signal and setting the state in the slot called from it.
I would expect it to break if you change the model! Those functions save and restore private class member variables directly without any sanity checks. Try restoring the state and then changing the model.
1,163,030
I can't narrow down this bug, *however* I seem to have the following problem: * `saveState()` of a `horizontalHeader()` * restart app * modify model so that it has one less column * `restoreState()` * Now, for some reason, the state of the headerview is totally messed up. I cannot show or hide any new columns, nor can I ever get a reasonable state back I know, this is not very descriptive but I'm hoping others have had this problem before.
2009/07/22
[ "https://Stackoverflow.com/questions/1163030", "https://Stackoverflow.com", "https://Stackoverflow.com/users/122933/" ]
For QMainWindow, the [`save/restoreState`](http://doc.trolltech.com/4.5/qmainwindow.html#restoreState) takes a version number. [QTableView's restoreState()](http://doc.qt.digia.com/qt/qheaderview.html#restoreState) does not, so you need to manage this case yourself. If you want to restore state even if the model doesn't match, you have these options: * Store the state together with a list of the columns that existed in the model upon save, so you can avoid restoring from the data if the columns don't match, and revert to defualt case * Implement your own save/restoreState functions that handle that case (ugh) * Add a proxy model that has provides bogus/dummy columns for state that is being restored, then remove those columns just afterwards.
I would expect it to break if you change the model! Those functions save and restore private class member variables directly without any sanity checks. Try restoring the state and then changing the model.
1,163,030
I can't narrow down this bug, *however* I seem to have the following problem: * `saveState()` of a `horizontalHeader()` * restart app * modify model so that it has one less column * `restoreState()` * Now, for some reason, the state of the headerview is totally messed up. I cannot show or hide any new columns, nor can I ever get a reasonable state back I know, this is not very descriptive but I'm hoping others have had this problem before.
2009/07/22
[ "https://Stackoverflow.com/questions/1163030", "https://Stackoverflow.com", "https://Stackoverflow.com/users/122933/" ]
Here is the solution I made using Boost Serialization. It handles new and removed columns, more or less. Works for my use cases. ``` // Because QHeaderView sucks struct QHeaderViewState { explicit QHeaderViewState(ssci::CustomTreeView const & view): m_headers(view.header()->count()) { QHeaderView const & headers(*view.header()); // Stored in *visual index* order for(int vi = 0; vi < headers.count();++vi) { int li = headers.logicalIndex(vi); HeaderState & header = m_headers[vi]; header.hidden = headers.isSectionHidden(li); header.size = headers.sectionSize(li); header.logical_index = li; header.visual_index = vi; header.name = view.model()->headerData(li,Qt::Horizontal).toString(); header.view = &view; } m_sort_indicator_shown = headers.isSortIndicatorShown(); if(m_sort_indicator_shown) { m_sort_indicator_section = headers.sortIndicatorSection(); m_sort_order = headers.sortIndicatorOrder(); } } QHeaderViewState(){} template<typename Archive> void serialize(Archive & ar, unsigned int) { ar & m_headers; ar & m_sort_indicator_shown; if(m_sort_indicator_shown) { ar & m_sort_indicator_section; ar & m_sort_order; } } void restoreState(ssci::CustomTreeView & view) const { QHeaderView & headers(*view.header()); const int max_columns = std::min(headers.count(), static_cast<int>(m_headers.size())); std::vector<HeaderState> header_state(m_headers); std::map<QString,HeaderState *> map; for(std::size_t ii = 0; ii < header_state.size(); ++ii) map[header_state[ii].name] = &header_state[ii]; // First set all sections to be hidden and update logical // indexes for(int li = 0; li < headers.count(); ++li) { headers.setSectionHidden(li,true); std::map<QString,HeaderState *>::iterator it = map.find(view.model()->headerData(li,Qt::Horizontal).toString()); if(it != map.end()) it->second->logical_index = li; } // Now restore for(int vi = 0; vi < max_columns; ++vi) { HeaderState const & header = header_state[vi]; const int li = header.logical_index; SSCI_ASSERT_BUG(vi == header.visual_index); headers.setSectionHidden(li,header.hidden); headers.resizeSection(li,header.size); headers.moveSection(headers.visualIndex(li),vi); } if(m_sort_indicator_shown) headers.setSortIndicator(m_sort_indicator_section, m_sort_order); } struct HeaderState { initialize<bool,false> hidden; initialize<int,0> size; initialize<int,0> logical_index; initialize<int,0> visual_index; QString name; CustomTreeView const *view; HeaderState():view(0){} template<typename Archive> void serialize(Archive & ar, unsigned int) { ar & hidden & size & logical_index & visual_index & name; } }; std::vector<HeaderState> m_headers; bool m_sort_indicator_shown; int m_sort_indicator_section; Qt::SortOrder m_sort_order; // iff m_sort_indicator_shown }; ```
I would expect it to break if you change the model! Those functions save and restore private class member variables directly without any sanity checks. Try restoring the state and then changing the model.
1,163,030
I can't narrow down this bug, *however* I seem to have the following problem: * `saveState()` of a `horizontalHeader()` * restart app * modify model so that it has one less column * `restoreState()` * Now, for some reason, the state of the headerview is totally messed up. I cannot show or hide any new columns, nor can I ever get a reasonable state back I know, this is not very descriptive but I'm hoping others have had this problem before.
2009/07/22
[ "https://Stackoverflow.com/questions/1163030", "https://Stackoverflow.com", "https://Stackoverflow.com/users/122933/" ]
I would expect it to break if you change the model! Those functions save and restore private class member variables directly without any sanity checks. Try restoring the state and then changing the model.
I'm attempting to fix this issue for Qt 5.6.2, after hitting the same issue. See [this link for a Qt patch under review](https://codereview.qt-project.org/167020), which makes restoreState() handle the case where the number of sections (e.g. columns) in the saved state does not match the number of sections in the current view.
1,163,030
I can't narrow down this bug, *however* I seem to have the following problem: * `saveState()` of a `horizontalHeader()` * restart app * modify model so that it has one less column * `restoreState()` * Now, for some reason, the state of the headerview is totally messed up. I cannot show or hide any new columns, nor can I ever get a reasonable state back I know, this is not very descriptive but I'm hoping others have had this problem before.
2009/07/22
[ "https://Stackoverflow.com/questions/1163030", "https://Stackoverflow.com", "https://Stackoverflow.com/users/122933/" ]
For QMainWindow, the [`save/restoreState`](http://doc.trolltech.com/4.5/qmainwindow.html#restoreState) takes a version number. [QTableView's restoreState()](http://doc.qt.digia.com/qt/qheaderview.html#restoreState) does not, so you need to manage this case yourself. If you want to restore state even if the model doesn't match, you have these options: * Store the state together with a list of the columns that existed in the model upon save, so you can avoid restoring from the data if the columns don't match, and revert to defualt case * Implement your own save/restoreState functions that handle that case (ugh) * Add a proxy model that has provides bogus/dummy columns for state that is being restored, then remove those columns just afterwards.
I personally never use `saveState()`/`restoreState()` in any Qt widget, since they just return a binary blob anyway. I want my config files to be human-readable, with simple types. That also gets rid of these kind of problems. In addition, `QHeaderView` has the naughty problem that `restoreState()` (or equivalents) only ever worked for me when the model has already been set, and then some time. I ended up connecting to the `QHeaderView::sectionCountChanged()` signal and setting the state in the slot called from it.
1,163,030
I can't narrow down this bug, *however* I seem to have the following problem: * `saveState()` of a `horizontalHeader()` * restart app * modify model so that it has one less column * `restoreState()` * Now, for some reason, the state of the headerview is totally messed up. I cannot show or hide any new columns, nor can I ever get a reasonable state back I know, this is not very descriptive but I'm hoping others have had this problem before.
2009/07/22
[ "https://Stackoverflow.com/questions/1163030", "https://Stackoverflow.com", "https://Stackoverflow.com/users/122933/" ]
I personally never use `saveState()`/`restoreState()` in any Qt widget, since they just return a binary blob anyway. I want my config files to be human-readable, with simple types. That also gets rid of these kind of problems. In addition, `QHeaderView` has the naughty problem that `restoreState()` (or equivalents) only ever worked for me when the model has already been set, and then some time. I ended up connecting to the `QHeaderView::sectionCountChanged()` signal and setting the state in the slot called from it.
I'm attempting to fix this issue for Qt 5.6.2, after hitting the same issue. See [this link for a Qt patch under review](https://codereview.qt-project.org/167020), which makes restoreState() handle the case where the number of sections (e.g. columns) in the saved state does not match the number of sections in the current view.
1,163,030
I can't narrow down this bug, *however* I seem to have the following problem: * `saveState()` of a `horizontalHeader()` * restart app * modify model so that it has one less column * `restoreState()` * Now, for some reason, the state of the headerview is totally messed up. I cannot show or hide any new columns, nor can I ever get a reasonable state back I know, this is not very descriptive but I'm hoping others have had this problem before.
2009/07/22
[ "https://Stackoverflow.com/questions/1163030", "https://Stackoverflow.com", "https://Stackoverflow.com/users/122933/" ]
For QMainWindow, the [`save/restoreState`](http://doc.trolltech.com/4.5/qmainwindow.html#restoreState) takes a version number. [QTableView's restoreState()](http://doc.qt.digia.com/qt/qheaderview.html#restoreState) does not, so you need to manage this case yourself. If you want to restore state even if the model doesn't match, you have these options: * Store the state together with a list of the columns that existed in the model upon save, so you can avoid restoring from the data if the columns don't match, and revert to defualt case * Implement your own save/restoreState functions that handle that case (ugh) * Add a proxy model that has provides bogus/dummy columns for state that is being restored, then remove those columns just afterwards.
Here is the solution I made using Boost Serialization. It handles new and removed columns, more or less. Works for my use cases. ``` // Because QHeaderView sucks struct QHeaderViewState { explicit QHeaderViewState(ssci::CustomTreeView const & view): m_headers(view.header()->count()) { QHeaderView const & headers(*view.header()); // Stored in *visual index* order for(int vi = 0; vi < headers.count();++vi) { int li = headers.logicalIndex(vi); HeaderState & header = m_headers[vi]; header.hidden = headers.isSectionHidden(li); header.size = headers.sectionSize(li); header.logical_index = li; header.visual_index = vi; header.name = view.model()->headerData(li,Qt::Horizontal).toString(); header.view = &view; } m_sort_indicator_shown = headers.isSortIndicatorShown(); if(m_sort_indicator_shown) { m_sort_indicator_section = headers.sortIndicatorSection(); m_sort_order = headers.sortIndicatorOrder(); } } QHeaderViewState(){} template<typename Archive> void serialize(Archive & ar, unsigned int) { ar & m_headers; ar & m_sort_indicator_shown; if(m_sort_indicator_shown) { ar & m_sort_indicator_section; ar & m_sort_order; } } void restoreState(ssci::CustomTreeView & view) const { QHeaderView & headers(*view.header()); const int max_columns = std::min(headers.count(), static_cast<int>(m_headers.size())); std::vector<HeaderState> header_state(m_headers); std::map<QString,HeaderState *> map; for(std::size_t ii = 0; ii < header_state.size(); ++ii) map[header_state[ii].name] = &header_state[ii]; // First set all sections to be hidden and update logical // indexes for(int li = 0; li < headers.count(); ++li) { headers.setSectionHidden(li,true); std::map<QString,HeaderState *>::iterator it = map.find(view.model()->headerData(li,Qt::Horizontal).toString()); if(it != map.end()) it->second->logical_index = li; } // Now restore for(int vi = 0; vi < max_columns; ++vi) { HeaderState const & header = header_state[vi]; const int li = header.logical_index; SSCI_ASSERT_BUG(vi == header.visual_index); headers.setSectionHidden(li,header.hidden); headers.resizeSection(li,header.size); headers.moveSection(headers.visualIndex(li),vi); } if(m_sort_indicator_shown) headers.setSortIndicator(m_sort_indicator_section, m_sort_order); } struct HeaderState { initialize<bool,false> hidden; initialize<int,0> size; initialize<int,0> logical_index; initialize<int,0> visual_index; QString name; CustomTreeView const *view; HeaderState():view(0){} template<typename Archive> void serialize(Archive & ar, unsigned int) { ar & hidden & size & logical_index & visual_index & name; } }; std::vector<HeaderState> m_headers; bool m_sort_indicator_shown; int m_sort_indicator_section; Qt::SortOrder m_sort_order; // iff m_sort_indicator_shown }; ```
1,163,030
I can't narrow down this bug, *however* I seem to have the following problem: * `saveState()` of a `horizontalHeader()` * restart app * modify model so that it has one less column * `restoreState()` * Now, for some reason, the state of the headerview is totally messed up. I cannot show or hide any new columns, nor can I ever get a reasonable state back I know, this is not very descriptive but I'm hoping others have had this problem before.
2009/07/22
[ "https://Stackoverflow.com/questions/1163030", "https://Stackoverflow.com", "https://Stackoverflow.com/users/122933/" ]
For QMainWindow, the [`save/restoreState`](http://doc.trolltech.com/4.5/qmainwindow.html#restoreState) takes a version number. [QTableView's restoreState()](http://doc.qt.digia.com/qt/qheaderview.html#restoreState) does not, so you need to manage this case yourself. If you want to restore state even if the model doesn't match, you have these options: * Store the state together with a list of the columns that existed in the model upon save, so you can avoid restoring from the data if the columns don't match, and revert to defualt case * Implement your own save/restoreState functions that handle that case (ugh) * Add a proxy model that has provides bogus/dummy columns for state that is being restored, then remove those columns just afterwards.
I'm attempting to fix this issue for Qt 5.6.2, after hitting the same issue. See [this link for a Qt patch under review](https://codereview.qt-project.org/167020), which makes restoreState() handle the case where the number of sections (e.g. columns) in the saved state does not match the number of sections in the current view.
1,163,030
I can't narrow down this bug, *however* I seem to have the following problem: * `saveState()` of a `horizontalHeader()` * restart app * modify model so that it has one less column * `restoreState()` * Now, for some reason, the state of the headerview is totally messed up. I cannot show or hide any new columns, nor can I ever get a reasonable state back I know, this is not very descriptive but I'm hoping others have had this problem before.
2009/07/22
[ "https://Stackoverflow.com/questions/1163030", "https://Stackoverflow.com", "https://Stackoverflow.com/users/122933/" ]
Here is the solution I made using Boost Serialization. It handles new and removed columns, more or less. Works for my use cases. ``` // Because QHeaderView sucks struct QHeaderViewState { explicit QHeaderViewState(ssci::CustomTreeView const & view): m_headers(view.header()->count()) { QHeaderView const & headers(*view.header()); // Stored in *visual index* order for(int vi = 0; vi < headers.count();++vi) { int li = headers.logicalIndex(vi); HeaderState & header = m_headers[vi]; header.hidden = headers.isSectionHidden(li); header.size = headers.sectionSize(li); header.logical_index = li; header.visual_index = vi; header.name = view.model()->headerData(li,Qt::Horizontal).toString(); header.view = &view; } m_sort_indicator_shown = headers.isSortIndicatorShown(); if(m_sort_indicator_shown) { m_sort_indicator_section = headers.sortIndicatorSection(); m_sort_order = headers.sortIndicatorOrder(); } } QHeaderViewState(){} template<typename Archive> void serialize(Archive & ar, unsigned int) { ar & m_headers; ar & m_sort_indicator_shown; if(m_sort_indicator_shown) { ar & m_sort_indicator_section; ar & m_sort_order; } } void restoreState(ssci::CustomTreeView & view) const { QHeaderView & headers(*view.header()); const int max_columns = std::min(headers.count(), static_cast<int>(m_headers.size())); std::vector<HeaderState> header_state(m_headers); std::map<QString,HeaderState *> map; for(std::size_t ii = 0; ii < header_state.size(); ++ii) map[header_state[ii].name] = &header_state[ii]; // First set all sections to be hidden and update logical // indexes for(int li = 0; li < headers.count(); ++li) { headers.setSectionHidden(li,true); std::map<QString,HeaderState *>::iterator it = map.find(view.model()->headerData(li,Qt::Horizontal).toString()); if(it != map.end()) it->second->logical_index = li; } // Now restore for(int vi = 0; vi < max_columns; ++vi) { HeaderState const & header = header_state[vi]; const int li = header.logical_index; SSCI_ASSERT_BUG(vi == header.visual_index); headers.setSectionHidden(li,header.hidden); headers.resizeSection(li,header.size); headers.moveSection(headers.visualIndex(li),vi); } if(m_sort_indicator_shown) headers.setSortIndicator(m_sort_indicator_section, m_sort_order); } struct HeaderState { initialize<bool,false> hidden; initialize<int,0> size; initialize<int,0> logical_index; initialize<int,0> visual_index; QString name; CustomTreeView const *view; HeaderState():view(0){} template<typename Archive> void serialize(Archive & ar, unsigned int) { ar & hidden & size & logical_index & visual_index & name; } }; std::vector<HeaderState> m_headers; bool m_sort_indicator_shown; int m_sort_indicator_section; Qt::SortOrder m_sort_order; // iff m_sort_indicator_shown }; ```
I'm attempting to fix this issue for Qt 5.6.2, after hitting the same issue. See [this link for a Qt patch under review](https://codereview.qt-project.org/167020), which makes restoreState() handle the case where the number of sections (e.g. columns) in the saved state does not match the number of sections in the current view.
13,249,356
I have the application (solution in VS2010) with +-10 projects. Some of these projects are quite large (dozens of folders and hundreds of files). When I make a change in project on lower level and I want to run my tests (+-10 seconds) then I have to wait 2 minutes for projects build. This is very inefficient. Is there any way to speed-up build? For example, split current projects into multiple projects or something else? Or are there some general advice and recommendations to speed-up building projects in Visual Studio?
2012/11/06
[ "https://Stackoverflow.com/questions/13249356", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1304812/" ]
In my experience solutions with large number of projects build slowly on vs2010 and there is not much you can do about it: 1. Reduce number of projects - larger single project will build faster then many smaller. 2. Prepare set of build configurations Build->ConfigruationManager to build only parts of your project since you don't have to build projects that depend on changed project if public interface is not changed. This can be tricky to use and some unexpected errors might occur in runtime. Also make sure that all your projects point to single `Bin\Debug Bin\Release` folder so that new dlls are loaded on application start. This is requited because if you don't build project its dependencies wont be copied to its output directory. 3. Upgrade to vs 2012. This is the best option you can choose.
Try to use tools that allow concurrent test execution coupled with shadow building - NCrunch or MightyMoose. Also try to get rid of unused references - for example move all tests that test only your core project to separate project so that they get executed right after core is built. Try not to use MS accessors, because they force to fully recompile all projects that they are referencing. And of course use SSD disks.
13,249,356
I have the application (solution in VS2010) with +-10 projects. Some of these projects are quite large (dozens of folders and hundreds of files). When I make a change in project on lower level and I want to run my tests (+-10 seconds) then I have to wait 2 minutes for projects build. This is very inefficient. Is there any way to speed-up build? For example, split current projects into multiple projects or something else? Or are there some general advice and recommendations to speed-up building projects in Visual Studio?
2012/11/06
[ "https://Stackoverflow.com/questions/13249356", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1304812/" ]
Try this: Go to "Tools" menu -> "Options" -> "Projects And Solutions" -> "Build And Run" And increase the value of "Maximum number of parallel project builds" to 32 or greater.
Try to use tools that allow concurrent test execution coupled with shadow building - NCrunch or MightyMoose. Also try to get rid of unused references - for example move all tests that test only your core project to separate project so that they get executed right after core is built. Try not to use MS accessors, because they force to fully recompile all projects that they are referencing. And of course use SSD disks.
2,621,584
My goal is to prenex-normalize the following sentence: $(\exists{z} : S(z)) \wedge \exists{x} :\forall{y} : [\forall{z}: S(z) \Rightarrow P(y,z)] \Rightarrow R(x,y)$ I tried many times but none of the things that I try seem to work. I can't wrap my mind around the part between the []-brackets. This is an exercise in a course that I take and we have a tool to check the correctness of a solution, most other exercises were no problem for me but I really struggle with this one.
2018/01/26
[ "https://math.stackexchange.com/questions/2621584", "https://math.stackexchange.com", "https://math.stackexchange.com/users/401361/" ]
To make the formulas a little more compact, I'm going to use the notation $\binom pq$ rather than $^pC\_q$ for number of combinations. Notice that $^4C\_1 \times {^{13}C\_5} = \binom41\binom{13}{5}$ is a constant, whereas $^{52}C\_n = \binom{52}{n}$ increases as $n$ increases, so $$ \frac{\binom41\binom{13}{5}}{\binom{52}{n}} $$ gets progressively *smaller* as $n$ gets larger, opposite from what you know the correct answer must do. Therefore this cannot be the answer. The formula above is correct in the case $n=5$ only. It is true that the probability of drawing at least one $5$-card flush in $n$ cards can be expressed as a fraction with denominator $\binom{52}{n},$ but in general the numerator is larger than $\binom41\binom{13}{5}.$ Let $K(n)$ be the number of $n$-card hands with at least one $5$-card flush, so that the desired probability is $$ \frac{K(n)}{\binom{52}{n}}, $$ and let's see how we can compute $K(n)$ for a few different values of $n.$ For $n=6,$ we have to consider the $\binom{13}{6}$ different sets of $6$ cards that might be drawn from one suit times the $4$ different suits from which they might be drawn; but we also have to consider the $\binom{13}{5}$ different sets of $5$ cards that might be drawn from one suit times the $\binom{13}{1}$ ways to draw the sixth card from another suite times the $4\times3$ different permutations of suits from which they might be drawn. So $$ K(6) = 4 \binom{13}{6} + 12 \binom{13}{5} \binom{13}{1} = 207636. $$ For $n=7$ the possibilities are not just $7$ of one suit or $6$ of one suit and $1$ of another; it could be $5$ of one suit and $2$ of another, or $5$ of one suit and $1$ each of two others. In that last case, the only choices of suits are $4$ choices for the long suit and which of the other $3$ suits does *not* occur; it doesn't matter which of the two singleton suits we write first. So $$ K(7) = 4 \binom{13}{7} + 12 \binom{13}{6} \binom{13}{1} + 12 \binom{13}{5} \binom{13}{2} + 12 \binom{13}{5} \binom{13}{1}^2 = 4089228 $$ It's hard to imagine how we're going to write a simple formula for $K(n)$ using the usual combinatoric functions, since for the next few $n,$ each time we add a card we increase the number of different possible counts of cards by suit; for example, for $n=8$ the number of cards in each suit can be $8$ (all one suit), $7 + 1,$ $6+2,$ $6+1+1,$ $5+3,$ $5+2+1,$ or $5+1+1.$ The formula would not even fit on one line of this answer format. For $n$ close to $17,$ the formulas are simpler if we count the number of non-flushes, that is, $\binom{52}{n} - K(n).$ For example, for $n=16,$ the only non-flushes obtained by drawing $4$ cards from each suit, $$ \binom{52}{16} - K(16) = \binom{13}{4}^4 = 261351000625. $$ For $n=15,$ we can only have $4$ cards from three of the suits and $3$ from the other, with $4$ different choices of the $3$-card suit, so $$ \binom{52}{15} - K(15) = 4 \binom{13}{4}^3 \binom{13}{3} = 418161601000. $$ For $n=14,$ the possible numbers of cards of each suit are $4+4+4+2$ or $4+4+3+3$, so $$ \binom{52}{14} - K(14) = 4 \binom{13}{4}^3 \binom{13}{2} + \binom62 \binom{13}{4}^2 \binom{13}{3}^2 = 364941033600. $$ Observing that $\binom{52}{6} - K(6) = 20150884$ and $\binom{52}{7} - K(7) = 129695332,$ we can see that the result of the computer calculation [offered in another answer](https://math.stackexchange.com/a/2622642) is correct for $n \in \{4,5,6,7,14,15, 16, 17\}.$
I've got kind of a dumb answer. I just wrote a program that counts the number $f$ of non-flush hands for a hand of $n$ cards and the total number of possible hands $t$ to arrive at the probability $P=1-f/t$. ``` ! flush.f90 -- Calculates probability of getting a flush module FlushFun use ISO_FORTRAN_ENV implicit none integer choose(0:13) contains function nfree(n) integer n integer(INT64) nfree integer n1, n2, n3 integer(INT64) L1, L2, L3 nfree = 0 do n1 = max(0,n-12), min(4,n) L1 = choose(n1) do n2 = max(0,n-n1-8), min(4,n-n1) L2 = L1*choose(n2) do n3 = max(0,n-n1-n2-4), min(4,n-n1-n2) L3 = L2*choose(n3) nfree = nfree+L3*choose(n-n1-n2-n3) end do end do end do end function nfree function ntotal(n) integer n integer(INT64) ntotal integer i ntotal = 1 do i = 1, N ntotal = ntotal*(52-i+1)/i end do end function ntotal subroutine init_params integer i integer(INT64) j integer(INT64) fact(0:13) fact = [(product([(j,j=1,i)]),i=0,13)] choose = [(fact(13)/fact(i)/fact(13-i),i=0,13)] end subroutine init_params end module FlushFun program flush use FlushFun implicit none integer(INT64) free, total real(REAL64) probability integer n call init_params write(*,'(a)') '\begin{array}{rrrl}' write(*,'(a)') '\text{Cards} & \text{Non-Flush} & \text{Total} & \text{Probability}\\' write(*,'(a)') '\hline' do n = 4,17 free = nfree(n) total = ntotal(n) probability = 1-real(free,REAL64)/total write(*,'(*(g0))') n, ' & ', free,' & ',total,' & ',probability,' \\' end do write(*,'(a)') '\end{array}' end program flush ``` $$\begin{array}{rrrl} \text{Cards} & \text{Non-Flush} & \text{Total} & \text{Probability}\\ \hline 4 & 270725 & 270725 & 0.0000000000000000 \\ 5 & 2593812 & 2598960 & 0.19807923169267161E-002 \\ 6 & 20150884 & 20358520 & 0.10198973206303807E-001 \\ 7 & 129695332 & 133784560 & 0.30565769323455561E-001 \\ 8 & 700131510 & 752538150 & 0.69639844837102283E-001 \\ 9 & 3187627300 & 3679075400 & 0.13357924113216058 \\ 10 & 12234737086 & 15820024220 & 0.22662968679070705 \\ 11 & 39326862432 & 60403728840 & 0.34893320019744667 \\ 12 & 104364416156 & 206379406870 & 0.49430799449026441 \\ 13 & 222766089260 & 635013559600 & 0.64919475199817445 \\ 14 & 364941033600 & 1768966344600 & 0.79369814767023128 \\ 15 & 418161601000 & 4481381406320 & 0.90668912929163414 \\ 16 & 261351000625 & 10363194502115 & 0.97478084575449575 \\ 17 & 0 & 21945588357420 & 1.0000000000000000 \\ \end{array}$$ Not carefully checked, but at least it gives the right answers for $n\in\{4,5,17\}$. **EDIT**: To show how you could solve this problem by hand I wrote a program that really does find all the partitions of $n$ into $4$ integers in $[0,4]$. The most partitions you get is $8$ for $n=8$. Consider the partition $8=4+2+2+0$. In the table below this is represented as $4$ clubs, $2$ diamonds, $2$ hearts and no spades, but there are actually $$\frac{4!}{1!2!1!}=12$$ Ways to choose the suits. For the given choice of suits, there are $\binom{13}{4}=715$ ways to select $4$ clubs, $\binom{13}{2}=78$ ways to select $2$ diamonds, $\binom{13}{2}=78$ ways to select $2$ hearts, and $\binom{13}{0}=1$ way to select $0$ spades, so there are $12\times715\times78\times78\times1=52200720$ possible non-flush hands with the $4-2-2-0$ distribution. Here is the program that shows these calculations: ``` ! flush2.f90 -- Calculates probability of getting a flush module FlushFun use ISO_FORTRAN_ENV implicit none integer choose(0:13) contains function nfree(n) integer n integer(INT64) nfree integer n1, n2, n3, n4 integer(INT64) L1, L2, L3, L4 integer(INT64) term integer current, w1, w2, w3, w4 nfree = 0 write(*,'(a)') '$$\begin{array}{rrrr|r|rrrr|r}' write(*,'(a)') '\rlap{\text{Number}}&&&&'// & '&\rlap{\text{Hands in Suit}}&&&&\\' write(*,'(a)') '\clubsuit&\diamondsuit&\heartsuit&'// & '\spadesuit&\text{Ways}&\clubsuit&\diamondsuit&'// & '\heartsuit&\spadesuit&\text{Total}\\' write(*,'(a)') '\hline' do n1 = min(4,n), (n+3)/4, -1 L1 = choose(n1) w1 = 1 current = 1 do n2 = min(n1,n-n1), (n-n1+2)/3, -1 L2 = choose(n2) current = merge(current+1,1,n2 == n1) w2 = w1*current do n3 = min(n2,n-n1-n2), (n-n1-n2+1)/2, -1 L3 = choose(n3) current = merge(current+1,1,n3 == n2) w3 = w2*current n4 = n-n1-n2-n3 L4 = choose(n4) current = merge(current+1,1,n4 == n3) w4 = w3*current term = 24/w4*L1*L2*L3*L4 write(*,'(*(g0))') n1,'&',n2,'&',n3,'&', & n4,'&',24/w4,'&',L1,'&',L2,'&',L3,'&', & L4,'&',term,'\\' nfree = nfree+term end do end do end do write(*,'(*(g0))') '\hline&&&&&&&&\llap{\text{Hands for ',n,' cards:}}&',nfree write(*,'(a)') '\end{array}$$' end function nfree subroutine init_params integer i integer(INT64) j integer(INT64) fact(0:13) fact = [(product([(j,j=1,i)]),i=0,13)] choose = [(fact(13)/fact(i)/fact(13-i),i=0,13)] end subroutine init_params end module FlushFun program flush2 use FlushFun implicit none integer(INT64) free integer n call init_params do n = 4,17 free = nfree(n) end do end program flush2 ``` And here are the tables in prints out: $$\begin{array}{rrrr|r|rrrr|r} \rlap{\text{Number}}&&&&&\rlap{\text{Hands in Suit}}&&&&\\ \clubsuit&\diamondsuit&\heartsuit&\spadesuit&\text{Ways}&\clubsuit&\diamondsuit&\heartsuit&\spadesuit&\text{Total}\\ \hline 4&0&0&0&4&715&1&1&1&2860\\ 3&1&0&0&12&286&13&1&1&44616\\ 2&2&0&0&6&78&78&1&1&36504\\ 2&1&1&0&12&78&13&13&1&158184\\ 1&1&1&1&1&13&13&13&13&28561\\ \hline&&&&&&&&\llap{\text{Hands for 4 cards:}}&270725 \end{array}$$ $$\begin{array}{rrrr|r|rrrr|r} \rlap{\text{Number}}&&&&&\rlap{\text{Hands in Suit}}&&&&\\ \clubsuit&\diamondsuit&\heartsuit&\spadesuit&\text{Ways}&\clubsuit&\diamondsuit&\heartsuit&\spadesuit&\text{Total}\\ \hline 4&1&0&0&12&715&13&1&1&111540\\ 3&2&0&0&12&286&78&1&1&267696\\ 3&1&1&0&12&286&13&13&1&580008\\ 2&2&1&0&12&78&78&13&1&949104\\ 2&1&1&1&4&78&13&13&13&685464\\ \hline&&&&&&&&\llap{\text{Hands for 5 cards:}}&2593812 \end{array}$$ $$\begin{array}{rrrr|r|rrrr|r} \rlap{\text{Number}}&&&&&\rlap{\text{Hands in Suit}}&&&&\\ \clubsuit&\diamondsuit&\heartsuit&\spadesuit&\text{Ways}&\clubsuit&\diamondsuit&\heartsuit&\spadesuit&\text{Total}\\ \hline 4&2&0&0&12&715&78&1&1&669240\\ 4&1&1&0&12&715&13&13&1&1450020\\ 3&3&0&0&6&286&286&1&1&490776\\ 3&2&1&0&24&286&78&13&1&6960096\\ 3&1&1&1&4&286&13&13&13&2513368\\ 2&2&2&0&4&78&78&78&1&1898208\\ 2&2&1&1&6&78&78&13&13&6169176\\ \hline&&&&&&&&\llap{\text{Hands for 6 cards:}}&20150884 \end{array}$$ $$\begin{array}{rrrr|r|rrrr|r} \rlap{\text{Number}}&&&&&\rlap{\text{Hands in Suit}}&&&&\\ \clubsuit&\diamondsuit&\heartsuit&\spadesuit&\text{Ways}&\clubsuit&\diamondsuit&\heartsuit&\spadesuit&\text{Total}\\ \hline 4&3&0&0&12&715&286&1&1&2453880\\ 4&2&1&0&24&715&78&13&1&17400240\\ 4&1&1&1&4&715&13&13&13&6283420\\ 3&3&1&0&12&286&286&13&1&12760176\\ 3&2&2&0&12&286&78&78&1&20880288\\ 3&2&1&1&12&286&78&13&13&45240624\\ 2&2&2&1&4&78&78&78&13&24676704\\ \hline&&&&&&&&\llap{\text{Hands for 7 cards:}}&129695332 \end{array}$$ $$\begin{array}{rrrr|r|rrrr|r} \rlap{\text{Number}}&&&&&\rlap{\text{Hands in Suit}}&&&&\\ \clubsuit&\diamondsuit&\heartsuit&\spadesuit&\text{Ways}&\clubsuit&\diamondsuit&\heartsuit&\spadesuit&\text{Total}\\ \hline 4&4&0&0&6&715&715&1&1&3067350\\ 4&3&1&0&24&715&286&13&1&63800880\\ 4&2&2&0&12&715&78&78&1&52200720\\ 4&2&1&1&12&715&78&13&13&113101560\\ 3&3&2&0&12&286&286&78&1&76561056\\ 3&3&1&1&6&286&286&13&13&82941144\\ 3&2&2&1&12&286&78&78&13&271443744\\ 2&2&2&2&1&78&78&78&78&37015056\\ \hline&&&&&&&&\llap{\text{Hands for 8 cards:}}&700131510 \end{array}$$ $$\begin{array}{rrrr|r|rrrr|r} \rlap{\text{Number}}&&&&&\rlap{\text{Hands in Suit}}&&&&\\ \clubsuit&\diamondsuit&\heartsuit&\spadesuit&\text{Ways}&\clubsuit&\diamondsuit&\heartsuit&\spadesuit&\text{Total}\\ \hline 4&4&1&0&12&715&715&13&1&79751100\\ 4&3&2&0&24&715&286&78&1&382805280\\ 4&3&1&1&12&715&286&13&13&414705720\\ 4&2&2&1&12&715&78&78&13&678609360\\ 3&3&3&0&4&286&286&286&1&93574624\\ 3&3&2&1&12&286&286&78&13&995293728\\ 3&2&2&2&4&286&78&78&78&542887488\\ \hline&&&&&&&&\llap{\text{Hands for 9 cards:}}&3187627300 \end{array}$$ $$\begin{array}{rrrr|r|rrrr|r} \rlap{\text{Number}}&&&&&\rlap{\text{Hands in Suit}}&&&&\\ \clubsuit&\diamondsuit&\heartsuit&\spadesuit&\text{Ways}&\clubsuit&\diamondsuit&\heartsuit&\spadesuit&\text{Total}\\ \hline 4&4&2&0&12&715&715&78&1&478506600\\ 4&4&1&1&6&715&715&13&13&518382150\\ 4&3&3&0&12&715&286&286&1&701809680\\ 4&3&2&1&24&715&286&78&13&4976468640\\ 4&2&2&2&4&715&78&78&78&1357218720\\ 3&3&3&1&4&286&286&286&13&1216470112\\ 3&3&2&2&6&286&286&78&78&2985881184\\ \hline&&&&&&&&\llap{\text{Hands for 10 cards:}}&12234737086 \end{array}$$ $$\begin{array}{rrrr|r|rrrr|r} \rlap{\text{Number}}&&&&&\rlap{\text{Hands in Suit}}&&&&\\ \clubsuit&\diamondsuit&\heartsuit&\spadesuit&\text{Ways}&\clubsuit&\diamondsuit&\heartsuit&\spadesuit&\text{Total}\\ \hline 4&4&3&0&12&715&715&286&1&1754524200\\ 4&4&2&1&12&715&715&78&13&6220585800\\ 4&3&3&1&12&715&286&286&13&9123525840\\ 4&3&2&2&12&715&286&78&78&14929405920\\ 3&3&3&2&4&286&286&286&78&7298820672\\ \hline&&&&&&&&\llap{\text{Hands for 11 cards:}}&39326862432 \end{array}$$ $$\begin{array}{rrrr|r|rrrr|r} \rlap{\text{Number}}&&&&&\rlap{\text{Hands in Suit}}&&&&\\ \clubsuit&\diamondsuit&\heartsuit&\spadesuit&\text{Ways}&\clubsuit&\diamondsuit&\heartsuit&\spadesuit&\text{Total}\\ \hline 4&4&4&0&4&715&715&715&1&1462103500\\ 4&4&3&1&12&715&715&286&13&22808814600\\ 4&4&2&2&6&715&715&78&78&18661757400\\ 4&3&3&2&12&715&286&286&78&54741155040\\ 3&3&3&3&1&286&286&286&286&6690585616\\ \hline&&&&&&&&\llap{\text{Hands for 12 cards:}}&104364416156 \end{array}$$ $$\begin{array}{rrrr|r|rrrr|r} \rlap{\text{Number}}&&&&&\rlap{\text{Hands in Suit}}&&&&\\ \clubsuit&\diamondsuit&\heartsuit&\spadesuit&\text{Ways}&\clubsuit&\diamondsuit&\heartsuit&\spadesuit&\text{Total}\\ \hline 4&4&4&1&4&715&715&715&13&19007345500\\ 4&4&3&2&12&715&715&286&78&136852887600\\ 4&3&3&3&4&715&286&286&286&66905856160\\ \hline&&&&&&&&\llap{\text{Hands for 13 cards:}}&222766089260 \end{array}$$ $$\begin{array}{rrrr|r|rrrr|r} \rlap{\text{Number}}&&&&&\rlap{\text{Hands in Suit}}&&&&\\ \clubsuit&\diamondsuit&\heartsuit&\spadesuit&\text{Ways}&\clubsuit&\diamondsuit&\heartsuit&\spadesuit&\text{Total}\\ \hline 4&4&4&2&4&715&715&715&78&114044073000\\ 4&4&3&3&6&715&715&286&286&250896960600\\ \hline&&&&&&&&\llap{\text{Hands for 14 cards:}}&364941033600 \end{array}$$ $$\begin{array}{rrrr|r|rrrr|r} \rlap{\text{Number}}&&&&&\rlap{\text{Hands in Suit}}&&&&\\ \clubsuit&\diamondsuit&\heartsuit&\spadesuit&\text{Ways}&\clubsuit&\diamondsuit&\heartsuit&\spadesuit&\text{Total}\\ \hline 4&4&4&3&4&715&715&715&286&418161601000\\ \hline&&&&&&&&\llap{\text{Hands for 15 cards:}}&418161601000 \end{array}$$ $$\begin{array}{rrrr|r|rrrr|r} \rlap{\text{Number}}&&&&&\rlap{\text{Hands in Suit}}&&&&\\ \clubsuit&\diamondsuit&\heartsuit&\spadesuit&\text{Ways}&\clubsuit&\diamondsuit&\heartsuit&\spadesuit&\text{Total}\\ \hline 4&4&4&4&1&715&715&715&715&261351000625\\ \hline&&&&&&&&\llap{\text{Hands for 16 cards:}}&261351000625 \end{array}$$ $$\begin{array}{rrrr|r|rrrr|r} \rlap{\text{Number}}&&&&&\rlap{\text{Hands in Suit}}&&&&\\ \clubsuit&\diamondsuit&\heartsuit&\spadesuit&\text{Ways}&\clubsuit&\diamondsuit&\heartsuit&\spadesuit&\text{Total}\\ \hline \hline&&&&&&&&\llap{\text{Hands for 17 cards:}}&0 \end{array}$$
2,621,584
My goal is to prenex-normalize the following sentence: $(\exists{z} : S(z)) \wedge \exists{x} :\forall{y} : [\forall{z}: S(z) \Rightarrow P(y,z)] \Rightarrow R(x,y)$ I tried many times but none of the things that I try seem to work. I can't wrap my mind around the part between the []-brackets. This is an exercise in a course that I take and we have a tool to check the correctness of a solution, most other exercises were no problem for me but I really struggle with this one.
2018/01/26
[ "https://math.stackexchange.com/questions/2621584", "https://math.stackexchange.com", "https://math.stackexchange.com/users/401361/" ]
I've got kind of a dumb answer. I just wrote a program that counts the number $f$ of non-flush hands for a hand of $n$ cards and the total number of possible hands $t$ to arrive at the probability $P=1-f/t$. ``` ! flush.f90 -- Calculates probability of getting a flush module FlushFun use ISO_FORTRAN_ENV implicit none integer choose(0:13) contains function nfree(n) integer n integer(INT64) nfree integer n1, n2, n3 integer(INT64) L1, L2, L3 nfree = 0 do n1 = max(0,n-12), min(4,n) L1 = choose(n1) do n2 = max(0,n-n1-8), min(4,n-n1) L2 = L1*choose(n2) do n3 = max(0,n-n1-n2-4), min(4,n-n1-n2) L3 = L2*choose(n3) nfree = nfree+L3*choose(n-n1-n2-n3) end do end do end do end function nfree function ntotal(n) integer n integer(INT64) ntotal integer i ntotal = 1 do i = 1, N ntotal = ntotal*(52-i+1)/i end do end function ntotal subroutine init_params integer i integer(INT64) j integer(INT64) fact(0:13) fact = [(product([(j,j=1,i)]),i=0,13)] choose = [(fact(13)/fact(i)/fact(13-i),i=0,13)] end subroutine init_params end module FlushFun program flush use FlushFun implicit none integer(INT64) free, total real(REAL64) probability integer n call init_params write(*,'(a)') '\begin{array}{rrrl}' write(*,'(a)') '\text{Cards} & \text{Non-Flush} & \text{Total} & \text{Probability}\\' write(*,'(a)') '\hline' do n = 4,17 free = nfree(n) total = ntotal(n) probability = 1-real(free,REAL64)/total write(*,'(*(g0))') n, ' & ', free,' & ',total,' & ',probability,' \\' end do write(*,'(a)') '\end{array}' end program flush ``` $$\begin{array}{rrrl} \text{Cards} & \text{Non-Flush} & \text{Total} & \text{Probability}\\ \hline 4 & 270725 & 270725 & 0.0000000000000000 \\ 5 & 2593812 & 2598960 & 0.19807923169267161E-002 \\ 6 & 20150884 & 20358520 & 0.10198973206303807E-001 \\ 7 & 129695332 & 133784560 & 0.30565769323455561E-001 \\ 8 & 700131510 & 752538150 & 0.69639844837102283E-001 \\ 9 & 3187627300 & 3679075400 & 0.13357924113216058 \\ 10 & 12234737086 & 15820024220 & 0.22662968679070705 \\ 11 & 39326862432 & 60403728840 & 0.34893320019744667 \\ 12 & 104364416156 & 206379406870 & 0.49430799449026441 \\ 13 & 222766089260 & 635013559600 & 0.64919475199817445 \\ 14 & 364941033600 & 1768966344600 & 0.79369814767023128 \\ 15 & 418161601000 & 4481381406320 & 0.90668912929163414 \\ 16 & 261351000625 & 10363194502115 & 0.97478084575449575 \\ 17 & 0 & 21945588357420 & 1.0000000000000000 \\ \end{array}$$ Not carefully checked, but at least it gives the right answers for $n\in\{4,5,17\}$. **EDIT**: To show how you could solve this problem by hand I wrote a program that really does find all the partitions of $n$ into $4$ integers in $[0,4]$. The most partitions you get is $8$ for $n=8$. Consider the partition $8=4+2+2+0$. In the table below this is represented as $4$ clubs, $2$ diamonds, $2$ hearts and no spades, but there are actually $$\frac{4!}{1!2!1!}=12$$ Ways to choose the suits. For the given choice of suits, there are $\binom{13}{4}=715$ ways to select $4$ clubs, $\binom{13}{2}=78$ ways to select $2$ diamonds, $\binom{13}{2}=78$ ways to select $2$ hearts, and $\binom{13}{0}=1$ way to select $0$ spades, so there are $12\times715\times78\times78\times1=52200720$ possible non-flush hands with the $4-2-2-0$ distribution. Here is the program that shows these calculations: ``` ! flush2.f90 -- Calculates probability of getting a flush module FlushFun use ISO_FORTRAN_ENV implicit none integer choose(0:13) contains function nfree(n) integer n integer(INT64) nfree integer n1, n2, n3, n4 integer(INT64) L1, L2, L3, L4 integer(INT64) term integer current, w1, w2, w3, w4 nfree = 0 write(*,'(a)') '$$\begin{array}{rrrr|r|rrrr|r}' write(*,'(a)') '\rlap{\text{Number}}&&&&'// & '&\rlap{\text{Hands in Suit}}&&&&\\' write(*,'(a)') '\clubsuit&\diamondsuit&\heartsuit&'// & '\spadesuit&\text{Ways}&\clubsuit&\diamondsuit&'// & '\heartsuit&\spadesuit&\text{Total}\\' write(*,'(a)') '\hline' do n1 = min(4,n), (n+3)/4, -1 L1 = choose(n1) w1 = 1 current = 1 do n2 = min(n1,n-n1), (n-n1+2)/3, -1 L2 = choose(n2) current = merge(current+1,1,n2 == n1) w2 = w1*current do n3 = min(n2,n-n1-n2), (n-n1-n2+1)/2, -1 L3 = choose(n3) current = merge(current+1,1,n3 == n2) w3 = w2*current n4 = n-n1-n2-n3 L4 = choose(n4) current = merge(current+1,1,n4 == n3) w4 = w3*current term = 24/w4*L1*L2*L3*L4 write(*,'(*(g0))') n1,'&',n2,'&',n3,'&', & n4,'&',24/w4,'&',L1,'&',L2,'&',L3,'&', & L4,'&',term,'\\' nfree = nfree+term end do end do end do write(*,'(*(g0))') '\hline&&&&&&&&\llap{\text{Hands for ',n,' cards:}}&',nfree write(*,'(a)') '\end{array}$$' end function nfree subroutine init_params integer i integer(INT64) j integer(INT64) fact(0:13) fact = [(product([(j,j=1,i)]),i=0,13)] choose = [(fact(13)/fact(i)/fact(13-i),i=0,13)] end subroutine init_params end module FlushFun program flush2 use FlushFun implicit none integer(INT64) free integer n call init_params do n = 4,17 free = nfree(n) end do end program flush2 ``` And here are the tables in prints out: $$\begin{array}{rrrr|r|rrrr|r} \rlap{\text{Number}}&&&&&\rlap{\text{Hands in Suit}}&&&&\\ \clubsuit&\diamondsuit&\heartsuit&\spadesuit&\text{Ways}&\clubsuit&\diamondsuit&\heartsuit&\spadesuit&\text{Total}\\ \hline 4&0&0&0&4&715&1&1&1&2860\\ 3&1&0&0&12&286&13&1&1&44616\\ 2&2&0&0&6&78&78&1&1&36504\\ 2&1&1&0&12&78&13&13&1&158184\\ 1&1&1&1&1&13&13&13&13&28561\\ \hline&&&&&&&&\llap{\text{Hands for 4 cards:}}&270725 \end{array}$$ $$\begin{array}{rrrr|r|rrrr|r} \rlap{\text{Number}}&&&&&\rlap{\text{Hands in Suit}}&&&&\\ \clubsuit&\diamondsuit&\heartsuit&\spadesuit&\text{Ways}&\clubsuit&\diamondsuit&\heartsuit&\spadesuit&\text{Total}\\ \hline 4&1&0&0&12&715&13&1&1&111540\\ 3&2&0&0&12&286&78&1&1&267696\\ 3&1&1&0&12&286&13&13&1&580008\\ 2&2&1&0&12&78&78&13&1&949104\\ 2&1&1&1&4&78&13&13&13&685464\\ \hline&&&&&&&&\llap{\text{Hands for 5 cards:}}&2593812 \end{array}$$ $$\begin{array}{rrrr|r|rrrr|r} \rlap{\text{Number}}&&&&&\rlap{\text{Hands in Suit}}&&&&\\ \clubsuit&\diamondsuit&\heartsuit&\spadesuit&\text{Ways}&\clubsuit&\diamondsuit&\heartsuit&\spadesuit&\text{Total}\\ \hline 4&2&0&0&12&715&78&1&1&669240\\ 4&1&1&0&12&715&13&13&1&1450020\\ 3&3&0&0&6&286&286&1&1&490776\\ 3&2&1&0&24&286&78&13&1&6960096\\ 3&1&1&1&4&286&13&13&13&2513368\\ 2&2&2&0&4&78&78&78&1&1898208\\ 2&2&1&1&6&78&78&13&13&6169176\\ \hline&&&&&&&&\llap{\text{Hands for 6 cards:}}&20150884 \end{array}$$ $$\begin{array}{rrrr|r|rrrr|r} \rlap{\text{Number}}&&&&&\rlap{\text{Hands in Suit}}&&&&\\ \clubsuit&\diamondsuit&\heartsuit&\spadesuit&\text{Ways}&\clubsuit&\diamondsuit&\heartsuit&\spadesuit&\text{Total}\\ \hline 4&3&0&0&12&715&286&1&1&2453880\\ 4&2&1&0&24&715&78&13&1&17400240\\ 4&1&1&1&4&715&13&13&13&6283420\\ 3&3&1&0&12&286&286&13&1&12760176\\ 3&2&2&0&12&286&78&78&1&20880288\\ 3&2&1&1&12&286&78&13&13&45240624\\ 2&2&2&1&4&78&78&78&13&24676704\\ \hline&&&&&&&&\llap{\text{Hands for 7 cards:}}&129695332 \end{array}$$ $$\begin{array}{rrrr|r|rrrr|r} \rlap{\text{Number}}&&&&&\rlap{\text{Hands in Suit}}&&&&\\ \clubsuit&\diamondsuit&\heartsuit&\spadesuit&\text{Ways}&\clubsuit&\diamondsuit&\heartsuit&\spadesuit&\text{Total}\\ \hline 4&4&0&0&6&715&715&1&1&3067350\\ 4&3&1&0&24&715&286&13&1&63800880\\ 4&2&2&0&12&715&78&78&1&52200720\\ 4&2&1&1&12&715&78&13&13&113101560\\ 3&3&2&0&12&286&286&78&1&76561056\\ 3&3&1&1&6&286&286&13&13&82941144\\ 3&2&2&1&12&286&78&78&13&271443744\\ 2&2&2&2&1&78&78&78&78&37015056\\ \hline&&&&&&&&\llap{\text{Hands for 8 cards:}}&700131510 \end{array}$$ $$\begin{array}{rrrr|r|rrrr|r} \rlap{\text{Number}}&&&&&\rlap{\text{Hands in Suit}}&&&&\\ \clubsuit&\diamondsuit&\heartsuit&\spadesuit&\text{Ways}&\clubsuit&\diamondsuit&\heartsuit&\spadesuit&\text{Total}\\ \hline 4&4&1&0&12&715&715&13&1&79751100\\ 4&3&2&0&24&715&286&78&1&382805280\\ 4&3&1&1&12&715&286&13&13&414705720\\ 4&2&2&1&12&715&78&78&13&678609360\\ 3&3&3&0&4&286&286&286&1&93574624\\ 3&3&2&1&12&286&286&78&13&995293728\\ 3&2&2&2&4&286&78&78&78&542887488\\ \hline&&&&&&&&\llap{\text{Hands for 9 cards:}}&3187627300 \end{array}$$ $$\begin{array}{rrrr|r|rrrr|r} \rlap{\text{Number}}&&&&&\rlap{\text{Hands in Suit}}&&&&\\ \clubsuit&\diamondsuit&\heartsuit&\spadesuit&\text{Ways}&\clubsuit&\diamondsuit&\heartsuit&\spadesuit&\text{Total}\\ \hline 4&4&2&0&12&715&715&78&1&478506600\\ 4&4&1&1&6&715&715&13&13&518382150\\ 4&3&3&0&12&715&286&286&1&701809680\\ 4&3&2&1&24&715&286&78&13&4976468640\\ 4&2&2&2&4&715&78&78&78&1357218720\\ 3&3&3&1&4&286&286&286&13&1216470112\\ 3&3&2&2&6&286&286&78&78&2985881184\\ \hline&&&&&&&&\llap{\text{Hands for 10 cards:}}&12234737086 \end{array}$$ $$\begin{array}{rrrr|r|rrrr|r} \rlap{\text{Number}}&&&&&\rlap{\text{Hands in Suit}}&&&&\\ \clubsuit&\diamondsuit&\heartsuit&\spadesuit&\text{Ways}&\clubsuit&\diamondsuit&\heartsuit&\spadesuit&\text{Total}\\ \hline 4&4&3&0&12&715&715&286&1&1754524200\\ 4&4&2&1&12&715&715&78&13&6220585800\\ 4&3&3&1&12&715&286&286&13&9123525840\\ 4&3&2&2&12&715&286&78&78&14929405920\\ 3&3&3&2&4&286&286&286&78&7298820672\\ \hline&&&&&&&&\llap{\text{Hands for 11 cards:}}&39326862432 \end{array}$$ $$\begin{array}{rrrr|r|rrrr|r} \rlap{\text{Number}}&&&&&\rlap{\text{Hands in Suit}}&&&&\\ \clubsuit&\diamondsuit&\heartsuit&\spadesuit&\text{Ways}&\clubsuit&\diamondsuit&\heartsuit&\spadesuit&\text{Total}\\ \hline 4&4&4&0&4&715&715&715&1&1462103500\\ 4&4&3&1&12&715&715&286&13&22808814600\\ 4&4&2&2&6&715&715&78&78&18661757400\\ 4&3&3&2&12&715&286&286&78&54741155040\\ 3&3&3&3&1&286&286&286&286&6690585616\\ \hline&&&&&&&&\llap{\text{Hands for 12 cards:}}&104364416156 \end{array}$$ $$\begin{array}{rrrr|r|rrrr|r} \rlap{\text{Number}}&&&&&\rlap{\text{Hands in Suit}}&&&&\\ \clubsuit&\diamondsuit&\heartsuit&\spadesuit&\text{Ways}&\clubsuit&\diamondsuit&\heartsuit&\spadesuit&\text{Total}\\ \hline 4&4&4&1&4&715&715&715&13&19007345500\\ 4&4&3&2&12&715&715&286&78&136852887600\\ 4&3&3&3&4&715&286&286&286&66905856160\\ \hline&&&&&&&&\llap{\text{Hands for 13 cards:}}&222766089260 \end{array}$$ $$\begin{array}{rrrr|r|rrrr|r} \rlap{\text{Number}}&&&&&\rlap{\text{Hands in Suit}}&&&&\\ \clubsuit&\diamondsuit&\heartsuit&\spadesuit&\text{Ways}&\clubsuit&\diamondsuit&\heartsuit&\spadesuit&\text{Total}\\ \hline 4&4&4&2&4&715&715&715&78&114044073000\\ 4&4&3&3&6&715&715&286&286&250896960600\\ \hline&&&&&&&&\llap{\text{Hands for 14 cards:}}&364941033600 \end{array}$$ $$\begin{array}{rrrr|r|rrrr|r} \rlap{\text{Number}}&&&&&\rlap{\text{Hands in Suit}}&&&&\\ \clubsuit&\diamondsuit&\heartsuit&\spadesuit&\text{Ways}&\clubsuit&\diamondsuit&\heartsuit&\spadesuit&\text{Total}\\ \hline 4&4&4&3&4&715&715&715&286&418161601000\\ \hline&&&&&&&&\llap{\text{Hands for 15 cards:}}&418161601000 \end{array}$$ $$\begin{array}{rrrr|r|rrrr|r} \rlap{\text{Number}}&&&&&\rlap{\text{Hands in Suit}}&&&&\\ \clubsuit&\diamondsuit&\heartsuit&\spadesuit&\text{Ways}&\clubsuit&\diamondsuit&\heartsuit&\spadesuit&\text{Total}\\ \hline 4&4&4&4&1&715&715&715&715&261351000625\\ \hline&&&&&&&&\llap{\text{Hands for 16 cards:}}&261351000625 \end{array}$$ $$\begin{array}{rrrr|r|rrrr|r} \rlap{\text{Number}}&&&&&\rlap{\text{Hands in Suit}}&&&&\\ \clubsuit&\diamondsuit&\heartsuit&\spadesuit&\text{Ways}&\clubsuit&\diamondsuit&\heartsuit&\spadesuit&\text{Total}\\ \hline \hline&&&&&&&&\llap{\text{Hands for 17 cards:}}&0 \end{array}$$
A simple approach! You draw say 10 cards. The probability that any of these cards is a particular suite is 1/4. Conversely the prob that any card in not say a diamond is 3/4. Then what is probability that 5 cards are the same suite is inverse that any 5 cards are Not the same suite. This is simply 3/4 ^ 5 = 23.7%. So prob of a simple 5 card flush from 10 cards is 76.3% which to a card player feels about right! Cheers
2,621,584
My goal is to prenex-normalize the following sentence: $(\exists{z} : S(z)) \wedge \exists{x} :\forall{y} : [\forall{z}: S(z) \Rightarrow P(y,z)] \Rightarrow R(x,y)$ I tried many times but none of the things that I try seem to work. I can't wrap my mind around the part between the []-brackets. This is an exercise in a course that I take and we have a tool to check the correctness of a solution, most other exercises were no problem for me but I really struggle with this one.
2018/01/26
[ "https://math.stackexchange.com/questions/2621584", "https://math.stackexchange.com", "https://math.stackexchange.com/users/401361/" ]
To make the formulas a little more compact, I'm going to use the notation $\binom pq$ rather than $^pC\_q$ for number of combinations. Notice that $^4C\_1 \times {^{13}C\_5} = \binom41\binom{13}{5}$ is a constant, whereas $^{52}C\_n = \binom{52}{n}$ increases as $n$ increases, so $$ \frac{\binom41\binom{13}{5}}{\binom{52}{n}} $$ gets progressively *smaller* as $n$ gets larger, opposite from what you know the correct answer must do. Therefore this cannot be the answer. The formula above is correct in the case $n=5$ only. It is true that the probability of drawing at least one $5$-card flush in $n$ cards can be expressed as a fraction with denominator $\binom{52}{n},$ but in general the numerator is larger than $\binom41\binom{13}{5}.$ Let $K(n)$ be the number of $n$-card hands with at least one $5$-card flush, so that the desired probability is $$ \frac{K(n)}{\binom{52}{n}}, $$ and let's see how we can compute $K(n)$ for a few different values of $n.$ For $n=6,$ we have to consider the $\binom{13}{6}$ different sets of $6$ cards that might be drawn from one suit times the $4$ different suits from which they might be drawn; but we also have to consider the $\binom{13}{5}$ different sets of $5$ cards that might be drawn from one suit times the $\binom{13}{1}$ ways to draw the sixth card from another suite times the $4\times3$ different permutations of suits from which they might be drawn. So $$ K(6) = 4 \binom{13}{6} + 12 \binom{13}{5} \binom{13}{1} = 207636. $$ For $n=7$ the possibilities are not just $7$ of one suit or $6$ of one suit and $1$ of another; it could be $5$ of one suit and $2$ of another, or $5$ of one suit and $1$ each of two others. In that last case, the only choices of suits are $4$ choices for the long suit and which of the other $3$ suits does *not* occur; it doesn't matter which of the two singleton suits we write first. So $$ K(7) = 4 \binom{13}{7} + 12 \binom{13}{6} \binom{13}{1} + 12 \binom{13}{5} \binom{13}{2} + 12 \binom{13}{5} \binom{13}{1}^2 = 4089228 $$ It's hard to imagine how we're going to write a simple formula for $K(n)$ using the usual combinatoric functions, since for the next few $n,$ each time we add a card we increase the number of different possible counts of cards by suit; for example, for $n=8$ the number of cards in each suit can be $8$ (all one suit), $7 + 1,$ $6+2,$ $6+1+1,$ $5+3,$ $5+2+1,$ or $5+1+1.$ The formula would not even fit on one line of this answer format. For $n$ close to $17,$ the formulas are simpler if we count the number of non-flushes, that is, $\binom{52}{n} - K(n).$ For example, for $n=16,$ the only non-flushes obtained by drawing $4$ cards from each suit, $$ \binom{52}{16} - K(16) = \binom{13}{4}^4 = 261351000625. $$ For $n=15,$ we can only have $4$ cards from three of the suits and $3$ from the other, with $4$ different choices of the $3$-card suit, so $$ \binom{52}{15} - K(15) = 4 \binom{13}{4}^3 \binom{13}{3} = 418161601000. $$ For $n=14,$ the possible numbers of cards of each suit are $4+4+4+2$ or $4+4+3+3$, so $$ \binom{52}{14} - K(14) = 4 \binom{13}{4}^3 \binom{13}{2} + \binom62 \binom{13}{4}^2 \binom{13}{3}^2 = 364941033600. $$ Observing that $\binom{52}{6} - K(6) = 20150884$ and $\binom{52}{7} - K(7) = 129695332,$ we can see that the result of the computer calculation [offered in another answer](https://math.stackexchange.com/a/2622642) is correct for $n \in \{4,5,6,7,14,15, 16, 17\}.$
An alternative approach is use a generating function. Let $a\_n$ be the number of $n$-card hands which do **not** include a 5-card flush, i.e., each suite has 0,1,2,3, or 4 cards in the hand. Define the generating function $$f(x) = \sum\_{n=0}^{\infty} a\_n x^n$$ Then $$f(x) = \left[ 1 + \binom{13}{1} x + \binom{13}{2} x^2 + \binom{13}{3} x^3 + \binom{13}{4} x^4 \right]^4$$ which yields, on expansion (I used a computer algebra system) $$f(x) = 1+52 x+1326 x^2+22100 x^3+270725 x^4+2593812 x^5+20150884 x^6+129695332 x^7+700131510 x^8+3187627300 x^9+12234737086 x^{10}+39326862432 x^{11}+104364416156 x^{12}+222766089260 x^{13}+364941033600 x^{14}+418161601000 x^{15}+261351000625 x^{16}$$ The probability that an $n$-card hand does not include a 5-card flush is $$p\_n = \frac{a\_n}{\binom{52}{n}}$$ so, for example, $$p\_6 = \frac{20150884}{\binom{52}{6}} = 0.989801$$ and the probability a 6-card hand **does** include a 5-card flush is $1-p\_6 = 0.010199$.
2,621,584
My goal is to prenex-normalize the following sentence: $(\exists{z} : S(z)) \wedge \exists{x} :\forall{y} : [\forall{z}: S(z) \Rightarrow P(y,z)] \Rightarrow R(x,y)$ I tried many times but none of the things that I try seem to work. I can't wrap my mind around the part between the []-brackets. This is an exercise in a course that I take and we have a tool to check the correctness of a solution, most other exercises were no problem for me but I really struggle with this one.
2018/01/26
[ "https://math.stackexchange.com/questions/2621584", "https://math.stackexchange.com", "https://math.stackexchange.com/users/401361/" ]
To make the formulas a little more compact, I'm going to use the notation $\binom pq$ rather than $^pC\_q$ for number of combinations. Notice that $^4C\_1 \times {^{13}C\_5} = \binom41\binom{13}{5}$ is a constant, whereas $^{52}C\_n = \binom{52}{n}$ increases as $n$ increases, so $$ \frac{\binom41\binom{13}{5}}{\binom{52}{n}} $$ gets progressively *smaller* as $n$ gets larger, opposite from what you know the correct answer must do. Therefore this cannot be the answer. The formula above is correct in the case $n=5$ only. It is true that the probability of drawing at least one $5$-card flush in $n$ cards can be expressed as a fraction with denominator $\binom{52}{n},$ but in general the numerator is larger than $\binom41\binom{13}{5}.$ Let $K(n)$ be the number of $n$-card hands with at least one $5$-card flush, so that the desired probability is $$ \frac{K(n)}{\binom{52}{n}}, $$ and let's see how we can compute $K(n)$ for a few different values of $n.$ For $n=6,$ we have to consider the $\binom{13}{6}$ different sets of $6$ cards that might be drawn from one suit times the $4$ different suits from which they might be drawn; but we also have to consider the $\binom{13}{5}$ different sets of $5$ cards that might be drawn from one suit times the $\binom{13}{1}$ ways to draw the sixth card from another suite times the $4\times3$ different permutations of suits from which they might be drawn. So $$ K(6) = 4 \binom{13}{6} + 12 \binom{13}{5} \binom{13}{1} = 207636. $$ For $n=7$ the possibilities are not just $7$ of one suit or $6$ of one suit and $1$ of another; it could be $5$ of one suit and $2$ of another, or $5$ of one suit and $1$ each of two others. In that last case, the only choices of suits are $4$ choices for the long suit and which of the other $3$ suits does *not* occur; it doesn't matter which of the two singleton suits we write first. So $$ K(7) = 4 \binom{13}{7} + 12 \binom{13}{6} \binom{13}{1} + 12 \binom{13}{5} \binom{13}{2} + 12 \binom{13}{5} \binom{13}{1}^2 = 4089228 $$ It's hard to imagine how we're going to write a simple formula for $K(n)$ using the usual combinatoric functions, since for the next few $n,$ each time we add a card we increase the number of different possible counts of cards by suit; for example, for $n=8$ the number of cards in each suit can be $8$ (all one suit), $7 + 1,$ $6+2,$ $6+1+1,$ $5+3,$ $5+2+1,$ or $5+1+1.$ The formula would not even fit on one line of this answer format. For $n$ close to $17,$ the formulas are simpler if we count the number of non-flushes, that is, $\binom{52}{n} - K(n).$ For example, for $n=16,$ the only non-flushes obtained by drawing $4$ cards from each suit, $$ \binom{52}{16} - K(16) = \binom{13}{4}^4 = 261351000625. $$ For $n=15,$ we can only have $4$ cards from three of the suits and $3$ from the other, with $4$ different choices of the $3$-card suit, so $$ \binom{52}{15} - K(15) = 4 \binom{13}{4}^3 \binom{13}{3} = 418161601000. $$ For $n=14,$ the possible numbers of cards of each suit are $4+4+4+2$ or $4+4+3+3$, so $$ \binom{52}{14} - K(14) = 4 \binom{13}{4}^3 \binom{13}{2} + \binom62 \binom{13}{4}^2 \binom{13}{3}^2 = 364941033600. $$ Observing that $\binom{52}{6} - K(6) = 20150884$ and $\binom{52}{7} - K(7) = 129695332,$ we can see that the result of the computer calculation [offered in another answer](https://math.stackexchange.com/a/2622642) is correct for $n \in \{4,5,6,7,14,15, 16, 17\}.$
A simple approach! You draw say 10 cards. The probability that any of these cards is a particular suite is 1/4. Conversely the prob that any card in not say a diamond is 3/4. Then what is probability that 5 cards are the same suite is inverse that any 5 cards are Not the same suite. This is simply 3/4 ^ 5 = 23.7%. So prob of a simple 5 card flush from 10 cards is 76.3% which to a card player feels about right! Cheers
2,621,584
My goal is to prenex-normalize the following sentence: $(\exists{z} : S(z)) \wedge \exists{x} :\forall{y} : [\forall{z}: S(z) \Rightarrow P(y,z)] \Rightarrow R(x,y)$ I tried many times but none of the things that I try seem to work. I can't wrap my mind around the part between the []-brackets. This is an exercise in a course that I take and we have a tool to check the correctness of a solution, most other exercises were no problem for me but I really struggle with this one.
2018/01/26
[ "https://math.stackexchange.com/questions/2621584", "https://math.stackexchange.com", "https://math.stackexchange.com/users/401361/" ]
An alternative approach is use a generating function. Let $a\_n$ be the number of $n$-card hands which do **not** include a 5-card flush, i.e., each suite has 0,1,2,3, or 4 cards in the hand. Define the generating function $$f(x) = \sum\_{n=0}^{\infty} a\_n x^n$$ Then $$f(x) = \left[ 1 + \binom{13}{1} x + \binom{13}{2} x^2 + \binom{13}{3} x^3 + \binom{13}{4} x^4 \right]^4$$ which yields, on expansion (I used a computer algebra system) $$f(x) = 1+52 x+1326 x^2+22100 x^3+270725 x^4+2593812 x^5+20150884 x^6+129695332 x^7+700131510 x^8+3187627300 x^9+12234737086 x^{10}+39326862432 x^{11}+104364416156 x^{12}+222766089260 x^{13}+364941033600 x^{14}+418161601000 x^{15}+261351000625 x^{16}$$ The probability that an $n$-card hand does not include a 5-card flush is $$p\_n = \frac{a\_n}{\binom{52}{n}}$$ so, for example, $$p\_6 = \frac{20150884}{\binom{52}{6}} = 0.989801$$ and the probability a 6-card hand **does** include a 5-card flush is $1-p\_6 = 0.010199$.
A simple approach! You draw say 10 cards. The probability that any of these cards is a particular suite is 1/4. Conversely the prob that any card in not say a diamond is 3/4. Then what is probability that 5 cards are the same suite is inverse that any 5 cards are Not the same suite. This is simply 3/4 ^ 5 = 23.7%. So prob of a simple 5 card flush from 10 cards is 76.3% which to a card player feels about right! Cheers
160,057
I want to know where the source is to look all tables available to query. For example, a few months back I came to know we can query `ApexClass`, `TestCoverage`, etc. ``` SELECT Id, CreatedBy.Name FROM ApexClass SELECT Id, RecordType.Name FROM RecordType ``` Is there a way I can know how many tables are available to query through SOQL?
2017/02/13
[ "https://salesforce.stackexchange.com/questions/160057", "https://salesforce.stackexchange.com", "https://salesforce.stackexchange.com/users/29281/" ]
The SOAP API has a list of [Standard Objects](https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_objects_list.htm), hyperlinked to each object with a list of standard fields and a brief description of those fields, plus any "special rules" that may apply to portal users, queries, etc. In the event that this link somehow breaks, you can just search the Internet for "standard salesforce objects" and you should find it as one of the top organic (non-ad) search results.
Access to standard objects depends from the features enabled in your organization. You can check what is available to your user right now by working with Schema and getGlobalDescribe() method. Following code executed in dev console will give you list of queryable objects for current user. ``` Map<String, Schema.SObjectType> gd = Schema.getGlobalDescribe(); for(Schema.SObjectType typeProcessed : gd.values()){ if(typeProcessed.getDescribe().isQueryable()){ system.debug(typeProcessed.getDescribe().getLocalName()); } } ```
160,057
I want to know where the source is to look all tables available to query. For example, a few months back I came to know we can query `ApexClass`, `TestCoverage`, etc. ``` SELECT Id, CreatedBy.Name FROM ApexClass SELECT Id, RecordType.Name FROM RecordType ``` Is there a way I can know how many tables are available to query through SOQL?
2017/02/13
[ "https://salesforce.stackexchange.com/questions/160057", "https://salesforce.stackexchange.com", "https://salesforce.stackexchange.com/users/29281/" ]
The SOAP API has a list of [Standard Objects](https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_objects_list.htm), hyperlinked to each object with a list of standard fields and a brief description of those fields, plus any "special rules" that may apply to portal users, queries, etc. In the event that this link somehow breaks, you can just search the Internet for "standard salesforce objects" and you should find it as one of the top organic (non-ad) search results.
I usually go to workbench to find the list of Standard & Custom Objects that I can query in SOQL in my org. But as mentioned by sfdcfox, the official documentation is very useful to understand how the standard field values are calculated for standard objects For ex: Opportunity Field Amount (You cannot just update this field value in all the cases. There are some gotchas). [![enter image description here](https://i.stack.imgur.com/dUkJT.png)](https://i.stack.imgur.com/dUkJT.png)
764,616
I am 99.9% sure that my system on my personal computer has been infiltrated. Allow me to first give my reasoning so the situation will be clear: Rough timeline of suspicious activity and subsequent actions taken: 4-26 23:00 I ended all programs and closed my laptop. 4-27 12:00 I opened my laptop after it had been in suspend mode for about 13 hours. Multiple windows were open including: Two chrome windows, system settings, software center. On my desktop there was a git installer (I checked, it has not been installed). 4-27 13:00 Chrome history displayed logins to my email, and other search history that I did not initiate (between 01:00 and 03:00 on 4-27), including "installing git". There was a tab, Digital Ocean "How to customize your bash prompt" open in my browser. It reopened several times after I closed it. I tightened security in Chrome. I disconnected from WiFi, but when I reconnected there was an up-down arrow symbol instead of the standard symbol, and there was no longer a list of networks in the drop down menu for Wifi Under 'Edit Connections' I noticed my laptop had connected to a network called "GFiberSetup 1802" at ~05:30 on 4-27. My neighbors at 1802 xx Drive just had google fiber installed, so I'm guessing it's related. 4-27 20:30 The `who` command revealed that a second user named guest-g20zoo was logged into my system. This is my private laptop that runs Ubuntu, there should not be anyone else on my system. Panicking, I ran `sudo pkill -9 -u guest-g20zoo` and disabled Networking and Wifi I looked in `/var/log/auth.log` and found this: ``` Apr 27 06:55:55 Rho useradd[23872]: new group: name=guest-g20zoo, GID=999 Apr 27 06:55:55 Rho useradd[23872]: new user: name=guest-g20zoo, UID=999, GID=999, home=/tmp/guest-g20zoo, shell=/bin/bash Apr 27 06:55:55 Rho su[23881]: Successful su for guest-g20zoo by root Apr 27 06:55:55 Rho su[23881]: + ??? root:guest-g20zoo Apr 27 06:55:55 Rho su[23881]: pam_unix(su:session): session opened for user guest-g20zoo by (uid=0) Apr 27 06:55:56 Rho systemd: pam_unix(systemd-user:session): session opened for user guest-g20zoo by (uid=0) Apr 27 06:55:56 Rho systemd-logind[767]: New session c3 of user guest-g20zoo. Apr 27 06:55:56 Rho su[23881]: pam_unix(su:session): session closed for user guest-g20zoo Apr 27 06:55:56 Rho systemd-logind[767]: Removed session c3. Apr 27 06:55:56 Rho lightdm: pam_unix(lightdm-autologin:session): session opened for user guest-g20zoo by (uid=0) Apr 27 06:55:56 Rho systemd: pam_unix(systemd-user:session): session closed for user guest-g20zoo Apr 27 06:55:56 Rho systemd-logind[767]: New session c4 of user guest-g20zoo. Apr 27 06:55:56 Rho systemd: pam_unix(systemd-user:session): session opened for user guest-g20zoo by (uid=0) Apr 27 06:56:51 Rho pkexec: pam_unix(polkit-1:session): session opened for user root by (uid=1000) Apr 27 06:56:51 Rho pkexec: pam_systemd(polkit-1:session): Cannot create session: Already running in a session ``` Sorry it's a lot of output, but that's the bulk of activity from guest-g20zoo in the log, all within a couple of minutes. I also checked `/etc/passwd`: ``` guest-G4J7WQ:x:120:132:Guest,,,:/tmp/guest-G4J7WQ:/bin/bash ``` And `/etc/shadow`: ``` root:!:16669:0:99999:7::: daemon:*:16547:0:99999:7::: . . . nobody:*:16547:0:99999:7::: rhobot:$6$encrypted-passwd-cut-for-length.:16918:0:99999:7::: guest-G4J7WQ:*:16689:0:99999:7::: . . ``` I don't entirely understand what this output means for my situation. Are `guest-g20zoo` and `guest-G4J7WQ` the same user? `lastlog` shows: ``` guest-G4J7WQ Never logged in ``` However, `last` shows: ``` guest-g20zoo Wed Apr 27 06:55 - 20:33 (13:37) ``` So it seems like they are not the same user, but guest-g20zoo was nowhere to be found in the output of `lastlog`. I would like to block access for user guest-g20zoo but since (s)he doesn't appear in `/etc/shadow` and I'm assuming doesn't use a password to login, but uses ssh, will `passwd -l guest-g20zoo` work? I tried `systemctl stop sshd`, but got this error message: ``` Failed to stop sshd.service: Unit sshd.service not loaded ``` Does this mean remote login was already disabled on my system, and therefore the above command is redundant? I have tried to find more information about this new user, like what ip address they logged in from, but I can't seem to find anything. Some potentially relevant information: Currently I'm connected to my university's network, and my WiFi icon looks fine, I can see all my network options, and there aren't any weird browsers popping up on their own. Does this indicate that whoever is logging into my system is within range of my WiFi router at my home? I ran `chkrootkit` and everything *seemed* fine, but I also don't know how to interpret all the output. I don't really know what to do here. I just want to be absolutely sure this person (or anyone else for that matter) will never be able to access my system again and I want to find and remove any hidden files created by them. Please and Thank You! P.S. - I already changed my password and encrypted my important files while WiFi and Networking were disabled.
2016/04/28
[ "https://askubuntu.com/questions/764616", "https://askubuntu.com", "https://askubuntu.com/users/447541/" ]
It looks like someone opened a guest session on your laptop while you where away from your room. If I were you I'd ask around, that may be a friend. The guest accounts you see in `/etc/passwd` and `/etc/shadow` are not suspicious to me, they are created by the system when someone open a guest session. > > Apr 27 06:55:55 Rho su[23881]: Successful su for guest-g20zoo by root > > > This line means `root` has access to the guest account, which could be normal but should be investigated. I've tried on my ubuntu1404LTS and don't see this behaviour. You should try to login with a guest session and grep your `auth.log` to see if this line appear everytime a guest user logs in. All the opened windows of chrome, that you've seen when you opened your laptop. Is it possible that you were seeing the guest session desktop ?
The "suspicious" activity is explained by the following: my laptop no longer suspends when the lid is closed, the laptop is a touch screen and reacted to applied pressure (possibly my cats). The provided lines from `/var/log/auth.log`, and the output of the `who` command are consistent with a guest session login. While I disabled guest session login from the greeter, it is still accessible from the drop down menu in the upper right hand corner in the Unity DE. Ergo, a guest session can be opened while I am logged in. I have tested the "applied pressure" theory; windows can and do open while the lid is closed. I also logged into a new guest session. Log lines identical to what I perceived as suspicious activity were present in `/var/log/auth.log` after I did this. I switched users, back to my account, and ran the `who` command - the output indicated there was a guest logged into the system. The up-down arrow WiFi logo has reverted to the standard WiFi logo, and all the available connections are visible. This was a problem with our network, and is unrelated.
764,616
I am 99.9% sure that my system on my personal computer has been infiltrated. Allow me to first give my reasoning so the situation will be clear: Rough timeline of suspicious activity and subsequent actions taken: 4-26 23:00 I ended all programs and closed my laptop. 4-27 12:00 I opened my laptop after it had been in suspend mode for about 13 hours. Multiple windows were open including: Two chrome windows, system settings, software center. On my desktop there was a git installer (I checked, it has not been installed). 4-27 13:00 Chrome history displayed logins to my email, and other search history that I did not initiate (between 01:00 and 03:00 on 4-27), including "installing git". There was a tab, Digital Ocean "How to customize your bash prompt" open in my browser. It reopened several times after I closed it. I tightened security in Chrome. I disconnected from WiFi, but when I reconnected there was an up-down arrow symbol instead of the standard symbol, and there was no longer a list of networks in the drop down menu for Wifi Under 'Edit Connections' I noticed my laptop had connected to a network called "GFiberSetup 1802" at ~05:30 on 4-27. My neighbors at 1802 xx Drive just had google fiber installed, so I'm guessing it's related. 4-27 20:30 The `who` command revealed that a second user named guest-g20zoo was logged into my system. This is my private laptop that runs Ubuntu, there should not be anyone else on my system. Panicking, I ran `sudo pkill -9 -u guest-g20zoo` and disabled Networking and Wifi I looked in `/var/log/auth.log` and found this: ``` Apr 27 06:55:55 Rho useradd[23872]: new group: name=guest-g20zoo, GID=999 Apr 27 06:55:55 Rho useradd[23872]: new user: name=guest-g20zoo, UID=999, GID=999, home=/tmp/guest-g20zoo, shell=/bin/bash Apr 27 06:55:55 Rho su[23881]: Successful su for guest-g20zoo by root Apr 27 06:55:55 Rho su[23881]: + ??? root:guest-g20zoo Apr 27 06:55:55 Rho su[23881]: pam_unix(su:session): session opened for user guest-g20zoo by (uid=0) Apr 27 06:55:56 Rho systemd: pam_unix(systemd-user:session): session opened for user guest-g20zoo by (uid=0) Apr 27 06:55:56 Rho systemd-logind[767]: New session c3 of user guest-g20zoo. Apr 27 06:55:56 Rho su[23881]: pam_unix(su:session): session closed for user guest-g20zoo Apr 27 06:55:56 Rho systemd-logind[767]: Removed session c3. Apr 27 06:55:56 Rho lightdm: pam_unix(lightdm-autologin:session): session opened for user guest-g20zoo by (uid=0) Apr 27 06:55:56 Rho systemd: pam_unix(systemd-user:session): session closed for user guest-g20zoo Apr 27 06:55:56 Rho systemd-logind[767]: New session c4 of user guest-g20zoo. Apr 27 06:55:56 Rho systemd: pam_unix(systemd-user:session): session opened for user guest-g20zoo by (uid=0) Apr 27 06:56:51 Rho pkexec: pam_unix(polkit-1:session): session opened for user root by (uid=1000) Apr 27 06:56:51 Rho pkexec: pam_systemd(polkit-1:session): Cannot create session: Already running in a session ``` Sorry it's a lot of output, but that's the bulk of activity from guest-g20zoo in the log, all within a couple of minutes. I also checked `/etc/passwd`: ``` guest-G4J7WQ:x:120:132:Guest,,,:/tmp/guest-G4J7WQ:/bin/bash ``` And `/etc/shadow`: ``` root:!:16669:0:99999:7::: daemon:*:16547:0:99999:7::: . . . nobody:*:16547:0:99999:7::: rhobot:$6$encrypted-passwd-cut-for-length.:16918:0:99999:7::: guest-G4J7WQ:*:16689:0:99999:7::: . . ``` I don't entirely understand what this output means for my situation. Are `guest-g20zoo` and `guest-G4J7WQ` the same user? `lastlog` shows: ``` guest-G4J7WQ Never logged in ``` However, `last` shows: ``` guest-g20zoo Wed Apr 27 06:55 - 20:33 (13:37) ``` So it seems like they are not the same user, but guest-g20zoo was nowhere to be found in the output of `lastlog`. I would like to block access for user guest-g20zoo but since (s)he doesn't appear in `/etc/shadow` and I'm assuming doesn't use a password to login, but uses ssh, will `passwd -l guest-g20zoo` work? I tried `systemctl stop sshd`, but got this error message: ``` Failed to stop sshd.service: Unit sshd.service not loaded ``` Does this mean remote login was already disabled on my system, and therefore the above command is redundant? I have tried to find more information about this new user, like what ip address they logged in from, but I can't seem to find anything. Some potentially relevant information: Currently I'm connected to my university's network, and my WiFi icon looks fine, I can see all my network options, and there aren't any weird browsers popping up on their own. Does this indicate that whoever is logging into my system is within range of my WiFi router at my home? I ran `chkrootkit` and everything *seemed* fine, but I also don't know how to interpret all the output. I don't really know what to do here. I just want to be absolutely sure this person (or anyone else for that matter) will never be able to access my system again and I want to find and remove any hidden files created by them. Please and Thank You! P.S. - I already changed my password and encrypted my important files while WiFi and Networking were disabled.
2016/04/28
[ "https://askubuntu.com/questions/764616", "https://askubuntu.com", "https://askubuntu.com/users/447541/" ]
**Wipe the hard drive and reinstall your operating system from scratch.** In any case of unauthorised access there is the possibility the attacker was able to get root privileges, so it is sensible to assume that it happened. In this case, auth.log appears to confirm this was indeed the case - unless this was *you* that switched user: > > Apr 27 06:55:55 Rho su[23881]: Successful su for guest-g20zoo by root > > > With root privileges in particular, they may have messed with the system in ways which are practically impossible to fix without a reinstall, such as by modifying boot scripts or installing new scripts and applications that run at boot, and so on. These could do things like run unauthorised network software (ie to form part of a botnet), or leave backdoors into your system. Trying to detect and repair this sort of thing without a reinstall is messy at best, and not guaranteed to rid you of everything.
The "suspicious" activity is explained by the following: my laptop no longer suspends when the lid is closed, the laptop is a touch screen and reacted to applied pressure (possibly my cats). The provided lines from `/var/log/auth.log`, and the output of the `who` command are consistent with a guest session login. While I disabled guest session login from the greeter, it is still accessible from the drop down menu in the upper right hand corner in the Unity DE. Ergo, a guest session can be opened while I am logged in. I have tested the "applied pressure" theory; windows can and do open while the lid is closed. I also logged into a new guest session. Log lines identical to what I perceived as suspicious activity were present in `/var/log/auth.log` after I did this. I switched users, back to my account, and ran the `who` command - the output indicated there was a guest logged into the system. The up-down arrow WiFi logo has reverted to the standard WiFi logo, and all the available connections are visible. This was a problem with our network, and is unrelated.
764,616
I am 99.9% sure that my system on my personal computer has been infiltrated. Allow me to first give my reasoning so the situation will be clear: Rough timeline of suspicious activity and subsequent actions taken: 4-26 23:00 I ended all programs and closed my laptop. 4-27 12:00 I opened my laptop after it had been in suspend mode for about 13 hours. Multiple windows were open including: Two chrome windows, system settings, software center. On my desktop there was a git installer (I checked, it has not been installed). 4-27 13:00 Chrome history displayed logins to my email, and other search history that I did not initiate (between 01:00 and 03:00 on 4-27), including "installing git". There was a tab, Digital Ocean "How to customize your bash prompt" open in my browser. It reopened several times after I closed it. I tightened security in Chrome. I disconnected from WiFi, but when I reconnected there was an up-down arrow symbol instead of the standard symbol, and there was no longer a list of networks in the drop down menu for Wifi Under 'Edit Connections' I noticed my laptop had connected to a network called "GFiberSetup 1802" at ~05:30 on 4-27. My neighbors at 1802 xx Drive just had google fiber installed, so I'm guessing it's related. 4-27 20:30 The `who` command revealed that a second user named guest-g20zoo was logged into my system. This is my private laptop that runs Ubuntu, there should not be anyone else on my system. Panicking, I ran `sudo pkill -9 -u guest-g20zoo` and disabled Networking and Wifi I looked in `/var/log/auth.log` and found this: ``` Apr 27 06:55:55 Rho useradd[23872]: new group: name=guest-g20zoo, GID=999 Apr 27 06:55:55 Rho useradd[23872]: new user: name=guest-g20zoo, UID=999, GID=999, home=/tmp/guest-g20zoo, shell=/bin/bash Apr 27 06:55:55 Rho su[23881]: Successful su for guest-g20zoo by root Apr 27 06:55:55 Rho su[23881]: + ??? root:guest-g20zoo Apr 27 06:55:55 Rho su[23881]: pam_unix(su:session): session opened for user guest-g20zoo by (uid=0) Apr 27 06:55:56 Rho systemd: pam_unix(systemd-user:session): session opened for user guest-g20zoo by (uid=0) Apr 27 06:55:56 Rho systemd-logind[767]: New session c3 of user guest-g20zoo. Apr 27 06:55:56 Rho su[23881]: pam_unix(su:session): session closed for user guest-g20zoo Apr 27 06:55:56 Rho systemd-logind[767]: Removed session c3. Apr 27 06:55:56 Rho lightdm: pam_unix(lightdm-autologin:session): session opened for user guest-g20zoo by (uid=0) Apr 27 06:55:56 Rho systemd: pam_unix(systemd-user:session): session closed for user guest-g20zoo Apr 27 06:55:56 Rho systemd-logind[767]: New session c4 of user guest-g20zoo. Apr 27 06:55:56 Rho systemd: pam_unix(systemd-user:session): session opened for user guest-g20zoo by (uid=0) Apr 27 06:56:51 Rho pkexec: pam_unix(polkit-1:session): session opened for user root by (uid=1000) Apr 27 06:56:51 Rho pkexec: pam_systemd(polkit-1:session): Cannot create session: Already running in a session ``` Sorry it's a lot of output, but that's the bulk of activity from guest-g20zoo in the log, all within a couple of minutes. I also checked `/etc/passwd`: ``` guest-G4J7WQ:x:120:132:Guest,,,:/tmp/guest-G4J7WQ:/bin/bash ``` And `/etc/shadow`: ``` root:!:16669:0:99999:7::: daemon:*:16547:0:99999:7::: . . . nobody:*:16547:0:99999:7::: rhobot:$6$encrypted-passwd-cut-for-length.:16918:0:99999:7::: guest-G4J7WQ:*:16689:0:99999:7::: . . ``` I don't entirely understand what this output means for my situation. Are `guest-g20zoo` and `guest-G4J7WQ` the same user? `lastlog` shows: ``` guest-G4J7WQ Never logged in ``` However, `last` shows: ``` guest-g20zoo Wed Apr 27 06:55 - 20:33 (13:37) ``` So it seems like they are not the same user, but guest-g20zoo was nowhere to be found in the output of `lastlog`. I would like to block access for user guest-g20zoo but since (s)he doesn't appear in `/etc/shadow` and I'm assuming doesn't use a password to login, but uses ssh, will `passwd -l guest-g20zoo` work? I tried `systemctl stop sshd`, but got this error message: ``` Failed to stop sshd.service: Unit sshd.service not loaded ``` Does this mean remote login was already disabled on my system, and therefore the above command is redundant? I have tried to find more information about this new user, like what ip address they logged in from, but I can't seem to find anything. Some potentially relevant information: Currently I'm connected to my university's network, and my WiFi icon looks fine, I can see all my network options, and there aren't any weird browsers popping up on their own. Does this indicate that whoever is logging into my system is within range of my WiFi router at my home? I ran `chkrootkit` and everything *seemed* fine, but I also don't know how to interpret all the output. I don't really know what to do here. I just want to be absolutely sure this person (or anyone else for that matter) will never be able to access my system again and I want to find and remove any hidden files created by them. Please and Thank You! P.S. - I already changed my password and encrypted my important files while WiFi and Networking were disabled.
2016/04/28
[ "https://askubuntu.com/questions/764616", "https://askubuntu.com", "https://askubuntu.com/users/447541/" ]
The "suspicious" activity is explained by the following: my laptop no longer suspends when the lid is closed, the laptop is a touch screen and reacted to applied pressure (possibly my cats). The provided lines from `/var/log/auth.log`, and the output of the `who` command are consistent with a guest session login. While I disabled guest session login from the greeter, it is still accessible from the drop down menu in the upper right hand corner in the Unity DE. Ergo, a guest session can be opened while I am logged in. I have tested the "applied pressure" theory; windows can and do open while the lid is closed. I also logged into a new guest session. Log lines identical to what I perceived as suspicious activity were present in `/var/log/auth.log` after I did this. I switched users, back to my account, and ran the `who` command - the output indicated there was a guest logged into the system. The up-down arrow WiFi logo has reverted to the standard WiFi logo, and all the available connections are visible. This was a problem with our network, and is unrelated.
Pull out the wireless card/stick and look over the traces. Make a record of your logs so askbuntu can help further. After that wipe your drives and try a different distro, try a live cd leave it running to see if there's a pattern to the attacks.
764,616
I am 99.9% sure that my system on my personal computer has been infiltrated. Allow me to first give my reasoning so the situation will be clear: Rough timeline of suspicious activity and subsequent actions taken: 4-26 23:00 I ended all programs and closed my laptop. 4-27 12:00 I opened my laptop after it had been in suspend mode for about 13 hours. Multiple windows were open including: Two chrome windows, system settings, software center. On my desktop there was a git installer (I checked, it has not been installed). 4-27 13:00 Chrome history displayed logins to my email, and other search history that I did not initiate (between 01:00 and 03:00 on 4-27), including "installing git". There was a tab, Digital Ocean "How to customize your bash prompt" open in my browser. It reopened several times after I closed it. I tightened security in Chrome. I disconnected from WiFi, but when I reconnected there was an up-down arrow symbol instead of the standard symbol, and there was no longer a list of networks in the drop down menu for Wifi Under 'Edit Connections' I noticed my laptop had connected to a network called "GFiberSetup 1802" at ~05:30 on 4-27. My neighbors at 1802 xx Drive just had google fiber installed, so I'm guessing it's related. 4-27 20:30 The `who` command revealed that a second user named guest-g20zoo was logged into my system. This is my private laptop that runs Ubuntu, there should not be anyone else on my system. Panicking, I ran `sudo pkill -9 -u guest-g20zoo` and disabled Networking and Wifi I looked in `/var/log/auth.log` and found this: ``` Apr 27 06:55:55 Rho useradd[23872]: new group: name=guest-g20zoo, GID=999 Apr 27 06:55:55 Rho useradd[23872]: new user: name=guest-g20zoo, UID=999, GID=999, home=/tmp/guest-g20zoo, shell=/bin/bash Apr 27 06:55:55 Rho su[23881]: Successful su for guest-g20zoo by root Apr 27 06:55:55 Rho su[23881]: + ??? root:guest-g20zoo Apr 27 06:55:55 Rho su[23881]: pam_unix(su:session): session opened for user guest-g20zoo by (uid=0) Apr 27 06:55:56 Rho systemd: pam_unix(systemd-user:session): session opened for user guest-g20zoo by (uid=0) Apr 27 06:55:56 Rho systemd-logind[767]: New session c3 of user guest-g20zoo. Apr 27 06:55:56 Rho su[23881]: pam_unix(su:session): session closed for user guest-g20zoo Apr 27 06:55:56 Rho systemd-logind[767]: Removed session c3. Apr 27 06:55:56 Rho lightdm: pam_unix(lightdm-autologin:session): session opened for user guest-g20zoo by (uid=0) Apr 27 06:55:56 Rho systemd: pam_unix(systemd-user:session): session closed for user guest-g20zoo Apr 27 06:55:56 Rho systemd-logind[767]: New session c4 of user guest-g20zoo. Apr 27 06:55:56 Rho systemd: pam_unix(systemd-user:session): session opened for user guest-g20zoo by (uid=0) Apr 27 06:56:51 Rho pkexec: pam_unix(polkit-1:session): session opened for user root by (uid=1000) Apr 27 06:56:51 Rho pkexec: pam_systemd(polkit-1:session): Cannot create session: Already running in a session ``` Sorry it's a lot of output, but that's the bulk of activity from guest-g20zoo in the log, all within a couple of minutes. I also checked `/etc/passwd`: ``` guest-G4J7WQ:x:120:132:Guest,,,:/tmp/guest-G4J7WQ:/bin/bash ``` And `/etc/shadow`: ``` root:!:16669:0:99999:7::: daemon:*:16547:0:99999:7::: . . . nobody:*:16547:0:99999:7::: rhobot:$6$encrypted-passwd-cut-for-length.:16918:0:99999:7::: guest-G4J7WQ:*:16689:0:99999:7::: . . ``` I don't entirely understand what this output means for my situation. Are `guest-g20zoo` and `guest-G4J7WQ` the same user? `lastlog` shows: ``` guest-G4J7WQ Never logged in ``` However, `last` shows: ``` guest-g20zoo Wed Apr 27 06:55 - 20:33 (13:37) ``` So it seems like they are not the same user, but guest-g20zoo was nowhere to be found in the output of `lastlog`. I would like to block access for user guest-g20zoo but since (s)he doesn't appear in `/etc/shadow` and I'm assuming doesn't use a password to login, but uses ssh, will `passwd -l guest-g20zoo` work? I tried `systemctl stop sshd`, but got this error message: ``` Failed to stop sshd.service: Unit sshd.service not loaded ``` Does this mean remote login was already disabled on my system, and therefore the above command is redundant? I have tried to find more information about this new user, like what ip address they logged in from, but I can't seem to find anything. Some potentially relevant information: Currently I'm connected to my university's network, and my WiFi icon looks fine, I can see all my network options, and there aren't any weird browsers popping up on their own. Does this indicate that whoever is logging into my system is within range of my WiFi router at my home? I ran `chkrootkit` and everything *seemed* fine, but I also don't know how to interpret all the output. I don't really know what to do here. I just want to be absolutely sure this person (or anyone else for that matter) will never be able to access my system again and I want to find and remove any hidden files created by them. Please and Thank You! P.S. - I already changed my password and encrypted my important files while WiFi and Networking were disabled.
2016/04/28
[ "https://askubuntu.com/questions/764616", "https://askubuntu.com", "https://askubuntu.com/users/447541/" ]
I just want to mention that "multiple browser tabs/windows open, Software Center open, files downloaded to desktop" is not very consistent with someone logging into your machine via SSH. An attacker logging via SSH would get a text console which is completely separate from what you see on your desktop. They also wouldn't need to google "how to install git" from your desktop session because they'd be sitting in front of their own computer, right? Even if they wanted to install Git (why?), they wouldn't need to download an installer because Git is in Ubuntu repositories, anyone who knows anything about Git or Ubuntu knows that. And why did they have to google how to customize bash prompt? I also suspect that "There was a tab... open in my browser. It reopened several times after I closed it" was actually multiple identical tabs open so you had to close them one by one. What I'm trying to say here is that the pattern of activity resembles a "monkey with a typewriter". You also did not mention you even had SSH server installed - it is not installed by default. So, if you're absolutely sure nobody had *physical access* your laptop without your knowledge, and your laptop has a touchscreen, and it doesn't suspend properly, and it spent some time in your backpack then I think it all can be simply a case of "pocket calling" - random screen touches combined with search suggestions and auto-correction opened multiple windows and performed google searches, clicking on random links and downloading random files. As a personal anecdote - it happens from time to time with my smartphone in my pocket, including opening multiple apps, changing system settings, sending semi-coherent SMS messages and watching random youtube videos.
The "suspicious" activity is explained by the following: my laptop no longer suspends when the lid is closed, the laptop is a touch screen and reacted to applied pressure (possibly my cats). The provided lines from `/var/log/auth.log`, and the output of the `who` command are consistent with a guest session login. While I disabled guest session login from the greeter, it is still accessible from the drop down menu in the upper right hand corner in the Unity DE. Ergo, a guest session can be opened while I am logged in. I have tested the "applied pressure" theory; windows can and do open while the lid is closed. I also logged into a new guest session. Log lines identical to what I perceived as suspicious activity were present in `/var/log/auth.log` after I did this. I switched users, back to my account, and ran the `who` command - the output indicated there was a guest logged into the system. The up-down arrow WiFi logo has reverted to the standard WiFi logo, and all the available connections are visible. This was a problem with our network, and is unrelated.
764,616
I am 99.9% sure that my system on my personal computer has been infiltrated. Allow me to first give my reasoning so the situation will be clear: Rough timeline of suspicious activity and subsequent actions taken: 4-26 23:00 I ended all programs and closed my laptop. 4-27 12:00 I opened my laptop after it had been in suspend mode for about 13 hours. Multiple windows were open including: Two chrome windows, system settings, software center. On my desktop there was a git installer (I checked, it has not been installed). 4-27 13:00 Chrome history displayed logins to my email, and other search history that I did not initiate (between 01:00 and 03:00 on 4-27), including "installing git". There was a tab, Digital Ocean "How to customize your bash prompt" open in my browser. It reopened several times after I closed it. I tightened security in Chrome. I disconnected from WiFi, but when I reconnected there was an up-down arrow symbol instead of the standard symbol, and there was no longer a list of networks in the drop down menu for Wifi Under 'Edit Connections' I noticed my laptop had connected to a network called "GFiberSetup 1802" at ~05:30 on 4-27. My neighbors at 1802 xx Drive just had google fiber installed, so I'm guessing it's related. 4-27 20:30 The `who` command revealed that a second user named guest-g20zoo was logged into my system. This is my private laptop that runs Ubuntu, there should not be anyone else on my system. Panicking, I ran `sudo pkill -9 -u guest-g20zoo` and disabled Networking and Wifi I looked in `/var/log/auth.log` and found this: ``` Apr 27 06:55:55 Rho useradd[23872]: new group: name=guest-g20zoo, GID=999 Apr 27 06:55:55 Rho useradd[23872]: new user: name=guest-g20zoo, UID=999, GID=999, home=/tmp/guest-g20zoo, shell=/bin/bash Apr 27 06:55:55 Rho su[23881]: Successful su for guest-g20zoo by root Apr 27 06:55:55 Rho su[23881]: + ??? root:guest-g20zoo Apr 27 06:55:55 Rho su[23881]: pam_unix(su:session): session opened for user guest-g20zoo by (uid=0) Apr 27 06:55:56 Rho systemd: pam_unix(systemd-user:session): session opened for user guest-g20zoo by (uid=0) Apr 27 06:55:56 Rho systemd-logind[767]: New session c3 of user guest-g20zoo. Apr 27 06:55:56 Rho su[23881]: pam_unix(su:session): session closed for user guest-g20zoo Apr 27 06:55:56 Rho systemd-logind[767]: Removed session c3. Apr 27 06:55:56 Rho lightdm: pam_unix(lightdm-autologin:session): session opened for user guest-g20zoo by (uid=0) Apr 27 06:55:56 Rho systemd: pam_unix(systemd-user:session): session closed for user guest-g20zoo Apr 27 06:55:56 Rho systemd-logind[767]: New session c4 of user guest-g20zoo. Apr 27 06:55:56 Rho systemd: pam_unix(systemd-user:session): session opened for user guest-g20zoo by (uid=0) Apr 27 06:56:51 Rho pkexec: pam_unix(polkit-1:session): session opened for user root by (uid=1000) Apr 27 06:56:51 Rho pkexec: pam_systemd(polkit-1:session): Cannot create session: Already running in a session ``` Sorry it's a lot of output, but that's the bulk of activity from guest-g20zoo in the log, all within a couple of minutes. I also checked `/etc/passwd`: ``` guest-G4J7WQ:x:120:132:Guest,,,:/tmp/guest-G4J7WQ:/bin/bash ``` And `/etc/shadow`: ``` root:!:16669:0:99999:7::: daemon:*:16547:0:99999:7::: . . . nobody:*:16547:0:99999:7::: rhobot:$6$encrypted-passwd-cut-for-length.:16918:0:99999:7::: guest-G4J7WQ:*:16689:0:99999:7::: . . ``` I don't entirely understand what this output means for my situation. Are `guest-g20zoo` and `guest-G4J7WQ` the same user? `lastlog` shows: ``` guest-G4J7WQ Never logged in ``` However, `last` shows: ``` guest-g20zoo Wed Apr 27 06:55 - 20:33 (13:37) ``` So it seems like they are not the same user, but guest-g20zoo was nowhere to be found in the output of `lastlog`. I would like to block access for user guest-g20zoo but since (s)he doesn't appear in `/etc/shadow` and I'm assuming doesn't use a password to login, but uses ssh, will `passwd -l guest-g20zoo` work? I tried `systemctl stop sshd`, but got this error message: ``` Failed to stop sshd.service: Unit sshd.service not loaded ``` Does this mean remote login was already disabled on my system, and therefore the above command is redundant? I have tried to find more information about this new user, like what ip address they logged in from, but I can't seem to find anything. Some potentially relevant information: Currently I'm connected to my university's network, and my WiFi icon looks fine, I can see all my network options, and there aren't any weird browsers popping up on their own. Does this indicate that whoever is logging into my system is within range of my WiFi router at my home? I ran `chkrootkit` and everything *seemed* fine, but I also don't know how to interpret all the output. I don't really know what to do here. I just want to be absolutely sure this person (or anyone else for that matter) will never be able to access my system again and I want to find and remove any hidden files created by them. Please and Thank You! P.S. - I already changed my password and encrypted my important files while WiFi and Networking were disabled.
2016/04/28
[ "https://askubuntu.com/questions/764616", "https://askubuntu.com", "https://askubuntu.com/users/447541/" ]
**Wipe the hard drive and reinstall your operating system from scratch.** In any case of unauthorised access there is the possibility the attacker was able to get root privileges, so it is sensible to assume that it happened. In this case, auth.log appears to confirm this was indeed the case - unless this was *you* that switched user: > > Apr 27 06:55:55 Rho su[23881]: Successful su for guest-g20zoo by root > > > With root privileges in particular, they may have messed with the system in ways which are practically impossible to fix without a reinstall, such as by modifying boot scripts or installing new scripts and applications that run at boot, and so on. These could do things like run unauthorised network software (ie to form part of a botnet), or leave backdoors into your system. Trying to detect and repair this sort of thing without a reinstall is messy at best, and not guaranteed to rid you of everything.
Do you have any friends that like to access your laptop remotely/physically while you're gone? If not: **Wipe the HDD with DBAN and reinstall the OS from scratch. Be sure to backup first.** Something may have been severely compromised within Ubuntu itself. When you reinstall: **Encrypt `/home`.** If the HDD/laptop itself is ever physically stolen, they cannot gain access to the data within `/home`. **Encrypt the HDD.** This prevents people from compromising `/boot` without logging in. You will also have to enter a boot-time password(I think). **Set a strong password.** If someone figures out the HDD password, they cannot access `/home` or login. **Encrypt your WiFi.** Someone may have gotten within the router's proximity and taken advantage of unencrypted Wifi and ssh'd into your laptop. **Disable the guest account.** The attacker may have ssh'd into your laptop, gotten a remote connection, logged in via Guest, and elevated the Guest account to root. This is a dangerous situation. If this happened, the attacker could run this **VERY DANGEROUS** command: ``` rm -rf --no-preserve-root / ``` This erases **A LOT** of data on the HDD, trashes `/home`, and even worse, leaves Ubuntu completely unable to even boot. You will just get thrown into grub rescue, and you will not be able to recover from this. The attacker could also completely destroy the `/home` directory, and so on. If you have a home network, the attacker could also all the other computers on that network unable to boot(if they run Linux). I hope this helps. :)
764,616
I am 99.9% sure that my system on my personal computer has been infiltrated. Allow me to first give my reasoning so the situation will be clear: Rough timeline of suspicious activity and subsequent actions taken: 4-26 23:00 I ended all programs and closed my laptop. 4-27 12:00 I opened my laptop after it had been in suspend mode for about 13 hours. Multiple windows were open including: Two chrome windows, system settings, software center. On my desktop there was a git installer (I checked, it has not been installed). 4-27 13:00 Chrome history displayed logins to my email, and other search history that I did not initiate (between 01:00 and 03:00 on 4-27), including "installing git". There was a tab, Digital Ocean "How to customize your bash prompt" open in my browser. It reopened several times after I closed it. I tightened security in Chrome. I disconnected from WiFi, but when I reconnected there was an up-down arrow symbol instead of the standard symbol, and there was no longer a list of networks in the drop down menu for Wifi Under 'Edit Connections' I noticed my laptop had connected to a network called "GFiberSetup 1802" at ~05:30 on 4-27. My neighbors at 1802 xx Drive just had google fiber installed, so I'm guessing it's related. 4-27 20:30 The `who` command revealed that a second user named guest-g20zoo was logged into my system. This is my private laptop that runs Ubuntu, there should not be anyone else on my system. Panicking, I ran `sudo pkill -9 -u guest-g20zoo` and disabled Networking and Wifi I looked in `/var/log/auth.log` and found this: ``` Apr 27 06:55:55 Rho useradd[23872]: new group: name=guest-g20zoo, GID=999 Apr 27 06:55:55 Rho useradd[23872]: new user: name=guest-g20zoo, UID=999, GID=999, home=/tmp/guest-g20zoo, shell=/bin/bash Apr 27 06:55:55 Rho su[23881]: Successful su for guest-g20zoo by root Apr 27 06:55:55 Rho su[23881]: + ??? root:guest-g20zoo Apr 27 06:55:55 Rho su[23881]: pam_unix(su:session): session opened for user guest-g20zoo by (uid=0) Apr 27 06:55:56 Rho systemd: pam_unix(systemd-user:session): session opened for user guest-g20zoo by (uid=0) Apr 27 06:55:56 Rho systemd-logind[767]: New session c3 of user guest-g20zoo. Apr 27 06:55:56 Rho su[23881]: pam_unix(su:session): session closed for user guest-g20zoo Apr 27 06:55:56 Rho systemd-logind[767]: Removed session c3. Apr 27 06:55:56 Rho lightdm: pam_unix(lightdm-autologin:session): session opened for user guest-g20zoo by (uid=0) Apr 27 06:55:56 Rho systemd: pam_unix(systemd-user:session): session closed for user guest-g20zoo Apr 27 06:55:56 Rho systemd-logind[767]: New session c4 of user guest-g20zoo. Apr 27 06:55:56 Rho systemd: pam_unix(systemd-user:session): session opened for user guest-g20zoo by (uid=0) Apr 27 06:56:51 Rho pkexec: pam_unix(polkit-1:session): session opened for user root by (uid=1000) Apr 27 06:56:51 Rho pkexec: pam_systemd(polkit-1:session): Cannot create session: Already running in a session ``` Sorry it's a lot of output, but that's the bulk of activity from guest-g20zoo in the log, all within a couple of minutes. I also checked `/etc/passwd`: ``` guest-G4J7WQ:x:120:132:Guest,,,:/tmp/guest-G4J7WQ:/bin/bash ``` And `/etc/shadow`: ``` root:!:16669:0:99999:7::: daemon:*:16547:0:99999:7::: . . . nobody:*:16547:0:99999:7::: rhobot:$6$encrypted-passwd-cut-for-length.:16918:0:99999:7::: guest-G4J7WQ:*:16689:0:99999:7::: . . ``` I don't entirely understand what this output means for my situation. Are `guest-g20zoo` and `guest-G4J7WQ` the same user? `lastlog` shows: ``` guest-G4J7WQ Never logged in ``` However, `last` shows: ``` guest-g20zoo Wed Apr 27 06:55 - 20:33 (13:37) ``` So it seems like they are not the same user, but guest-g20zoo was nowhere to be found in the output of `lastlog`. I would like to block access for user guest-g20zoo but since (s)he doesn't appear in `/etc/shadow` and I'm assuming doesn't use a password to login, but uses ssh, will `passwd -l guest-g20zoo` work? I tried `systemctl stop sshd`, but got this error message: ``` Failed to stop sshd.service: Unit sshd.service not loaded ``` Does this mean remote login was already disabled on my system, and therefore the above command is redundant? I have tried to find more information about this new user, like what ip address they logged in from, but I can't seem to find anything. Some potentially relevant information: Currently I'm connected to my university's network, and my WiFi icon looks fine, I can see all my network options, and there aren't any weird browsers popping up on their own. Does this indicate that whoever is logging into my system is within range of my WiFi router at my home? I ran `chkrootkit` and everything *seemed* fine, but I also don't know how to interpret all the output. I don't really know what to do here. I just want to be absolutely sure this person (or anyone else for that matter) will never be able to access my system again and I want to find and remove any hidden files created by them. Please and Thank You! P.S. - I already changed my password and encrypted my important files while WiFi and Networking were disabled.
2016/04/28
[ "https://askubuntu.com/questions/764616", "https://askubuntu.com", "https://askubuntu.com/users/447541/" ]
It looks like someone opened a guest session on your laptop while you where away from your room. If I were you I'd ask around, that may be a friend. The guest accounts you see in `/etc/passwd` and `/etc/shadow` are not suspicious to me, they are created by the system when someone open a guest session. > > Apr 27 06:55:55 Rho su[23881]: Successful su for guest-g20zoo by root > > > This line means `root` has access to the guest account, which could be normal but should be investigated. I've tried on my ubuntu1404LTS and don't see this behaviour. You should try to login with a guest session and grep your `auth.log` to see if this line appear everytime a guest user logs in. All the opened windows of chrome, that you've seen when you opened your laptop. Is it possible that you were seeing the guest session desktop ?
I just want to mention that "multiple browser tabs/windows open, Software Center open, files downloaded to desktop" is not very consistent with someone logging into your machine via SSH. An attacker logging via SSH would get a text console which is completely separate from what you see on your desktop. They also wouldn't need to google "how to install git" from your desktop session because they'd be sitting in front of their own computer, right? Even if they wanted to install Git (why?), they wouldn't need to download an installer because Git is in Ubuntu repositories, anyone who knows anything about Git or Ubuntu knows that. And why did they have to google how to customize bash prompt? I also suspect that "There was a tab... open in my browser. It reopened several times after I closed it" was actually multiple identical tabs open so you had to close them one by one. What I'm trying to say here is that the pattern of activity resembles a "monkey with a typewriter". You also did not mention you even had SSH server installed - it is not installed by default. So, if you're absolutely sure nobody had *physical access* your laptop without your knowledge, and your laptop has a touchscreen, and it doesn't suspend properly, and it spent some time in your backpack then I think it all can be simply a case of "pocket calling" - random screen touches combined with search suggestions and auto-correction opened multiple windows and performed google searches, clicking on random links and downloading random files. As a personal anecdote - it happens from time to time with my smartphone in my pocket, including opening multiple apps, changing system settings, sending semi-coherent SMS messages and watching random youtube videos.
764,616
I am 99.9% sure that my system on my personal computer has been infiltrated. Allow me to first give my reasoning so the situation will be clear: Rough timeline of suspicious activity and subsequent actions taken: 4-26 23:00 I ended all programs and closed my laptop. 4-27 12:00 I opened my laptop after it had been in suspend mode for about 13 hours. Multiple windows were open including: Two chrome windows, system settings, software center. On my desktop there was a git installer (I checked, it has not been installed). 4-27 13:00 Chrome history displayed logins to my email, and other search history that I did not initiate (between 01:00 and 03:00 on 4-27), including "installing git". There was a tab, Digital Ocean "How to customize your bash prompt" open in my browser. It reopened several times after I closed it. I tightened security in Chrome. I disconnected from WiFi, but when I reconnected there was an up-down arrow symbol instead of the standard symbol, and there was no longer a list of networks in the drop down menu for Wifi Under 'Edit Connections' I noticed my laptop had connected to a network called "GFiberSetup 1802" at ~05:30 on 4-27. My neighbors at 1802 xx Drive just had google fiber installed, so I'm guessing it's related. 4-27 20:30 The `who` command revealed that a second user named guest-g20zoo was logged into my system. This is my private laptop that runs Ubuntu, there should not be anyone else on my system. Panicking, I ran `sudo pkill -9 -u guest-g20zoo` and disabled Networking and Wifi I looked in `/var/log/auth.log` and found this: ``` Apr 27 06:55:55 Rho useradd[23872]: new group: name=guest-g20zoo, GID=999 Apr 27 06:55:55 Rho useradd[23872]: new user: name=guest-g20zoo, UID=999, GID=999, home=/tmp/guest-g20zoo, shell=/bin/bash Apr 27 06:55:55 Rho su[23881]: Successful su for guest-g20zoo by root Apr 27 06:55:55 Rho su[23881]: + ??? root:guest-g20zoo Apr 27 06:55:55 Rho su[23881]: pam_unix(su:session): session opened for user guest-g20zoo by (uid=0) Apr 27 06:55:56 Rho systemd: pam_unix(systemd-user:session): session opened for user guest-g20zoo by (uid=0) Apr 27 06:55:56 Rho systemd-logind[767]: New session c3 of user guest-g20zoo. Apr 27 06:55:56 Rho su[23881]: pam_unix(su:session): session closed for user guest-g20zoo Apr 27 06:55:56 Rho systemd-logind[767]: Removed session c3. Apr 27 06:55:56 Rho lightdm: pam_unix(lightdm-autologin:session): session opened for user guest-g20zoo by (uid=0) Apr 27 06:55:56 Rho systemd: pam_unix(systemd-user:session): session closed for user guest-g20zoo Apr 27 06:55:56 Rho systemd-logind[767]: New session c4 of user guest-g20zoo. Apr 27 06:55:56 Rho systemd: pam_unix(systemd-user:session): session opened for user guest-g20zoo by (uid=0) Apr 27 06:56:51 Rho pkexec: pam_unix(polkit-1:session): session opened for user root by (uid=1000) Apr 27 06:56:51 Rho pkexec: pam_systemd(polkit-1:session): Cannot create session: Already running in a session ``` Sorry it's a lot of output, but that's the bulk of activity from guest-g20zoo in the log, all within a couple of minutes. I also checked `/etc/passwd`: ``` guest-G4J7WQ:x:120:132:Guest,,,:/tmp/guest-G4J7WQ:/bin/bash ``` And `/etc/shadow`: ``` root:!:16669:0:99999:7::: daemon:*:16547:0:99999:7::: . . . nobody:*:16547:0:99999:7::: rhobot:$6$encrypted-passwd-cut-for-length.:16918:0:99999:7::: guest-G4J7WQ:*:16689:0:99999:7::: . . ``` I don't entirely understand what this output means for my situation. Are `guest-g20zoo` and `guest-G4J7WQ` the same user? `lastlog` shows: ``` guest-G4J7WQ Never logged in ``` However, `last` shows: ``` guest-g20zoo Wed Apr 27 06:55 - 20:33 (13:37) ``` So it seems like they are not the same user, but guest-g20zoo was nowhere to be found in the output of `lastlog`. I would like to block access for user guest-g20zoo but since (s)he doesn't appear in `/etc/shadow` and I'm assuming doesn't use a password to login, but uses ssh, will `passwd -l guest-g20zoo` work? I tried `systemctl stop sshd`, but got this error message: ``` Failed to stop sshd.service: Unit sshd.service not loaded ``` Does this mean remote login was already disabled on my system, and therefore the above command is redundant? I have tried to find more information about this new user, like what ip address they logged in from, but I can't seem to find anything. Some potentially relevant information: Currently I'm connected to my university's network, and my WiFi icon looks fine, I can see all my network options, and there aren't any weird browsers popping up on their own. Does this indicate that whoever is logging into my system is within range of my WiFi router at my home? I ran `chkrootkit` and everything *seemed* fine, but I also don't know how to interpret all the output. I don't really know what to do here. I just want to be absolutely sure this person (or anyone else for that matter) will never be able to access my system again and I want to find and remove any hidden files created by them. Please and Thank You! P.S. - I already changed my password and encrypted my important files while WiFi and Networking were disabled.
2016/04/28
[ "https://askubuntu.com/questions/764616", "https://askubuntu.com", "https://askubuntu.com/users/447541/" ]
It looks like someone opened a guest session on your laptop while you where away from your room. If I were you I'd ask around, that may be a friend. The guest accounts you see in `/etc/passwd` and `/etc/shadow` are not suspicious to me, they are created by the system when someone open a guest session. > > Apr 27 06:55:55 Rho su[23881]: Successful su for guest-g20zoo by root > > > This line means `root` has access to the guest account, which could be normal but should be investigated. I've tried on my ubuntu1404LTS and don't see this behaviour. You should try to login with a guest session and grep your `auth.log` to see if this line appear everytime a guest user logs in. All the opened windows of chrome, that you've seen when you opened your laptop. Is it possible that you were seeing the guest session desktop ?
Do you have any friends that like to access your laptop remotely/physically while you're gone? If not: **Wipe the HDD with DBAN and reinstall the OS from scratch. Be sure to backup first.** Something may have been severely compromised within Ubuntu itself. When you reinstall: **Encrypt `/home`.** If the HDD/laptop itself is ever physically stolen, they cannot gain access to the data within `/home`. **Encrypt the HDD.** This prevents people from compromising `/boot` without logging in. You will also have to enter a boot-time password(I think). **Set a strong password.** If someone figures out the HDD password, they cannot access `/home` or login. **Encrypt your WiFi.** Someone may have gotten within the router's proximity and taken advantage of unencrypted Wifi and ssh'd into your laptop. **Disable the guest account.** The attacker may have ssh'd into your laptop, gotten a remote connection, logged in via Guest, and elevated the Guest account to root. This is a dangerous situation. If this happened, the attacker could run this **VERY DANGEROUS** command: ``` rm -rf --no-preserve-root / ``` This erases **A LOT** of data on the HDD, trashes `/home`, and even worse, leaves Ubuntu completely unable to even boot. You will just get thrown into grub rescue, and you will not be able to recover from this. The attacker could also completely destroy the `/home` directory, and so on. If you have a home network, the attacker could also all the other computers on that network unable to boot(if they run Linux). I hope this helps. :)
764,616
I am 99.9% sure that my system on my personal computer has been infiltrated. Allow me to first give my reasoning so the situation will be clear: Rough timeline of suspicious activity and subsequent actions taken: 4-26 23:00 I ended all programs and closed my laptop. 4-27 12:00 I opened my laptop after it had been in suspend mode for about 13 hours. Multiple windows were open including: Two chrome windows, system settings, software center. On my desktop there was a git installer (I checked, it has not been installed). 4-27 13:00 Chrome history displayed logins to my email, and other search history that I did not initiate (between 01:00 and 03:00 on 4-27), including "installing git". There was a tab, Digital Ocean "How to customize your bash prompt" open in my browser. It reopened several times after I closed it. I tightened security in Chrome. I disconnected from WiFi, but when I reconnected there was an up-down arrow symbol instead of the standard symbol, and there was no longer a list of networks in the drop down menu for Wifi Under 'Edit Connections' I noticed my laptop had connected to a network called "GFiberSetup 1802" at ~05:30 on 4-27. My neighbors at 1802 xx Drive just had google fiber installed, so I'm guessing it's related. 4-27 20:30 The `who` command revealed that a second user named guest-g20zoo was logged into my system. This is my private laptop that runs Ubuntu, there should not be anyone else on my system. Panicking, I ran `sudo pkill -9 -u guest-g20zoo` and disabled Networking and Wifi I looked in `/var/log/auth.log` and found this: ``` Apr 27 06:55:55 Rho useradd[23872]: new group: name=guest-g20zoo, GID=999 Apr 27 06:55:55 Rho useradd[23872]: new user: name=guest-g20zoo, UID=999, GID=999, home=/tmp/guest-g20zoo, shell=/bin/bash Apr 27 06:55:55 Rho su[23881]: Successful su for guest-g20zoo by root Apr 27 06:55:55 Rho su[23881]: + ??? root:guest-g20zoo Apr 27 06:55:55 Rho su[23881]: pam_unix(su:session): session opened for user guest-g20zoo by (uid=0) Apr 27 06:55:56 Rho systemd: pam_unix(systemd-user:session): session opened for user guest-g20zoo by (uid=0) Apr 27 06:55:56 Rho systemd-logind[767]: New session c3 of user guest-g20zoo. Apr 27 06:55:56 Rho su[23881]: pam_unix(su:session): session closed for user guest-g20zoo Apr 27 06:55:56 Rho systemd-logind[767]: Removed session c3. Apr 27 06:55:56 Rho lightdm: pam_unix(lightdm-autologin:session): session opened for user guest-g20zoo by (uid=0) Apr 27 06:55:56 Rho systemd: pam_unix(systemd-user:session): session closed for user guest-g20zoo Apr 27 06:55:56 Rho systemd-logind[767]: New session c4 of user guest-g20zoo. Apr 27 06:55:56 Rho systemd: pam_unix(systemd-user:session): session opened for user guest-g20zoo by (uid=0) Apr 27 06:56:51 Rho pkexec: pam_unix(polkit-1:session): session opened for user root by (uid=1000) Apr 27 06:56:51 Rho pkexec: pam_systemd(polkit-1:session): Cannot create session: Already running in a session ``` Sorry it's a lot of output, but that's the bulk of activity from guest-g20zoo in the log, all within a couple of minutes. I also checked `/etc/passwd`: ``` guest-G4J7WQ:x:120:132:Guest,,,:/tmp/guest-G4J7WQ:/bin/bash ``` And `/etc/shadow`: ``` root:!:16669:0:99999:7::: daemon:*:16547:0:99999:7::: . . . nobody:*:16547:0:99999:7::: rhobot:$6$encrypted-passwd-cut-for-length.:16918:0:99999:7::: guest-G4J7WQ:*:16689:0:99999:7::: . . ``` I don't entirely understand what this output means for my situation. Are `guest-g20zoo` and `guest-G4J7WQ` the same user? `lastlog` shows: ``` guest-G4J7WQ Never logged in ``` However, `last` shows: ``` guest-g20zoo Wed Apr 27 06:55 - 20:33 (13:37) ``` So it seems like they are not the same user, but guest-g20zoo was nowhere to be found in the output of `lastlog`. I would like to block access for user guest-g20zoo but since (s)he doesn't appear in `/etc/shadow` and I'm assuming doesn't use a password to login, but uses ssh, will `passwd -l guest-g20zoo` work? I tried `systemctl stop sshd`, but got this error message: ``` Failed to stop sshd.service: Unit sshd.service not loaded ``` Does this mean remote login was already disabled on my system, and therefore the above command is redundant? I have tried to find more information about this new user, like what ip address they logged in from, but I can't seem to find anything. Some potentially relevant information: Currently I'm connected to my university's network, and my WiFi icon looks fine, I can see all my network options, and there aren't any weird browsers popping up on their own. Does this indicate that whoever is logging into my system is within range of my WiFi router at my home? I ran `chkrootkit` and everything *seemed* fine, but I also don't know how to interpret all the output. I don't really know what to do here. I just want to be absolutely sure this person (or anyone else for that matter) will never be able to access my system again and I want to find and remove any hidden files created by them. Please and Thank You! P.S. - I already changed my password and encrypted my important files while WiFi and Networking were disabled.
2016/04/28
[ "https://askubuntu.com/questions/764616", "https://askubuntu.com", "https://askubuntu.com/users/447541/" ]
It looks like someone opened a guest session on your laptop while you where away from your room. If I were you I'd ask around, that may be a friend. The guest accounts you see in `/etc/passwd` and `/etc/shadow` are not suspicious to me, they are created by the system when someone open a guest session. > > Apr 27 06:55:55 Rho su[23881]: Successful su for guest-g20zoo by root > > > This line means `root` has access to the guest account, which could be normal but should be investigated. I've tried on my ubuntu1404LTS and don't see this behaviour. You should try to login with a guest session and grep your `auth.log` to see if this line appear everytime a guest user logs in. All the opened windows of chrome, that you've seen when you opened your laptop. Is it possible that you were seeing the guest session desktop ?
**Wipe the hard drive and reinstall your operating system from scratch.** In any case of unauthorised access there is the possibility the attacker was able to get root privileges, so it is sensible to assume that it happened. In this case, auth.log appears to confirm this was indeed the case - unless this was *you* that switched user: > > Apr 27 06:55:55 Rho su[23881]: Successful su for guest-g20zoo by root > > > With root privileges in particular, they may have messed with the system in ways which are practically impossible to fix without a reinstall, such as by modifying boot scripts or installing new scripts and applications that run at boot, and so on. These could do things like run unauthorised network software (ie to form part of a botnet), or leave backdoors into your system. Trying to detect and repair this sort of thing without a reinstall is messy at best, and not guaranteed to rid you of everything.
764,616
I am 99.9% sure that my system on my personal computer has been infiltrated. Allow me to first give my reasoning so the situation will be clear: Rough timeline of suspicious activity and subsequent actions taken: 4-26 23:00 I ended all programs and closed my laptop. 4-27 12:00 I opened my laptop after it had been in suspend mode for about 13 hours. Multiple windows were open including: Two chrome windows, system settings, software center. On my desktop there was a git installer (I checked, it has not been installed). 4-27 13:00 Chrome history displayed logins to my email, and other search history that I did not initiate (between 01:00 and 03:00 on 4-27), including "installing git". There was a tab, Digital Ocean "How to customize your bash prompt" open in my browser. It reopened several times after I closed it. I tightened security in Chrome. I disconnected from WiFi, but when I reconnected there was an up-down arrow symbol instead of the standard symbol, and there was no longer a list of networks in the drop down menu for Wifi Under 'Edit Connections' I noticed my laptop had connected to a network called "GFiberSetup 1802" at ~05:30 on 4-27. My neighbors at 1802 xx Drive just had google fiber installed, so I'm guessing it's related. 4-27 20:30 The `who` command revealed that a second user named guest-g20zoo was logged into my system. This is my private laptop that runs Ubuntu, there should not be anyone else on my system. Panicking, I ran `sudo pkill -9 -u guest-g20zoo` and disabled Networking and Wifi I looked in `/var/log/auth.log` and found this: ``` Apr 27 06:55:55 Rho useradd[23872]: new group: name=guest-g20zoo, GID=999 Apr 27 06:55:55 Rho useradd[23872]: new user: name=guest-g20zoo, UID=999, GID=999, home=/tmp/guest-g20zoo, shell=/bin/bash Apr 27 06:55:55 Rho su[23881]: Successful su for guest-g20zoo by root Apr 27 06:55:55 Rho su[23881]: + ??? root:guest-g20zoo Apr 27 06:55:55 Rho su[23881]: pam_unix(su:session): session opened for user guest-g20zoo by (uid=0) Apr 27 06:55:56 Rho systemd: pam_unix(systemd-user:session): session opened for user guest-g20zoo by (uid=0) Apr 27 06:55:56 Rho systemd-logind[767]: New session c3 of user guest-g20zoo. Apr 27 06:55:56 Rho su[23881]: pam_unix(su:session): session closed for user guest-g20zoo Apr 27 06:55:56 Rho systemd-logind[767]: Removed session c3. Apr 27 06:55:56 Rho lightdm: pam_unix(lightdm-autologin:session): session opened for user guest-g20zoo by (uid=0) Apr 27 06:55:56 Rho systemd: pam_unix(systemd-user:session): session closed for user guest-g20zoo Apr 27 06:55:56 Rho systemd-logind[767]: New session c4 of user guest-g20zoo. Apr 27 06:55:56 Rho systemd: pam_unix(systemd-user:session): session opened for user guest-g20zoo by (uid=0) Apr 27 06:56:51 Rho pkexec: pam_unix(polkit-1:session): session opened for user root by (uid=1000) Apr 27 06:56:51 Rho pkexec: pam_systemd(polkit-1:session): Cannot create session: Already running in a session ``` Sorry it's a lot of output, but that's the bulk of activity from guest-g20zoo in the log, all within a couple of minutes. I also checked `/etc/passwd`: ``` guest-G4J7WQ:x:120:132:Guest,,,:/tmp/guest-G4J7WQ:/bin/bash ``` And `/etc/shadow`: ``` root:!:16669:0:99999:7::: daemon:*:16547:0:99999:7::: . . . nobody:*:16547:0:99999:7::: rhobot:$6$encrypted-passwd-cut-for-length.:16918:0:99999:7::: guest-G4J7WQ:*:16689:0:99999:7::: . . ``` I don't entirely understand what this output means for my situation. Are `guest-g20zoo` and `guest-G4J7WQ` the same user? `lastlog` shows: ``` guest-G4J7WQ Never logged in ``` However, `last` shows: ``` guest-g20zoo Wed Apr 27 06:55 - 20:33 (13:37) ``` So it seems like they are not the same user, but guest-g20zoo was nowhere to be found in the output of `lastlog`. I would like to block access for user guest-g20zoo but since (s)he doesn't appear in `/etc/shadow` and I'm assuming doesn't use a password to login, but uses ssh, will `passwd -l guest-g20zoo` work? I tried `systemctl stop sshd`, but got this error message: ``` Failed to stop sshd.service: Unit sshd.service not loaded ``` Does this mean remote login was already disabled on my system, and therefore the above command is redundant? I have tried to find more information about this new user, like what ip address they logged in from, but I can't seem to find anything. Some potentially relevant information: Currently I'm connected to my university's network, and my WiFi icon looks fine, I can see all my network options, and there aren't any weird browsers popping up on their own. Does this indicate that whoever is logging into my system is within range of my WiFi router at my home? I ran `chkrootkit` and everything *seemed* fine, but I also don't know how to interpret all the output. I don't really know what to do here. I just want to be absolutely sure this person (or anyone else for that matter) will never be able to access my system again and I want to find and remove any hidden files created by them. Please and Thank You! P.S. - I already changed my password and encrypted my important files while WiFi and Networking were disabled.
2016/04/28
[ "https://askubuntu.com/questions/764616", "https://askubuntu.com", "https://askubuntu.com/users/447541/" ]
It looks like someone opened a guest session on your laptop while you where away from your room. If I were you I'd ask around, that may be a friend. The guest accounts you see in `/etc/passwd` and `/etc/shadow` are not suspicious to me, they are created by the system when someone open a guest session. > > Apr 27 06:55:55 Rho su[23881]: Successful su for guest-g20zoo by root > > > This line means `root` has access to the guest account, which could be normal but should be investigated. I've tried on my ubuntu1404LTS and don't see this behaviour. You should try to login with a guest session and grep your `auth.log` to see if this line appear everytime a guest user logs in. All the opened windows of chrome, that you've seen when you opened your laptop. Is it possible that you were seeing the guest session desktop ?
Pull out the wireless card/stick and look over the traces. Make a record of your logs so askbuntu can help further. After that wipe your drives and try a different distro, try a live cd leave it running to see if there's a pattern to the attacks.
764,616
I am 99.9% sure that my system on my personal computer has been infiltrated. Allow me to first give my reasoning so the situation will be clear: Rough timeline of suspicious activity and subsequent actions taken: 4-26 23:00 I ended all programs and closed my laptop. 4-27 12:00 I opened my laptop after it had been in suspend mode for about 13 hours. Multiple windows were open including: Two chrome windows, system settings, software center. On my desktop there was a git installer (I checked, it has not been installed). 4-27 13:00 Chrome history displayed logins to my email, and other search history that I did not initiate (between 01:00 and 03:00 on 4-27), including "installing git". There was a tab, Digital Ocean "How to customize your bash prompt" open in my browser. It reopened several times after I closed it. I tightened security in Chrome. I disconnected from WiFi, but when I reconnected there was an up-down arrow symbol instead of the standard symbol, and there was no longer a list of networks in the drop down menu for Wifi Under 'Edit Connections' I noticed my laptop had connected to a network called "GFiberSetup 1802" at ~05:30 on 4-27. My neighbors at 1802 xx Drive just had google fiber installed, so I'm guessing it's related. 4-27 20:30 The `who` command revealed that a second user named guest-g20zoo was logged into my system. This is my private laptop that runs Ubuntu, there should not be anyone else on my system. Panicking, I ran `sudo pkill -9 -u guest-g20zoo` and disabled Networking and Wifi I looked in `/var/log/auth.log` and found this: ``` Apr 27 06:55:55 Rho useradd[23872]: new group: name=guest-g20zoo, GID=999 Apr 27 06:55:55 Rho useradd[23872]: new user: name=guest-g20zoo, UID=999, GID=999, home=/tmp/guest-g20zoo, shell=/bin/bash Apr 27 06:55:55 Rho su[23881]: Successful su for guest-g20zoo by root Apr 27 06:55:55 Rho su[23881]: + ??? root:guest-g20zoo Apr 27 06:55:55 Rho su[23881]: pam_unix(su:session): session opened for user guest-g20zoo by (uid=0) Apr 27 06:55:56 Rho systemd: pam_unix(systemd-user:session): session opened for user guest-g20zoo by (uid=0) Apr 27 06:55:56 Rho systemd-logind[767]: New session c3 of user guest-g20zoo. Apr 27 06:55:56 Rho su[23881]: pam_unix(su:session): session closed for user guest-g20zoo Apr 27 06:55:56 Rho systemd-logind[767]: Removed session c3. Apr 27 06:55:56 Rho lightdm: pam_unix(lightdm-autologin:session): session opened for user guest-g20zoo by (uid=0) Apr 27 06:55:56 Rho systemd: pam_unix(systemd-user:session): session closed for user guest-g20zoo Apr 27 06:55:56 Rho systemd-logind[767]: New session c4 of user guest-g20zoo. Apr 27 06:55:56 Rho systemd: pam_unix(systemd-user:session): session opened for user guest-g20zoo by (uid=0) Apr 27 06:56:51 Rho pkexec: pam_unix(polkit-1:session): session opened for user root by (uid=1000) Apr 27 06:56:51 Rho pkexec: pam_systemd(polkit-1:session): Cannot create session: Already running in a session ``` Sorry it's a lot of output, but that's the bulk of activity from guest-g20zoo in the log, all within a couple of minutes. I also checked `/etc/passwd`: ``` guest-G4J7WQ:x:120:132:Guest,,,:/tmp/guest-G4J7WQ:/bin/bash ``` And `/etc/shadow`: ``` root:!:16669:0:99999:7::: daemon:*:16547:0:99999:7::: . . . nobody:*:16547:0:99999:7::: rhobot:$6$encrypted-passwd-cut-for-length.:16918:0:99999:7::: guest-G4J7WQ:*:16689:0:99999:7::: . . ``` I don't entirely understand what this output means for my situation. Are `guest-g20zoo` and `guest-G4J7WQ` the same user? `lastlog` shows: ``` guest-G4J7WQ Never logged in ``` However, `last` shows: ``` guest-g20zoo Wed Apr 27 06:55 - 20:33 (13:37) ``` So it seems like they are not the same user, but guest-g20zoo was nowhere to be found in the output of `lastlog`. I would like to block access for user guest-g20zoo but since (s)he doesn't appear in `/etc/shadow` and I'm assuming doesn't use a password to login, but uses ssh, will `passwd -l guest-g20zoo` work? I tried `systemctl stop sshd`, but got this error message: ``` Failed to stop sshd.service: Unit sshd.service not loaded ``` Does this mean remote login was already disabled on my system, and therefore the above command is redundant? I have tried to find more information about this new user, like what ip address they logged in from, but I can't seem to find anything. Some potentially relevant information: Currently I'm connected to my university's network, and my WiFi icon looks fine, I can see all my network options, and there aren't any weird browsers popping up on their own. Does this indicate that whoever is logging into my system is within range of my WiFi router at my home? I ran `chkrootkit` and everything *seemed* fine, but I also don't know how to interpret all the output. I don't really know what to do here. I just want to be absolutely sure this person (or anyone else for that matter) will never be able to access my system again and I want to find and remove any hidden files created by them. Please and Thank You! P.S. - I already changed my password and encrypted my important files while WiFi and Networking were disabled.
2016/04/28
[ "https://askubuntu.com/questions/764616", "https://askubuntu.com", "https://askubuntu.com/users/447541/" ]
**Wipe the hard drive and reinstall your operating system from scratch.** In any case of unauthorised access there is the possibility the attacker was able to get root privileges, so it is sensible to assume that it happened. In this case, auth.log appears to confirm this was indeed the case - unless this was *you* that switched user: > > Apr 27 06:55:55 Rho su[23881]: Successful su for guest-g20zoo by root > > > With root privileges in particular, they may have messed with the system in ways which are practically impossible to fix without a reinstall, such as by modifying boot scripts or installing new scripts and applications that run at boot, and so on. These could do things like run unauthorised network software (ie to form part of a botnet), or leave backdoors into your system. Trying to detect and repair this sort of thing without a reinstall is messy at best, and not guaranteed to rid you of everything.
Pull out the wireless card/stick and look over the traces. Make a record of your logs so askbuntu can help further. After that wipe your drives and try a different distro, try a live cd leave it running to see if there's a pattern to the attacks.
2,234,441
I get an XML string from a certain source. I create a DOMDocument object and load the XML string into it (with DOMDocument::loadXML()). Then I navigate through the XML doc using various methods (e.g. DOMXPath), until I find the node (a DOMNode, of course) that I want. This node has a bunch of descendants, and I want to take that entire node (and its descendants) and create a new DOMDocument object from it. I'm not sure how to do this; I tried creating a new DOMDocument and using DOMDocument::importNode(), but this appears to only work if the DOMDocument already has a main document node in it, in which case it appends the imported node as a child of the main document node, which is not what I want -- I want the imported node to BECOME the DOMDocument main node. Maybe there's an easier way to do this (i.e. an easier way to extract the part of the original XML that I want to turn into its own document), but I don't know of it. I'm relatively new to DOMDocument, although I've used SimpleXMLElement enough to be annoyed by it.
2010/02/10
[ "https://Stackoverflow.com/questions/2234441", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20903/" ]
You can also create a new DOMDocument and call appendChild() on it to add a root node: ``` $new = new DomDocument; $new->appendChild($new->importNode($node, true)); ``` That worked for me.
Can't you just create a new DOMDocument and load the node's XML? ``` $new = new DOMDocument; $new->loadXML($node->ownerDocument->saveXML($node)); ``` I'm unable to try it right now but that should work.
35,427,666
Which method in `vscode-languageserver::IConnection` has to be implemented to provide functionality "Go To Definition" over multiple files? I was studying `Language Server Node Example` and vscode "API documentation", but I didn't find any info.
2016/02/16
[ "https://Stackoverflow.com/questions/35427666", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5902074/" ]
The following code snippet illustrates how to implement "Go To Definition" using `vscode-languageserver`: ```ts connection.onInitialize((params): InitializeResult => { ... return { capabilities: { definitionProvider: true, ... } } }); connection.onDefinition((textDocumentIdentifier: TextDocumentIdentifier): Definition => { return Location.create(textDocumentIdentifier.uri, { start: { line: 2, character: 5 }, end: { line: 2, character: 6 } }); }); ```
I think you have to create a class implementing the `DefinitionProvider` and then register it using `registerDefinitionProvider`. Take a look [here](https://github.com/Microsoft/vscode-go/blob/master/src/goMain.ts) and [here](https://github.com/Microsoft/vscode-go/blob/master/src/goDeclaration.ts) for an example.
3,991,377
I have a Master and Detail table, the Detail linking to the Master record on a FK reference. I need to display all the data from the Master table, and the corresponding number of details for each record, i.e. ``` MASTER TABLE ID Name Age 1 John 15 2 Jane 14 3 Joe 15 DETAIL MasterID Subjects 1 Trigonometry 1 Chemistry 1 Physics 1 History 2 Trigonometry 2 Physics ``` Thus, when I ran the SQL statement, I would have the following result: ``` ID Name Age #Subjects 1 John 15 4 2 Jane 14 2 3 Joe 15 0 ``` Thanks!
2010/10/21
[ "https://Stackoverflow.com/questions/3991377", "https://Stackoverflow.com", "https://Stackoverflow.com/users/71406/" ]
This may be useful ``` SELECT mt.ID, mt.NAME, mt.AGE, COUNT(d.MasterID) as [#Subjects] FROM MasterTable mt LEFT OUTER JOIN Detail d on mt.ID = d.ID GROUP BY mt.ID, mt.NAME, mt.AGE ORDER BY mt.ID ```
``` select id, name, age, ( select count(*) from detail where master.id = detail.id ) as record_count from master ``` syntax adjusted depending on what db you are using
60,843,085
The columns in my dataframe has long names, so when I make a pairplot, the labels overlaps one another. I would like to rotate my labels 90 degrees, so they don't collide. I tried looking up online and documentation, but could not find a solution. Here is something I wrote & the error message: ``` plt.figure(figsize=(10,10)) g = sn.pairplot(df, kind="scatter") g.set_xticklabels(g.get_xticklabels(), rotation=90) g.set_yticklabels(g.get_yticklabels(), rotation=90) ``` ```none AttributeError: 'PairGrid' object has no attribute 'set_xticklabels' ``` **How can I rotate labels (both x and y) in a Seaborn PairGrid?** *Note: Sorry, my wifi can't upload the image for reference.*
2020/03/25
[ "https://Stackoverflow.com/questions/60843085", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8742400/" ]
Thanks to William's answer, I now know what to look for to solve my problem! Below is how I did it. ``` g = sn.pairplot(dfsub.sample(50), kind="scatter", hue=target) for ax in g.axes.flatten(): # rotate x axis labels ax.set_xlabel(ax.get_xlabel(), rotation = 90) # rotate y axis labels ax.set_ylabel(ax.get_ylabel(), rotation = 0) # set y labels alignment ax.yaxis.get_label().set_horizontalalignment('right') ```
You can iterate over the axes directly using the `axes` member of the `PairGrid` object returned by `PairPlot`. Something like this ```py for ax in g.axes.flatten(): ax.tick_params(rotation = 90) ``` Should do the trick
60,843,085
The columns in my dataframe has long names, so when I make a pairplot, the labels overlaps one another. I would like to rotate my labels 90 degrees, so they don't collide. I tried looking up online and documentation, but could not find a solution. Here is something I wrote & the error message: ``` plt.figure(figsize=(10,10)) g = sn.pairplot(df, kind="scatter") g.set_xticklabels(g.get_xticklabels(), rotation=90) g.set_yticklabels(g.get_yticklabels(), rotation=90) ``` ```none AttributeError: 'PairGrid' object has no attribute 'set_xticklabels' ``` **How can I rotate labels (both x and y) in a Seaborn PairGrid?** *Note: Sorry, my wifi can't upload the image for reference.*
2020/03/25
[ "https://Stackoverflow.com/questions/60843085", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8742400/" ]
You can iterate over the axes directly using the `axes` member of the `PairGrid` object returned by `PairPlot`. Something like this ```py for ax in g.axes.flatten(): ax.tick_params(rotation = 90) ``` Should do the trick
Adding to @techtana's answer. If you set `cornor=True` while plotting pairplot, then you need to skip `ax`es of `NoneType`: ``` g = sns.pairplot(df, diag_kind='kde', corner=True) for ax in g.axes.flatten(): if ax: # rotate x axis labels ax.set_xlabel(ax.get_xlabel(), rotation = -30) # rotate y axis labels ax.set_ylabel(ax.get_ylabel(), rotation = 0) # set y labels alignment ax.yaxis.get_label().set_horizontalalignment('right') ```
60,843,085
The columns in my dataframe has long names, so when I make a pairplot, the labels overlaps one another. I would like to rotate my labels 90 degrees, so they don't collide. I tried looking up online and documentation, but could not find a solution. Here is something I wrote & the error message: ``` plt.figure(figsize=(10,10)) g = sn.pairplot(df, kind="scatter") g.set_xticklabels(g.get_xticklabels(), rotation=90) g.set_yticklabels(g.get_yticklabels(), rotation=90) ``` ```none AttributeError: 'PairGrid' object has no attribute 'set_xticklabels' ``` **How can I rotate labels (both x and y) in a Seaborn PairGrid?** *Note: Sorry, my wifi can't upload the image for reference.*
2020/03/25
[ "https://Stackoverflow.com/questions/60843085", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8742400/" ]
Thanks to William's answer, I now know what to look for to solve my problem! Below is how I did it. ``` g = sn.pairplot(dfsub.sample(50), kind="scatter", hue=target) for ax in g.axes.flatten(): # rotate x axis labels ax.set_xlabel(ax.get_xlabel(), rotation = 90) # rotate y axis labels ax.set_ylabel(ax.get_ylabel(), rotation = 0) # set y labels alignment ax.yaxis.get_label().set_horizontalalignment('right') ```
Adding to @techtana's answer. If you set `cornor=True` while plotting pairplot, then you need to skip `ax`es of `NoneType`: ``` g = sns.pairplot(df, diag_kind='kde', corner=True) for ax in g.axes.flatten(): if ax: # rotate x axis labels ax.set_xlabel(ax.get_xlabel(), rotation = -30) # rotate y axis labels ax.set_ylabel(ax.get_ylabel(), rotation = 0) # set y labels alignment ax.yaxis.get_label().set_horizontalalignment('right') ```
766,378
In my debian all files, even the system ones have permissions rw-r--r--, so it means that all users can view ANY file even some system configuration or database files and so on. How do I prevent users from reading all system files ? Is there any way how to set global permissions so users cannot read all the files ?
2016/03/27
[ "https://serverfault.com/questions/766378", "https://serverfault.com", "https://serverfault.com/users/314359/" ]
I don't think that denying access to all system files for all users is a good idea. Some of those files are necessary to work in a system. But there are several ways to restrict specific users. For example, if you wanted to deny user `joe` access to anything in `/etc`, you could use `ACLs` (manipulated with setfacl/getfacl commands), like this: `setfacl -Rm u:joe:--- /etc` Other ideas would be to use selinux policy, or keep users in chroot. I think `chmod 700` on system directories is a bad idea, because it will deny access to various system users like `nobody`, `ftp` or `mail`, which are used by some system services.
An interesting aspect of Linux permissions is that the default permission is typically 777 (-rwxrwxrwx) and then umask is used to automatically remove permissions, so that when new directories or files are created, the newly created directory or file is not 777, and instead is something like 644 (-rw-r--r--) or 666 (-rw-rw-rw-). If you wish to remove the default read permission for all files/directories, you can adjust the umask. However, changing umask is probably not the solution to the task you face. I think the solution would be to control access using chmod and chown or setfacl and getfacl. For example, lets say only root should have access to /var/private. You could use the following commands so that only root can read, write and access the directory and files in the directory. Set root as both the owner and group owner of /var/private: ``` chown -R root:root /var/private ``` You could also set the permission on the directory so that only root can access the directory (-rwx------): ``` chmod 0700 /var/private ``` You could then recursively set the permission on all files in the directory so that only root can read, write and execute files in the directory (-rwx-----): ``` chmod 0700 -R /var/private/* ``` Note: I do not know how you are using your database. If your database files are accessible from a Web browser, such as through PHP or ASP.Net, this permission change may prevent PHP or ASP.Net from being able to interact with database records.
766,378
In my debian all files, even the system ones have permissions rw-r--r--, so it means that all users can view ANY file even some system configuration or database files and so on. How do I prevent users from reading all system files ? Is there any way how to set global permissions so users cannot read all the files ?
2016/03/27
[ "https://serverfault.com/questions/766378", "https://serverfault.com", "https://serverfault.com/users/314359/" ]
> > In my debian all files, even the system ones have permissions rw-r--r--, so it means that all users can view ANY file even some system configuration or database files and so on. > > > Unless you fiddled the permissions, they are absolutely fine as they are out of the box. Please do not change them, especially not in that circumference. System (configuration) files are meant and save to be read by everyone. In certain cases they must be readable (`/etc/bash.bashrc` or `/etc/default`) and on other cases they are already protected (`/etc/shadow`). Database files, that in Debian reside in `/var/lib` are also protected. ``` drwx------ 10 mysql mysql 4.0K Feb 26 12:49 /var/lib/mysql ``` You can assume that for most software from the Debian repositories the permissions are safe as they are. There are exceptions of course. Web hosting is one of them, where you usually have to make bigger permission-adjustments to the document root and PHP-FPM socket files. If you do not absolutely know what implications a change of the permissions on the 'default' folders have, you should decide against it. The only place where the default permissions are indeed too liberal is within the `/home`directory, at least in my opinion.
An interesting aspect of Linux permissions is that the default permission is typically 777 (-rwxrwxrwx) and then umask is used to automatically remove permissions, so that when new directories or files are created, the newly created directory or file is not 777, and instead is something like 644 (-rw-r--r--) or 666 (-rw-rw-rw-). If you wish to remove the default read permission for all files/directories, you can adjust the umask. However, changing umask is probably not the solution to the task you face. I think the solution would be to control access using chmod and chown or setfacl and getfacl. For example, lets say only root should have access to /var/private. You could use the following commands so that only root can read, write and access the directory and files in the directory. Set root as both the owner and group owner of /var/private: ``` chown -R root:root /var/private ``` You could also set the permission on the directory so that only root can access the directory (-rwx------): ``` chmod 0700 /var/private ``` You could then recursively set the permission on all files in the directory so that only root can read, write and execute files in the directory (-rwx-----): ``` chmod 0700 -R /var/private/* ``` Note: I do not know how you are using your database. If your database files are accessible from a Web browser, such as through PHP or ASP.Net, this permission change may prevent PHP or ASP.Net from being able to interact with database records.
5,134,523
Consider this code: ``` #define F(x, ...) X = x and VA_ARGS = __VA_ARGS__ #define G(...) F(__VA_ARGS__) F(1, 2, 3) G(1, 2, 3) ``` The expected output is `X = 1 and VA_ARGS = 2, 3` for both macros, and that's what I'm getting with GCC, however, MSVC expands this as: ``` X = 1 and VA_ARGS = 2, 3 X = 1, 2, 3 and VA_ARGS = ``` That is, `__VA_ARGS__` is expanded as a single argument, instead of being broken down to multiple ones. Any way around this?
2011/02/27
[ "https://Stackoverflow.com/questions/5134523", "https://Stackoverflow.com", "https://Stackoverflow.com/users/366240/" ]
Edit: This issue might be resolved by using `/Zc:preprocessor` or `/experimental:preprocessor` option in recent MSVC. For the details, please see [here](https://learn.microsoft.com/en-us/cpp/preprocessor/preprocessor-experimental-overview?view=msvc-160). MSVC's preprocessor seems to behave quite differently from the standard specification. Probably the following workaround will help: ``` #define EXPAND( x ) x #define F(x, ...) X = x and VA_ARGS = __VA_ARGS__ #define G(...) EXPAND( F(__VA_ARGS__) ) ```
I posted [the following Microsoft support issue](https://connect.microsoft.com/VisualStudio/feedback/details/676585/bug-in-cl-c-compiler-in-correct-expansion-of-va-args): > > The following program gives compilation error because the precompiler > expands `__VA_ARGS__` incorrectly: > > > > ``` > #include <stdio.h> > > #define A2(a1, a2) ((a1)+(a2)) > > #define A_VA(...) A2(__VA_ARGS__) > > int main(int argc, char *argv[]) > { > printf("%d\n", A_VA(1, 2)); > return 0; > } > > ``` > > The preprocessor expands the printf to: > printf("%d\n", ((1, 2)+())); > > > instead of > printf("%d\n", ((1)+(2))); > > > I received the following unsatisfying answer from a Microsoft compiler team developer: > > Hi: The Visual C++ compiler is behaving correctly in this case. If you combine the rule that tokens that match the '...' at the inital macro invocation are combined to form a single entity (16.3/p12) with the rule that sub-macros are expanded before argument replacement (16.3.1/p1) then in this case the compiler believes that A2 is invoked with a single argument: hence the error message. > > >
5,134,523
Consider this code: ``` #define F(x, ...) X = x and VA_ARGS = __VA_ARGS__ #define G(...) F(__VA_ARGS__) F(1, 2, 3) G(1, 2, 3) ``` The expected output is `X = 1 and VA_ARGS = 2, 3` for both macros, and that's what I'm getting with GCC, however, MSVC expands this as: ``` X = 1 and VA_ARGS = 2, 3 X = 1, 2, 3 and VA_ARGS = ``` That is, `__VA_ARGS__` is expanded as a single argument, instead of being broken down to multiple ones. Any way around this?
2011/02/27
[ "https://Stackoverflow.com/questions/5134523", "https://Stackoverflow.com", "https://Stackoverflow.com/users/366240/" ]
Edit: This issue might be resolved by using `/Zc:preprocessor` or `/experimental:preprocessor` option in recent MSVC. For the details, please see [here](https://learn.microsoft.com/en-us/cpp/preprocessor/preprocessor-experimental-overview?view=msvc-160). MSVC's preprocessor seems to behave quite differently from the standard specification. Probably the following workaround will help: ``` #define EXPAND( x ) x #define F(x, ...) X = x and VA_ARGS = __VA_ARGS__ #define G(...) EXPAND( F(__VA_ARGS__) ) ```
What version of MSVC are you using? You will need Visual C++ 2010. `__VA_ARGS__` was first introduced by C99. MSVC never attempted to support C99, so the support was not added. Now, however, `__VA_ARGS__` is included in the new C++ standard, C++2011 (previously known as C++0x), which Microsoft apparently plans to support, so it has been supported in recent versions of MSVC. BTW, you will need to use a `.cpp` suffix to your source file to get this support. MSVC hasn't updated its C frontend for a long time.
5,134,523
Consider this code: ``` #define F(x, ...) X = x and VA_ARGS = __VA_ARGS__ #define G(...) F(__VA_ARGS__) F(1, 2, 3) G(1, 2, 3) ``` The expected output is `X = 1 and VA_ARGS = 2, 3` for both macros, and that's what I'm getting with GCC, however, MSVC expands this as: ``` X = 1 and VA_ARGS = 2, 3 X = 1, 2, 3 and VA_ARGS = ``` That is, `__VA_ARGS__` is expanded as a single argument, instead of being broken down to multiple ones. Any way around this?
2011/02/27
[ "https://Stackoverflow.com/questions/5134523", "https://Stackoverflow.com", "https://Stackoverflow.com/users/366240/" ]
I posted [the following Microsoft support issue](https://connect.microsoft.com/VisualStudio/feedback/details/676585/bug-in-cl-c-compiler-in-correct-expansion-of-va-args): > > The following program gives compilation error because the precompiler > expands `__VA_ARGS__` incorrectly: > > > > ``` > #include <stdio.h> > > #define A2(a1, a2) ((a1)+(a2)) > > #define A_VA(...) A2(__VA_ARGS__) > > int main(int argc, char *argv[]) > { > printf("%d\n", A_VA(1, 2)); > return 0; > } > > ``` > > The preprocessor expands the printf to: > printf("%d\n", ((1, 2)+())); > > > instead of > printf("%d\n", ((1)+(2))); > > > I received the following unsatisfying answer from a Microsoft compiler team developer: > > Hi: The Visual C++ compiler is behaving correctly in this case. If you combine the rule that tokens that match the '...' at the inital macro invocation are combined to form a single entity (16.3/p12) with the rule that sub-macros are expanded before argument replacement (16.3.1/p1) then in this case the compiler believes that A2 is invoked with a single argument: hence the error message. > > >
What version of MSVC are you using? You will need Visual C++ 2010. `__VA_ARGS__` was first introduced by C99. MSVC never attempted to support C99, so the support was not added. Now, however, `__VA_ARGS__` is included in the new C++ standard, C++2011 (previously known as C++0x), which Microsoft apparently plans to support, so it has been supported in recent versions of MSVC. BTW, you will need to use a `.cpp` suffix to your source file to get this support. MSVC hasn't updated its C frontend for a long time.
10,177,524
This is a simple problem but i've been pulling my hair out the past two hours trying to figure a way to get it to work. Basically I have a jquery navigation set-up. I have 4 tabs, each tab is a parent category with child categories. When a tab is clicked, a drop down with the children appears. I have it all set-up but can't figure a way to add a class of "active" to the child categories based on whatever category is selected. Unless i've blanked and this is sitting right in front of my eyes, I can't find an obvious way of doing this. I think the problem is, I haven't hard coded the navigation links as the client want's to manage these themselves, so i've dynamically displayed the categories, adding an 'if' statement to this is adding the if statement to all of the categories so the class is being added to all of the child tabs. Here is my code: ``` <div id="tabbed-cats"> {exp:channel:entries channel="product"} <ul class="tabs"> <li class="nav-one"><a href="#bathroom" {categories}{if category_id == "1"}class="current"{/if}{/categories}>Bathroom</a></li> <li class="nav-two"><a href="#homecare" {categories}{if category_id == "2"}class="current"{/if}{/categories}>Homecare</a></li> <li class="nav-three"><a href="#transfer-equipment" {categories}{if category_id == "3"}class="current"{/if}{/categories}>Transfer Equipment</a></li> <li class="nav-four last"><a href="#mobility" {categories}{if category_id == "4"}class="current"{/if}{/categories}>Mobility</a></li> </ul> {/exp:channel:entries} <div class="list-wrap"> {exp:channel:entries channel="product"} <ul id="bathroom" {categories}{if category_id == "2" OR category_id == "3" OR category_id == "4"}class="hide"{/if}{/categories}> {exp:child_categories channel="product" parent="1" category_group="1" show_empty="yes"} {child_category_start} <li><a {categories}{if category_id == "5"}class="active"{/if}{/categories} href="{path='products/category/{child_category_url_title}'}">{child_category_name}</a></li> {child_category_end} {/exp:child_categories} </ul> {/exp:channel:entries} {exp:channel:entries channel="product"} <ul id="homecare" {categories}{if category_id == "1" OR category_id == "3" OR category_id == "4"}class="hide"{/if}{/categories}> {exp:child_categories channel="product" parent="2" category_group="1" show_empty="yes"} {child_category_start} <li><a {categories}{if category_id == "6"}class="active"{/if}{/categories} href="{path='products/category/{child_category_url_title}'}">{child_category_name}</a></li> {child_category_end} {/exp:child_categories} </ul> {/exp:channel:entries} {exp:channel:entries channel="product"} <ul id="transfer-equipment" {categories}{if category_id == "1" OR category_id == "2" OR category_id == "4"}class="hide"{/if}{/categories}> {exp:child_categories channel="product" parent="3" category_group="1" show_empty="yes"} {child_category_start} <li><a {categories}{if category_id == "8"}class="active"{/if}{/categories} href="{path='products/category/{child_category_url_title}'}">{child_category_name}</a></li> {child_category_end} {/exp:child_categories} </ul> {/exp:channel:entries} {exp:channel:entries channel="product"} <ul id="mobility" {categories}{if category_id == "1" OR category_id == "2" OR category_id == "3"}class="hide"{/if}{/categories}> {exp:child_categories channel="product" parent="4" category_group="1" show_empty="yes"} {child_category_start} <li><a {categories}{if category_id == "7"}class="active"{/if}{/categories} href="{path='products/category/{child_category_url_title}'}">{child_category_name}</a></li> {child_category_end} {/exp:child_categories} </ul> {/exp:channel:entries} </div><!-- END LIST WRAP --> <br style="clear:both;" /> ```
2012/04/16
[ "https://Stackoverflow.com/questions/10177524", "https://Stackoverflow.com", "https://Stackoverflow.com/users/988005/" ]
In EE 2.4 you can now use `{if active}class="foobar"{/if}` try that and see.
You want to be computing against the category URL title in your URL. I'm not totally familiar with the Child Categories plugin you're using, but it appears as though this should work within your `{exp:child_categories}` loop: `{if child_category_url_tile == segment_3} class="active"{/if}` I don't totally understand what you're doing in your code, as you're calling the same channel entries loop 5 times, then filtering what you display based on conditional category statements each time. If this is actually your full code, you should seriously consider rethinking and refactoring. Your overhead here is insane!
32,263,334
My problem - process try change entity that already changed and have newest version id. When i do flush() in my code in UnitOfWork's commit() rising OptimisticLockException and catching in same place by catch-all block. And in this catch doctrine closing EntityManager. If i want skip this entity and continue with another from ArrayCollection, i should not use flush()? Try recreate EntityManager: ``` }catch (OptimisticLockException $e){ $this->em = $this->container->get('doctrine')->getManager(); echo "\n||OptimisticLockException."; continue; } ``` And still get ``` [Doctrine\ORM\ORMException] The EntityManager is closed. ``` Strange. If i do ``` $this->em->lock($entity, LockMode::OPTIMISTIC, $entity->getVersion()); ``` and then do flush() i get OptimisticLockException and closed entity manager. if i do ``` $this->getContainer()->get('doctrine')->resetManager(); $em = $doctrine->getManager(); ``` Old data unregistered with this entity manager and i even can't write logs in database, i get error: ``` [Symfony\Component\Debug\Exception\ContextErrorException] Notice: Undefined index: 00000000514cef3c000000002ff4781e ```
2015/08/28
[ "https://Stackoverflow.com/questions/32263334", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2103893/" ]
You should check entity version before you try to flush it to avoid exception. In other words you should not call flush() method if the lock fails. You can use `EntityManager#lock()` method for checking whether you can flush entity or not. ```php /** @var EntityManager $em */ $entity = $em->getRepository('Post')->find($_REQUEST['id']); // Get expected version (easiest way is to have the version number as a hidden form field) $expectedVersion = $_REQUEST['version']; // Update your entity $entity->setText($_REQUEST['text']); try { //assert you edit right version $em->lock($entity, LockMode::OPTIMISTIC, $expectedVersion); //if $em->lock() fails flush() is not called and EntityManager is not closed $em->flush(); } catch (OptimisticLockException $e) { echo "Sorry, but someone else has already changed this entity. Please apply the changes again!"; } ``` Check the example in Doctrine docs [optimistic locking](http://doctrine-orm.readthedocs.org/en/latest/reference/transactions-and-concurrency.html#optimistic-locking)
Unfortunately, nearly 4 years later, Doctrine is still unable to recover from an optimistic lock properly. Using the `lock` function as suggested in the doc doesn't work if the db was changed by another server or php worker thread. The `lock` function only makes sure the version number wasn't changed by the current php script since the entity was loaded into memory. It doesn't read the db to make sure the version number is still the expected one. And even if it did read the db, there is still the potential for a race condition between the time the `lock` function checks the current version in the db and the flush is performed. Consider this scenario: * server A reads the entity, * server B reads the same entity, * server B updates the db, * server A updates the db <== optimistic lock exception The exception is triggered when `flush` is called and there is nothing that can be done to prevent it. Even a pessimistic lock won't help unless you can afford to loose performance and actually lock your db for a (relatively) long time. Doctrine's solution (`update... where version = :expected_version`) is good in theory. But, sadly, Doctrine was designed to become unusable once an exception is triggered. **Any** exception. Every entity is detached. Even if the optimistic lock can be easily solved by re-reading the entity and applying the change again, Doctrine makes it very hard to do so.
5,547,844
Please try to help me.. How to open and write commands in Command Prompt using asp.net3.5,C#.net... if i click a Button in my UI it should open the commaond Prompt and i want excute few commands there... Thank you..
2011/04/05
[ "https://Stackoverflow.com/questions/5547844", "https://Stackoverflow.com", "https://Stackoverflow.com/users/692294/" ]
Try to use this code you need to add the namespace ``` using System.Diagnostics; var processStartInfo = new ProcessStartInfo { Arguments = "ping google.com", FileName = "cmd" }; Process process = Process.Start(processStartInfo); ```
You said > > if i click a Button in my UI > > > so do you mean on the client side from browser.. sorry that's not possible from any JavaScript Code. You can't start a process on clients system with any code running in Browser. Something should be installed as a Desktop app to do that.
5,547,844
Please try to help me.. How to open and write commands in Command Prompt using asp.net3.5,C#.net... if i click a Button in my UI it should open the commaond Prompt and i want excute few commands there... Thank you..
2011/04/05
[ "https://Stackoverflow.com/questions/5547844", "https://Stackoverflow.com", "https://Stackoverflow.com/users/692294/" ]
It sounds like you want to open the command prompt from a browsers on the client PC. To do this you either need to: * Use an ActiveX control, which will require that the user approve the installation of the ActiveX control. * Use the WScript.Shell object which is very unlikely to be available (for security reasons) unless your site is in a "very trusted" zone. I.e. you can't expect a normal user to allow this to happen - this is only really going to be useful on your own PC. If this is OK then you can find an example of running an application from JavaScript using the WScript.Shell object here (this is the easiest of the two options). * [How to run an external program, e.g. notepad, using hyperlink?](https://stackoverflow.com/questions/2800081/how-to-run-an-external-program-e-g-notepad-using-hyperlink)
You said > > if i click a Button in my UI > > > so do you mean on the client side from browser.. sorry that's not possible from any JavaScript Code. You can't start a process on clients system with any code running in Browser. Something should be installed as a Desktop app to do that.
5,547,844
Please try to help me.. How to open and write commands in Command Prompt using asp.net3.5,C#.net... if i click a Button in my UI it should open the commaond Prompt and i want excute few commands there... Thank you..
2011/04/05
[ "https://Stackoverflow.com/questions/5547844", "https://Stackoverflow.com", "https://Stackoverflow.com/users/692294/" ]
Try to use this code you need to add the namespace ``` using System.Diagnostics; var processStartInfo = new ProcessStartInfo { Arguments = "ping google.com", FileName = "cmd" }; Process process = Process.Start(processStartInfo); ```
It sounds like you want to open the command prompt from a browsers on the client PC. To do this you either need to: * Use an ActiveX control, which will require that the user approve the installation of the ActiveX control. * Use the WScript.Shell object which is very unlikely to be available (for security reasons) unless your site is in a "very trusted" zone. I.e. you can't expect a normal user to allow this to happen - this is only really going to be useful on your own PC. If this is OK then you can find an example of running an application from JavaScript using the WScript.Shell object here (this is the easiest of the two options). * [How to run an external program, e.g. notepad, using hyperlink?](https://stackoverflow.com/questions/2800081/how-to-run-an-external-program-e-g-notepad-using-hyperlink)
30,548,655
I am writing a c++ function to calculate the size of an C-type array in C++ I noticed a very strange behavior when using these two different codes: **code 1:** ``` int sz = sizeof array / sizeof *array; ``` **code 2:** ``` int array_size(const int *pointer) { int count=0; if(pointer) while(*pointer) { count++; pointer++; } return count; } ``` When I applied these two method on a array, it gave me very strange behavior: **example 1 :** ``` int array[10] = {31,24,65,32,14,5};// defined to be size 10 but init with size 6 ``` the code one will give me size = 10, but code 2 will give me size 6,and when I print out the element that is pointed by \*pointer, it will give me the correct array elements: ``` 31 24 65 32 14 5 ``` **example 2** ``` int array[] = {31,24,65,32,14,5}; // no declared size but init with 6 ``` Code 1 will give me size 6, code 2 will give me size 12, and when I print out the element that is pointed by \*pointer in code 2, it gives me : ``` 31 24 65 32 14 5 -802013403 -150942493 1461458784 32767 -1918962231 32767 ``` which is really not right, so what could be the problem that cause this behavior? and what are those numbers? Thanks for your answer
2015/05/30
[ "https://Stackoverflow.com/questions/30548655", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3871348/" ]
This array has 10 elements, regardless of how you initialize it: ``` int array[10] = {31,24,65,32,14,5}; ``` But the initialization sets the first 6 elements to certain values, and the rest to `0`. It is equivalent to this: ``` int array[10] = {31,24,65,32,14,5,0,0,0,0}; ``` The first calculation using `sizeof` uses the actual size fo the array (its length times the size of an `int`), while the second one counts elements until it finds a `0`. So it doesn't calculate the length of the array, but the length of the first non-zero sequence in the array. Note that the second method only "works" if the array has an element with value `0`. Otherwise you go out of bounds and invoke undefined behaviour.
code 2 is not right. you can't assume an array end with 0
30,548,655
I am writing a c++ function to calculate the size of an C-type array in C++ I noticed a very strange behavior when using these two different codes: **code 1:** ``` int sz = sizeof array / sizeof *array; ``` **code 2:** ``` int array_size(const int *pointer) { int count=0; if(pointer) while(*pointer) { count++; pointer++; } return count; } ``` When I applied these two method on a array, it gave me very strange behavior: **example 1 :** ``` int array[10] = {31,24,65,32,14,5};// defined to be size 10 but init with size 6 ``` the code one will give me size = 10, but code 2 will give me size 6,and when I print out the element that is pointed by \*pointer, it will give me the correct array elements: ``` 31 24 65 32 14 5 ``` **example 2** ``` int array[] = {31,24,65,32,14,5}; // no declared size but init with 6 ``` Code 1 will give me size 6, code 2 will give me size 12, and when I print out the element that is pointed by \*pointer in code 2, it gives me : ``` 31 24 65 32 14 5 -802013403 -150942493 1461458784 32767 -1918962231 32767 ``` which is really not right, so what could be the problem that cause this behavior? and what are those numbers? Thanks for your answer
2015/05/30
[ "https://Stackoverflow.com/questions/30548655", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3871348/" ]
This array has 10 elements, regardless of how you initialize it: ``` int array[10] = {31,24,65,32,14,5}; ``` But the initialization sets the first 6 elements to certain values, and the rest to `0`. It is equivalent to this: ``` int array[10] = {31,24,65,32,14,5,0,0,0,0}; ``` The first calculation using `sizeof` uses the actual size fo the array (its length times the size of an `int`), while the second one counts elements until it finds a `0`. So it doesn't calculate the length of the array, but the length of the first non-zero sequence in the array. Note that the second method only "works" if the array has an element with value `0`. Otherwise you go out of bounds and invoke undefined behaviour.
`array_size` assumes that there is a `0` just past the end of the array. That assumption is unjustified.
30,548,655
I am writing a c++ function to calculate the size of an C-type array in C++ I noticed a very strange behavior when using these two different codes: **code 1:** ``` int sz = sizeof array / sizeof *array; ``` **code 2:** ``` int array_size(const int *pointer) { int count=0; if(pointer) while(*pointer) { count++; pointer++; } return count; } ``` When I applied these two method on a array, it gave me very strange behavior: **example 1 :** ``` int array[10] = {31,24,65,32,14,5};// defined to be size 10 but init with size 6 ``` the code one will give me size = 10, but code 2 will give me size 6,and when I print out the element that is pointed by \*pointer, it will give me the correct array elements: ``` 31 24 65 32 14 5 ``` **example 2** ``` int array[] = {31,24,65,32,14,5}; // no declared size but init with 6 ``` Code 1 will give me size 6, code 2 will give me size 12, and when I print out the element that is pointed by \*pointer in code 2, it gives me : ``` 31 24 65 32 14 5 -802013403 -150942493 1461458784 32767 -1918962231 32767 ``` which is really not right, so what could be the problem that cause this behavior? and what are those numbers? Thanks for your answer
2015/05/30
[ "https://Stackoverflow.com/questions/30548655", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3871348/" ]
`array_size` assumes that there is a `0` just past the end of the array. That assumption is unjustified.
code 2 is not right. you can't assume an array end with 0
38,649,720
I have implemented the BaseActivity pattern in my app and everything works great except when trying to show an Alert Dialog box. This is what happens [![enter image description here](https://i.stack.imgur.com/wmgBG.png)](https://i.stack.imgur.com/wmgBG.png) when I try to cancel the dialog box I'm left with this. [![enter image description here](https://i.stack.imgur.com/jQdvh.png)](https://i.stack.imgur.com/jQdvh.png) Here's the code for showing the dialog box which resides in the base activity: ``` new AlertDialog.Builder(this) .setTitle("Logging out") .setMessage("Are you sure?") .setPositiveButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { UIUtils.setAnimation(swipeRefreshLayout, true); UserBaas.logoutUser(); } }) .setNegativeButton("No", null) .show(); ``` This problem is persistent in an emulator and on an actual device. What could be the issue? ``` switch (item) { case NAVDRAWER_ITEM_HOME: startActivity(new Intent(this, MainActivity.class)); break; case NAVDRAWER_ITEM_MEMOS: intent = new Intent(this, MemoGroupActivity.class); intent.putExtra("section", MemoGroupActivity.MEMO); createBackStack(intent); break; case NAVDRAWER_ITEM_GROUPS: intent = new Intent(this, MemoGroupActivity.class); intent.putExtra("section", MemoGroupActivity.GROUP); createBackStack(intent); break; case NAVDRAWER_ITEM_CONNECTIONS: createBackStack(new Intent(this, ConnectionsActivity.class)); break; case NAVDRAWER_ITEM_DOCUMENTS: createBackStack(new Intent(this, DocumentsActivity.class)); break; case NAVDRAWER_ITEM_SETTINGS: createBackStack(new Intent(this, SettingsActivity.class)); break; case NAVDRAWER_ITEM_LOGOUT: showLogoutDialog(); break; } ``` And heres the code for UIUtils.setAnimation() ``` public static void setAnimation(SwipeRefreshLayout swipeRefreshLayout, boolean value) { swipeRefreshLayout.setEnabled(value); swipeRefreshLayout.setRefreshing(value); } ```
2016/07/29
[ "https://Stackoverflow.com/questions/38649720", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3716006/" ]
Ok, so over time I've answered my own questions on this topic. First, Elastic Beanstalk uses CloudFormation behind the scenes, so this is why there is a "stack". Next, Spring Cloud AWS tries to make connections to DBs and such easier by binding to other resources that may have been created in the same stack. This is reasonable - if you are expecting it. If not, as @barthand says, it is probably better to turn this feature off with cloud.aws.stack.auto=false than have the app fail to start up. Third, When using Elastic Beanstalk, you have the opportunity to associate an execution role with your instance - otherwise the code in your instance isn't able to do much of anything with the AWS SDK. To explore the resources in a CloudFormation stack, Spring Cloud AWS tries to make some API calls, and by default these are not allowed. To make them allowed, I added these permissions to the role: ``` "Statement": [ { "Effect": "Allow", "Action": [ "cloudformation:DescribeStacks", "cloudformation:DescribeStackEvents", "cloudformation:DescribeStackResource", "cloudformation:DescribeStackResources", "cloudformation:GetTemplate", "cloudformation:List*" ], "Resource": "*" } ] ``` So to answer my original questions: 1. Yes it is definitely possible (and easy!) to run a Spring Cloud AWS program in Elastic Beanstalk. 2. Special requirements - Need to open the permissions on the associated role to include CloudFormation read operations, or... 3. Disable these using cloud.aws.stack.auto=false Hope this info helps someone in the future
`spring-cloud-aws` seems to assume by default that you're running your app using your custom CloudFormation template. In case of Elastic Beanstalk, you simply need to tell `spring-cloud-aws` to resign from obtaining information about the stack automatically: ``` cloud.aws.stack.auto = false ``` Not sure why it is not mentioned in the docs. For basic Java apps, Elastic Beanstalk seems to be an obvious choice.
21,924,911
Can anyone help me how to change the date format of this jquery validation from YYYY-MM-DD to MM/DD/YYYY. Example: ``` 2014-02-21 must be 02/21/2014 ``` I tried to change this: `new RegExp(/^(\d{4})[\/\-\.](0?[1-9]|1[012])[\/\-\.](0?[1-9]|[12][0-9]|3[01])$/);` To: `new RegExp(/^((0?[13578]|10|12)(-|\/)(([1-9])|(0[1-9])|([12])([0-9]?)|(3[01]?))(-|\/)((19)([2-9])(\d{1})|(20)([01])(\d{1})|([8901])(\d{1}))|(0?[2469]|11)(-|\/)(([1-9])|(0[1-9])|([12])([0-9]?)|(3[0]?))(-|\/)((19)([2-9])(\d{1})|(20)([01])(\d{1})|([8901])(\d{1})))$/);` But still I can't get the right validation I want.. Here's the code: ``` "date": { // Check if date is valid by leap year "func": function (field) { var pattern = new RegExp(/^(\d{4})[\/\-\.](0?[1-9]|1[012])[\/\-\.](0?[1-9]|[12][0-9]|3[01])$/); //<---- The Original Pattern of YYYY-MM-DD var match = pattern.exec(field.val()); if (match == null) return false; var year = match[1]; var month = match[2]*1; var day = match[3]*1; var date = new Date(year, month - 1, day); // because months starts from 0. return (date.getFullYear() == year && date.getMonth() == (month - 1) && date.getDate() == day); }, "alertText": "* Invalid date, must be in YYYY-MM-DD format" } ``` Please help me.. thanks.. :)
2014/02/21
[ "https://Stackoverflow.com/questions/21924911", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2897924/" ]
Congratulations! You moved to a much better API than the one you had before. There are many reasons why the `DbContext` API is better than the older `ObjectContext` API, but in your case it may initially feel like a downgrade. ### Where's my `EntityState`, where's my `Reference`? Separation of concerns is the key here. The `DbContext` API aims at *persistence ignorance*: separation between business logic and data layer concerns. Entities generated by the `ObjectContext` API are far too busy tracking their own state, loading their own references and collections and notifying their own changes. Any business logic easily gets entwined with persistence logic. The entity classes generated by the `DbContext` generator are POCOs. All these data-related responsibilities have moved to the change tracker. The POCOs can concentrate on business logic. (They're still not the same as a DDD domain, but that's a different discussion). If you want, you can still go back to the `ObjectContext` API, but I wouldn't recommend it. Your code reveals that the API encourages bad practices: * Objects loading their own references or collections easily lead to the N + 1 anti pattern (1 query loading objects followed by "N" queries per object). * For objects to be able to load their own data the context must be alive, so this encourages the long-lived context anti pattern. The `DbContext` API encourages you to load object graphs as needed and then dispose the context. But it depends. In smart client applications you may have a context per form. In web applications a context per request is highly recommended. As you say in your comment to Tieson T. you can rely on lazy loading to occur whenever you access a navigation property and the [conditions for lazy loading](http://msdn.microsoft.com/en-us/data/jj574232#lazy) are met, but the above-mentioned anti patterns still apply. So I think for the time being you can leave your application code as-is, but take a look at the patterns the `DbContext` API encourages you to adhere to. As for me, lazy loading is close to being an anti pattern.
I'll have to look for the others, but `State` can be found via: ``` context.Entry(yourEFobject).State ``` where `context` is your `DbContext` instance. As @GertArnold alludes to in his comment, Entity objects in EF6 are simple POCOs, so you can't read state, etc. directly from them. This answer seems to cover `.IsLoaded` and `.Load`: <https://stackoverflow.com/a/13366108/534109> Content from that answer included for completeness: ``` context.Entry(yourEntity) .Collection(entity => entity.NavigationProperty) .IsLoaded; context.Entry(yourEntity) .Collection(entity => entity.NavigationProperty) .Load(); ```
36,229
A few times in the past week I will wake up to my furnace turning on, hearing a click when it tries to ignite, then turn off. This will happen for a couple minutes before the furnace quits trying. However, after a certain period of time, it will turn on again with no issues. What should I do so it doesn't happen ever?
2013/11/28
[ "https://diy.stackexchange.com/questions/36229", "https://diy.stackexchange.com", "https://diy.stackexchange.com/users/2177/" ]
I have a similar problem, also. This is how I repaired my furnace: when it tries to come on to soon (like less then 10 minutes) it won't open the gas valve. Try to do this three times. When you hear a "click" sound tap the gas valve with a plastic handle of a nut driver for instance. The tapping should open the valve. If you can verify that the furnace stay's on for about 15 minutes before it turns off it should be fine. I believe that the solenoid at the valve may be the problem. It may be getting stuck and the tapping jars it loose. Hope this helps.
My problem was close to the same everything worked as it should but the flame would only stay lit for 7 seconds. I followed the trouble shooting tree in the install guide. It said "flame lights but won't stay lit-check flame sensor l.e.d. if flashing clean or replace the sensor." I cleaned it, with out removing it, with fine steel wool. The l.e.d. light stopped blinking and stayed on with the flame and the furnace heats until the thermostat is satisfied. Hope this helps most install guides are in a pouch on the furnace.
36,229
A few times in the past week I will wake up to my furnace turning on, hearing a click when it tries to ignite, then turn off. This will happen for a couple minutes before the furnace quits trying. However, after a certain period of time, it will turn on again with no issues. What should I do so it doesn't happen ever?
2013/11/28
[ "https://diy.stackexchange.com/questions/36229", "https://diy.stackexchange.com", "https://diy.stackexchange.com/users/2177/" ]
***WARNING:** Furnaces are expensive, complex pieces of equipment. If you don't have the proper tools and/or knowledge, it's often best to let the professionals handle maintenance and repair.* Gas Furnace Ignition Sequence: ============================== 1. Thermostat calls for heat. 2. Pilot gas valve opens. 3. Ignition control starts (spark or glow). 4. Pilot gas ignites. 5. Flame sensor detects pilot flame. 6. Main gas valve opens. 7. Main burners ignite. 8. Blower timer starts. 9. Flame sensor detects main burner flame. 10. Blower starts. High Efficiency Gas Furnace Ignition Sequence: ============================================== 1. Thermostat calls for heat. 2. Draft inducer starts. 3. Vacuum switch detects negative pressure. 4. Pilot valve opens. 5. Ignition control starts (spark or glow). 6. Pilot gas ignites. 7. Flame sensor detects pilot flame. 8. Main gas valve opens. 9. Main burners ignite. 10. Blower timer starts. 11. Flame sensor detects main burner flame. 12. Blower starts. Ignition Problems: ================== Vacuum Switch Not Closing ------------------------- In a high efficiency furnace, if the vacuum switch does not close after a certain timeout. The furnace will shut down, then possibly retry a few times depending on model. If after a given number of tries the switch still does not close, the furnace will enter lock out. Once in lock out, the furnace has to be manually reset (depending on model). The vacuum switch will look something like this... ![Vacuum switch](https://i.stack.imgur.com/JuyoF.jpg) And will have a rubber tube connecting it to the draft inducer. This part cannot be repaired, and must be replaced if it's faulty. Pilot Not Igniting ------------------ If the pilot does not light, you'll first want to check to make sure there is something trying to ignite it. Typically a spark or glow ignitor is used, so first you'll want to determine which is being used. ### Glow Ignitor A glow ignitor looks similar to this, though may not be visible without further disassembly. ![Glow ignitor](https://i.stack.imgur.com/m3OVd.jpg) It works by passing a current through it, causing it to heat up and glow. It should heat up enough to ignite the pilot gas. If it doesn't heat up, it should be replaced. ### Spark Ignitor A spark ignitor looks like this. ![Spark Ignitor](https://i.stack.imgur.com/KugBz.jpg) Take notice of the thick, often orange or red wire that is typically used to connect the ignitor to the ignition control module. This device works by generating an electrical arc between the two probes, causing the pilot gas to ignite. If there is no spark, you'll have to replace the ignition control module and/or the ignitor itself. If the [ignitor is not igniting the gas](https://diy.stackexchange.com/q/32529/33), but there is a spark. You can try cleaning the electrodes with fine steel wool, to remove any carbon buildup. Pilot Not Proving ----------------- For a pilot to "prove", it simply means that the flame sensor has sensed the pilot flame. If there is no pilot or the sensor doesn't detect it, the furnace will often purge the system and then try again. Furnaces will often try a set number of times, before entering lock out. If you can see the pilot flame, but the sensor is not detecting it. Try gently cleaning the sensor with fine steel wool, to remove any built up carbon. Also make sure the sensor is in the proper location with respect to the flame (Check the owners manual for proper placement), and adjust as necessary. If that doesn't work, replace the sensor. Main Burner Not Proving ----------------------- If the main burner ignites, but the furnace shuts down before the blower starts. You'll want to check the main flame (or rollout, high limit, etc) sensor(s). If your furnace has error code indicators, check those and compare to the owners manual for translation. In this case, you'll want to test and/or replace each sensor and/or contact an HVAC technician
I did all the above checks on my gas furnace and none solved the issue. Then I blew compressed air through each of the gas venturis (the hourglass shaped tubes that mix the natural gas with the air - flames come out the back). It turns out that over the years that the furnace was in service, the dust build-up in the venturis was enough to affect the gas flow and ignition across the venturis. Of course if you are going to try this fix, turn the gas and power off first etc.
36,229
A few times in the past week I will wake up to my furnace turning on, hearing a click when it tries to ignite, then turn off. This will happen for a couple minutes before the furnace quits trying. However, after a certain period of time, it will turn on again with no issues. What should I do so it doesn't happen ever?
2013/11/28
[ "https://diy.stackexchange.com/questions/36229", "https://diy.stackexchange.com", "https://diy.stackexchange.com/users/2177/" ]
My furnace would ignite the pilot and energize the induction motor but the main burner valve would not open. At first I suspected a bad coil on the vale selonoid but continuity check indicated it was good. Then traced around with my meter and got to the pressure switch. It was not switching when the induction fan ran. I removed the tube from the furnace and could make it switch by gently applying a vaccum with my mouth. I ended up dismantling the induction intake plenum an found that over the years condensation from the airconditioner had dissolved some of the zinc plating and carried it down to the port of for the pressure switch tube. There it would evaporate and eventually built up enough of a zinc deposit to completely plug the port. Using a small drill bit turned by hand I cleared the port and reassembled the furnace. That was it, worked the first time and every time. Quite the learning experience!.
I had the same problem on a 25 year old furnace. I thought the exhaust was stopped up again, But it was just the vacuum switch causing it. It had dust build up in it. All I had to do was blow into the line connected to the sensor, and it was fine.
36,229
A few times in the past week I will wake up to my furnace turning on, hearing a click when it tries to ignite, then turn off. This will happen for a couple minutes before the furnace quits trying. However, after a certain period of time, it will turn on again with no issues. What should I do so it doesn't happen ever?
2013/11/28
[ "https://diy.stackexchange.com/questions/36229", "https://diy.stackexchange.com", "https://diy.stackexchange.com/users/2177/" ]
***WARNING:** Furnaces are expensive, complex pieces of equipment. If you don't have the proper tools and/or knowledge, it's often best to let the professionals handle maintenance and repair.* Gas Furnace Ignition Sequence: ============================== 1. Thermostat calls for heat. 2. Pilot gas valve opens. 3. Ignition control starts (spark or glow). 4. Pilot gas ignites. 5. Flame sensor detects pilot flame. 6. Main gas valve opens. 7. Main burners ignite. 8. Blower timer starts. 9. Flame sensor detects main burner flame. 10. Blower starts. High Efficiency Gas Furnace Ignition Sequence: ============================================== 1. Thermostat calls for heat. 2. Draft inducer starts. 3. Vacuum switch detects negative pressure. 4. Pilot valve opens. 5. Ignition control starts (spark or glow). 6. Pilot gas ignites. 7. Flame sensor detects pilot flame. 8. Main gas valve opens. 9. Main burners ignite. 10. Blower timer starts. 11. Flame sensor detects main burner flame. 12. Blower starts. Ignition Problems: ================== Vacuum Switch Not Closing ------------------------- In a high efficiency furnace, if the vacuum switch does not close after a certain timeout. The furnace will shut down, then possibly retry a few times depending on model. If after a given number of tries the switch still does not close, the furnace will enter lock out. Once in lock out, the furnace has to be manually reset (depending on model). The vacuum switch will look something like this... ![Vacuum switch](https://i.stack.imgur.com/JuyoF.jpg) And will have a rubber tube connecting it to the draft inducer. This part cannot be repaired, and must be replaced if it's faulty. Pilot Not Igniting ------------------ If the pilot does not light, you'll first want to check to make sure there is something trying to ignite it. Typically a spark or glow ignitor is used, so first you'll want to determine which is being used. ### Glow Ignitor A glow ignitor looks similar to this, though may not be visible without further disassembly. ![Glow ignitor](https://i.stack.imgur.com/m3OVd.jpg) It works by passing a current through it, causing it to heat up and glow. It should heat up enough to ignite the pilot gas. If it doesn't heat up, it should be replaced. ### Spark Ignitor A spark ignitor looks like this. ![Spark Ignitor](https://i.stack.imgur.com/KugBz.jpg) Take notice of the thick, often orange or red wire that is typically used to connect the ignitor to the ignition control module. This device works by generating an electrical arc between the two probes, causing the pilot gas to ignite. If there is no spark, you'll have to replace the ignition control module and/or the ignitor itself. If the [ignitor is not igniting the gas](https://diy.stackexchange.com/q/32529/33), but there is a spark. You can try cleaning the electrodes with fine steel wool, to remove any carbon buildup. Pilot Not Proving ----------------- For a pilot to "prove", it simply means that the flame sensor has sensed the pilot flame. If there is no pilot or the sensor doesn't detect it, the furnace will often purge the system and then try again. Furnaces will often try a set number of times, before entering lock out. If you can see the pilot flame, but the sensor is not detecting it. Try gently cleaning the sensor with fine steel wool, to remove any built up carbon. Also make sure the sensor is in the proper location with respect to the flame (Check the owners manual for proper placement), and adjust as necessary. If that doesn't work, replace the sensor. Main Burner Not Proving ----------------------- If the main burner ignites, but the furnace shuts down before the blower starts. You'll want to check the main flame (or rollout, high limit, etc) sensor(s). If your furnace has error code indicators, check those and compare to the owners manual for translation. In this case, you'll want to test and/or replace each sensor and/or contact an HVAC technician
My problem was close to the same everything worked as it should but the flame would only stay lit for 7 seconds. I followed the trouble shooting tree in the install guide. It said "flame lights but won't stay lit-check flame sensor l.e.d. if flashing clean or replace the sensor." I cleaned it, with out removing it, with fine steel wool. The l.e.d. light stopped blinking and stayed on with the flame and the furnace heats until the thermostat is satisfied. Hope this helps most install guides are in a pouch on the furnace.
36,229
A few times in the past week I will wake up to my furnace turning on, hearing a click when it tries to ignite, then turn off. This will happen for a couple minutes before the furnace quits trying. However, after a certain period of time, it will turn on again with no issues. What should I do so it doesn't happen ever?
2013/11/28
[ "https://diy.stackexchange.com/questions/36229", "https://diy.stackexchange.com", "https://diy.stackexchange.com/users/2177/" ]
I have a similar problem, also. This is how I repaired my furnace: when it tries to come on to soon (like less then 10 minutes) it won't open the gas valve. Try to do this three times. When you hear a "click" sound tap the gas valve with a plastic handle of a nut driver for instance. The tapping should open the valve. If you can verify that the furnace stay's on for about 15 minutes before it turns off it should be fine. I believe that the solenoid at the valve may be the problem. It may be getting stuck and the tapping jars it loose. Hope this helps.
I did all the above checks on my gas furnace and none solved the issue. Then I blew compressed air through each of the gas venturis (the hourglass shaped tubes that mix the natural gas with the air - flames come out the back). It turns out that over the years that the furnace was in service, the dust build-up in the venturis was enough to affect the gas flow and ignition across the venturis. Of course if you are going to try this fix, turn the gas and power off first etc.
36,229
A few times in the past week I will wake up to my furnace turning on, hearing a click when it tries to ignite, then turn off. This will happen for a couple minutes before the furnace quits trying. However, after a certain period of time, it will turn on again with no issues. What should I do so it doesn't happen ever?
2013/11/28
[ "https://diy.stackexchange.com/questions/36229", "https://diy.stackexchange.com", "https://diy.stackexchange.com/users/2177/" ]
I have a similar problem, also. This is how I repaired my furnace: when it tries to come on to soon (like less then 10 minutes) it won't open the gas valve. Try to do this three times. When you hear a "click" sound tap the gas valve with a plastic handle of a nut driver for instance. The tapping should open the valve. If you can verify that the furnace stay's on for about 15 minutes before it turns off it should be fine. I believe that the solenoid at the valve may be the problem. It may be getting stuck and the tapping jars it loose. Hope this helps.
Had one furnace that would get all the way through to lighting the main burners with good flame and then start blower motor. After 4 or 5 seconds the flame would shut off and after another 15-20 seconds (with blower still on) the flame sequence would start and light again. This would repeat two or three times. Turns out the flame would shut off on heat exchanger high temp limit, blower would cool down heat exchanger, and high limit switch, and flame sequence would start again. The rain cap on the flue stack above the roof had slid down and was choking off the flue exhaust flow over heating the heat exchanger. Fix was to install sheet metal screws fixing the rain cap in the proper position. Operation normal after that.
36,229
A few times in the past week I will wake up to my furnace turning on, hearing a click when it tries to ignite, then turn off. This will happen for a couple minutes before the furnace quits trying. However, after a certain period of time, it will turn on again with no issues. What should I do so it doesn't happen ever?
2013/11/28
[ "https://diy.stackexchange.com/questions/36229", "https://diy.stackexchange.com", "https://diy.stackexchange.com/users/2177/" ]
My furnace would ignite the pilot and energize the induction motor but the main burner valve would not open. At first I suspected a bad coil on the vale selonoid but continuity check indicated it was good. Then traced around with my meter and got to the pressure switch. It was not switching when the induction fan ran. I removed the tube from the furnace and could make it switch by gently applying a vaccum with my mouth. I ended up dismantling the induction intake plenum an found that over the years condensation from the airconditioner had dissolved some of the zinc plating and carried it down to the port of for the pressure switch tube. There it would evaporate and eventually built up enough of a zinc deposit to completely plug the port. Using a small drill bit turned by hand I cleared the port and reassembled the furnace. That was it, worked the first time and every time. Quite the learning experience!.
Had one furnace that would get all the way through to lighting the main burners with good flame and then start blower motor. After 4 or 5 seconds the flame would shut off and after another 15-20 seconds (with blower still on) the flame sequence would start and light again. This would repeat two or three times. Turns out the flame would shut off on heat exchanger high temp limit, blower would cool down heat exchanger, and high limit switch, and flame sequence would start again. The rain cap on the flue stack above the roof had slid down and was choking off the flue exhaust flow over heating the heat exchanger. Fix was to install sheet metal screws fixing the rain cap in the proper position. Operation normal after that.
36,229
A few times in the past week I will wake up to my furnace turning on, hearing a click when it tries to ignite, then turn off. This will happen for a couple minutes before the furnace quits trying. However, after a certain period of time, it will turn on again with no issues. What should I do so it doesn't happen ever?
2013/11/28
[ "https://diy.stackexchange.com/questions/36229", "https://diy.stackexchange.com", "https://diy.stackexchange.com/users/2177/" ]
I have a similar problem, also. This is how I repaired my furnace: when it tries to come on to soon (like less then 10 minutes) it won't open the gas valve. Try to do this three times. When you hear a "click" sound tap the gas valve with a plastic handle of a nut driver for instance. The tapping should open the valve. If you can verify that the furnace stay's on for about 15 minutes before it turns off it should be fine. I believe that the solenoid at the valve may be the problem. It may be getting stuck and the tapping jars it loose. Hope this helps.
Mine would open the main valve and good flame and valve would close immediately but kept trying (a buzzing sound and hearing the repeat attempts took me to the basement). I thought a flame sensor but as I had just replaced a loud inducer motor, I pulled the vacuum hose off and applied vacuum and got water. Drained hose, made the vac. switch activate a couple times and no buzz and normal operating. Need chimney work...Guess a "T" trap for now.
36,229
A few times in the past week I will wake up to my furnace turning on, hearing a click when it tries to ignite, then turn off. This will happen for a couple minutes before the furnace quits trying. However, after a certain period of time, it will turn on again with no issues. What should I do so it doesn't happen ever?
2013/11/28
[ "https://diy.stackexchange.com/questions/36229", "https://diy.stackexchange.com", "https://diy.stackexchange.com/users/2177/" ]
***WARNING:** Furnaces are expensive, complex pieces of equipment. If you don't have the proper tools and/or knowledge, it's often best to let the professionals handle maintenance and repair.* Gas Furnace Ignition Sequence: ============================== 1. Thermostat calls for heat. 2. Pilot gas valve opens. 3. Ignition control starts (spark or glow). 4. Pilot gas ignites. 5. Flame sensor detects pilot flame. 6. Main gas valve opens. 7. Main burners ignite. 8. Blower timer starts. 9. Flame sensor detects main burner flame. 10. Blower starts. High Efficiency Gas Furnace Ignition Sequence: ============================================== 1. Thermostat calls for heat. 2. Draft inducer starts. 3. Vacuum switch detects negative pressure. 4. Pilot valve opens. 5. Ignition control starts (spark or glow). 6. Pilot gas ignites. 7. Flame sensor detects pilot flame. 8. Main gas valve opens. 9. Main burners ignite. 10. Blower timer starts. 11. Flame sensor detects main burner flame. 12. Blower starts. Ignition Problems: ================== Vacuum Switch Not Closing ------------------------- In a high efficiency furnace, if the vacuum switch does not close after a certain timeout. The furnace will shut down, then possibly retry a few times depending on model. If after a given number of tries the switch still does not close, the furnace will enter lock out. Once in lock out, the furnace has to be manually reset (depending on model). The vacuum switch will look something like this... ![Vacuum switch](https://i.stack.imgur.com/JuyoF.jpg) And will have a rubber tube connecting it to the draft inducer. This part cannot be repaired, and must be replaced if it's faulty. Pilot Not Igniting ------------------ If the pilot does not light, you'll first want to check to make sure there is something trying to ignite it. Typically a spark or glow ignitor is used, so first you'll want to determine which is being used. ### Glow Ignitor A glow ignitor looks similar to this, though may not be visible without further disassembly. ![Glow ignitor](https://i.stack.imgur.com/m3OVd.jpg) It works by passing a current through it, causing it to heat up and glow. It should heat up enough to ignite the pilot gas. If it doesn't heat up, it should be replaced. ### Spark Ignitor A spark ignitor looks like this. ![Spark Ignitor](https://i.stack.imgur.com/KugBz.jpg) Take notice of the thick, often orange or red wire that is typically used to connect the ignitor to the ignition control module. This device works by generating an electrical arc between the two probes, causing the pilot gas to ignite. If there is no spark, you'll have to replace the ignition control module and/or the ignitor itself. If the [ignitor is not igniting the gas](https://diy.stackexchange.com/q/32529/33), but there is a spark. You can try cleaning the electrodes with fine steel wool, to remove any carbon buildup. Pilot Not Proving ----------------- For a pilot to "prove", it simply means that the flame sensor has sensed the pilot flame. If there is no pilot or the sensor doesn't detect it, the furnace will often purge the system and then try again. Furnaces will often try a set number of times, before entering lock out. If you can see the pilot flame, but the sensor is not detecting it. Try gently cleaning the sensor with fine steel wool, to remove any built up carbon. Also make sure the sensor is in the proper location with respect to the flame (Check the owners manual for proper placement), and adjust as necessary. If that doesn't work, replace the sensor. Main Burner Not Proving ----------------------- If the main burner ignites, but the furnace shuts down before the blower starts. You'll want to check the main flame (or rollout, high limit, etc) sensor(s). If your furnace has error code indicators, check those and compare to the owners manual for translation. In this case, you'll want to test and/or replace each sensor and/or contact an HVAC technician
Had one furnace that would get all the way through to lighting the main burners with good flame and then start blower motor. After 4 or 5 seconds the flame would shut off and after another 15-20 seconds (with blower still on) the flame sequence would start and light again. This would repeat two or three times. Turns out the flame would shut off on heat exchanger high temp limit, blower would cool down heat exchanger, and high limit switch, and flame sequence would start again. The rain cap on the flue stack above the roof had slid down and was choking off the flue exhaust flow over heating the heat exchanger. Fix was to install sheet metal screws fixing the rain cap in the proper position. Operation normal after that.
36,229
A few times in the past week I will wake up to my furnace turning on, hearing a click when it tries to ignite, then turn off. This will happen for a couple minutes before the furnace quits trying. However, after a certain period of time, it will turn on again with no issues. What should I do so it doesn't happen ever?
2013/11/28
[ "https://diy.stackexchange.com/questions/36229", "https://diy.stackexchange.com", "https://diy.stackexchange.com/users/2177/" ]
***WARNING:** Furnaces are expensive, complex pieces of equipment. If you don't have the proper tools and/or knowledge, it's often best to let the professionals handle maintenance and repair.* Gas Furnace Ignition Sequence: ============================== 1. Thermostat calls for heat. 2. Pilot gas valve opens. 3. Ignition control starts (spark or glow). 4. Pilot gas ignites. 5. Flame sensor detects pilot flame. 6. Main gas valve opens. 7. Main burners ignite. 8. Blower timer starts. 9. Flame sensor detects main burner flame. 10. Blower starts. High Efficiency Gas Furnace Ignition Sequence: ============================================== 1. Thermostat calls for heat. 2. Draft inducer starts. 3. Vacuum switch detects negative pressure. 4. Pilot valve opens. 5. Ignition control starts (spark or glow). 6. Pilot gas ignites. 7. Flame sensor detects pilot flame. 8. Main gas valve opens. 9. Main burners ignite. 10. Blower timer starts. 11. Flame sensor detects main burner flame. 12. Blower starts. Ignition Problems: ================== Vacuum Switch Not Closing ------------------------- In a high efficiency furnace, if the vacuum switch does not close after a certain timeout. The furnace will shut down, then possibly retry a few times depending on model. If after a given number of tries the switch still does not close, the furnace will enter lock out. Once in lock out, the furnace has to be manually reset (depending on model). The vacuum switch will look something like this... ![Vacuum switch](https://i.stack.imgur.com/JuyoF.jpg) And will have a rubber tube connecting it to the draft inducer. This part cannot be repaired, and must be replaced if it's faulty. Pilot Not Igniting ------------------ If the pilot does not light, you'll first want to check to make sure there is something trying to ignite it. Typically a spark or glow ignitor is used, so first you'll want to determine which is being used. ### Glow Ignitor A glow ignitor looks similar to this, though may not be visible without further disassembly. ![Glow ignitor](https://i.stack.imgur.com/m3OVd.jpg) It works by passing a current through it, causing it to heat up and glow. It should heat up enough to ignite the pilot gas. If it doesn't heat up, it should be replaced. ### Spark Ignitor A spark ignitor looks like this. ![Spark Ignitor](https://i.stack.imgur.com/KugBz.jpg) Take notice of the thick, often orange or red wire that is typically used to connect the ignitor to the ignition control module. This device works by generating an electrical arc between the two probes, causing the pilot gas to ignite. If there is no spark, you'll have to replace the ignition control module and/or the ignitor itself. If the [ignitor is not igniting the gas](https://diy.stackexchange.com/q/32529/33), but there is a spark. You can try cleaning the electrodes with fine steel wool, to remove any carbon buildup. Pilot Not Proving ----------------- For a pilot to "prove", it simply means that the flame sensor has sensed the pilot flame. If there is no pilot or the sensor doesn't detect it, the furnace will often purge the system and then try again. Furnaces will often try a set number of times, before entering lock out. If you can see the pilot flame, but the sensor is not detecting it. Try gently cleaning the sensor with fine steel wool, to remove any built up carbon. Also make sure the sensor is in the proper location with respect to the flame (Check the owners manual for proper placement), and adjust as necessary. If that doesn't work, replace the sensor. Main Burner Not Proving ----------------------- If the main burner ignites, but the furnace shuts down before the blower starts. You'll want to check the main flame (or rollout, high limit, etc) sensor(s). If your furnace has error code indicators, check those and compare to the owners manual for translation. In this case, you'll want to test and/or replace each sensor and/or contact an HVAC technician
I had the same problem on a 25 year old furnace. I thought the exhaust was stopped up again, But it was just the vacuum switch causing it. It had dust build up in it. All I had to do was blow into the line connected to the sensor, and it was fine.
40,816,415
I've faced with issue of overwriting root routes, when import child routes using loadChildren() call. App routes declared as: ``` const routes: Routes = [ { path: '', redirectTo: 'own', pathMatch: 'full' }, { path: 'own', component: OwnComponent }, { path: 'nested', loadChildren: () => NestedModule}, ]; export const routing = RouterModule.forRoot(routes); ``` Nested submodule's routes: ``` const routes: Routes = [ { path: 'page1', component: NestedPage1Component }, { path: 'page2', component: NestedPage2Component }, { path: '', redirectTo: 'page1', pathMatch: 'full' }, ]; @NgModule({ imports: [RouterModule.forChild(routes)], exports: [RouterModule] }) export class Module1RoutingModule {} ``` I can get /own, /nested/page1, /nested/page2, but when I try to get root / - I'm getting redirect to /page1. Why does that happen, as it's declared in child module with RouterModule.forChild, how does it redirects not to /own ? I've created simple plunk for repro - <https://plnkr.co/edit/8FE7C5JyiqjRZZvCCxXB?p=preview> Does somebody experienced that behavior?
2016/11/26
[ "https://Stackoverflow.com/questions/40816415", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5435640/" ]
Here is your forked and modified plunker: <https://plnkr.co/edit/XilkY55WXle2hFF0Pelx?p=preview> Do not import that lazy-load module and change the root routes like this: ```js //import { Module1Module } from "./module1/module1.module"; // do NOT import it ! export const routes: Routes = [ { path: '', redirectTo: 'own', pathMatch: 'full' }, { path: 'own', component: OwnComponent }, { path: 'module1', loadChildren: 'src/module1/module1.module#Module1Module' }, ]; ``` And the nested routes: ```js const routes: Routes = [ //{ path: 'page1', component: Module1Page1Component }, //{ path: 'page2', component: Module1Page2Component }, //{ path: '', redirectTo: 'page1', pathMatch: 'full' }, // do the routes like this.. { path: '', component: Module1Component, children: [ { path: '', redirectTo: 'page1', pathMatch: 'full' }, { path: 'page1', component: Module1Page1Component }, { path: 'page2', component: Module1Page2Component } ] }, ]; ```
We need some CAPS on that "DO NOT IMPORT THE LAZY LOADED MODULE" :) That fixed an issue I had with my approach, explained in a related question: <https://stackoverflow.com/a/45718262/885259> Thanks!
51,316,579
I'm trying to create a JSON file in the following format: ``` [ { "startTimestamp" : "2016-01-03 13:55:00", "platform" : "MobileWeb", "product" : "20013509_825", "ctr" : 0.0150 }, {...} ] ``` And the values are stored in the following way: * `startTimeStamp` is in a list called `timestampsJSON` * `platform` is in a dictionary in this form `productBoughtPlatform[product] = platform` * `product` is in a dictionary in this form `productBoughtCount[product] = count` * `ctr` is in a dictionary in this form `CTR_Product[product] = ctr` I was trying to make something of the kind: ``` response = json.dumps({"startTimestamp":ts, for ts in timestampsJSON.items() "platform":plat, for plat in productBoughtPlatform.items() "product":pro, for pro, key in productBoughtCount.items() "ctr":ctr, for ctr in CTR_Product.items()}) ``` I know the syntax is invalid, but can somebody suggest a way to structure this data in a JSON? Thanks!
2018/07/13
[ "https://Stackoverflow.com/questions/51316579", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2356619/" ]
I get same warning even after the new login: [![enter image description here](https://i.stack.imgur.com/Kakkx.png)](https://i.stack.imgur.com/Kakkx.png) I get that if the package name is incorrect, on top of the 404 error. If you need to be logged in just log back in. If you don't need to be logged in just **check that you have the correct package name**. In my case `react-native-create-app` didn't exist.. After adding the correct name: `create-react-native-app` it worked.
After performing `npm login` try to reopen CLI you are using in order to run npm commands. It worked for me
51,316,579
I'm trying to create a JSON file in the following format: ``` [ { "startTimestamp" : "2016-01-03 13:55:00", "platform" : "MobileWeb", "product" : "20013509_825", "ctr" : 0.0150 }, {...} ] ``` And the values are stored in the following way: * `startTimeStamp` is in a list called `timestampsJSON` * `platform` is in a dictionary in this form `productBoughtPlatform[product] = platform` * `product` is in a dictionary in this form `productBoughtCount[product] = count` * `ctr` is in a dictionary in this form `CTR_Product[product] = ctr` I was trying to make something of the kind: ``` response = json.dumps({"startTimestamp":ts, for ts in timestampsJSON.items() "platform":plat, for plat in productBoughtPlatform.items() "product":pro, for pro, key in productBoughtCount.items() "ctr":ctr, for ctr in CTR_Product.items()}) ``` I know the syntax is invalid, but can somebody suggest a way to structure this data in a JSON? Thanks!
2018/07/13
[ "https://Stackoverflow.com/questions/51316579", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2356619/" ]
I get same warning even after the new login: [![enter image description here](https://i.stack.imgur.com/Kakkx.png)](https://i.stack.imgur.com/Kakkx.png) I get that if the package name is incorrect, on top of the 404 error. If you need to be logged in just log back in. If you don't need to be logged in just **check that you have the correct package name**. In my case `react-native-create-app` didn't exist.. After adding the correct name: `create-react-native-app` it worked.
Make sure you have your npmrc file set up ok. <https://docs.npmjs.com/files/npmrc>
51,316,579
I'm trying to create a JSON file in the following format: ``` [ { "startTimestamp" : "2016-01-03 13:55:00", "platform" : "MobileWeb", "product" : "20013509_825", "ctr" : 0.0150 }, {...} ] ``` And the values are stored in the following way: * `startTimeStamp` is in a list called `timestampsJSON` * `platform` is in a dictionary in this form `productBoughtPlatform[product] = platform` * `product` is in a dictionary in this form `productBoughtCount[product] = count` * `ctr` is in a dictionary in this form `CTR_Product[product] = ctr` I was trying to make something of the kind: ``` response = json.dumps({"startTimestamp":ts, for ts in timestampsJSON.items() "platform":plat, for plat in productBoughtPlatform.items() "product":pro, for pro, key in productBoughtCount.items() "ctr":ctr, for ctr in CTR_Product.items()}) ``` I know the syntax is invalid, but can somebody suggest a way to structure this data in a JSON? Thanks!
2018/07/13
[ "https://Stackoverflow.com/questions/51316579", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2356619/" ]
I get same warning even after the new login: [![enter image description here](https://i.stack.imgur.com/Kakkx.png)](https://i.stack.imgur.com/Kakkx.png) I get that if the package name is incorrect, on top of the 404 error. If you need to be logged in just log back in. If you don't need to be logged in just **check that you have the correct package name**. In my case `react-native-create-app` didn't exist.. After adding the correct name: `create-react-native-app` it worked.
Steps to follow: 1. Run `npm login` 2. Enter your 1. Username 2. Password 3. Email addressNote: if you don't have this credentials, you have to sign up at <https://www.npmjs.com/signup> 3. Run `npm install bootstrap --save` This should work.
15,769,789
<http://jsfiddle.net/Jg3FP/1/> This doesn't line up correctly in various browsers but works fine in js fiddle, I'm not doing anything exotic. Why does it behave like this and how do I fix it? ![enter image description here](https://i.stack.imgur.com/1teFL.jpg) ![enter image description here](https://i.stack.imgur.com/yFHli.jpg) ``` <div id="diceDiv"> <div id="dice1Div">#</div> <input type="checkbox"/> <div id="dice2Div">#</div> <input type="checkbox"/> <div id="dice3Div">#</div> <input type="checkbox" /> <div id="dice4Div">#</div> <input type="checkbox"/> <div id="dice5Div">#</div> <input type="checkbox"/> <div id="dice6Div">#</div> <input type="checkbox"/> <br/> <input type="button" value="Roll" /> </div> <div id="log"></div> <div id="score"></div> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script type="text/javascript"> $("div div").css("float", "left"); $("div input").css("clear", "right"); </script> ```
2013/04/02
[ "https://Stackoverflow.com/questions/15769789", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1850535/" ]
That's because jsFiddle sets for you the correct headers, especially the doctype without which IE switches to a mode emulating the behavior of older versions. Try to start your HTML file like this : ``` <!DOCTYPE html> <html> <head> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> ```
There are some issues in your HTML. Regarding the [float](https://developer.mozilla.org/en-US/docs/CSS/float) concept: you are clearing `right` floats when instead you're setting `left` floats for the divs. Also you should move every jQuery call you expect to run at display time into [$(document).ready()](http://api.jquery.com/ready/). `DIV` is normally a block element, and I took the liberty to modify your HTML so that every option has one div around it. In this way you let the block formatting do the "clearing" for you. Also, I applied zero padding and margin to the checkboxes. You can change that if needed. See the HTML (you can save and run it locally): --- ``` <!DOCTYPE html> <html> <head> <title>Sample</title> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script> $(document).ready(function () { $('#diceDiv INPUT').css({padding: '0px', margin: '0px'}) }); </script> </head> <body> <div id="diceDiv"> <div> <span id="dice1Div">#</span><input type="checkbox"/> </div> <div> <span id="dice2Div">#</span><input type="checkbox"/> </div> <div> <span id="dice3Div">#</span><input type="checkbox" /> </div> <div> <span id="dice4Div">#</span><input type="checkbox"/> </div> <div> <span id="dice5Div">#</span><input type="checkbox"/> </div> <div> <span id="dice6Div">#</span><input type="checkbox"/> </div> <br/> <input type="button" value="Roll" /> </div> <div id="log"></div> <div id="score"></div> </body> </html> ```
2,412,582
I'm preparing a query for mySQL to grab record from the previous week, but I have to treat weeks as Monday - Sunday. I had originally done this: ``` WHERE YEARWEEK(contactDate) = YEARWEEK(DATE_SUB(CURDATE(),INTERVAL 7 DAY)) ``` to discover that mySQL treats weeks as Sunday - Monday. So instead I'm parsing getting the begin & end dates in php like this: ``` $i = 0; while(date('D',mktime(0,0,0,date('m'), date('d')-$i, date('y'))) != "Mon") { $i++; } $start_date = date('Y-n-j', mktime(0,0,0,date('m'), date('d')-($i+7), date('y'))); $end_date = date('Y-n-j', mktime(0,0,0,date('m'), date('d')-($i+1), date('y'))); ``` This works - it gets the current week's date for monday (walking backwards until a monday is hit) then calculates the previous week's dates based on that date. My question is: Is there a better way to do this? Just seems sloppy, and I expect someone out there can give me a cleaner way to do it - or perhaps not because I need Monday - Sunday weeks. Edit ---- Apparently, there is: ``` $start = date('Y-m-d',strtotime('last monday -7 days')); $end = date('Y-m-d',strtotime('last monday -1 days')); ``` That's about a million times more readable. Thank you.
2010/03/09
[ "https://Stackoverflow.com/questions/2412582", "https://Stackoverflow.com", "https://Stackoverflow.com/users/260302/" ]
you can use [strtotime](http://php.net/manual/en/function.strtotime.php) for this kind of date issues ``` echo strtotime("last Monday"); ```
Marvin's answer is really elegant, although if you really wanted to go for performance you could do it with a little arithmetic. You could derive a formula/method to convert an arbitrary date to "days since some starting point" (probably 01.01.0000) and then the rest of the operations would be easy with that. Getting the day of week from such a number is as simple as subtracting and getting the remainder of a division. Actually, PHP had a Date class in its PEAR library which did exactly this.
2,412,582
I'm preparing a query for mySQL to grab record from the previous week, but I have to treat weeks as Monday - Sunday. I had originally done this: ``` WHERE YEARWEEK(contactDate) = YEARWEEK(DATE_SUB(CURDATE(),INTERVAL 7 DAY)) ``` to discover that mySQL treats weeks as Sunday - Monday. So instead I'm parsing getting the begin & end dates in php like this: ``` $i = 0; while(date('D',mktime(0,0,0,date('m'), date('d')-$i, date('y'))) != "Mon") { $i++; } $start_date = date('Y-n-j', mktime(0,0,0,date('m'), date('d')-($i+7), date('y'))); $end_date = date('Y-n-j', mktime(0,0,0,date('m'), date('d')-($i+1), date('y'))); ``` This works - it gets the current week's date for monday (walking backwards until a monday is hit) then calculates the previous week's dates based on that date. My question is: Is there a better way to do this? Just seems sloppy, and I expect someone out there can give me a cleaner way to do it - or perhaps not because I need Monday - Sunday weeks. Edit ---- Apparently, there is: ``` $start = date('Y-m-d',strtotime('last monday -7 days')); $end = date('Y-m-d',strtotime('last monday -1 days')); ``` That's about a million times more readable. Thank you.
2010/03/09
[ "https://Stackoverflow.com/questions/2412582", "https://Stackoverflow.com", "https://Stackoverflow.com/users/260302/" ]
you can use [strtotime](http://php.net/manual/en/function.strtotime.php) for this kind of date issues ``` echo strtotime("last Monday"); ```
(complementing on marvin and Stomped ) Also you can use it this way ``` echo date('Y-m-d',strtotime('-1 Monday')); //last Monday echo date('Y-m-d',strtotime('-2 Monday')); //two Mondays ago echo date('Y-m-d',strtotime('+1 Monday')); //next Monday ```
2,412,582
I'm preparing a query for mySQL to grab record from the previous week, but I have to treat weeks as Monday - Sunday. I had originally done this: ``` WHERE YEARWEEK(contactDate) = YEARWEEK(DATE_SUB(CURDATE(),INTERVAL 7 DAY)) ``` to discover that mySQL treats weeks as Sunday - Monday. So instead I'm parsing getting the begin & end dates in php like this: ``` $i = 0; while(date('D',mktime(0,0,0,date('m'), date('d')-$i, date('y'))) != "Mon") { $i++; } $start_date = date('Y-n-j', mktime(0,0,0,date('m'), date('d')-($i+7), date('y'))); $end_date = date('Y-n-j', mktime(0,0,0,date('m'), date('d')-($i+1), date('y'))); ``` This works - it gets the current week's date for monday (walking backwards until a monday is hit) then calculates the previous week's dates based on that date. My question is: Is there a better way to do this? Just seems sloppy, and I expect someone out there can give me a cleaner way to do it - or perhaps not because I need Monday - Sunday weeks. Edit ---- Apparently, there is: ``` $start = date('Y-m-d',strtotime('last monday -7 days')); $end = date('Y-m-d',strtotime('last monday -1 days')); ``` That's about a million times more readable. Thank you.
2010/03/09
[ "https://Stackoverflow.com/questions/2412582", "https://Stackoverflow.com", "https://Stackoverflow.com/users/260302/" ]
you can use [strtotime](http://php.net/manual/en/function.strtotime.php) for this kind of date issues ``` echo strtotime("last Monday"); ```
I have to point out for all the readers here there is a big issue with marvin's answer Here is the catch The "last Monday" function will return date the "latest" Monday.It will be explained like this , if today is Monday, then it will return the date of "LAST WEEK" Monday, however if today is not Monday, it will return "THIS WEEK" Monday The Question is request to return "Last Week" Monday. Therefore the result will be incorrect if today is not Monday. I have solved the issue and wrapped in my Date Time Helper It will be only one line after you "INCLUDE" the class $lastWeekMonday = Model\_DTHpr::getLastWeekMonday(); Check Here <https://github.com/normandqq/Date-Time-Helper>
2,412,582
I'm preparing a query for mySQL to grab record from the previous week, but I have to treat weeks as Monday - Sunday. I had originally done this: ``` WHERE YEARWEEK(contactDate) = YEARWEEK(DATE_SUB(CURDATE(),INTERVAL 7 DAY)) ``` to discover that mySQL treats weeks as Sunday - Monday. So instead I'm parsing getting the begin & end dates in php like this: ``` $i = 0; while(date('D',mktime(0,0,0,date('m'), date('d')-$i, date('y'))) != "Mon") { $i++; } $start_date = date('Y-n-j', mktime(0,0,0,date('m'), date('d')-($i+7), date('y'))); $end_date = date('Y-n-j', mktime(0,0,0,date('m'), date('d')-($i+1), date('y'))); ``` This works - it gets the current week's date for monday (walking backwards until a monday is hit) then calculates the previous week's dates based on that date. My question is: Is there a better way to do this? Just seems sloppy, and I expect someone out there can give me a cleaner way to do it - or perhaps not because I need Monday - Sunday weeks. Edit ---- Apparently, there is: ``` $start = date('Y-m-d',strtotime('last monday -7 days')); $end = date('Y-m-d',strtotime('last monday -1 days')); ``` That's about a million times more readable. Thank you.
2010/03/09
[ "https://Stackoverflow.com/questions/2412582", "https://Stackoverflow.com", "https://Stackoverflow.com/users/260302/" ]
you can use [strtotime](http://php.net/manual/en/function.strtotime.php) for this kind of date issues ``` echo strtotime("last Monday"); ```
``` strtotime("previous week Monday") ``` Monday of the previous week.
2,412,582
I'm preparing a query for mySQL to grab record from the previous week, but I have to treat weeks as Monday - Sunday. I had originally done this: ``` WHERE YEARWEEK(contactDate) = YEARWEEK(DATE_SUB(CURDATE(),INTERVAL 7 DAY)) ``` to discover that mySQL treats weeks as Sunday - Monday. So instead I'm parsing getting the begin & end dates in php like this: ``` $i = 0; while(date('D',mktime(0,0,0,date('m'), date('d')-$i, date('y'))) != "Mon") { $i++; } $start_date = date('Y-n-j', mktime(0,0,0,date('m'), date('d')-($i+7), date('y'))); $end_date = date('Y-n-j', mktime(0,0,0,date('m'), date('d')-($i+1), date('y'))); ``` This works - it gets the current week's date for monday (walking backwards until a monday is hit) then calculates the previous week's dates based on that date. My question is: Is there a better way to do this? Just seems sloppy, and I expect someone out there can give me a cleaner way to do it - or perhaps not because I need Monday - Sunday weeks. Edit ---- Apparently, there is: ``` $start = date('Y-m-d',strtotime('last monday -7 days')); $end = date('Y-m-d',strtotime('last monday -1 days')); ``` That's about a million times more readable. Thank you.
2010/03/09
[ "https://Stackoverflow.com/questions/2412582", "https://Stackoverflow.com", "https://Stackoverflow.com/users/260302/" ]
(complementing on marvin and Stomped ) Also you can use it this way ``` echo date('Y-m-d',strtotime('-1 Monday')); //last Monday echo date('Y-m-d',strtotime('-2 Monday')); //two Mondays ago echo date('Y-m-d',strtotime('+1 Monday')); //next Monday ```
Marvin's answer is really elegant, although if you really wanted to go for performance you could do it with a little arithmetic. You could derive a formula/method to convert an arbitrary date to "days since some starting point" (probably 01.01.0000) and then the rest of the operations would be easy with that. Getting the day of week from such a number is as simple as subtracting and getting the remainder of a division. Actually, PHP had a Date class in its PEAR library which did exactly this.
2,412,582
I'm preparing a query for mySQL to grab record from the previous week, but I have to treat weeks as Monday - Sunday. I had originally done this: ``` WHERE YEARWEEK(contactDate) = YEARWEEK(DATE_SUB(CURDATE(),INTERVAL 7 DAY)) ``` to discover that mySQL treats weeks as Sunday - Monday. So instead I'm parsing getting the begin & end dates in php like this: ``` $i = 0; while(date('D',mktime(0,0,0,date('m'), date('d')-$i, date('y'))) != "Mon") { $i++; } $start_date = date('Y-n-j', mktime(0,0,0,date('m'), date('d')-($i+7), date('y'))); $end_date = date('Y-n-j', mktime(0,0,0,date('m'), date('d')-($i+1), date('y'))); ``` This works - it gets the current week's date for monday (walking backwards until a monday is hit) then calculates the previous week's dates based on that date. My question is: Is there a better way to do this? Just seems sloppy, and I expect someone out there can give me a cleaner way to do it - or perhaps not because I need Monday - Sunday weeks. Edit ---- Apparently, there is: ``` $start = date('Y-m-d',strtotime('last monday -7 days')); $end = date('Y-m-d',strtotime('last monday -1 days')); ``` That's about a million times more readable. Thank you.
2010/03/09
[ "https://Stackoverflow.com/questions/2412582", "https://Stackoverflow.com", "https://Stackoverflow.com/users/260302/" ]
Marvin's answer is really elegant, although if you really wanted to go for performance you could do it with a little arithmetic. You could derive a formula/method to convert an arbitrary date to "days since some starting point" (probably 01.01.0000) and then the rest of the operations would be easy with that. Getting the day of week from such a number is as simple as subtracting and getting the remainder of a division. Actually, PHP had a Date class in its PEAR library which did exactly this.
I have to point out for all the readers here there is a big issue with marvin's answer Here is the catch The "last Monday" function will return date the "latest" Monday.It will be explained like this , if today is Monday, then it will return the date of "LAST WEEK" Monday, however if today is not Monday, it will return "THIS WEEK" Monday The Question is request to return "Last Week" Monday. Therefore the result will be incorrect if today is not Monday. I have solved the issue and wrapped in my Date Time Helper It will be only one line after you "INCLUDE" the class $lastWeekMonday = Model\_DTHpr::getLastWeekMonday(); Check Here <https://github.com/normandqq/Date-Time-Helper>
2,412,582
I'm preparing a query for mySQL to grab record from the previous week, but I have to treat weeks as Monday - Sunday. I had originally done this: ``` WHERE YEARWEEK(contactDate) = YEARWEEK(DATE_SUB(CURDATE(),INTERVAL 7 DAY)) ``` to discover that mySQL treats weeks as Sunday - Monday. So instead I'm parsing getting the begin & end dates in php like this: ``` $i = 0; while(date('D',mktime(0,0,0,date('m'), date('d')-$i, date('y'))) != "Mon") { $i++; } $start_date = date('Y-n-j', mktime(0,0,0,date('m'), date('d')-($i+7), date('y'))); $end_date = date('Y-n-j', mktime(0,0,0,date('m'), date('d')-($i+1), date('y'))); ``` This works - it gets the current week's date for monday (walking backwards until a monday is hit) then calculates the previous week's dates based on that date. My question is: Is there a better way to do this? Just seems sloppy, and I expect someone out there can give me a cleaner way to do it - or perhaps not because I need Monday - Sunday weeks. Edit ---- Apparently, there is: ``` $start = date('Y-m-d',strtotime('last monday -7 days')); $end = date('Y-m-d',strtotime('last monday -1 days')); ``` That's about a million times more readable. Thank you.
2010/03/09
[ "https://Stackoverflow.com/questions/2412582", "https://Stackoverflow.com", "https://Stackoverflow.com/users/260302/" ]
``` strtotime("previous week Monday") ``` Monday of the previous week.
Marvin's answer is really elegant, although if you really wanted to go for performance you could do it with a little arithmetic. You could derive a formula/method to convert an arbitrary date to "days since some starting point" (probably 01.01.0000) and then the rest of the operations would be easy with that. Getting the day of week from such a number is as simple as subtracting and getting the remainder of a division. Actually, PHP had a Date class in its PEAR library which did exactly this.
2,412,582
I'm preparing a query for mySQL to grab record from the previous week, but I have to treat weeks as Monday - Sunday. I had originally done this: ``` WHERE YEARWEEK(contactDate) = YEARWEEK(DATE_SUB(CURDATE(),INTERVAL 7 DAY)) ``` to discover that mySQL treats weeks as Sunday - Monday. So instead I'm parsing getting the begin & end dates in php like this: ``` $i = 0; while(date('D',mktime(0,0,0,date('m'), date('d')-$i, date('y'))) != "Mon") { $i++; } $start_date = date('Y-n-j', mktime(0,0,0,date('m'), date('d')-($i+7), date('y'))); $end_date = date('Y-n-j', mktime(0,0,0,date('m'), date('d')-($i+1), date('y'))); ``` This works - it gets the current week's date for monday (walking backwards until a monday is hit) then calculates the previous week's dates based on that date. My question is: Is there a better way to do this? Just seems sloppy, and I expect someone out there can give me a cleaner way to do it - or perhaps not because I need Monday - Sunday weeks. Edit ---- Apparently, there is: ``` $start = date('Y-m-d',strtotime('last monday -7 days')); $end = date('Y-m-d',strtotime('last monday -1 days')); ``` That's about a million times more readable. Thank you.
2010/03/09
[ "https://Stackoverflow.com/questions/2412582", "https://Stackoverflow.com", "https://Stackoverflow.com/users/260302/" ]
(complementing on marvin and Stomped ) Also you can use it this way ``` echo date('Y-m-d',strtotime('-1 Monday')); //last Monday echo date('Y-m-d',strtotime('-2 Monday')); //two Mondays ago echo date('Y-m-d',strtotime('+1 Monday')); //next Monday ```
I have to point out for all the readers here there is a big issue with marvin's answer Here is the catch The "last Monday" function will return date the "latest" Monday.It will be explained like this , if today is Monday, then it will return the date of "LAST WEEK" Monday, however if today is not Monday, it will return "THIS WEEK" Monday The Question is request to return "Last Week" Monday. Therefore the result will be incorrect if today is not Monday. I have solved the issue and wrapped in my Date Time Helper It will be only one line after you "INCLUDE" the class $lastWeekMonday = Model\_DTHpr::getLastWeekMonday(); Check Here <https://github.com/normandqq/Date-Time-Helper>
2,412,582
I'm preparing a query for mySQL to grab record from the previous week, but I have to treat weeks as Monday - Sunday. I had originally done this: ``` WHERE YEARWEEK(contactDate) = YEARWEEK(DATE_SUB(CURDATE(),INTERVAL 7 DAY)) ``` to discover that mySQL treats weeks as Sunday - Monday. So instead I'm parsing getting the begin & end dates in php like this: ``` $i = 0; while(date('D',mktime(0,0,0,date('m'), date('d')-$i, date('y'))) != "Mon") { $i++; } $start_date = date('Y-n-j', mktime(0,0,0,date('m'), date('d')-($i+7), date('y'))); $end_date = date('Y-n-j', mktime(0,0,0,date('m'), date('d')-($i+1), date('y'))); ``` This works - it gets the current week's date for monday (walking backwards until a monday is hit) then calculates the previous week's dates based on that date. My question is: Is there a better way to do this? Just seems sloppy, and I expect someone out there can give me a cleaner way to do it - or perhaps not because I need Monday - Sunday weeks. Edit ---- Apparently, there is: ``` $start = date('Y-m-d',strtotime('last monday -7 days')); $end = date('Y-m-d',strtotime('last monday -1 days')); ``` That's about a million times more readable. Thank you.
2010/03/09
[ "https://Stackoverflow.com/questions/2412582", "https://Stackoverflow.com", "https://Stackoverflow.com/users/260302/" ]
(complementing on marvin and Stomped ) Also you can use it this way ``` echo date('Y-m-d',strtotime('-1 Monday')); //last Monday echo date('Y-m-d',strtotime('-2 Monday')); //two Mondays ago echo date('Y-m-d',strtotime('+1 Monday')); //next Monday ```
``` strtotime("previous week Monday") ``` Monday of the previous week.
2,412,582
I'm preparing a query for mySQL to grab record from the previous week, but I have to treat weeks as Monday - Sunday. I had originally done this: ``` WHERE YEARWEEK(contactDate) = YEARWEEK(DATE_SUB(CURDATE(),INTERVAL 7 DAY)) ``` to discover that mySQL treats weeks as Sunday - Monday. So instead I'm parsing getting the begin & end dates in php like this: ``` $i = 0; while(date('D',mktime(0,0,0,date('m'), date('d')-$i, date('y'))) != "Mon") { $i++; } $start_date = date('Y-n-j', mktime(0,0,0,date('m'), date('d')-($i+7), date('y'))); $end_date = date('Y-n-j', mktime(0,0,0,date('m'), date('d')-($i+1), date('y'))); ``` This works - it gets the current week's date for monday (walking backwards until a monday is hit) then calculates the previous week's dates based on that date. My question is: Is there a better way to do this? Just seems sloppy, and I expect someone out there can give me a cleaner way to do it - or perhaps not because I need Monday - Sunday weeks. Edit ---- Apparently, there is: ``` $start = date('Y-m-d',strtotime('last monday -7 days')); $end = date('Y-m-d',strtotime('last monday -1 days')); ``` That's about a million times more readable. Thank you.
2010/03/09
[ "https://Stackoverflow.com/questions/2412582", "https://Stackoverflow.com", "https://Stackoverflow.com/users/260302/" ]
``` strtotime("previous week Monday") ``` Monday of the previous week.
I have to point out for all the readers here there is a big issue with marvin's answer Here is the catch The "last Monday" function will return date the "latest" Monday.It will be explained like this , if today is Monday, then it will return the date of "LAST WEEK" Monday, however if today is not Monday, it will return "THIS WEEK" Monday The Question is request to return "Last Week" Monday. Therefore the result will be incorrect if today is not Monday. I have solved the issue and wrapped in my Date Time Helper It will be only one line after you "INCLUDE" the class $lastWeekMonday = Model\_DTHpr::getLastWeekMonday(); Check Here <https://github.com/normandqq/Date-Time-Helper>
209,331
I've got a table `t` with ~23 million rows (4248 MB in size). There's a column `row_id` in it, with a `not null` constraint. And a unique index `p1` on `t(row_id)`. When I do `select count(*) from t` to count all the rows in the table, the planner tells me: ``` Seq Scan on t (cost=0.00..686191.06 rows=23176906 width=0) ``` I would have expected a fast `Index Only Scan` (index p1 occupies only 698 MB - 6x less). If I do `SET enable_seqscan = off`, then the planner still insists on reading the table rows: ``` QUERY PLAN -> Bitmap Heap Scan on t (cost=210923.32..897114.38 rows=23176906 width=0) -> Bitmap Index Scan on p1 (cost=0.00..205129.09 rows=23176906 width=0) ``` Why is the unique index ignored in this case? What's the catch? I am using PostgreSQL 10.4 For a clean room test I did the following: ``` create table tmp ( row_id varchar(15) unique not null, <10 original cols> ); insert into tmp (row_id, <10 cols>) select row_id, <10 cols> from t; commit; analyze tmp; set enable_seqscan = on; explain (analyze, buffers) select count(*) from tmp; QUERY PLAN Aggregate (cost=744070.45..744070.46 rows=1 width=8) (actual time=5631.501..5631.502 rows=1 loops=1) Buffers: shared hit=209109 read=245254 -> Seq Scan on tmp (cost=0.00..686128.96 rows=23176596 width=0) (actual time=0.014..3481.967 rows=23176906 loops=1) Buffers: shared hit=209109 read=245254 Planning time: 0.064 ms Execution time: 5631.531 ms SET enable_seqscan = off; explain (analyze, buffers) select count(*) from tmp; QUERY PLAN Aggregate (cost=980282.14..980282.15 rows=1 width=8) (actual time=16224.408..16224.408 rows=1 loops=1) Buffers: shared hit=26285 read=542015 -> Bitmap Heap Scan on tmp (cost=236211.69..922340.65 rows=23176596 width=0) (actual time=10030.115..14157.288 rows=23176906 loops=1) Heap Blocks: exact=454363 Buffers: shared hit=26285 read=542015 -> Bitmap Index Scan on tmp_row_id_key (cost=0.00..230417.54 rows=23176596 width=0) (actual time=9929.582..9929.582 rows=23176906 loops=1) Buffers: shared hit=26285 read=87652 Planning time: 0.051 ms Execution time: 16229.303 ms ``` No parallel index scan so far. PostgreSQL insists on accessing the table for some obscured reason.
2018/06/11
[ "https://dba.stackexchange.com/questions/209331", "https://dba.stackexchange.com", "https://dba.stackexchange.com/users/153219/" ]
As to why you do not get an index scan with `SET enable_seqscan = off`, **you should be getting an index-only scan**. Your situation can not yet be recreated with the data you've provided. This certainly works with PostgreSQL 10.4. I can't speak to your own use case, and there are a lot of reasons why you *may* not get an index scan in the real world. Ultimately, debugging a question along those lines will result in an answer that is simply "planner estimates" but will require a lot more data about your environment, configuration, and the plans with and without `SET enable_seqscan = off`. Sample Data =========== ``` BEGIN; CREATE TABLE foo ( x int NOT NULL UNIQUE ); INSERT INTO foo (x) SELECT generate_series(1,1e6); COMMIT; ANALYZE foo; -- don't forget to analyze ``` With `seq_scan` =============== ``` test=# EXPLAIN SELECT count(*) FROM foo; QUERY PLAN -------------------------------------------------------------------------------------- Finalize Aggregate (cost=10633.55..10633.56 rows=1 width=8) -> Gather (cost=10633.33..10633.54 rows=2 width=8) Workers Planned: 2 -> Partial Aggregate (cost=9633.33..9633.34 rows=1 width=8) -> Parallel Seq Scan on foo (cost=0.00..8591.67 rows=416667 width=0) (5 rows) ``` Notice we're doing a *"Parallel Seq Scan"* Without `seq_scan` ================== ``` SET enable_seq_scan = off; test=# EXPLAIN SELECT count(*) FROM foo; QUERY PLAN -------------------------------------------------------------------------------------------------------------- Finalize Aggregate (cost=26616.97..26616.98 rows=1 width=8) -> Gather (cost=26616.76..26616.97 rows=2 width=8) Workers Planned: 2 -> Partial Aggregate (cost=25616.76..25616.77 rows=1 width=8) -> Parallel Index Only Scan using foo_x_key on foo (cost=0.42..24575.09 rows=416667 width=0) (5 rows) ``` **Notice we're doing a *"Parallel Index Only Scan"***
*[Community wiki answer](https://dba.stackexchange.com/help/privileges/edit-community-wiki):* Your question is addressed by the [Is "count(\*)" much faster now?](https://wiki.postgresql.org/wiki/Index-only_scans#Is_.22count.28.2A.29.22_much_faster_now.3F) section of the PostgreSQL wiki page about *Index-only scans*. > > A traditional complaint made of PostgreSQL, generally when comparing it unfavourably with MySQL (at least when using the MyIsam storage engine, which doesn't use MVCC) has been "count(\*) is slow". Index-only scans *can* be used to satisfy these queries without there being any predicate to limit the number of rows returned, and without forcing an index to be used by specifying that the tuples should be ordered by an indexed column. However, in practice that isn't particularly likely. > > > It is important to realise that the planner is concerned with minimising the total cost of the query. With databases, the cost of I/O typically dominates. For that reason, "count(\*) without any predicate" queries will only use an index-only scan if the index is significantly smaller than its table. This typically only happens when the table's row width is much wider than some indexes'. > > > An index-only scan will have to visit the heap tuples if visibility cannot be determined by looking at the visibility map. There is a big 'it depends' when checking which case yours is. Under optimal circumstances, you'll get an index-only scan. Otherwise, if the tuples have to be checked for visibility, a sequential scan quickly becomes the winner, as it does not have the overhead of checking the index first. You get a `bitmap_heap_scan` with `enable seq_scan=off`, so the planner behaves as advertised: > > It is impossible to suppress sequential scans entirely, but turning this variable off discourages the planner from using one if there are other methods available. > > > The details are in other sections of the same wiki page.
209,331
I've got a table `t` with ~23 million rows (4248 MB in size). There's a column `row_id` in it, with a `not null` constraint. And a unique index `p1` on `t(row_id)`. When I do `select count(*) from t` to count all the rows in the table, the planner tells me: ``` Seq Scan on t (cost=0.00..686191.06 rows=23176906 width=0) ``` I would have expected a fast `Index Only Scan` (index p1 occupies only 698 MB - 6x less). If I do `SET enable_seqscan = off`, then the planner still insists on reading the table rows: ``` QUERY PLAN -> Bitmap Heap Scan on t (cost=210923.32..897114.38 rows=23176906 width=0) -> Bitmap Index Scan on p1 (cost=0.00..205129.09 rows=23176906 width=0) ``` Why is the unique index ignored in this case? What's the catch? I am using PostgreSQL 10.4 For a clean room test I did the following: ``` create table tmp ( row_id varchar(15) unique not null, <10 original cols> ); insert into tmp (row_id, <10 cols>) select row_id, <10 cols> from t; commit; analyze tmp; set enable_seqscan = on; explain (analyze, buffers) select count(*) from tmp; QUERY PLAN Aggregate (cost=744070.45..744070.46 rows=1 width=8) (actual time=5631.501..5631.502 rows=1 loops=1) Buffers: shared hit=209109 read=245254 -> Seq Scan on tmp (cost=0.00..686128.96 rows=23176596 width=0) (actual time=0.014..3481.967 rows=23176906 loops=1) Buffers: shared hit=209109 read=245254 Planning time: 0.064 ms Execution time: 5631.531 ms SET enable_seqscan = off; explain (analyze, buffers) select count(*) from tmp; QUERY PLAN Aggregate (cost=980282.14..980282.15 rows=1 width=8) (actual time=16224.408..16224.408 rows=1 loops=1) Buffers: shared hit=26285 read=542015 -> Bitmap Heap Scan on tmp (cost=236211.69..922340.65 rows=23176596 width=0) (actual time=10030.115..14157.288 rows=23176906 loops=1) Heap Blocks: exact=454363 Buffers: shared hit=26285 read=542015 -> Bitmap Index Scan on tmp_row_id_key (cost=0.00..230417.54 rows=23176596 width=0) (actual time=9929.582..9929.582 rows=23176906 loops=1) Buffers: shared hit=26285 read=87652 Planning time: 0.051 ms Execution time: 16229.303 ms ``` No parallel index scan so far. PostgreSQL insists on accessing the table for some obscured reason.
2018/06/11
[ "https://dba.stackexchange.com/questions/209331", "https://dba.stackexchange.com", "https://dba.stackexchange.com/users/153219/" ]
As to why you do not get an index scan with `SET enable_seqscan = off`, **you should be getting an index-only scan**. Your situation can not yet be recreated with the data you've provided. This certainly works with PostgreSQL 10.4. I can't speak to your own use case, and there are a lot of reasons why you *may* not get an index scan in the real world. Ultimately, debugging a question along those lines will result in an answer that is simply "planner estimates" but will require a lot more data about your environment, configuration, and the plans with and without `SET enable_seqscan = off`. Sample Data =========== ``` BEGIN; CREATE TABLE foo ( x int NOT NULL UNIQUE ); INSERT INTO foo (x) SELECT generate_series(1,1e6); COMMIT; ANALYZE foo; -- don't forget to analyze ``` With `seq_scan` =============== ``` test=# EXPLAIN SELECT count(*) FROM foo; QUERY PLAN -------------------------------------------------------------------------------------- Finalize Aggregate (cost=10633.55..10633.56 rows=1 width=8) -> Gather (cost=10633.33..10633.54 rows=2 width=8) Workers Planned: 2 -> Partial Aggregate (cost=9633.33..9633.34 rows=1 width=8) -> Parallel Seq Scan on foo (cost=0.00..8591.67 rows=416667 width=0) (5 rows) ``` Notice we're doing a *"Parallel Seq Scan"* Without `seq_scan` ================== ``` SET enable_seq_scan = off; test=# EXPLAIN SELECT count(*) FROM foo; QUERY PLAN -------------------------------------------------------------------------------------------------------------- Finalize Aggregate (cost=26616.97..26616.98 rows=1 width=8) -> Gather (cost=26616.76..26616.97 rows=2 width=8) Workers Planned: 2 -> Partial Aggregate (cost=25616.76..25616.77 rows=1 width=8) -> Parallel Index Only Scan using foo_x_key on foo (cost=0.42..24575.09 rows=416667 width=0) (5 rows) ``` **Notice we're doing a *"Parallel Index Only Scan"***
An index only scan is not going to look very attractive unless most of the table's pages are marked as all-visible. So you need to VACUUM the table. PostgreSQL's default autovacuum settings are tuned to prevent bloat, not to keep index-only scans happy, so it may require manual intervention to keep the table well-enough vacuumed for your purpose. Note that it still might prefer the full table scan. The index only scan is more CPU intensive than the full table scan, and its IO can be more random and less sequential. If the table is 20 times larger than the index, it will probably prefer the index-only scan, but at 6 times larger it is a bit of a toss up.
209,331
I've got a table `t` with ~23 million rows (4248 MB in size). There's a column `row_id` in it, with a `not null` constraint. And a unique index `p1` on `t(row_id)`. When I do `select count(*) from t` to count all the rows in the table, the planner tells me: ``` Seq Scan on t (cost=0.00..686191.06 rows=23176906 width=0) ``` I would have expected a fast `Index Only Scan` (index p1 occupies only 698 MB - 6x less). If I do `SET enable_seqscan = off`, then the planner still insists on reading the table rows: ``` QUERY PLAN -> Bitmap Heap Scan on t (cost=210923.32..897114.38 rows=23176906 width=0) -> Bitmap Index Scan on p1 (cost=0.00..205129.09 rows=23176906 width=0) ``` Why is the unique index ignored in this case? What's the catch? I am using PostgreSQL 10.4 For a clean room test I did the following: ``` create table tmp ( row_id varchar(15) unique not null, <10 original cols> ); insert into tmp (row_id, <10 cols>) select row_id, <10 cols> from t; commit; analyze tmp; set enable_seqscan = on; explain (analyze, buffers) select count(*) from tmp; QUERY PLAN Aggregate (cost=744070.45..744070.46 rows=1 width=8) (actual time=5631.501..5631.502 rows=1 loops=1) Buffers: shared hit=209109 read=245254 -> Seq Scan on tmp (cost=0.00..686128.96 rows=23176596 width=0) (actual time=0.014..3481.967 rows=23176906 loops=1) Buffers: shared hit=209109 read=245254 Planning time: 0.064 ms Execution time: 5631.531 ms SET enable_seqscan = off; explain (analyze, buffers) select count(*) from tmp; QUERY PLAN Aggregate (cost=980282.14..980282.15 rows=1 width=8) (actual time=16224.408..16224.408 rows=1 loops=1) Buffers: shared hit=26285 read=542015 -> Bitmap Heap Scan on tmp (cost=236211.69..922340.65 rows=23176596 width=0) (actual time=10030.115..14157.288 rows=23176906 loops=1) Heap Blocks: exact=454363 Buffers: shared hit=26285 read=542015 -> Bitmap Index Scan on tmp_row_id_key (cost=0.00..230417.54 rows=23176596 width=0) (actual time=9929.582..9929.582 rows=23176906 loops=1) Buffers: shared hit=26285 read=87652 Planning time: 0.051 ms Execution time: 16229.303 ms ``` No parallel index scan so far. PostgreSQL insists on accessing the table for some obscured reason.
2018/06/11
[ "https://dba.stackexchange.com/questions/209331", "https://dba.stackexchange.com", "https://dba.stackexchange.com/users/153219/" ]
*[Community wiki answer](https://dba.stackexchange.com/help/privileges/edit-community-wiki):* Your question is addressed by the [Is "count(\*)" much faster now?](https://wiki.postgresql.org/wiki/Index-only_scans#Is_.22count.28.2A.29.22_much_faster_now.3F) section of the PostgreSQL wiki page about *Index-only scans*. > > A traditional complaint made of PostgreSQL, generally when comparing it unfavourably with MySQL (at least when using the MyIsam storage engine, which doesn't use MVCC) has been "count(\*) is slow". Index-only scans *can* be used to satisfy these queries without there being any predicate to limit the number of rows returned, and without forcing an index to be used by specifying that the tuples should be ordered by an indexed column. However, in practice that isn't particularly likely. > > > It is important to realise that the planner is concerned with minimising the total cost of the query. With databases, the cost of I/O typically dominates. For that reason, "count(\*) without any predicate" queries will only use an index-only scan if the index is significantly smaller than its table. This typically only happens when the table's row width is much wider than some indexes'. > > > An index-only scan will have to visit the heap tuples if visibility cannot be determined by looking at the visibility map. There is a big 'it depends' when checking which case yours is. Under optimal circumstances, you'll get an index-only scan. Otherwise, if the tuples have to be checked for visibility, a sequential scan quickly becomes the winner, as it does not have the overhead of checking the index first. You get a `bitmap_heap_scan` with `enable seq_scan=off`, so the planner behaves as advertised: > > It is impossible to suppress sequential scans entirely, but turning this variable off discourages the planner from using one if there are other methods available. > > > The details are in other sections of the same wiki page.
An index only scan is not going to look very attractive unless most of the table's pages are marked as all-visible. So you need to VACUUM the table. PostgreSQL's default autovacuum settings are tuned to prevent bloat, not to keep index-only scans happy, so it may require manual intervention to keep the table well-enough vacuumed for your purpose. Note that it still might prefer the full table scan. The index only scan is more CPU intensive than the full table scan, and its IO can be more random and less sequential. If the table is 20 times larger than the index, it will probably prefer the index-only scan, but at 6 times larger it is a bit of a toss up.
25,165,387
So i am having an issue in which the bing maps are not rendered completely on Safari 7. They are loaded fine on Chrome and IE. *Example* - copy and paste the link into Safari 7 on a Mac : <http://www.levi.com/GB/en_GB/findAStore> As You can see only half the map renders the other half is gray, i get no errors in the console, the only warning i get is: **"Invalid CSS property declaration at:\* style.css"** Is anyone else running into this issue? is there a fix for it?
2014/08/06
[ "https://Stackoverflow.com/questions/25165387", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3915205/" ]
Try `text-align:left` in the style of the mapViewer div, it is likely that the map is inheriting the property `text-align: center` and that also applies to images of the map
Sytle.css is a file in your website. Start by looking into that file. Maybe comment out the reference and see if the issue still persists. Bing maps works fine in Safari 7. The forum post you saw on the Bing Maps forums about Safari 7 ended up being an error in the users code and not with Bing Maps. In your case you have not specified a css position, width or height property for the map. This is the #1 cause of issues between different browsers. IE and Chrome are fine with this, but other browsers like Safari require these to render correctly.
25,165,387
So i am having an issue in which the bing maps are not rendered completely on Safari 7. They are loaded fine on Chrome and IE. *Example* - copy and paste the link into Safari 7 on a Mac : <http://www.levi.com/GB/en_GB/findAStore> As You can see only half the map renders the other half is gray, i get no errors in the console, the only warning i get is: **"Invalid CSS property declaration at:\* style.css"** Is anyone else running into this issue? is there a fix for it?
2014/08/06
[ "https://Stackoverflow.com/questions/25165387", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3915205/" ]
Try `text-align:left` in the style of the mapViewer div, it is likely that the map is inheriting the property `text-align: center` and that also applies to images of the map
I also encountered this issue. `text-align: center` causes it and `text-align: left` fixes it. rbrundritt, as this problem has come up repeatedly and your answer is always that the issue is style position, width, or height, you should know that the issue is that the div's `text-align` style impacts the rendering of the maps on Safari and iOS in Bing 7 and that setting to `text-align: left` will fix it.
16,349,073
I have a problem with the following code: ``` question1.setText("question1_" + question_number() + "()"); ``` I have multiple methods that return a string value and are named "question1\_x" (x is a number) and the method question\_number returns a random number. When i run the code like this the "question1" text is set to "question1\_x()" , but what i need it to do is set the text as the "question1\_x()" method returns it. Simply i like ["question1\_" + question\_number() + "()"] to be seen by ".setText" as a method and not as a string. Thank you in advance :)
2013/05/02
[ "https://Stackoverflow.com/questions/16349073", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2184672/" ]
Java won't let you do this unless you resort to reflection. **Reflection is almost certainly the wrong solution to this problem.** Any time you want to have numbered methods and/or fields, step back and consider using a proper collection (say, a list) instead. Start by replacing your numbered methods with a single method that takes a number: ``` String question1(int questionNumber) ```
If I understand this right, you want to call a method inside setText by its name. It can't be done the way you're trying to do it. You need to use Reflections Api. Look at the example below: > > Class myClass = Class.forName(""); > > > Method m = myClass.getMethod(""question1\_" + question\_number()", (Class[]) null); > > > Object retVal = m.invoke(object\_to\_invoke\_on, arguments); > > > setText(retVal); > > > However, this has performance penalties. It'll be 2-3 times slower than a normal method call. In your case you can avoid this altogether by designing it right.
1,604,871
I'm dealing with the following variant of the well-known [Jeep problem](https://en.wikipedia.org/wiki/Jeep_problem): > > A 1000 mile wide desert needs to be crossed in a Jeep. The mileage is one mile / gallon and the Jeep can transport up to 1000 gallons of gas at any time. Fuel may be dropped off at any location in the desert and picked up later. There are 3000 gallons of gas in the base camp. How much fuel can the Jeep transport to the camp on the other side of desert? > > > So instead of "exploring" the desert or trying to drive as far as possible, the problem here is to transport as much fuel as possible for a given distance. I've thought about reducing this problem to the well-studied ones, but I can't come up with anything that makes sense. I don't even know how to approach this. Any pointers?
2016/01/08
[ "https://math.stackexchange.com/questions/1604871", "https://math.stackexchange.com", "https://math.stackexchange.com/users/303693/" ]
Let's represent your starting location as $0$ and the destination as $1000$. Let $f(x)$ be the greatest amount of fuel that can possibly be transported to or past $x$ miles from the starting point. For example, if you pick up $1000$ gallons, drive to $1$ (one mile), drop off $998$ gallons, drive back, repeat the trip to $1$ and back, and on the third trip out you drive to $100$ where you drop $801$ gallons of fuel, then you will have transported $2995$ gallons to point $1$: the $1996$ gallons you cached there and the $999$ gallons that were in the jeep when you passed $1$ on the third trip from $0$. You should be able to show that for $0 \leq x \leq 200$, $f(x) = 3000 - 5x$. The intuitive reason is that you will either have to pass every point between $0$ and $200$ five times (three times outbound and twice in the return direction) have to abandon some fuel without using it; and the latter strategy will deliver less fuel to points beyond where you abandoned the fuel. The previous example that transported $2995$ gallons to or past point $1$ was therefore optimal, or at least was optimal up to $1$. It follows that only $2000$ gallons can reach $200$ no matter where you leave your caches along the way. You should then be able to show that for $0 \leq y \leq \frac{1000}{3}$, $f(200 + y) = 2000 - 3y$. Moreover, you achieve this by delivering exactly $2000$ gallons of fuel to $200$, including the fuel in the jeep the last time you arrive at $200$ in the forward direction, then making sure you have $1000$ gallons in the jeep each time you drive forward from $200$. Finally, for $0 \leq z \leq 1000$, $f\left(200 + \frac{1000}{3} + z\right) = 1000 - z$. You achieve this by delivering exactly $1000$ gallons of fuel to $200 + \frac{1000}{3}$ and then fully loading the jeep with any fuel you have cached at that point and making just one trip forward. The answer is $f(1000)$.
Not sure this is the best, but I would: 1. load jeep up, travel 200mi, dump 600 gallons, go back to base 2. repeat step 1) 3. load jeep, go 200 mi. There is now 2000 gallons, 800mi from destination 4. travel 333 1/3mi, dump 333 1/3gallons, go back to 800mi mark. 5. load jeep, travel 333 1/3 mi. There's now 1000 gallons, 466 2/3 miles from destination 6. travel 466 2/3 miles, and you have 533 1/3 gallons left.
16,424,803
I have the HTML like ``` <div id="abc"> <ul> <li class="first">One<img src="images/plus.png" /></li> <li class="first">Two<img src="images/plus.png" /></li> <li class="first">Three<img src="images/plus.png" /></li> <li class="first">Four<img src="images/plus.png" /></li> </ul> <div class="content"> <h3>Title1</h3> <p>Title1 Description</p> </div> <div class="content"> <h3>Title2</h3> <p>Title2 Description</p> </div> <div class="content"> <h3>Title3</h3> <p>Title3 Description</p> </div> <div class="content"> <h3>Title4</h3> <p>Title4 Description</p> </div> </div> ``` When I click on the first plus image the first div should be displayed below One. When I click on plus image near Two the second image should be displayed below Two. I tried lot of ways but no luck. Please provide a solution. Thanks in advance.
2013/05/07
[ "https://Stackoverflow.com/questions/16424803", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1784484/" ]
There are no general rule of thumb for this, depends on application build. For example: 1. For bank website: 15/30 Seconds might be appropriate 2. For a simple CMS application: 15 minutes long session is good enough.
Personally for an ecommerce site I would be more worried about sessions being too short rather than too long. You can always force users to authenticate again before they are allowed to go to a billing page. This eliminates the possibility of someone stealing the session and buying whatever they want.
8,000,694
So this is my code, I am wondering why changeUp isn't sending an alert to me or setting the variable value: ``` var selecteduname; var xmlhttp; function changeUp() { document.getElementById("useruname").onChange = function() { selecteduname = this.value; alert(selecteduname); updateAdduser(); } function loadXMLDoc() { if (window.XMLHttpRequest) { xmlhttp=new XMLHttpRequest(); } else { xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } } function updateAdduser() {loadXMLDoc(); xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { var json = xmlhttp.responseText; var fields = JSON.parse(json); Object.keys(fields).forEach(function (name) { var input = document.getElementsByName(name); input.value = fields[name]; }); } } xmlhttp.open("GET", "ajaxuseradd.psp?uname="+selecteduname, true); xmlhttp.send(); } </script> ``` and ``` <form action="adduser.psp" method="get"> <fieldset> <label for="uname">Username:</label> <select name="uname" id="useruname" onChange="changeUp();"> <% Blah blah blah Python Code to generate option values %> <%= options %> //More Python code, this actually puts them into the select box </select> </fieldset> <fieldset> <label for="fname">First Name:</label> <input type="text" name="fname" /> </fieldset> <fieldset> <label for="lname">Last Name:</label> <input type="text" name="lname" /> </fieldset> <fieldset> <label for="email">Email:</label> <input type="text" name="email"> </fieldset> ```
2011/11/03
[ "https://Stackoverflow.com/questions/8000694", "https://Stackoverflow.com", "https://Stackoverflow.com/users/756566/" ]
As commented above, the property name is "onchange", not "onChange". Javascript is case-sensitive, so those two are definitely different. Also, the code you posted looks like it's missing a `}` somewhere. As it is, everything's inside the `changeUp` function. Which, coincidentally, never closes before that ending script tag. However, there's something else going on here. This line in your markup: ``` <select name="uname" id="useruname" onChange="changeUp();"> ``` Gets completely wiped out by this line in your code: ``` document.getElementById("useruname").onChange = function() { ``` Here's how I'd fix it up. First, the javascript: ``` function createAjax() { if(window.XMLHttpRequest) return new XMLHttpRequest(); else return new ActiveXObject("Microsoft.XMLHTTP"); } function updateAddUser(username) { var ajax = createAjax(); ajax.onreadystatechange = function() { if(ajax.readyState == 4 && ajax.status == 200) { var json = ajax.responseText; var fields = JSON.parse(json); Object.keys(fields).forEach(function (name) { var input = document.getElementsByName(name); input.value = fields[name]; }); } } ajax.open("GET", "ajaxuseradd.psp?uname=" + username, true); ajax.send(); } ``` Then you can just change the HTML `select` tag to: ``` <select name="uname" id="useruname" onchange="updateAddUser(this.value)"> ``` Having said all that, I would strongly urge you try something like [jQuery](http://jquery.com). It would make the javascript code as trivial as: ``` $('#username').change(function(){ $.get('ajaxuseradd.php', {uname:$(this).val()}, function(data, status, xhr) { $.each(data, function(key,value) { $('#'+key).val(value); }); }, 'json'); }); ``` Yeah, that's really terse, I know. More expressively, it could be written like this: ``` $('#username').change(function() { var userName = $(this).val(); $.ajax({ type: 'GET', url: 'ajaxuseradd.php', data: { uname: userName }, success: function(data, status, xhr) { $.each(data, function(key, value) { $('#' + key).val(value); }); }, dataType: 'json' }) }); ```
You are missing a brace. Try running jslint on your code. Secondly, You are trying to assign a function to the onChange event inside the method changeUp. Whereas changeUp is again the same method invoked in the first place. May be causing recursion. Thanks, RR
16,290,782
I'm currently having a problem when passing an array to a directive via an attribute of that directive. I can read it as a String but i need it as an array so this is what i came up with but it doesn't work. Help anyone? thks in advance Javascript:: ``` app.directive('post', function($parse){ return { restrict: "E", scope:{ title: "@", author: "@", content: "@", cover: "@", date: "@" }, templateUrl: 'components/postComponent.html', link: function(scope, element, attrs){ scope.tags = $parse(attrs.tags) } } } ``` HTML:: ``` <post title="sample title" tags="['HTML5', 'AngularJS', 'Javascript']" ... > ```
2013/04/30
[ "https://Stackoverflow.com/questions/16290782", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2334176/" ]
If you're accessing this array from your scope, i.e. loaded in a controller, you can just pass the name of the variable: [Binding array to directive variable in AngularJS](https://stackoverflow.com/questions/14695792/binding-array-to-directive-variable-in-angularjs) **Directive:** ``` scope:{ title: "@", author: "@", content: "@", cover: "@", date: "@", tags: "=" }, ``` **Template:** ``` <post title="sample title" tags="arrayName" ... > ```
you can also have to use $scope instead of attrs. then you will get array object, otherwise you will get an string. ``` scope:{ title: "@", author: "@", content: "@", cover: "@", date: "@", tags: "=" }, link: function(scope, element, attrs){ scope.tags = scope.tags } ```
54,477,023
I am trying to connect *Google.com* using the below code but getting ``` java.net.ConnectException: Connection Timed out ``` . Please help! ``` private static String getUrlContents(String theUrl) { StringBuilder content = new StringBuilder(); // many of these calls can throw exceptions, so i've just // wrapped them all in one try/catch statement. try { // create a url object URL url = new URL(theUrl); // create a urlconnection object URLConnection urlConnection = url.openConnection(); // wrap the urlconnection in a bufferedreader BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); String line; // read from the urlconnection via the bufferedreader while ((line = bufferedReader.readLine()) != null) { content.append(line + "\n"); } bufferedReader.close(); } catch (Exception e) { e.printStackTrace(); } return content.toString(); } ```
2019/02/01
[ "https://Stackoverflow.com/questions/54477023", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11000301/" ]
I just tried your code and it works fine. It seems it's a network problem, maybe you don't have Internet access, or firewall is stoping connections. Supposing you are in UNIX system try to: 1. `ping www.google.com -C 1` If this you don't get an answer and you have normal access connection (i.e. from your browser) it may be a firewall problem. 2. `traceroute www.google.com` to check the number of hops that should be normally one or two for google's servers. If you are on CentOS you should try to stop the firewall for testing beacuse it's quite restrictive: `sudo systemctl stop firewalld` Remember to start it again and add the rules you need to perform your requests.
So, you are **not asking how to do**: *How to read content from an URL in java?* That is already answered in [Read url to string in few lines of java code](https://stackoverflow.com/questions/4328711/read-url-to-string-in-few-lines-of-java-code). You **described a problem** you like to get analysed or even solved: > > getting `java.net.ConnectException: Connection timed out` > > > See [following answer](https://stackoverflow.com/a/5907240/5730279) to question [Connection timed out. Why?](https://stackoverflow.com/questions/5907037/connection-timed-out-why) > > Things you should look at: > > > * can you **ping** the host (google.com) ? > * can you connect to <http://www.google.com> using a **web browser**? > * can you connect to <https://www.google.com> using **HTTPS** in a **web browser**? > * can you connect to <http://www.google.com> using **your program**? > * can you connect to any other URL using your program? > > > The chances are that your problem is firewall related. My first guess would be that you don't have the correct environment variables or Java system properties set to tell the JVM to use a local proxy server for outgoing HTTP / HTTPS requests > > > An alternative approach to read content from an URL may be the free open-source **JSoup** library. Take a look on how to use it for your case: <http://jsoup.org/cookbook/input/load-document-from-url> With JSoup you can even parse the returned HTML document elegantly.
45,165,243
This is an excerpt from a Conway's Game of Life-program that I'm writing. In this part I'm trying to get the program to read a file that specifies what cells are to be populated at the start of the game (i.e. the seed). I get a weird bug. In the `read_line` function, the program crashes on`line[i++] = ch` statement. When I debug the program, I see that the `line`-pointer is NULL when it crashes. Fair enough, I think, I should initialize `line`. But here is the (for me) strange part: The `read_line` function has already successfully execute twice and got me the first two lines (`4\n` and `3 6\n`) from the seed file. And when I look at the execution in the debugger, I see that line is indeed holding a value in those first two executions of `read_line`. How is this possible? How can `line` be initialized without me initializing it and then suddenly not be initialized anymore? ``` #include <stdio.h> #include <string.h> #include <stdlib.h> #include <time.h> #define MAX_COORDINATE_SIZE 50 #define MAX_FILENAME_SIZE 20 #define MAX_GENERATIONS 10 #define MAX_REPETITION_PERIOD 4 struct coord{ //Holds coordinates to a cell int x; int y; }; struct cell{ int pop; //Populated int age; }; struct coord *read_init(FILE *fp, int *i); static int read_line(FILE *fp, char *line, int max_length); struct coord read_coords(char *line); struct cell **create_board(int x, int y); struct cell **start_game(FILE *fp, int nrows, int ncols); struct cell new_cell(int x, int y, int pop, int age); void print_board(struct cell **board, int nrows, int ncols); void populate_board(struct coord *coords, struct cell ***board, int *n); int main(int argc, const char * argv[]) { int gens; char gens_string[MAX_GENERATIONS]; if(argc != 3){ fprintf(stderr, "Usage: %s <seed-file> <generations>\n<seed-file> can me up to %d characters long\n", argv[0], MAX_FILENAME_SIZE); exit(1); } FILE *fp = fopen(argv[1], "r"); strncat(gens_string, argv[2], MAX_GENERATIONS); gens = atoi(gens_string); int nrows = 10; int ncols = 10; struct cell **board= start_game(fp, nrows, ncols); print_board(board, nrows, ncols); return 0; } struct coord *read_init(FILE *fp, int *n){ //Takes in filename and returns list of coordinates to be populated char raw_n[100]; struct coord *coords; char *line; read_line(fp, raw_n, 100); // get the first line of the file (number of popuated cells) *n = atoi(raw_n);//make an int out of raw_n coords = malloc(sizeof(struct coord)*(*n)); //Allocate memory for each coord for(int i = 0; i<(*n); i++){ // for each line in the file (each populated cell) read_line(fp, line, MAX_COORDINATE_SIZE); coords[i] = read_coords(line); //Put coordinates in coords line = '\0'; } return coords; // return coordinates } static int read_line ( FILE *fp, char *line, int max_length) { int i; char ch; /* initialize index to string character */ i = 0; /* read to end of line, filling in characters in string up to its maximum length, and ignoring the rest, if any */ for(;;) { /* read next character */ ch = fgetc(fp); /* check for end of file error */ if ( ch == EOF ) return -1; /* check for end of line */ if ( ch == '\n' ) { /* terminate string and return */ line[i] = '\0'; return 0; } /* fill character in string if it is not already full*/ if ( i < max_length ) line[i++] = ch; } /* the program should never reach here */ return -1; } struct coord read_coords(char *line){ // Returns coordinates read from char *line struct coord c; char *x; char *y; x = malloc(sizeof(char)*MAX_COORDINATE_SIZE); y = malloc(sizeof(char)*MAX_COORDINATE_SIZE); int i = 0; do{ x[i] = line[i]; //Get the x coordinate i++; }while(line[i] != ' '); i++; do{ y[i-2] = line[i]; i++; }while(line[i] != '\0'); c.x = atoi(x)-1; c.y = atoi(y)-1; return c; } void init_board(int nrows, int ncols, struct cell ***board){ *board = malloc(nrows * sizeof(*board) + nrows * ncols * sizeof(**board)); //Now set the address of each row or whatever stackoverflow says struct cell * const firstrow = *board + nrows; for(int i = 0; i < nrows; i++) { (*board)[i] = firstrow + i * ncols; } for(int i = 0; i < nrows; i++){ //fill the entire board with pieces for(int j = 0; j < ncols; j++){ (*board)[i][j] = new_cell(i, j, 0, 0); } } } void print_board(struct cell **board, int nrows, int ncols){ printf("--------------------\n"); for(int i = 0; i<nrows; i++){ for(int j = 0; j<ncols; j++){ if(board[i][j].pop == 1){ printf("%d ", board[i][j].age); }else if(board[i][j].pop == 0){ printf(" "); }else{ printf("\n\nERROR!"); exit(0); } } printf("\n"); } printf("--------------------"); printf("\n"); } struct cell **start_game(FILE *fp, int nrows, int ncols){ //x,y are no of rows/columns, fn is filename int n; // n is the number of populated cells specified in the seed struct coord *coords = read_init(fp, &n); // get the list of coords to populate board with struct cell **board; init_board(nrows, ncols, &board); // Set up the board populate_board(coords, &board, &n); //populate the cells specified in the seed return board; } void populate_board(struct coord *coords, struct cell ***board, int *n){ for(int i = 0; i < *n; i++){ (*board)[coords[i].x][coords[i].y].pop = 1; //populate the cell } } struct cell new_cell(int x, int y, int pop, int age){ //Return new populated or non-populated cell with specified coordinates struct cell c; c.pop = pop; c.age = age; return c; } ``` The seed file: ``` 4 3 6 4 6 5 6 5 7 ``` EDIT: The error message: `Thread 1: EXC_BAD_ACCESS (code=1, address=0x0)` I shall add that if I add a line `line = malloc(sizeof(char)*MAX_COORDINATE_SIZE+1)` after the declaration of line in `read_init`, I still get the same error.
2017/07/18
[ "https://Stackoverflow.com/questions/45165243", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3128156/" ]
In read\_init() : ``` struct coord *read_init(FILE *fp, int *n){ //... char *line; //... for(int i = 0; i<(*n); i++) { read_line(fp, line, MAX_COORDINATE_SIZE); coords[i] = read_coords(line); //Put coordinates in coords line = '\0'; // <<--- you set line to NULL here. *line = 0; // this is what you wanted to do, is not necessary... } // .... } ```
> > I get a weird bug. > > > I suggest asking some questions about the compiler output. We should never blindly ignore warnings, after all. Speaking of reading things, I think you're spending too long reading StackOverflow and not long enough reading K&R2e and doing the exercises. We'll come back to that. > > In the `read_line` function, the program crashes on `line[i++] = ch` statement ... But here is the (for me) strange part: ... The `read_line` function has already successfully execute twice and got me the first two lines (`4\n` and `3 6\n`) from the seed file > > > The C and C++ standards rationalise the concept of "undefined behaviour" for this class of errors that are computationally difficult to diagnose. In other words, because you made an error, the behaviour of your program is undefined. It isn't *required* that your malfunctioning code crash every time, as that would be *defining the undefined*; instead they leave this "undefined" and the first two times your erroneously code *works* (whatever that means), purely by coincidence that the uninitialised variable points somewhere accessible. Later on you assign `line = '\0';`, which changes `line` to be a null pointer, and then you try to assign into whatever that null pointer points at. That's more undefined behaviour. > > How is this possible? How can line be initialized without me initializing it and then suddenly not be initialized anymore? > > > `line` isn't initialised; you're using it uninitialised, which happens to coincidentally *work* (but needs fixing), then you assign it to be a null pointer and dereference a null pointer (more UB that needs fixing). Such is the nature of undefined behaviour. Such is the nature of learning C by guessing. You need a book! > > I shall add that if I add a line `line = malloc(sizeof(char)*MAX_COORDINATE_SIZE+1)` after the declaration of line in `read_init`, I still get the same error. > > > You need to fix all of the errors, not just the one. For assistance you could see the warnings/errors your compiler emits. I see more uninitialised access here: ``` char gens_string[MAX_GENERATIONS]; // <--- where's the initialisation?? // Snip strncat(gens_string, argv[2], MAX_GENERATIONS); // Boom ``` There's some really sus code around this comment: `//Now set the address of each row or whatever stackoverflow says` ... and on that note I want to point out that there are some subtly toxic know-it-alls who answer questions despite having as many misunderstandings as you, a humble person, and so *you shouldn't hope to get the same quality of education from StackOverflow as you would from K&R2e*... but apparently I'd be toxic for pointing out the egomaniacs and suggesting decent resources to learn from, so that's none of my business ‍♂️ let's just let the sociopaths sabotage the education of everyone huh? > > > ``` > (*board)[i] = firstrow + i * ncols; > > ``` > > Look, there is no guarantee that this even compiles let alone that the address on the right has a suitable alignment to store the type of value on the left. [Misaligned access causes more undefined behaviour](https://en.m.wikipedia.org/wiki/Bus_error), which may also *work coincidentally* rather than *logically*. Just as you've never seen alignment violations before, so too has the person who suggested you use this code. Assuming the alignment requirements for your implementation are satisfied by this code, we then have the same questions to raise here: > > > ``` > (*board)[i][j] = new_cell(i, j, 0, 0); > > ``` > > Your whole program needs remodelling around the declaration of `board` changing from `struct cell **board` to `struct cell (*board)[ncols];`, for example. It'll become much simpler, and a whole class of bugs related to alignment requirements will disappear. To see the extent of the simplification, here's what your `init_board` ought to look like: ``` void init_board(int nrows, int ncols, struct cell (**board)[ncols]){ *board = malloc(nrows * sizeof(*board)); // NOTE: I snipped the erroneous StackOverflow logic around the comment mentioned above; you don't need that crud because of the more suitable choice of type for(int i = 0; i < nrows; i++){ //fill the entire board with pieces for(int j = 0; j < ncols; j++){ (*board)[i][j] = (struct cell){ 0, 0 }; } } } ```
127,227
how would you improve the buttons on the top of the screen? To grab attention of the user I tried to change a bit their color (they are dark blue instead of black), but I think that they are not coherent with the rest of the screen. [![screen](https://i.stack.imgur.com/yiO22.png)](https://i.stack.imgur.com/yiO22.png)
2019/08/02
[ "https://ux.stackexchange.com/questions/127227", "https://ux.stackexchange.com", "https://ux.stackexchange.com/users/129146/" ]
Generally, circles are used to show information (think social media profile pics); we see them less as buttons. Try making the buttons rounded rectangles. I don't think coloring the icons necessarily helps make them more discoverable, and color might compete with what the user is trying to do visually on the canvas. Monochrome might be the way to go. [![A screenshot of Apple's Preview image editing buttons](https://i.stack.imgur.com/gSVTC.png)](https://i.stack.imgur.com/gSVTC.png)
It all depends on the product strategy if the target is to be an advanced graphic processing program it's worth thinking about the menu comprehensively and holistic. [![enter image description here](https://i.stack.imgur.com/gScBZ.png)](https://i.stack.imgur.com/gScBZ.png) [![enter image description here](https://i.stack.imgur.com/xkxrS.png)](https://i.stack.imgur.com/xkxrS.png) --- If it is however a one-time function in the application then - three buttons with active state of active tool should be good: [![enter image description here](https://i.stack.imgur.com/425za.png)](https://i.stack.imgur.com/425za.png) --- Or put the interface elements on the left side of the canvas with the addition of a text / description of what they are doing
127,227
how would you improve the buttons on the top of the screen? To grab attention of the user I tried to change a bit their color (they are dark blue instead of black), but I think that they are not coherent with the rest of the screen. [![screen](https://i.stack.imgur.com/yiO22.png)](https://i.stack.imgur.com/yiO22.png)
2019/08/02
[ "https://ux.stackexchange.com/questions/127227", "https://ux.stackexchange.com", "https://ux.stackexchange.com/users/129146/" ]
Generally, circles are used to show information (think social media profile pics); we see them less as buttons. Try making the buttons rounded rectangles. I don't think coloring the icons necessarily helps make them more discoverable, and color might compete with what the user is trying to do visually on the canvas. Monochrome might be the way to go. [![A screenshot of Apple's Preview image editing buttons](https://i.stack.imgur.com/gSVTC.png)](https://i.stack.imgur.com/gSVTC.png)
Put your buttons at the bottom. When user looks for navigation buttons he well clearly see them.
127,227
how would you improve the buttons on the top of the screen? To grab attention of the user I tried to change a bit their color (they are dark blue instead of black), but I think that they are not coherent with the rest of the screen. [![screen](https://i.stack.imgur.com/yiO22.png)](https://i.stack.imgur.com/yiO22.png)
2019/08/02
[ "https://ux.stackexchange.com/questions/127227", "https://ux.stackexchange.com", "https://ux.stackexchange.com/users/129146/" ]
Generally, circles are used to show information (think social media profile pics); we see them less as buttons. Try making the buttons rounded rectangles. I don't think coloring the icons necessarily helps make them more discoverable, and color might compete with what the user is trying to do visually on the canvas. Monochrome might be the way to go. [![A screenshot of Apple's Preview image editing buttons](https://i.stack.imgur.com/gSVTC.png)](https://i.stack.imgur.com/gSVTC.png)
I agree with Stacy H's answer. I would like to add that placing those buttons at the top and center of the screen is placing them in possibly the hardest place to access. The Users hand and arm will often cover the actual content while accessing those buttons and the User must reach for the buttons. Left(start) and/or right(end) sides or underneath the canvas would achieve easier access. The placement of the EditText underneath is odd too, as that is prime realestate for usable widgets and will be covered up by a soft input keyboard. It seems to be the least sensible place for the EditText.
67,281,326
I have a form with sub-forms using ControlValueAccessor profile-form.component.ts ``` form: FormGroup; this.form = this.formBuilder.group({ firstName: [], lastName: ["", Validators.maxLength(10)], email: ["", Validators.required] }); get lastNameControl() { return this.form.controls.lastName; } initForm() { ... this.form.patchValue({ firstName: "thompson", lastName: "vilaaaaaaaaaaaaaaaaaaaa", email: "abc@gmail.com" }); ... } ``` profile-form.component.html ``` <label for="last-name">Last Name</label> <input formControlName="lastName" id="last-name" /> <div *ngIf="lastNameControl.touched && lastNameControl.invalid" class="error"> last name max length is 10 </div> ``` Problem: The initial data are loaded to the form, but the validations are not triggered (for example: field Last Name is not validated). I have to touch the field then the validation start working. How to trigger validations right after the `patchValue` done. please refer to the code: <https://stackblitz.com/edit/angular-wg5mxz?file=src/app/app.component.ts> Any suggestion is appreciated.
2021/04/27
[ "https://Stackoverflow.com/questions/67281326", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1845475/" ]
> > To prevent the validator from displaying errors before the user has a chance to edit the form, you should check for either the dirty or touched states in a control. > > > When the user changes the value in the watched field, the control is marked as "dirty". > When the user blurs the form control element, the control is marked as "touched". > > > You should delete `lastNameControl.touched` from your `*ngIf` Check <https://angular.io/guide/form-validation> for more information
Its only because you are showing the error when lastName or email is touched as @godocmat mentioned. If you just remove the lastNameControl.touched or emailControl.touched from \*ngIf, it works. Check <https://stackblitz.com/edit/angular-xced6b?file=src%2Fapp%2Fprofile-form%2Fprofile-form.component.html>
31,488,517
Is there any built-in function to get the maximum accuracy for a binary probabilistic classifier in scikit-learn? E.g. to get the maximum F1-score I do: ``` # AUCPR precision, recall, thresholds = sklearn.metrics.precision_recall_curve(y_true, y_score) auprc = sklearn.metrics.auc(recall, precision) max_f1 = 0 for r, p, t in zip(recall, precision, thresholds): if p + r == 0: continue if (2*p*r)/(p + r) > max_f1: max_f1 = (2*p*r)/(p + r) max_f1_threshold = t ``` I could compute the maximum accuracy in a similar fashion: ``` accuracies = [] thresholds = np.arange(0,1,0.1) for threshold in thresholds: y_pred = np.greater(y_score, threshold).astype(int) accuracy = sklearn.metrics.accuracy_score(y_true, y_pred) accuracies.append(accuracy) accuracies = np.array(accuracies) max_accuracy = accuracies.max() max_accuracy_threshold = thresholds[accuracies.argmax()] ``` but I wonder whether there is any built-in function.
2015/07/18
[ "https://Stackoverflow.com/questions/31488517", "https://Stackoverflow.com", "https://Stackoverflow.com/users/395857/" ]
``` from sklearn.metrics import accuracy_score from sklearn.metrics import roc_curve fpr, tpr, thresholds = roc_curve(y_true, probs) accuracy_scores = [] for thresh in thresholds: accuracy_scores.append(accuracy_score(y_true, [m > thresh for m in probs])) accuracies = np.array(accuracy_scores) max_accuracy = accuracies.max() max_accuracy_threshold = thresholds[accuracies.argmax()] ```
I started to improve the solution by transforming the `thresholds = np.arange(0,1,0.1)` into a smarter, dichotomous way of finding the maximum Then I realized, after 2 hours of work, that getting **all the accuracies** were far more cheaper than just finding the maximum !! (Yes it is totally counter-intuitive). I wrote a lot of comments here below to explain my code. Feel free to delete all these to make the code more readable. ``` import numpy as np # Definition : we predict True if y_score > threshold def ROC_curve_data(y_true, y_score): y_true = np.asarray(y_true, dtype=np.bool_) y_score = np.asarray(y_score, dtype=np.float_) assert(y_score.size == y_true.size) order = np.argsort(y_score) # Just ordering stuffs y_true = y_true[order] # The thresholds to consider are just the values of score, and 0 (accept everything) thresholds = np.insert(y_score[order],0,0) TP = [sum(y_true)] # Number of True Positives (For Threshold = 0 => We accept everything => TP[0] = # of postive in true y) FP = [sum(~y_true)] # Number of True Positives (For Threshold = 0 => We accept everything => TP[0] = # of postive in true y) TN = [0] # Number of True Negatives (For Threshold = 0 => We accept everything => we don't have negatives !) FN = [0] # Number of True Negatives (For Threshold = 0 => We accept everything => we don't have negatives !) for i in range(1, thresholds.size) : # "-1" because the last threshold # At this step, we stop predicting y_score[i-1] as True, but as False.... what y_true value say about it ? # if y_true was True, that step was a mistake ! TP.append(TP[-1] - int(y_true[i-1])) FN.append(FN[-1] + int(y_true[i-1])) # if y_true was False, that step was good ! FP.append(FP[-1] - int(~y_true[i-1])) TN.append(TN[-1] + int(~y_true[i-1])) TP = np.asarray(TP, dtype=np.int_) FP = np.asarray(FP, dtype=np.int_) TN = np.asarray(TN, dtype=np.int_) FN = np.asarray(FN, dtype=np.int_) accuracy = (TP + TN) / (TP + FP + TN + FN) sensitivity = TP / (TP + FN) specificity = TN / (FP + TN) return((thresholds, TP, FP, TN, FN)) ``` The all process is just a single loop, and the algorithm is just trivial. In fact, the stupidly simple function is 10 times faster than the solution proposed before me (commpute the accuracies for `thresholds = np.arange(0,1,0.1)`) and 30 times faster than my previous smart-ass-dychotomous-algorithm... You can then easily compute **ANY** KPI you want, for example : ``` def max_accuracy(thresholds, TP, FP, TN, FN) : accuracy = (TP + TN) / (TP + FP + TN + FN) return(max(accuracy)) def max_min_sensitivity_specificity(thresholds, TP, FP, TN, FN) : sensitivity = TP / (TP + FN) specificity = TN / (FP + TN) return(max(np.minimum(sensitivity, specificity))) ``` If you want to test it : ``` y_score = np.random.uniform(size = 100) y_true = [np.random.binomial(1, p) for p in y_score] data = ROC_curve_data(y_true, y_score) %matplotlib inline # Because I personnaly use Jupyter, you can remove it otherwise import matplotlib.pyplot as plt plt.step(data[0], data[1]) plt.step(data[0], data[2]) plt.step(data[0], data[3]) plt.step(data[0], data[4]) plt.show() print("Max accuracy is", max_accuracy(*data)) print("Max of Min(Sensitivity, Specificity) is", max_min_sensitivity_specificity(*data)) ``` Enjoy ;)
220,837
I am trying to solve a system of 9 linear coupled ODE using `DSolve`. To try things out I do : ``` e1 = app'[t] == a a03[t] + b app[t] e2 = a03'[t] == d a03[t] - c app[t] DSolve[{e1, e2, a03[0] == 1, app[0] == 2}, {app, a03}, {t}] ``` It works perfectly. Now I try to solve the real thing : ``` ex1 = Derivative[1][app][t] == 2*a03[t]*A21 + 2*A21*a30[t] + 2*I*app[t]*B22 + I*a3p[t]*w + I*Conjugate[a3p[t]]*w - 2*I*app[t]*w + (-4*a33[t] + Conjugate[apm[t]] + apm[t])*Subscript[A, c]^11; ex2 = Derivative[1][apm][t] == (Conjugate[app[t]] + app[t])*Subscript[A, c]^11 - I*((-a3m[t] + Conjugate[a3p[t]])*w + 2*(a03[t] + a30[t])*Subscript[B, c]^11); ex3 = Derivative[1][a30][t] == -2*A21*(Conjugate[app[t]] - app[t]) - 2*I*(Conjugate[a0m[t]] - Conjugate[a0p[t]])*w + 2*I*(4 + Conjugate[apm[t]] + apm[t])*Subscript[B, c]^11; ex4 = Derivative[1][a03][t] == -2*A21*(Conjugate[app[t]] - app[t]) - 2*I*(a0m[t] - a0p[t])*w + 2*I*(4 + Conjugate[apm[t]] + apm[t])*Subscript[B, c]^11; ex5 = Derivative[1][a33][t] == 2*I*((-a3m[t] + a3p[t] - Conjugate[a3m[t]] + Conjugate[a3p[t]])*w + 2*I*(Conjugate[app[t]] + app[t])*Subscript[A, c]^11 + 4*(a03[t] + a30[t])*Subscript[B, c]^11); ex6 = Derivative[1][a0p][t] == 4*I*((-I)*A21*Conjugate[a3m[t]] + a0p[t]*B22 + a03[t]*w - a0p[t]*w - I*a0m[t]*Subscript[A, c]^11 - Conjugate[a3p[t]]*Subscript[B, c]^11); ex7 = Derivative[1][a0m][t] == -4*I*((-I)*A21*Conjugate[a3p[t]] + a0m[t]*B22 + a03[t]*w - a0m[t]*w + I*a0p[t]*Subscript[A, c]^11 + Conjugate[a3m[t]]*Subscript[B, c]^11); ex8 = Derivative[1][a3m][t] == 2*I*(-2*I*A21*Conjugate[a0p[t]] - 2*a3m[t]*B22 - 2*a33[t]*w + 2*a3m[t]*w - Conjugate[app[t]]*w + apm[t]*w - 2*I*(a3p[t] + 2*Conjugate[a3p[t]])*Subscript[A, c]^11 + 2*(2*a0m[t] + Conjugate[a0m[t]])*Subscript[B, c]^11); ex9 = Derivative[1][a3p][t] == 2*I*(2*I*A21*Conjugate[a0m[t]] + 2*a3p[t]*B22 + 2*a33[t]*w - 2*a3p[t]*w - Conjugate[apm[t]]*w + app[t]*w - 2*I*(a3m[t] + 2*Conjugate[a3m[t]])*Subscript[A, c]^11 + 2*(2*a0p[t] + Conjugate[a0p[t]])*Subscript[B, c]^11); DSolve[{ex1, ex2, ex3, ex4, ex5, ex6, ex7, ex8, ex9}, {app, apm, a30, a03, a33, a0p, a0m, a3m, a3p}, t] ``` This however fails and gives the following output : ``` DSolve[{Derivative[1][app][t] == 2*A21*a03[t] + 2*A21*a30[t] + I*w*a3p[t] + 2*I*B22*app[t] - 2*I*w*app[t] + I*w*Conjugate[a3p[t]] + (-4*a33[t] + apm[t] + Conjugate[apm[t]])*Subscript[A, c]^11, Derivative[1][apm][t] == (app[t] + Conjugate[app[t]])*Subscript[A, c]^11 - I*(w*(-a3m[t] + Conjugate[a3p[t]]) + 2*(a03[t] + a30[t])*Subscript[B, c]^11), Derivative[1][a30][t] == -2*I*w*(Conjugate[a0m[t]] - Conjugate[a0p[t]]) - 2*A21*(-app[t] + Conjugate[app[t]]) + 2*I*(4 + apm[t] + Conjugate[apm[t]])*Subscript[B, c]^11, Derivative[1][a03][t] == -2*I*w*(a0m[t] - a0p[t]) - 2*A21*(-app[t] + Conjugate[app[t]]) + 2*I*(4 + apm[t] + Conjugate[apm[t]])*Subscript[B, c]^11, Derivative[1][a33][t] == 2*I*(w*(-a3m[t] + a3p[t] - Conjugate[a3m[t]] + Conjugate[a3p[t]]) + 2*I*(app[t] + Conjugate[app[t]])*Subscript[A, c]^11 + 4*(a03[t] + a30[t])*Subscript[B, c]^11), Derivative[1][a0p][t] == 4*I*(w*a03[t] + B22*a0p[t] - w*a0p[t] - I*A21*Conjugate[a3m[t]] - I*a0m[t]*Subscript[A, c]^11 - Conjugate[a3p[t]]*Subscript[B, c]^11), Derivative[1][a0m][t] == -4*I*(w*a03[t] + B22*a0m[t] - w*a0m[t] - I*A21*Conjugate[a3p[t]] + I*a0p[t]*Subscript[A, c]^11 + Conjugate[a3m[t]]*Subscript[B, c]^11), Derivative[1][a3m][t] == 2*I*(-2*w*a33[t] - 2*B22*a3m[t] + 2*w*a3m[t] + w*apm[t] - 2*I*A21*Conjugate[a0p[t]] - w*Conjugate[app[t]] - 2*I*(a3p[t] + 2*Conjugate[a3p[t]])*Subscript[A, c]^11 + 2*(2*a0m[t] + Conjugate[a0m[t]])*Subscript[B, c]^11), Derivative[1][a3p][t] == 2*I*(2*w*a33[t] + 2*B22*a3p[t] - 2*w*a3p[t] + w*app[t] + 2*I*A21*Conjugate[a0m[t]] - w*Conjugate[apm[t]] - 2*I*(a3m[t] + 2*Conjugate[a3m[t]])*Subscript[A, c]^11 + 2*(2*a0p[t] + Conjugate[a0p[t]])*Subscript[B, c]^11)}, {app, apm, a30, a03, a33, a0p, a0m, a3m, a3p}, t] ``` Can someone please tell me where I went wrong? Edit : I have experimented and discovered that : ``` DSolve[f'[x] == a f[x], f, x] ``` , takes less than one second, but the following takes around 15 seconds to evaluate : ``` DSolve[f'[gh] == a Conjugate[f[gh]], f, gh] ```
2020/05/01
[ "https://mathematica.stackexchange.com/questions/220837", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/72104/" ]
We can simplifier this system up to linear matrix equation $u'(t)=A.u+B$ using code below ``` ex1 = Derivative[1][app][t] == 2*a03[t]*A21 + 2*A21*a30[t] + 2*I*app[t]*B22 + I*a3p[t]*w + I*Conjugate[a3p[t]]*w - 2*I*app[t]*w + (-4*a33[t] + Conjugate[apm[t]] + apm[t])* Subscript[A, c]^11; ex2 = Derivative[1][apm][ t] == (Conjugate[app[t]] + app[t])*Subscript[A, c]^11 - I*((-a3m[t] + Conjugate[a3p[t]])*w + 2*(a03[t] + a30[t])*Subscript[B, c]^11); ex3 = Derivative[1][a30][t] == -2*A21*(Conjugate[app[t]] - app[t]) - 2*I*(Conjugate[a0m[t]] - Conjugate[a0p[t]])*w + 2*I*(4 + Conjugate[apm[t]] + apm[t])*Subscript[B, c]^11; ex4 = Derivative[1][a03][t] == -2*A21*(Conjugate[app[t]] - app[t]) - 2*I*(a0m[t] - a0p[t])*w + 2*I*(4 + Conjugate[apm[t]] + apm[t])*Subscript[B, c]^11; ex5 = Derivative[1][a33][t] == 2*I*((-a3m[t] + a3p[t] - Conjugate[a3m[t]] + Conjugate[a3p[t]])* w + 2*I*(Conjugate[app[t]] + app[t])*Subscript[A, c]^11 + 4*(a03[t] + a30[t])*Subscript[B, c]^11); ex6 = Derivative[1][a0p][t] == 4*I*((-I)*A21*Conjugate[a3m[t]] + a0p[t]*B22 + a03[t]*w - a0p[t]*w - I*a0m[t]*Subscript[A, c]^11 - Conjugate[a3p[t]]*Subscript[B, c]^11); ex7 = Derivative[1][a0m][t] == -4* I*((-I)*A21*Conjugate[a3p[t]] + a0m[t]*B22 + a03[t]*w - a0m[t]*w + I*a0p[t]*Subscript[A, c]^11 + Conjugate[a3m[t]]*Subscript[B, c]^11); ex8 = Derivative[1][a3m][t] == 2*I*(-2*I*A21*Conjugate[a0p[t]] - 2*a3m[t]*B22 - 2*a33[t]*w + 2*a3m[t]*w - Conjugate[app[t]]*w + apm[t]*w - 2*I*(a3p[t] + 2*Conjugate[a3p[t]])*Subscript[A, c]^11 + 2*(2*a0m[t] + Conjugate[a0m[t]])*Subscript[B, c]^11); ex9 = Derivative[1][a3p][t] == 2*I*(2*I*A21*Conjugate[a0m[t]] + 2*a3p[t]*B22 + 2*a33[t]*w - 2*a3p[t]*w - Conjugate[apm[t]]*w + app[t]*w - 2*I*(a3m[t] + 2*Conjugate[a3m[t]])*Subscript[A, c]^11 + 2*(2*a0p[t] + Conjugate[a0p[t]])*Subscript[B, c]^11); exp = {ex1, ex2, ex3, ex4, ex5, ex6, ex7, ex8, ex9}; var = {app, apm, a30, a03, a33, a0p, a0m, a3m, a3p}; rep = Table[ var[[i]][t] -> x[i][t] + I y[i][t], {i, Length[var]}]; par = {B22 -> b22r + I b22, A21 -> a21r + I a21, Subscript[A, c]^11 -> acr + I ac , Subscript[B, c]^11 -> bcr + I bc, w -> w1 + I w2}; rep1 = Table[ var[[i]]'[t] -> x[i]'[t] + I y[i]'[t], {i, Length[var]}]; rep2 = Flatten[Table[{Conjugate[x[i][t]] -> x[i][t], Conjugate[y[i][t]] -> y[i][t]}, {i, Length[var]}], 1]; exp1 = exp /. Join[rep, rep1] /. rep2 /. par; eqs = ComplexExpand[exp1]; X = Array[x, Length[var]]; Y = Array[y, Length[var]]; vars = Join[X, Y]; eq1 = eqs /. {I -> Z}; eqx = eq1 /. {Z -> 0}; eq2 = eq1 /. Z -> 1; eqy = Table[ First[eq2[[i]]] - First[eqx[[i]]] == Last[eq2[[i]]] - Last[eqx[[i]]], {i, Length[eq2]}]; ``` Finally we have 18 equations with separated real and complex part of all variables and parameters ``` eq18 = Join[eqx, eqy] ``` Now we can evaluate matrix of this equation ``` varst = Table[vars[[i]][t], {i, Length[vars]}]; {b, m} = CoefficientArrays[eq18, varst] ``` We can check how it looks like ``` m // MatrixForm b // Normal ``` We can calculate constant vector as follows ``` varst1 = Table[vars[[i]]'[t], {i, Length[vars]}]; b0 = b - varst1; ``` So our matrix equation has a form (don't try to solve it with `DSolve`): ``` eqF = varst1 == m.varst - b0; ```
Calling ``` app[t] = appr[t] + I appi[t] .......................... a3m[t] = a3mr[t] + I a3mi[t] ``` we can develop an equivalent ODE system with the structure ``` appr'[t] + I appi'[t] == F1r[appr[t],...,a3mi[t]] + I F1i[appr[t],...,a3mi[t]] .............................................................................. a3mr'[t] + I a3mi'[t] == F9r[appr[t],...,a3mi[t]] + I F9i[appr[t],...,a3mi[t]] ``` which is equivalent to the real system ``` appr'[t] == F1r[appr[t],...,a3mi[t]] appi'[t] == F1i[appr[t],...,a3mi[t]] .................................... a3mr'[t] == F9r[appr[t],...,a3mi[t]] a3mi'[t] == F9i[appr[t],...,a3mi[t]] ``` As the **Fkr, Fki** are linear the resulting system will appear as $$ \dot X(t) = A X(t) $$ with solution $$ X(t) = e^{A t}c\_0 $$
31,284,003
**Updated with Code:** I have a string array in my controller like below, ``` var app = angular.module('myApp', []); app.controller('mycontroller', function($scope) { $scope.menuitems =['Home','About']; }; }); ``` I need to display it in the navigation pane (navigation should be on the leftside) Below is my html code. ``` <body class="container-fluid"> <div class="col-md-2"> <ul class="nav nav-pills nav-stacked" ng-repeat="x in menuitems track by $index"> <li>{{x}}</li> </ul> </div> </body> ``` I did get the string values bound to the navigation pane. It is showing text like {{x}}. Kindly help
2015/07/08
[ "https://Stackoverflow.com/questions/31284003", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4419549/" ]
1. In your javascript code `};` is unnecessary. 2. You haven't attached `controller` to the `div`. Code. Javascript: ``` var app = angular.module('myApp', []); app.controller('mycontroller', function($scope) { $scope.menuitems = ['Home', 'About']; //}; // REMOVE THIS }); ``` HTML: ``` <div class="col-md-2" ng-controller="mycontroller"> <!-- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ --> <ul class="nav nav-pills nav-stacked" ng-repeat="x in menuitems track by $index"> <li>{{x}}</li> </ul> ```
You haven't specified to make use of `mycontroller` in your html code. ``` <body class="container-fluid"> <div class="col-md-2" ng-controller='mycontroller'> <ul class="nav nav-pills nav-stacked" ng-repeat = "x in menuitems track by $index"> <li>{{x}}</li> </ul> </div> </body> ```
31,284,003
**Updated with Code:** I have a string array in my controller like below, ``` var app = angular.module('myApp', []); app.controller('mycontroller', function($scope) { $scope.menuitems =['Home','About']; }; }); ``` I need to display it in the navigation pane (navigation should be on the leftside) Below is my html code. ``` <body class="container-fluid"> <div class="col-md-2"> <ul class="nav nav-pills nav-stacked" ng-repeat="x in menuitems track by $index"> <li>{{x}}</li> </ul> </div> </body> ``` I did get the string values bound to the navigation pane. It is showing text like {{x}}. Kindly help
2015/07/08
[ "https://Stackoverflow.com/questions/31284003", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4419549/" ]
1. In your javascript code `};` is unnecessary. 2. You haven't attached `controller` to the `div`. Code. Javascript: ``` var app = angular.module('myApp', []); app.controller('mycontroller', function($scope) { $scope.menuitems = ['Home', 'About']; //}; // REMOVE THIS }); ``` HTML: ``` <div class="col-md-2" ng-controller="mycontroller"> <!-- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ --> <ul class="nav nav-pills nav-stacked" ng-repeat="x in menuitems track by $index"> <li>{{x}}</li> </ul> ```
Hey i guess the mistake is you should give the ng-repeat in li tag try it . It should work
31,284,003
**Updated with Code:** I have a string array in my controller like below, ``` var app = angular.module('myApp', []); app.controller('mycontroller', function($scope) { $scope.menuitems =['Home','About']; }; }); ``` I need to display it in the navigation pane (navigation should be on the leftside) Below is my html code. ``` <body class="container-fluid"> <div class="col-md-2"> <ul class="nav nav-pills nav-stacked" ng-repeat="x in menuitems track by $index"> <li>{{x}}</li> </ul> </div> </body> ``` I did get the string values bound to the navigation pane. It is showing text like {{x}}. Kindly help
2015/07/08
[ "https://Stackoverflow.com/questions/31284003", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4419549/" ]
1. In your javascript code `};` is unnecessary. 2. You haven't attached `controller` to the `div`. Code. Javascript: ``` var app = angular.module('myApp', []); app.controller('mycontroller', function($scope) { $scope.menuitems = ['Home', 'About']; //}; // REMOVE THIS }); ``` HTML: ``` <div class="col-md-2" ng-controller="mycontroller"> <!-- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ --> <ul class="nav nav-pills nav-stacked" ng-repeat="x in menuitems track by $index"> <li>{{x}}</li> </ul> ```
Try the below code: ``` <body class="container-fluid"> <div class="col-md-2"> <ul class="nav nav-pills nav-stacked" > <li ng-repeat="x in menuitems">{{x}}</li> </ul> </div> </body> ```