text
stringlengths
64
81.1k
meta
dict
Q: ReheapUp and ReheapDown Recursive to Iterative Conversion C# I've been asked to convert recursive ReheapUp and ReheapDown algorithms to an alternative iterative form. Here is the psuedocode for the recursive versions: ReheapUp(node) begin if NOT node = 0 parent ← (node - 1) / 2 // integer division if heap[node] > heap[parent] Swap(heap[parent], heap[node]) ReheapUp(parent) end-if end-if end ReheapDown(node) begin leftChild ← node * 2 + 1 rightChild ← node * 2 + 2 if leftChild <= lastUsed largest ← leftChild if rightChild <= lastUsed AND array[largest] < array[rightChild] largest ← rightChild end-if if array[node] < array[largest] Swap(array[node], array[largest]) ReheapDown(largest) end-if end-if end Here are my attempts: private void ReheapUp(int index) { bool Terminate; int Processing = index; do { Terminate = true; if (Processing != 0) { int Parent = PARENT(Processing); if (_Data[Processing].CompareTo(_Data[Parent]) > 0) { Utility.Swap(ref _Data[Parent], ref _Data[Processing]); Terminate = false; Processing = Parent; } } } while (!Terminate); } private void ReheapDown(int index) { bool Terminate; int Processing = index, Largest = -1; do { Terminate = true; int LeftChild = CLEFT(Processing), RightChild = CRIGHT(Processing); if (LeftChild <= _LastUsed) { Largest = LeftChild; if (RightChild <= _LastUsed && _Data[Largest].CompareTo(_Data[RightChild]) < 0) Largest = RightChild; if (_Data[index].CompareTo(_Data[Largest]) < 0) { Utility.Swap(ref _Data[Processing], ref _Data[Largest]); Terminate = false; Processing = Largest; } } } while (!Terminate); } Please tell me what I'm doing wrong. A: Your ReheapDown method has a small issue. This should work: private void ReheapDown(int index) { bool Terminate; int Processing = index, Largest = -1; do { Terminate = true; int LeftChild = CLEFT(Processing), RightChild = CRIGHT(Processing); if (LeftChild <= _LastUsed) { Largest = LeftChild; if (RightChild <= _LastUsed && _Data[Largest].CompareTo(_Data[RightChild]) < 0) Largest = RightChild; if (_Data[Processing].CompareTo(_Data[Largest]) < 0) { Utility.Swap(ref _Data[Processing], ref _Data[Largest]); Terminate = false; Processing = Largest; } } } while (!Terminate); }
{ "pile_set_name": "StackExchange" }
Q: Is better a switch or a const table? (embedded SW) I wonder if, when it is possible, Is it more efficient a switch or a const table? For example, what would perform better: switch(input) { case 0: value = VALUE_0; break; case 1: value = VALUE_1; break; case 2: value = VALUE_2; break; case 3: value = VALUE_3; break; case 4: value = VALUE_4; break; case 5: value = VALUE_5; break; case 6: value = VALUE_6; break; default: break; } Or something like this: const uint8_t INPUT_TO_VALUE_TABLE[N_VALUE] = { VALUE_0, VALUE_1, VALUE_2, VALUE_3, VALUE_4, VALUE_5, VALUE_6, } ... ... value = INPUT_TO_VALUE_TABLE[input]; I have shown a dummy example, but I have also the code for using a switch calling different functions or a function pointer table. The code is for is for a 8bits micro (I don'w know if it makes any difference for this topic). A: Well, you should consider disassembling the compiled code to see what's actually getting generated, but I'd expect that you end up with less code in the second case, and there's less branching. In the first case, there are seven assignment statements, and a bunch of jumps (out of the switch statement). In the second, there's one array reference, and one assignment. Since your cases are all contiguous, it's easy to handle the default case: value = ( input < 6 ) ? INPUT_TO_VALUE_TABLE[input] : default_value; Let's look at some assembly. This is compiled with gcc -S, version 4.6.3, so it's not the same as the assembly you'd get, but we should getting the same general kind of result. This answer won't absolutely answer the question of which will be better in your case; you'll have to do some tests on your own, but it looks pretty sure that the table is going to be preferable. The switch option: We'll start with the switch: void switch_input( int input ) { switch(input) { case 0: value = VALUE_0; break; case 1: value = VALUE_1; break; case 2: value = VALUE_2; break; case 3: value = VALUE_3; break; case 4: value = VALUE_4; break; case 5: value = VALUE_5; break; case 6: value = VALUE_6; break; default: value = VALUE_DEFAULT; break; } } This has lots of jumps in it, as there are seven different assignments, and based on the value of input, we have to be able to jump to each one, and then jump to the end of the switch. switch_input: .LFB0: .cfi_startproc pushq %rbp .cfi_def_cfa_offset 16 .cfi_offset 6, -16 movq %rsp, %rbp .cfi_def_cfa_register 6 movl %edi, -4(%rbp) cmpl $6, -4(%rbp) ja .L2 movl -4(%rbp), %eax movq .L10(,%rax,8), %rax jmp *%rax .section .rodata .align 8 .align 4 .L10: .quad .L3 .quad .L4 .quad .L5 .quad .L6 .quad .L7 .quad .L8 .quad .L9 .text .L3: movl $0, value(%rip) jmp .L1 .L4: movl $1, value(%rip) jmp .L1 .L5: movl $2, value(%rip) jmp .L1 .L6: movl $3, value(%rip) jmp .L1 .L7: movl $4, value(%rip) jmp .L1 .L8: movl $5, value(%rip) jmp .L1 .L9: movl $6, value(%rip) jmp .L1 .L2: movl $-1, value(%rip) nop .L1: popq %rbp .cfi_def_cfa 7, 8 ret .cfi_endproc The table option The table option can use just a single assignment, and instead having lots of code that we can jump to, we just need a table of values. We don't need to jump into that table, either; we just need to compute an index, and then unconditionally load a value from it. void index_input( int input ) { value = ( input < N_VALUE ) ? INPUT_TO_VALUE_TABLE[input] : VALUE_DEFAULT; } (Yes, we really should be using an unsigned integer there so that we know it won't be less than zero.) index_input: .LFB1: .cfi_startproc pushq %rbp .cfi_def_cfa_offset 16 .cfi_offset 6, -16 movq %rsp, %rbp .cfi_def_cfa_register 6 movl %edi, -4(%rbp) cmpl $5, -4(%rbp) jg .L13 movl -4(%rbp), %eax cltq movl INPUT_TO_VALUE_TABLE(,%rax,4), %eax jmp .L14 .L13: movl $-1, %eax .L14: movl %eax, value(%rip) popq %rbp .cfi_def_cfa 7, 8 ret .cfi_endproc Appendix The C code (example.c) int value; #define N_VALUE 7 #define VALUE_0 0 #define VALUE_1 1 #define VALUE_2 2 #define VALUE_3 3 #define VALUE_4 4 #define VALUE_5 5 #define VALUE_6 6 #define VALUE_DEFAULT -1 void switch_input( int input ) { switch(input) { case 0: value = VALUE_0; break; case 1: value = VALUE_1; break; case 2: value = VALUE_2; break; case 3: value = VALUE_3; break; case 4: value = VALUE_4; break; case 5: value = VALUE_5; break; case 6: value = VALUE_6; break; default: value = VALUE_DEFAULT; break; } } const int INPUT_TO_VALUE_TABLE[N_VALUE] = { VALUE_0, VALUE_1, VALUE_2, VALUE_3, VALUE_4, VALUE_5, VALUE_6 }; void index_input( int input ) { value = ( input < 6 ) ? INPUT_TO_VALUE_TABLE[input] : VALUE_DEFAULT; } The assembly (example.s) Generated by gcc -S. .file "example.c" .comm value,4,4 .text .globl switch_input .type switch_input, @function switch_input: .LFB0: .cfi_startproc pushq %rbp .cfi_def_cfa_offset 16 .cfi_offset 6, -16 movq %rsp, %rbp .cfi_def_cfa_register 6 movl %edi, -4(%rbp) cmpl $6, -4(%rbp) ja .L2 movl -4(%rbp), %eax movq .L10(,%rax,8), %rax jmp *%rax .section .rodata .align 8 .align 4 .L10: .quad .L3 .quad .L4 .quad .L5 .quad .L6 .quad .L7 .quad .L8 .quad .L9 .text .L3: movl $0, value(%rip) jmp .L1 .L4: movl $1, value(%rip) jmp .L1 .L5: movl $2, value(%rip) jmp .L1 .L6: movl $3, value(%rip) jmp .L1 .L7: movl $4, value(%rip) jmp .L1 .L8: movl $5, value(%rip) jmp .L1 .L9: movl $6, value(%rip) jmp .L1 .L2: movl $-1, value(%rip) nop .L1: popq %rbp .cfi_def_cfa 7, 8 ret .cfi_endproc .LFE0: .size switch_input, .-switch_input .globl INPUT_TO_VALUE_TABLE .section .rodata .align 16 .type INPUT_TO_VALUE_TABLE, @object .size INPUT_TO_VALUE_TABLE, 28 INPUT_TO_VALUE_TABLE: .long 0 .long 1 .long 2 .long 3 .long 4 .long 5 .long 6 .text .globl index_input .type index_input, @function index_input: .LFB1: .cfi_startproc pushq %rbp .cfi_def_cfa_offset 16 .cfi_offset 6, -16 movq %rsp, %rbp .cfi_def_cfa_register 6 movl %edi, -4(%rbp) cmpl $5, -4(%rbp) jg .L13 movl -4(%rbp), %eax cltq movl INPUT_TO_VALUE_TABLE(,%rax,4), %eax jmp .L14 .L13: movl $-1, %eax .L14: movl %eax, value(%rip) popq %rbp .cfi_def_cfa 7, 8 ret .cfi_endproc .LFE1: .size index_input, .-index_input .ident "GCC: (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3" .section .note.GNU-stack,"",@progbits
{ "pile_set_name": "StackExchange" }
Q: Can a checkable Qstandard item be centered within a QStandardItemModel column? I have a table class with a column of check boxes. I'd like to center these within the column but using item.setTextAlignment(Qt.AlignCenter) doesn't work. from PyQt5.QtWidgets import * from PyQt5.QtCore import (QDate, QDateTime, QRegExp, QSortFilterProxyModel, Qt, QTime, QModelIndex, QSize, pyqtSignal, QObject) from PyQt5.QtGui import QStandardItemModel, QIcon, QStandardItem class Table(QWidget): def __init__(self, parent=None): QWidget.__init__(self, parent) self.initUI() self.show() def initUI(self): mainLayout = QVBoxLayout() self.proxyModel = QSortFilterProxyModel() self.proxyModel.setDynamicSortFilter(True) self.sourceModel = QStandardItemModel(0, 2, self) self.sourceModel.setHeaderData(0, Qt.Horizontal, '') self.sourceModel.setHeaderData(1, Qt.Horizontal, 'Value') self.proxyModel.setSourceModel(self.sourceModel) self.proxyGroupBox = QGroupBox('data') self.proxyView = QTreeView() self.proxyView.setRootIsDecorated(False) self.proxyView.setAlternatingRowColors(True) self.proxyView.setModel(self.proxyModel) self.proxyView.setEditTriggers(QAbstractItemView.NoEditTriggers) proxyLayout = QGridLayout() proxyLayout.addWidget(self.proxyView, 0, 0, 1, 3) self.proxyGroupBox.setLayout(proxyLayout) mainLayout.addWidget(self.proxyGroupBox) self.setLayout(mainLayout) for i in range(5): self.proxyView.resizeColumnToContents(0) item = QStandardItem(True) item.setCheckable(True) item.setCheckState(False) #item.setTextAlignment(Qt.AlignCenter) self.sourceModel.setItem(i, 0, item) self.sourceModel.setData(self.sourceModel.index(i, 1), i+1) def setSourceModel(self, model): self.proxyModel.setSourceModel(model) if __name__=='__main__': import sys app = QApplication(sys.argv) window = Table() sys.exit(app.exec_()) Is there anyway to center each item of the first column? A: If you want to change the alignment of the checkbox then you must use a QProxyStyle: class CheckBoxProxyStyle(QProxyStyle): def subElementRect(self, element, option, widget): rect = super().subElementRect(element, option, widget) if element == QStyle.SE_ItemViewItemCheckIndicator: rect.moveCenter(option.rect.center()) return rect self.proxyView = QTreeView() self.proxyView.setStyle(CheckBoxProxyStyle(self.proxyView.style()))
{ "pile_set_name": "StackExchange" }
Q: Adding Constraint to Paragraph field I have a Content Type with a field that references 6 different paragraph types. The field is set up to accept unlimited values. For one of the types I would like to have exactly four values added. I've been trying to add a Constraint but it seems that Constraints are built to check if a fields values are valid and not if there are only four items Is using hook_entity_bundle_field_info_alter the correct hook or should I be focused on using hook_entity_type_alter or maybe even some other method? A: Yes, use hook_entity_bundle_field_info_alter and when you add a constraint to the field (and not to a item or property), your constraint gets the entire field item list, so you can check how many items you have of which type, see FieldConfigInterface::addConstraint: function mymodule_entity_bundle_field_info_alter(&$fields, \Drupal\Core\Entity\EntityTypeInterface $entity_type, $bundle) { if ($entity_type->id() == 'node' && $bundle == 'page') { $fields['field_paragraph']->addConstraint('MymoduleParagraphTypes'); } } Example for a constraint restricting the field to four paragraph items of a specific type: public function validate($items, Constraint $constraint) { $paragraphs = array_filter($items->referencedEntities(), function ($paragraph) { return $paragraph->bundle() === 'image'; }); if (!empty($paragraphs) && count($paragraphs) != 4) { $this->context->addViolation($constraint->errorMessage); } } You can generate the constraint with the Drush command: drush generate plugin-constraint
{ "pile_set_name": "StackExchange" }
Q: Function bounds in gnuplot I want to plot multiple bounded functions in gnuplot. I.e. plot x from 0 to 2 and x^2 from 1 to 3 and have them show up together. How do you plot functions with different bounds? I know how to do a piecewise function, like (x < 1 ? x : x**2). This is not what I want to do. A: plot 0 <= x && x <= 2 ? x : 1/0, \ 1 <= x && x <= 3 ? x**2 : 1/0 We need to define what to draw outside the desired range, so we just use an undefined function f(x)=1/0 so that nothing is graphed in these ranges.
{ "pile_set_name": "StackExchange" }
Q: Calling a Javascript function from Wicket I want to pass the output of a block of javascript code in html to its corresponding wicket component. I tried AbstractDefaultAjaxBehaviour and it doesn't seem to work. Here's what I'm working with: HTML // In <body> <div wicket:id="container"> <script type="text/javascript" wicket:id="channelScript"> function initChannel() { window.alert('got it'); } </script> </div> private WebMarkupContainer container = new WebMarkupContainer("container"); private Label channelScript = new Label("channelScript", "initChannel();"); add(container); final AbstractDefaultAjaxBehavior channel = new AbstractDefaultAjaxBehavior() { protected void respond(final AjaxRequestTarget target) { channelScript.setEscapeModelStrings(false); target.add(channelScript); // initChannel is not triggerred } }; container.add(channel); I also tried this: add(new AjaxEventBehavior("onload") { @Override protected void onEvent(AjaxRequestTarget target) { channelScript.setEscapeModelStrings(false); target.add(new Label(channelScript)); } } Please what am I doing wrong? Thanks UPDATE I will be passing series of variables from wicket to JS such that every javascript output is displayed using wicket component. I just realized that I will have to make do with dom ready state to begin the interaction. So that's fine. But then I'm still confused and clueless about how the wicket component will change state to receive updated response from javascript. Is there a wicket component that triggers itself asynchronously? A: Don't use a Label as script container. Wicket has some proper ways to do that. The following code would be on option (assuming that you are on wicket 1.5) @Override public void renderHead(final Component component, final IHeaderResponse response) { super.renderHead(component, response); response.renderJavaScript("initChannel();", "myScriptID"); } If you want to perform a script after you site was fully loaded, you can use this: response.renderOnLoadJavaScript("doSomething();"); In wicket 1.4 this works differently. You have to use HeaderContributors there.
{ "pile_set_name": "StackExchange" }
Q: Are all metric translations isometries Let $(M, d)$ be a metric space. I define a translation of $M$ to be a function $f$ from $M$ to $M$ such that $d(x, f(x)) = d(y, f(y))$ for all $x$ and $y$ in $M$. My conjecture is that every translation on $M$ is an isometry under the same metric. Can anyone prove this, or give me a counterexample? A: If we don't require continuity of $f$, we have a counterexample $f\colon \mathbb{R}\to\mathbb{R}$ with $$f(x) = \begin{cases}x + 1 &, x \in \mathbb{Q}\\ x-1 &, x \notin\mathbb{Q}.\end{cases}$$ For continuous $f$, we get a counterexample by considering a discrete metric space $(M,d)$, with $d(x,y) = 1$ for $x\neq y$, that contains at least three points. Let $x_0,x_1$ be two distinct points, and $$f(x) = \begin{cases}x_0 &, x \neq x_0\\ x_1 &, x = x_0. \end{cases}$$ Then $d(x,f(x)) = 1$ for all $x$, but $d(f(x),f(y)) = 0$ for all $x,y \in M\setminus \{x_0\}$.
{ "pile_set_name": "StackExchange" }
Q: Is it possible to overload contract actions? I had a method: -- t.hpp -- [[eosio::action]] void exchange(); -- t.cpp -- void token::exchange() { ... } EOSIO_DISPATCH(eosio::token, (exchange)) and then decided that if a parameter were passed, I'd want to do something different, so I added: -- t.hpp -- [[eosio::action]] void exchange(); [[eosio::action]] void exchange(asset auction); -- t.cpp -- void token::exchange() { ... } void token::exchange(asset auction) { ... } EOSIO_DISPATCH(eosio::token, (exchange)) but this produces an error: t.cpp:378:1: error: no matching function for call to 'execute_action' EOSIO_DISPATCH(eosio::token, (exchange)) can I not do this? or if I can, how is it done? A: Non-variant actions aren't overloadable. If you need actions with different behavior, then give them different names. Variant actions aren't ready for general use. They have (undocumented) methods of declaring them, and client code needs to pack them into transactions in a different way than normal.
{ "pile_set_name": "StackExchange" }
Q: Complex number calculation I'm supposed to show $ z^{10} $, when z = $ \frac{1+ \sqrt{3i} }{1- \sqrt{3i} } $ I can work it out to $ \frac{(1+\sqrt{3}\sqrt{i})^{10}}{(1-\sqrt{3}\sqrt{i})^{10}} $ However this is inconclusive because I need to show $ z^{10} $ in the form x+yi, and I can't figure out the real and imaginary parts from from this answer because of the exponent. What must I do? A: Hint First you should obtain the polar form of $z$, $$z = r e^{i\varphi}$$ For $\varphi\in[0,2\pi)$ and $r>0$ real. Then $$z^{10} = r^{10} e^{i10\varphi}$$ Where you can simplify $10\varphi\!\!\! \mod\! 2\pi$.
{ "pile_set_name": "StackExchange" }
Q: Does NP-hardness imply P-hardness? If a problem is NP-hard (using polynomial time reductions), does that imply that it is P-hard (using log space or NC reductions)? It seems intuitive that if it is as hard as any problem in NP that it should be as hard as any problem in P, but I don't see how to chain the reductions and get a log space (or NC) reduction. A: No such implication is known. In particular it may be that $L \ne P = NP$ in which case all problems (including trivial ones) are NP-hard under poly-time reductions (as the reduction can just solve the problem), but trivial ones (in particular ones that lie in L) are surely not P-hard under logspace reductions (as otherwise L=P). The same goes for NC instead of L.
{ "pile_set_name": "StackExchange" }
Q: Exclude first row filtering JTable I got a problem when filtering my JTable. In fact, on my first row I have JComboBoxes in each column. And when I sort which the items of JCombo the first row is also being filtered and disappear. Here is my Table model: public static class MyModel extends AbstractTableModel { private static final long serialVersionUID = -768739845735375515L; private List<Object[]> data; private List<String> columnNames; public MyModel(List<String> columnNames, List<Object[]> data) { super(); this.columnNames = columnNames; this.data = data; } @Override public int getRowCount() { return data.size(); } @Override public int getColumnCount() { return columnNames.size(); } @Override public String getColumnName(int column) { return columnNames.get(column); } @Override public Object getValueAt(int rowIndex, int columnIndex) { return data.get(rowIndex)[columnIndex]; } @Override public boolean isCellEditable(int row, int col) { // Pour modifier uniquement la cellule Statut if (row == 0) { return true; } else { return false; } } public void setValueAt(Object value, int row, int col) { data.get(row)[col] = value; fireTableCellUpdated(row, col); } public void removeRow(int row) { data.remove(row); } } And the combo listener : private void ComboListener(final JComboBox comboBox){ comboBox.addActionListener( new ActionListener(){ public void actionPerformed(ActionEvent e){ try{ String selectedItem = comboBox.getSelectedItem().toString(); sorter.setRowFilter(RowFilter.regexFilter(selectedItem)); }catch(Exception ex){} } } ); } A: I'm assuming you're talking about filtering, not sorting, based on your current code. You could make use of the int.. indices argument when creating your filter: int[] indices = new int[yourModel.getRowCount() -1]; for (int i = 0; i < indices.length; i++) { indices[i] = i+1; } sorter.setRowFilter(RowFilter.regexFilter(selectedItem, indices)); This will cause your filter to apply to all the rows except row 0.
{ "pile_set_name": "StackExchange" }
Q: Angular Resource Encoding URL I have a resource defined as follows: app.factory("DatumItem", function($resource) { return $resource('/data/:id', {id: '@id'}); }); In my view I have: <div ng-click="go('/datum/' + d.to_param)">Test</div> where go() is defined in my controller as: $scope.go = function (params) { $location.path(params); }; For the item in question, d.param is equal to TkZUOWZwcnc9Uldo%0ASzRvd2FiWk But when I call DatumItem.get() with the correct ID, it is changing the id to TkZUOWZwcnc9Uldo%250ASzRvd2FiWk Is there a way to prevent the % from being encoded to a %25 in this case? I've tried a combination of using encodeURI, encodeURIComponent to no avail. any help would be greatly appreciated, thanks! A: Since the URL is already URIencoded you need to decode it before passing it to angular: $scope.go = function (params) { $location.path(decodeURIComponent(params)); };
{ "pile_set_name": "StackExchange" }
Q: How to convert char to integer in C? Possible Duplicates: How to convert a single char into an int Character to integer in C Can any body tell me how to convert a char to int? char c[]={'1',':','3'}; int i=int(c[0]); printf("%d",i); When I try this it gives 49. A: In the old days, when we could assume that most computers used ASCII, we would just do int i = c[0] - '0'; But in these days of Unicode, it's not a good idea. It was never a good idea if your code had to run on a non-ASCII computer. Edit: Although it looks hackish, evidently it is guaranteed by the standard to work. Thanks @Earwicker. A: The standard function atoi() will likely do what you want. A simple example using "atoi": #include <unistd.h> int main(int argc, char *argv[]) { int useconds = atoi(argv[1]); usleep(useconds); }
{ "pile_set_name": "StackExchange" }
Q: Nested ScrollViews not displaying properly I have come across a small problem whilst trying to implement a pair of nested scroll views. I have managed to implement them however the images i have do not seem to be displaying properly. They were fine individually, but with the scroll views nested the frames seem to change size and position. and here is some of my code to possibly demonstrate what i am doing wrong. - (void)loadView { { CGRect baseScrollViewFrame = [self frameForBaseScrollView]; baseScrollView = [[UIScrollView alloc] initWithFrame:baseScrollViewFrame]; [baseScrollView setBackgroundColor:[UIColor blackColor]]; [baseScrollView setCanCancelContentTouches:NO]; baseScrollView.indicatorStyle = UIScrollViewIndicatorStyleWhite; baseScrollView.showsVerticalScrollIndicator = NO; baseScrollView.showsHorizontalScrollIndicator = YES; baseScrollView.scrollEnabled = YES; baseScrollView.pagingEnabled = YES; //baseScrollView.delaysContentTouches = NO; baseScrollView.userInteractionEnabled = YES; baseScrollView.contentSize = CGSizeMake(baseScrollViewFrame.size.width * [self imageCount], baseScrollViewFrame.size.height); baseScrollView.delegate = self; self.view = baseScrollView; [baseScrollView release]; This is for the base HORIZONTAL scroll view CGRect pagingScrollViewFrame = [self frameForPagingScrollView]; pagingScrollView = [[UIScrollView alloc] initWithFrame:pagingScrollViewFrame]; pagingScrollView.pagingEnabled = YES; pagingScrollView.backgroundColor = [UIColor blackColor]; [pagingScrollView setCanCancelContentTouches:NO]; pagingScrollView.indicatorStyle = UIScrollViewIndicatorStyleWhite; pagingScrollView.showsVerticalScrollIndicator = YES; pagingScrollView.showsHorizontalScrollIndicator = NO; pagingScrollView.scrollEnabled = YES; pagingScrollView.contentSize = CGSizeMake(pagingScrollViewFrame.size.width, pagingScrollViewFrame.size.height * [self imageCount]); pagingScrollView.delegate = self; [baseScrollView addSubview:pagingScrollView]; This is for the paging VERTICAL scroll view. Please someone, tell me what i am doing wrong. Thanks alot A: Perhaps looks at the delegate methods that you are implementing. You are setting the delegate of both scrollview's to "self". In these methods, are you checking to see which scrollview called it? It also seems a bit odd that you are setting BOTH the height and width according to imageCount. If image count were 10 for example, you would have 100 pages (10 pages wide by 10 pages tall).
{ "pile_set_name": "StackExchange" }
Q: echo a True conditional statement out of many in php I have an array. if ( $date_month == $months['1'] || $date_month == $months['2'] || $date_month == $months['3'] || $date_month == $months['4'] || $date_month == $months['5'] || $date_month == $months['6'] || $date_month == $months['7'] || $date_month == $months['8'] || $date_month == $months['9'] || $date_month == $months['10'] || $date_month == $months['11'] || $date_month == $months['12'] ) { echo "its true"; }else{ echo "its false"; } I want to echo the value of the one thats true. Currently I have to write if statements for each. Was wondering if there was a way to just echo which ever on is true in the conditional. Any help is greatly appreciated. A: You could use the PHP function: in_array(): if (in_array($month, $month_array)){ echo "Found"; }else{ echo "Not Found"; } Or you could do: if( $month_array[$month]){ echo "true"; }else{ echo "false"; }
{ "pile_set_name": "StackExchange" }
Q: how to get value of n if the value of n * log n is given? Possible Duplicate: How can I solve for $n$ in the equation $n \log n = C$? how to get value of n if the value of n * log n is given ? I am stuck with this: n log n = 6 * 10^6 how to tackle such equations ? A: If you can't solve it by inspection, it is unlikely there is a "nice" solution. In that case you can use the fact that $\log n \ll n$ and varies slowly. So in this problem, you can write it as $n=\frac {6 \cdot 10^6}{\log n}$ Then for a first guess use $n=6 \cdot 10^6$, take the log to get $6.778$, plug that in and evaluate $n$, iterating until it converges. A: In general, the equation $x \log(x) = a$ cannot be solved for $x$ in closed form in terms of elementary functions. "Elementary functions" refers to the functions formed via the composition of the basic arithmetic operations +, -, *, /, the exponential and logarithm functions, and the trigonometric functions (though the inclusion of these last functions is redundant if one uses complex numbers, due to Euler's formula.), with the composition being finite. Usually, elementary solutions are considered the best, though, as this shows, they are in many cases not possible. (There are analogies of this in other areas of mathematics -- e.g. in Euclidean geometry, constructions relying only on compass and straightedge are considered the best. Again, there are many cases in which such construction is not possible.) This is because elementary functions are simple and have numerous useful properties. That being said, if one is willing to venture outside the realm of elementary functions, one can solve this equation. One commonly used non-elementary, but still simple to describe, function is the Lambert W function, defined as the inverse of $f(x) = xe^x$. Note this is similar to a logarithm function, but not quite the same. Such an inverse is not a proper function, since $f(x) = xe^x$ is not injective, however, we usually define a "principal branch" similar to, say, square root, by inverting on the interval $[-1, \infty)$. The Lambert W-function is denoted $W(x)$. To use it to solve your equation, make the substitution $x = e^u$. EDIT: In fact, this can be used as a proof that there is no elementary solution, because this shows that if you can solve the equation, you can express the Lambert W function in terms of its solution, but we know that one is not elementary. (The proof of that is much harder, however.) However, if your $\log$ is base-10, then there is an elementary solution, namely $n = 10^6$! The form of the right-hand side makes me wonder whether a base-10 log was meant.
{ "pile_set_name": "StackExchange" }
Q: Alinhar radio button mobile Estou tendo problemas para deixar o radio button ao lado do texto. Só na versão mobile que está "quebrando" (O texto fica em cima e os radio buttom vão para a linha de baixo). Preciso que fique assim: Esse é meu código: <div class="row"> <div class="form-group col-md-12 col-sm-12"> <p align="center">Isso é um texto de exemplo :)</p> <div class="radio" > <label class="radio-inline"><input type="radio" value="Sim" name="optradio">Sim</label> <label class="radio-inline"><input type="radio" value="Não" name="optradio">Não</label> </div> </div> </div> Olha como esta ficando: Mesmo se eu diminuir o tamanho do radio ele não fica ao lado do texto :/ A: Fiz alguns pequenos acréscimos no seu código, tente sempre que possível utilizar as classes que o bootstrap disponibiliza, isso vai fazer com essas "quebras" não aconteçam. Outro ponto importante é cuidar para não utilizar essas classes em elementos inapropriados. Qualquer dúvida da uma olhada na documentação. <div class="row"> <div class="form-group col-md-12 col-sm-12"> <div class="alinhamento"> <p align="center">Isso é um texto de exemplo :)</p> <div class="radios"> <label class="radio-inline"><input type="radio" value="Sim" name="optradio">Sim</label> <label class="radio-inline"><input type="radio" value="Não" name="optradio">Não</label> </div> <input type="text" class="form-control" id="inputTest"> </div> </div> </div> Segue JsFiddle com o código.
{ "pile_set_name": "StackExchange" }
Q: Where is the web icon in the app list for? In the app list, you can press a letter to go to the right section. However, there is also an web icon at the end (right bottom). What does it do? There is never an app under this section. A: That's reserved for apps with characters not in the phone's native language, as described here.
{ "pile_set_name": "StackExchange" }
Q: Optimization of array function that calculates products I have the following array formula that calculates the returns on a particular stock in a particular year: =IF(AND(NOT(E2=E3),H2=H3),PRODUCT(IF($E$2:E2=E1,$O$2:O2,""))-1,"") But since I have 500,000 row entries as soon as I hit row 50,000 I get an error from Excel stating that my machine does not have enough resources to compute the values. How shall I optimize the function so that it actually works? E column refers to a counter to check the years and ticker values of stocks. If year is different from the previous value the function will output 1. It will also output 1 when the name of stock has changed. So for example you may have values for year 1993 and the next value is 1993 too but the name of stock is different, so clearly the return should be calculated anew, and I use 1 as an indication for that. Then I have another column that runs a cumulative sum of those 1s. When a new 1 in that previous column is encountered I add 1 to the running total and keep printing same number until I observe a new one. This makes possible use of the array function, if the column that contains running total values (E column) has a next value that is different from previous I use my twist on SUMIF but with PRODUCT IF. This will return the product of all the corresponding running total E column values. A: The source of the inefficiency, I believe, is in the steady increase with row number of the number of cells that must be examined in order to evaluate each successive array formula. In row 50,000, for example, your formula must examine cells in all the rows above it. I'm a big fan of array formulas, so it pains me to say this, but I wouldn't do it this way. Instead, use additional columns to compute, in each row, the pieces of your formula that are needed to return the desired result. By taking that approach, you're exploiting Excel's very efficient recalculation engine to compute only what's needed. As for the final product, compute that from a cumulative running product in an auxiliary column, and that resets to the value now in column O when column P in the row above contains a number. This approach is much more "local" and avoids formulas that depend on large numbers of cells. I realize that text is not the best language for describing this, and my poor writing skills might be adding to the challenge, so please let me know if more detail is needed. Interesting problem, thanks.
{ "pile_set_name": "StackExchange" }
Q: Always show function keys on control strip when using terminal I would like to show the function keys when using the terminal app. However, when I use system preferences to try to set this up in Keyboard Shortcuts, the Terminal app is not selectable. Screenshots: A: The reason for this is that Apple doesn't seem to treat its Terminal app in the same way as other apps in terms of permanently setting Functions keys in the Touch Bar. Instead, you need to follow these steps: Launch the Terminal app Go to View > Customize Touch Bar Drag the Function keys onto the Touch Bar Click Done Another option is to use another app as your terminal (such as iTerm2) and follow the usual steps for permanently setting the Function keys on the Touch Bar. Based on your screenshots, it seems you know the steps for doing this, but just to be sure and for the benefit of others: Go to Apple > System Preferences Select the Keyboard preference pane Click on the Shortcuts tab In the left sidebar, select the Function Keys option On the right-hand side click on the plus + button Search for the app you want to use (e.g. iTerm2) Add the app Now, whenever you are using the app, the Touch Bar should display all the function keys.
{ "pile_set_name": "StackExchange" }
Q: Convert normal, infix expression to arraylist of tokens I want to convert something like 233 + 4 *(4-8) +5 to [233,+,4,*,(,4,-,8,),+,5] Where the latter is an array of Strings. So far I have: String s = "233 + 4 *(4-8) +5"; for(int i = 0; i<s.length(); i++) { int j = i + 1; String sub = s.substring(i,j); String checkdigit = s.substring(i,j); while(checkdigit.matches("\\d|\\.") && j<s.length()) { checkdigit = s.substring(j,j+1); j++; } System.out.print(sub); if(!sub.equals(" ")) expression.add(sub); } But I'm getting null pointer exceptions. Can someone help me correct this? Also if anyone could help me parse this so that it accepted negative values (like -5) as well that would be helpful. Edit: By the way the . is for doubles (like 5.0) Edit 2: If anyone knows any Java API classes that can replace my code, please show how I could replace my code with them. A: Parsing an arithmetic expression is a bit more complicated than it seems first (for example it is difficult to distinguish between a minus mark and a negative number). While you can write your own parser, I recommend you to use a general parser (e.g. ANTLR or JavaCC) by providing your desired grammar to it or to look for a simpler arithmetic-specific library (e.g. JEP or some open-source equivalent). Here is a link which help you to use ANTLR to parse a arithmetic expression: http://www.antlr.org/wiki/display/ANTLR3/Five+minute+introduction+to+ANTLR+3
{ "pile_set_name": "StackExchange" }
Q: The magnetic field of a magnetic monopole Let us define the magnetic field $$\vec{B} = g\frac{\vec{r}}{r^3}$$ for some constant $g$. How can we show that the divergence of this field correspond to the charge distribution of a single magnetic pole (monopole)? EDIT: If I calculate the divergence I get $$ \begin{align} \nabla\cdot\vec{B} &= \nabla\cdot\left(g\frac{\vec{r}}{r^3}\right) \\ &= g\left(\nabla\frac{1}{r^3}\right)\cdot\vec{r}+\frac{g}{r^3}\left(\nabla\cdot\vec{r}\right)\\ &=g\left(-3\frac{\vec{r}}{r^5}\right)\cdot\vec{r}+\frac{g}{r^3}(1+1+1)\\ &=-3g\frac{1}{r^3}+3g\frac{1}{r^3}\\ &= 0 \end{align} $$ which contradicts that there is a sink or source of magnetic flux. A: For each $r>0$, the divergence of the magnetic field of the monopole is zero as you have already checked; \begin{align} \nabla\cdot\mathbf B(\mathbf x) = 0, \qquad \text{for all $\mathbf x\neq \mathbf 0$}. \end{align} But what if we also want to find the divergence of this field at the origin? After all, that is where the point source sits. We might expect that there is some sense in which the divergence there should be nonzero to reflect the fact that there is a point source sitting there. The problem is that the magnetic field is singular there, and the standard divergence is therefore not defined there. However, in electrodynamics, we get around this by interpreting the fields not merely as functions $\mathbf E,\mathbf B:\mathbb R^3\to\mathbb R^3$, namely ordinary vector fields in three dimensions, but as distributions (aka generalized functions). As as it turns out, when we do this, there is a sense in which the magnetic field you wrote down has nonzero divergence at the origin (in fact the divergence is "infinite" there). I'll leave it to you to investigate the details, but the punchline is that you need something called the distributional derivative to perform the computation rigorously. Physicists often perform the distributional derivative of the monopole field by "regulating" the singularity at the origin, but this is not necessary. Whichever method you use, the result you're looking for is \begin{align} \nabla\cdot\frac{\mathbf x}{|\mathbf x|^3} = 4\pi\delta^{(3)}(\mathbf x) \end{align} where $\delta^{(3)}$ denotes the delta distribution in three Euclidean dimensions. Applying this to the magnetic monopole field, we see that its divergence corresponds to a magnetic charge density that looks like the delta distribution; this is precisely the behavior expected of a monopole. Addendum. Since user PhysiXxx has posted the procedure for proving the identity I claim above by using the regularization procedure to which I referred, I suppose I might as well show how you prove the identity when it is interpreted in the sense of distributions. A distribution is a linear functional that acts on so-called test functions and outputs real numbers. To view a sufficiently well-behaved function $f:\mathbb R^3\to\mathbb R$ as a distribution, we need to associate a linear function $T_f$ to it. The standard way of doing this is to define \begin{align} T_f[\phi] = \int _{\mathbb R^3} d^3x\, f(\mathbf x) \phi(\mathbf x). \end{align} The delta distribution centered at a point $\mathbf a\in\mathbb R^3$ cannot be described as a distribution associated to a function $f$ in this way, instead, it is defined as \begin{align} \delta_{\mathbf a}^{(3)}[\phi] = \phi(\mathbf a) \end{align} Physicists will often write this as \begin{align} \delta_{\mathbf a}^{(3)}[\phi] = \int_{\mathbb R^3}d^3 x\, \delta^{(3)}(\mathbf x - \mathbf a)\phi(\mathbf x) \end{align} as if there is a function that generates the delta distribution, even though there isn't, because it makes formal manipulations easier. Now, consider the function \begin{align} h(\mathbf x) = \nabla\cdot\frac{\mathbf x}{|\mathbf x|^2} \end{align} I claim that if we use the expression $T_h$ with which to associate a distribution with $h$, then, $T_h = -4\pi \delta_{\mathbf 0}$. To prove this, it suffices to show that $T_h[\phi] = -4\pi\phi(\mathbf 0)$ for all test functions $\phi$. To this end, we note that \begin{align} T_h[\phi] &= \int_{\mathbb R^3} d^3 x\, \left(\nabla\cdot\frac{\mathbf x}{|\mathbf x|^3}\right) \phi(\mathbf x) \\ &= \int_{\mathbb R^3} d^3 x\, \nabla\cdot\left(\frac{\mathbf x}{|\mathbf x|^3} \phi(\mathbf x)\right) - \int_{\mathbb R^3} d^3 x\, \frac{\mathbf x}{|\mathbf x|^3}\cdot \nabla\phi(\mathbf x) \end{align} The first integral vanishes because, by Stoke's theorem (aka the divergence theorem in 3D), it is a boundary term, but in this case, the boundary is at infinity, and the thing of which we are taking the divergence is assumed to vanish rapidly at infinity (this is part of the definition of test functions). For the second integral, we use spherical coordinates. In spherical coordinates, we can write \begin{align} d^3 x = r^2\sin\theta dr\,d\theta\,d\phi, \qquad \frac{\mathbf x}{|\mathbf x|^3} = \frac{\hat{\mathbf r}}{r^2}, \qquad (\nabla\phi)_r = \ \frac{\partial\phi}{\partial r} \end{align} Combining these observations with algebraic some simplifications gives the desired result: \begin{align} T_h[\phi] &= - \int_0^{2\pi}d\phi\int_0^\pi d\theta\int_0^\infty dr \frac{\partial\phi}{\partial r}(r,\theta,\phi) = -4\pi \phi(\mathbf 0) \end{align} In the last step we used the fundamental theorem of calculus, the fact that $\phi$ vanishes as $r\to\infty$ and the fact that when $r\to 0$, the average value of a function over the sphere of radius $r$ becomes its value at the origin, namely \begin{align} \lim_{r\to 0} \frac{1}{4\pi}\int_0^{2\phi}d\theta\int_0^\pi d\phi\, \phi(r,\theta, \phi) = \phi(\mathbf 0) \end{align} A: The joshpysics's answer is good. I'm only want to tell about some details. Let's have field $$ \mathbf A = g\frac{\mathbf r}{|\mathbf r|^{3}}. \qquad (.1) $$ It has singularity at zero. We can eliminate it by modification $(.1)$ by $$ \mathbf A = g\frac{\mathbf r}{|\mathbf r|^{3}} \to g\frac{\mathbf r}{(r^{2} + a^{2})^{\frac{3}{2}}}. $$ Then we can take derivative in each point of a field. After taking derivative we can set $a$ to zero. For example, $$ (\nabla \cdot \mathbf A ) = \frac{3g}{(r^{2} + a^{2})^{\frac{3}{2}}} - \frac{3gr^{2}}{(r^{2} + a^{2})^{\frac{5}{2}}} = \frac{3ga^{2}}{(r^{2} + a^{2})^{\frac{5}{2}}} = 4 \pi g \delta_{a}(\mathbf r) = 4 \pi \rho_{a}(\mathbf r), $$ where $$ \delta_{a}(\mathbf r) = \frac{3}{4 \pi}\frac{a^{2}}{\left( r^{2} + a^{2}\right)^{\frac{5}{2}}} $$ have the properties of Dirac delta: when $a$ sets to zero, $$ \lim_{r \to 0}\delta_{a}(\mathbf r ) = \infty, \quad \lim_{r \to r_{0} \neq 0}\delta_{a}(\mathbf r ) = 0, $$ and $$ \int \limits_{-\infty}^{\infty}\delta_{a}(\mathbf r)d^{3}\mathbf r = 1, $$ which is easy verified. This procedure is called regularization. It is convenient for describing the field of point-like charge. Another interesting fact. We can derive Maxwell equations using only Coulomb law, superposition principle and Special relativity (which can be formulated by using some simple postulates (postulates of homogeneous space-time, isotropic space, relativity principle and the principle of causality)). A: The distribution approach nicely described by joshphysics and PhysiXxx wholly answer your question and show why your proof doesn't work, but there another way to reason with the correct part of your proof. It is, of course, ultimately mathematically equivalent. Simply work out the flux through a spherical shell $\mathcal{S}$ centred on the origin; from the problem's symmetry we get: $$\oint_\mathcal{S} \mathbf{B} \cdot \hat{\mathbf{r}} \, \mathrm{d} S = 4\,\pi\,R^2\,g\frac{R}{R^3}= 4\,\pi\,g$$ This is the magnetic charge within a shell of radius $R$. Now, your proof, as stated elsewhere, fails at the origin, but it does work everywhere else. So this tells you, by the divergence theorem, that there is no charge inside any arbitrary closed, orientable surface not containing the origin and also by the divergence theorem, the above result holds for any surface of the same homotopy class (with respect to $\mathbb{R}^3 \sim {0}$ i.e. Euclidean 3-space with the origin taken away) as the spherical shell: otherwise put: any surface that can be gotten as a continuous deformation of the sphere $\mathcal{S}$ that does not pass any part of the surface through the origin. So therefore the charge must be wholly contained within any spherical shell of radius $\epsilon > 0$, no matter how small $\epsilon$ may be. In everyday words - the charge is wholly concentrated at the origin.
{ "pile_set_name": "StackExchange" }
Q: Class name isn't being inserted on hover I am trying to insert animated fadeIn when the user hovers over the div with a class of project-title-wrapper. I only want the instance they are hovering over to change. My current code is: $(function() { var animationName = 'animated fadeIn'; var animationEnd = 'webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend'; $('.project-title-wrapper').on('hover', function() { $('.project-title-wrapper').addClass(animationName).one(animationEnd, function() { $(this).removeClass(animationName); }); }); }); This doesn't work. I also tried: $(function() { var animationName = 'animated fadeIn'; var animationEnd = 'webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend'; $('.project-title-wrapper').hover(function() { $('.project-title-wrapper').addClass(animationName).one(animationEnd, function() { $(this).removeClass(animationName); }); }); }); However, this changes every instance Thanks in advance A: Try using the this keyword to get just the hovered instance. $('.project-title-wrapper').hover(function() { $(this).addClass(animationName).one(animationEnd, function() { $(this).removeClass(animationName); }); }); I'd also change out the .hover method for a more simple .on('mouseenter') as using the .hover method triggers on both mouseenter and mouseout which means the class will get added when the user stops hovering as well (leading to some interesting behavior when the user hovers over a thing, pauses until the animation ends, and then hovers over the next thing). Further, as I cannot see a reason to constantly bind and unbind the animationEnd handlers, I'd write it like this: $('.project-title-wrapper').on(animationEnd, function() { $(this).removeClass(animationName); }).on('mouseenter', function() { $(this).addClass(animationName); }); $(function() { var animationName = 'animated fadeIn'; var animationEnd = 'webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend'; $('.project-title-wrapper').on(animationEnd, function() { $(this).removeClass(animationName); }).on('mouseenter', function() { $(this).addClass(animationName); }); }); .project-title-wrapper { background-color: #060; height: 3em; opacity: 0.5; } .project-title-wrapper.animated.fadeIn { animation-duration: 1s; animation-name: fadeIn; } @keyframes fadeIn { from { background-color: #060; opacity: 0.5; } to { background-color: #0D0; opacity: 1; } } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="project-title-wrapper">First</div> <div class="project-title-wrapper">Second</div> <div class="project-title-wrapper">Third</div>
{ "pile_set_name": "StackExchange" }
Q: Binding a static library into a Xamarin iOS project I've decided to take a step back and just try to get a very simple proof of concept to work. I've progressed a little further thanks to one of the Xamarin Lightning Lectures around this topic. I’ve been following this tutorial: https://university.xamarin.com/lightninglectures/ios-bindings-in-cc Here’s what I’ve done so far: 1) I have a simple C file “example.c” with 3 functions: addOne(int n), subtractOne(int n), get_time() 2) As shown in the tutorial, I used SWIG to create a C wrapper class - “example_wrap.c” (along with the C# wrapper classes). 3) I created the static library in Xcode and built a FAT binary with all architectures (lipo used to combine libs). The tutorial talks about creating 2 projects - one with the C# wrapper classes and the other a single view iOS app. The iOS project has the libexample.a static library(as a BundledResource). Everything was going well until trying to build the iOS app. I can't get the iOS app to compile. I've removed any calls to the static library for now to isolate the issue....I'm just trying to get it to compile and link correctly. So all I have now is just a blank iOS app with the bundled static library. But I'm still having problems. I have the following added to the mtouch arguments: -cxx -gcc_flags "-L${ProjectDir} -lexample -force_load ${ProjectDir}/libexample.a" When compiling, I get these errors: Undefined symbols for architecture x86_64: "subtractOne(int)", referenced from: _CSharp_subtractOne in libexample.a(example_wrap.o) "addOne(int)", referenced from: _CSharp_addOne in libexample.a(example_wrap.o) "get_time()", referenced from: _CSharp_get_time in libexample.a(example_wrap.o) ld: symbol(s) not found for architecture x86_64 clang: error: linker command failed with exit code 1 (use -v to see invocation) I double checked the symbols in the libexample.a file by running “nm -arch x86_64 libexample.a” from the command line. It appears that all the symbols are listed for that architecture. Here’s a link to the zip file with my libexample.a and C files: https://drive.google.com/open?id=0B2WtJ38rvldKYmlZckU3QjNBeUE I’m sure this is just a configuration error but I can’t seem to pinpoint where I’m going wrong. Thanks. A: I thought I'd answer my own question here - after getting some help from Xamarin support, it looks like I might have mixed up how I created the static library - I had to make sure the files were compiled as 'C' files, instead of C++. After I generated the static library correctly, the compiler was able to recognize the missing symbols.
{ "pile_set_name": "StackExchange" }
Q: Subtracting a smaller data frame from a larger data-frame in R without unique row ID I have two data frames in R: Large and Small. The smaller one is contained in the larger one. Importantly, there are no unique identifiers for each row in either data frame. How can I obtain the following: Large - Small [large minus small] Small data-frame (SmallDF): ID CSF1PO CSF1PO.1 D10S1248 D10S1248.1 D12S391 D12S391.1 203079 10 11 14 16 -9 -9 203079 8 12 14 17 -9 -9 203080 10 12 13 13 -9 -9 Large data-frame (BigDF): ID CSF1PO CSF1PO.1 D10S1248 D10S1248.1 D12S391 D12S391.1 203078 -9 -9 15 15 18 20 203078 -9 -9 14 15 17 19 203079 10 11 14 16 -9 -9 203079 8 12 14 17 -9 -9 203080 10 12 13 13 -9 -9 203080 10 11 14 16 -9 -9 203081 10 12 14 16 -9 -9 203081 11 12 15 16 -9 -9 203082 11 11 13 15 -9 -9 203082 11 11 13 14 -9 -9 The small data frame corresponds to the rows 3, 4 and 5 of the larger data frame. I have tried the following. BigDF[ !(BigDF$ID %in% SmallDF$ID), ] This doesn't work because there are unique identifiers in either row. The output I get is exactly the same as BigDF. I have also tried the following. library(dplyr) setdiff(BigDF, SmallDF) The output I receive is exactly the same as BigDF. Any help would be appreciated! Thanks. A: library(dplyr) anti_join(BigDF, SmallDF) This is equivalent to: anti_join(BigDF, SmallDF, by=c("ID", "CSF1PO", "CSF1PO.1", "D10S1248", "D10S1248.1", "D12S391", "D12S391.1")) Obviously, if you had two variables which uniquely identify a row, you can specify just these variables in the vector passed to by: anti_join(BigDF, SmallDF, by=c("ID", "CSF1PO.1"))
{ "pile_set_name": "StackExchange" }
Q: Python Numpy Poisson Distribution I am generating a Gaussian, for the sake of completeness, that's my implementation: from numpy import * x=linspace(0,1,1000) y=exp(-(x-0.5)**2/(2.0*(0.1/(2*sqrt(2*log(2))))**2)) with peak at 0.5 and fwhm=0.1. So far so not interesting. In the next step I calculate the poisson distribution of my set of data using numpys random.poisson implementation. poi = random.poisson(lam=y) I'm having two major problems. A specialty of poisson is that the variance equals the exp. value, comparing the output of mean() and var() does confuse me as the outputs are not equal. When plotting this, the poisson dist. takes up integer values only and the max. value is around 7, sometimes 6, whilst my old function y has its max. at 1. Afai understand, the poisson-function should give me sort of a 'fit' of my actual function y. How come the max. values are not equal? Sorry for my mathematical incorrectness, actually I'm doing this to emulate poisson-distributed noise but I guess you understand 'fit' in this context. EDIT: 3. question: What's the 'size' variable used for in this context? I've seen different types of usage but in the end they did not give me different results but failing when choosing it wrong... EDIT2: OK, from the answer I got I think that I was not clear enough (although it already helped me correct some other stupid errors I did, thanks for that!). What I want to do is apply poisson (white) noise to the function y. As described by MSeifert in the post below, I now use the expectation value as lam. But this only gives me the noise. I guess I have some understanding problems on the level of how th{is,e} noise is applied (and maybe it's more physics related?!). A: First of all, I'll write this answer assuming you import numpy as np because it clearly distinguishes numpy functions from the builtins or those of the math and random package of python. I think it is not necessary to answer your specified questions because your basic assumption is wrong: Yes, the poisson-statistics has a mean that equals the variance but that assumes you use a constant lam. But you don't. You input the y-values of your gaussian, so you cannot expect them to be constant (they are by your definition gaussian!). Use np.random.poisson(lam=0.5) to get one random value from a poisson distribution. But be careful since this poisson distribution is not even approximately identical to your gaussian distribution because you are in the "low-mean" interval where both of these are significantly different, see for example the Wikipedia article about Poisson distribution. Also you are creating random numbers, so you shouldn't really plot them but plot a np.histogram of them. Since statistical distributions are all about probabilitiy density functions (see Probability density function). Before, I already mentioned that you create a poisson distribution with a constant lam so now it is time to talk about the size: You create random numbers, so to approximate the real poisson distribution you need to draw a lot of random numbers. There the size comes in: np.random.poisson(lam=0.5, size=10000) for example creates an array of 10000 elements each drawn from a poissonian probability density function for a mean value of 0.5. And if you haven't read it in the Wikipedia article mentioned before the poisson distribution gives by definition only unsigned (>= 0) integer as result. So I guess what you wanted to do is create a gaussian and poisson distribution containing 1000 values: gaussian = np.random.normal(0.5, 2*np.sqrt(2*np.log(2)), 1000) poisson = np.random.poisson(0.5, 1000) and then to plot it, plot the histograms: import matplotlib.pyplot as plt plt.hist(gaussian) plt.hist(poisson) plt.show() or use the np.histogram instead. To get statistics from your random samples you can still use np.var and np.mean on the gaussian and poisson samples. And this time (at least on my sample run) they give good results: print(np.mean(gaussian)) 0.653517935138 print(np.var(gaussian)) 5.4848398775 print(np.mean(poisson)) 0.477 print(np.var(poisson)) 0.463471 Notice how the gaussian values are almost exactly what we defined as parameters. On the other hand poisson mean and var are almost equal. You can increase the precision of the mean and var by increasing the size above. Why the poisson distribution doesn't approximate your original signal Your original signal contains only values between 0 and 1, so the poisson distribution only allows positive integer and the standard deviation is linked to the mean value. So far from the mean of the gaussian your signal is approximatly 0, so the poisson distribution will almost always draw 0. Where the gaussian has it's maximum the value is 1. The poisson distribution for 1 looks like this (left is the signal + poisson and on the right the poisson distribution around a value of 1) so you'll get a lot of 0 and 1 and some 2 in that region. But also there is some probability that you draw values up to 7. This is exactly the antisymmetry that I mentioned. If you change the amplitude of your gaussian (multiply it by 1000 for example) the "fit" is much better since the poisson distribution is almost symmetric there:
{ "pile_set_name": "StackExchange" }
Q: SAP User Exit EXIT_SAPLBARM_003 I am trying to use User Exit EXIT_SAPLBARM_003 however I cannot seem to get it activated. In CMOD I created a project and added XMRM0001 as the Enhancement Assignment, by default the only components that I see is EXIT_SAPLBARM_001 and EXIT_SAPLBARM_003, but EXIT_SAPLBARM_002 and EXIT_SAPLBARM_004 are missing. I realize in the picture the User Exit is not active, but that's because I am trying to add EXIT_SAPLBARM_003. Any tips would be greatly appreciated as always. Thanks! A: You can modify the User Exit on SMOD and add the Function Module. Att.
{ "pile_set_name": "StackExchange" }
Q: How to minimize impact on terrain at camp? I recently went backpacking above treeline in Colorado. It was in a National Wilderness and there were no designated camping areas. Finding a flat enough spot for 3 tents proved to be difficult at best. While respecting the rule of camping at least 100 ft from the trail and water bodies we ended up walking off trail more that I'd like. Given that a group of 2-6 people can, unfortunately, do a lot of stomping while finding a camp site that is 100+ ft from trail finding a camp site that is 100+ ft from water walking 100+ ft to the food cooking area walking another direction to a waste area (and digging holes) tying food up in a tree What are some way to minimize our impact on the terrain while following all the other guidelines? A: Interesting question. Some suggestions: In bear country many trekkers cook their evening meal by the trail, then walk on to camp. This reduces the need to move around your campsite. Again, you could cut down trips to your latrine area by seeing to your needs before you reach the camp. You could try to narrow down campsite selection before you go, using large-scale maps, satellite maps, and asking the locals. Or check out the terrain from above as you walk. This would reduce the need for recces off the trail. If you wear boots, you could walk around camp in bare feet or use a lightweight foot-covering to reduce erosion a little. A: I agree with all of the tactics mentioned by @Tullochgorum, except for the bare feet -- Ouch! However, the terrain and your feet will thank you for wearing light weight camp shoes. As for looking for a suitable campsite, one or two people can do that -- six people do not have to go out scouting in all directions. Another way to reduce your impact in some circumstances is to remember that guidelines are just that -- guidelines -- not rules that must never be bent. If you are above timberline on an unfrequented trail, and especially if you are going to decamp early next morning, it may be better to camp on a sandy spot less than 100 feet from the trail than tromp down the wildflowers making an extensive search. Also a group of six well above timberline has little to fear from a black bear by cooking at their campsite. And bear canisters, while they should be placed outside the perimeter of the campsite, need not be placed 100 feet away. The rules that can't be broken have to do with waste, garbage, cooking scraps, washing up and litter. Please note that I am not recommending bending guidelines merely because one is tired or it is getting dark, or because one is dismissive of rules or thinks that one party doesn't make a difference. A: Kudos to you for at least trying to follow the LNT guidelines. You certainly see a LOT of well-used sites in designated Wilderness areas that do not meet the distance from trail/water criteria. Saw many of those sites last week in the Lost Creek Wilderness, including several that had significant trash issues, too. :( In addition to the other suggestions offered, try to not follow in others' footsteps through the vegetation so as to not form a "path". It will recover quicker. I also try to walk on whatever durable surfaces (i.e., rocks) that are available.
{ "pile_set_name": "StackExchange" }
Q: C++ `srand()` function producing a pattern? New to C++ and following the beginner's tutorial here. Refer to the section titled Random Numbers in C++. Using exactly the code given: #include <iostream> #include <ctime> #include <cstdlib> using namespace std; int main () { int i,j; // set the seed srand( (unsigned)time( NULL ) ); /* generate 10 random numbers. */ for( i = 0; i < 10; i++ ) { // generate actual random number j = rand(); cout <<" Random Number : " << j << endl; } return 0; } I'm seeding srand() with time() (compiled with g++) and so the generated result should be completely random. However, here's the result I'm getting: $ ./a.out Random Number : 1028986599 Random Number : 491960102 Random Number : 561393364 Random Number : 1442607477 Random Number : 813491309 Random Number : 1467533561 Random Number : 986873932 Random Number : 1373969343 Random Number : 411091610 Random Number : 761796871 $ ./a.out Random Number : 1029003406 Random Number : 774435351 Random Number : 36559790 Random Number : 280067488 Random Number : 1957600239 Random Number : 1937744833 Random Number : 1087901476 Random Number : 684336574 Random Number : 1869869533 Random Number : 621550933 $ ./a.out Random Number : 1029020213 Random Number : 1056910600 Random Number : 1659209863 Random Number : 1265011146 Random Number : 954225522 Random Number : 260472458 Random Number : 1188929020 Random Number : 2142187452 Random Number : 1181163809 Random Number : 481304995 As you can see from the first number generated on each ./a.out execution, the first number in the 10-loop is increasing on each execution. And it seems to always be about 1.02 million. Further testing suggests this pattern always holds and it's not a coincidence. I can only assume that it's increasing due to the seed time(), which is always increasing. But that suggests the rand() function isn't truly random and is predictable. A: But that suggests the rand() function isn't truly random and is predictable. Yes, that's absolutely correct. Typically, rand is implement with a very simple pseudo-random number generator. The use of rand is not appropriate when numbers that are truly random or unpredictable are required. Under the hood, your implementation probably uses a Linear congruential generator and your three examples are all inside the same linear interval, at least for the first output.
{ "pile_set_name": "StackExchange" }
Q: Calling Shell - explorer search in VBA - Workaround I have a code in VBA that will call explorer with a given search parameter and will find and list files with a given name in explorer on a specific location. code: RetVal = Shell( _ "c:\Windows\explorer.exe ""search-ms:displayname=Search%20Results&crumb=System.Generic.String%3A~%3D" _ & filename & "%20kind%3A%3Dfolder&crumb=location:" _ & location, vbNormalFocus) It works nicely while I was using it on English windows. Is there any way to improve this code so it would work on other language platforms or at least a workaround for it to make it work on German Windows? Edit: To clarify what I need to happen: There are hyperlinks in a workbook with different names (ex. "banana"), when a user opens a hyperlink named "banana", the script calls the shell, opens an explorer window and lists all the files (these files are not excel files like .xls) containing the word "banana" in an already defined folder. Since other language Windows explorers use different search commands, it only works on English Windows. A search on German Windows would look like something this: search-ms:displayname=Suchergebnisse%20in%20"SYS%20(C%3A)"&crumb=System.Generic.String%3A & filename & &crumb=location: & location If you want to try it yourselves note that the location should also look something like this: C%3A%5C for C:\ in order to make it work. Edit2: So I have figured out what the problem was. The part %20kind%3A%3Dfolder is different in German Windows, so as I got rid of that, it started working on both platforms. Here is the working version: RetVal = Shell("c:\Windows\explorer.exe ""search-ms:displayname=backup%20for:%20" & _ backup & "&crumb=System.Generic.String%3A~%3D" & backup & _ "%20&crumb=location:" & location, vbNormalFocus) I am still looking for a way to get the same results without using Shell. A: 2nd Answer demonstrating FSO Sub GetFiles() Dim FSO as Object 'Late binding <- Prefered method 'or As New FileSystemObject for Early Binding 'but don't forget to add a reference to Scripting Runtime! Dim oFile as Object Dim oFolder as Object Dim sFileSpec as String Dim r As Integer r = 1 sFileSpec = "banana" Set FSO = CreateObject("Scripting.FileSystemObject") Set oFolder = FSO.GetFolder("C:\path\to\Predefined\Folder\") 'Or use the folder picker method already used For Each oFile In oFolder.Files If Instr(1, oFile.Name, sFileSpec, vbTextCompare) Then With Worksheets("Sheet1") .Cells(r, 1) = "File Name:" .Cells(r, 3) = "File Size:" .Cells(r, 5) = "Date:" .Cells(r, 2) = oFile.Name .Cells(r, 4) = oFile.Size .Cells(r, 5) = oFile.DateLastModified End With r = r + 1 End If Next oFile End Sub
{ "pile_set_name": "StackExchange" }
Q: How to use Incremental Backup I have a mysql database at a remote server that gets updated once in a while and what i normally do to transfer it to my locale machine is to mysql -u root -padmin databasename > backup.sql Then on the workbench of my local machine i just delete the old database and import this new database. I usually did this because updates came in once a month. So i wasn't bothered. But now the data has gotten pretty big and i can't afford to do this anymore. I just thought there is a better approach so i looked into incremental backups but i don't quite get it. In my situation, how will i use incremental backups ? So that in the remote server i only backup the latest changes in the remote database then import to my local database ? A: As long as you are using InnoDB, the percona guys can help you with xtrabackup: http://www.percona.com/software/percona-xtrabackup It has incremental options and also restores quickly. I'm not sure it supports myisam (since that engine is not ACID). We use it at work to great effect.
{ "pile_set_name": "StackExchange" }
Q: Dynamically assign information to an "Add_Click" event on a GUI button in powershell I want to Dynamically assign information to an "Add_Click" event on a GUI button in powershell. So an overview - I am making a GUI tool, that loads some buttons for custom "fixes" for peoples PC's. Each button is loaded from a script, and each script contains variables for information such as, Button Name, Button Icon, as well as a function that does whatever the script is meant to do. So as per example below, I am finding the problem is where I assign the Add_Click event. I'm sorry not sure how to explain better, but it does not seem to expand the $script variable, it will save the add_click as the variable, so that when I run the program, all buttons are using whatever was last stored in the variable $script (so all the buttons look different, but run the same script). What I want to be able to do, is have each button use an Add_Click to run whatever script is stored in $script at the time the Add_Click is assigned in the "Foreach" loop. Example script: #Button Container (Array to store all the Buttons) $ComputerActionButtons = @() #Get all the script files that we will load as buttons $buttonsFileArray = Get-ChildItem "$dir\Addin\ " | Select -ExpandProperty Name #Load Buttons $ButtonTempCount = 1 Foreach ($script in $buttonsFileArray){ . $dir\Addin\$script Write-Host "Loading Button: $ButtonName" # Generate button $TempButton = New-Object System.Windows.Forms.Button $TempButton.Location = New-Object System.Drawing.Size(140,20) $TempButton.Size = New-Object System.Drawing.Size(100,100) $TempButton.Text = "$ButtonName" $TempButton.Image = $ButtonIcon $TempButton.TextImageRelation = "ImageAboveText" $TempButton.Add_Click({& $dir\Addin\$script}) $ComputerActionButtons += $TempButton } #Add Buttons to panel $CAButtonLoc = 20 Foreach ($button in $ComputerActionButtons){ $button.Location = New-Object System.Drawing.Size(50,$CAButtonLoc) $ComputerActionsPanel.Controls.Add($button) $CAButtonLoc = $CAButtonLoc + 120 } I have been researching variables, found you can do a New-Variable and Get-Variable command to dynamically set and get variable names, but using this does not seem to help because of the original problem. I hope I have explained this well enough, please let me know if I can give more information to help. Thank you, Adam A: You need to create a closure over the $script value at the time of assignment, instead of relying on the value of $script at runtime. Fortunately, all ScriptBlocks support this with the GetNewClosure() method. foreach($i in 1..3){ $blocks += {echo $i}.GetNewClosure() } $blocks |Foreach-Object {$_.Invoke()} which produces: 1 2 3 As opposed to foreach($i in 1..3){ $blocks += {echo $i} } $blocks |Foreach-Object {$_.Invoke()} which produces: 3 3 3 What GetNewClosure() does is that it "captures" the variables referenced inside the ScriptBlock at that time and binds it to the local scope of the scriptblock. This way the original $i variable (or $script for that matter) is "hidden" beneath an $i variable that has the same value as $i used to have - namely at the time GetNewClosure() was called A: Instead of using GetNewClosure, which create new dynamic module, capture local scope variables to it and bind ScriptBlock to that module, so in fact you lose access to any function defined not in global scope, you can just store any button specific data in the button itself. Control base class have Tag property where you can store any data you want. $TempButton.Tag=@{Script=$script} $TempButton.Add_Click({param($Sender) & "$dir\Addin\$($Sender.Tag.Script)"})
{ "pile_set_name": "StackExchange" }
Q: Combinatorial proof for $\sum_{i=r}^{n}(2i-r)\binom{i-1}{r-1}^2=r\binom{n}{r}^2$ I was wondering if we could combinatorially interprete the following identity $$\sum_{i=r}^{n}(2i-r)\binom{i-1}{r-1}^2=r\binom{n}{r}^2$$ A: As usual let $[n]=\{1,\ldots,n\}$. Let $[n]^r$ be the family of $r$-subsets of $[n]$. Then $r\binom{n}r^2$ is the cardinality of $$\mathscr{T}=\{\langle A,B,i\rangle\in[n]^r\times[n]^r\times[n]:i\in A\}\;.$$ That is, it’s the number of ways to choose two $r$-subsets of $[n]$, $A$ and $B$, and then to single out a specific element of $A$, the first $r$-subset. For $\langle A,B,i\rangle\in\mathscr{T}$ let $m_{\langle A,B,i\rangle}=\max(A\cup B)$; clearly $r\le m_{\langle A,B,i\rangle}\le n$. For $k=0,\ldots,n-r$ let $$\mathscr{T}_k=\{T\in\mathscr{T}:m_T=r+k\}\;.$$ Say that $T=\langle A,B,i\rangle\in\mathscr{T}_k$. If $m_T=\max A$, there are $\binom{r+k-1}{r-1}$ ways to choose the rest of $A$, $\binom{r+k}r$ ways to choose $B$, and $r$ ways to choose $i$, for a total of $$r\binom{r+k}r\binom{r+k-1}{r-1}=r\cdot\frac{r+k}r\binom{r+k-1}{r-1}^2=(r+k)\binom{r+k-1}{r-1}^2$$ possibilities. There are just as many possibilities with $m_T=\max B$. However, that double counts the case in which $\max A=\max B$, which can be chosen in $$r\binom{r+k-1}{r-1}^2$$ ways. The grand total is therefore $$\begin{align*} |\mathscr{T}_k|&=2(r+k)\binom{r+k-1}{r-1}^2-r\binom{r+k-1}{r-1}^2\\\\ &=\big(2(r+k)-r\big)\binom{r+k-1}{r-1}^2\\\\ &=(2i-r)\binom{i-1}{r-1}^2\;, \end{align*}$$ where $i=r+k$. Thus, $$r\binom{n}r^2=|\mathscr{T}|=\sum_{k=0}^{n-r}|\mathscr{T}_k|=\sum_{k=0}^{n-r}\big(2(r+k)-r\big)\binom{r+i-1}{r-1}^2=\sum_{i=r}^n(2i-r)\binom{i-1}{r-1}^2\;.$$
{ "pile_set_name": "StackExchange" }
Q: Would there be a better way of doing this? post.Min.ToString("0.00").Replace(",", ".").Replace(".00", string.Empty) post.Min is a double such as 12,34 or 12,00. Expected output is 12.34 or 12. I basically want to replace the comma by a point, and cut the .00 part if any. I am asking because I couldn't find anything, or because I don't exactly know what to search. This has an high change of being a duplicate, I simply can't find it. Please let me know. A: The simplest solution would appear to be to use CultureInfo.InvariantCulture, and I reject the suggestion that this is any more complicated than using a series of replaces as you demonstrated in your question. post.Min.ToString("0.##", CultureInfo.InvariantCulture); # is the digit placeholder, described as the docs like this: Replaces the "#" symbol with the corresponding digit if one is present; otherwise, no digit appears in the result string. Try it online If you use this in a lot of places, and that's why you want to keep it simple, you could make an extension method: public static class MyExtensions { public static string ToHappyString(this double value) { return value.ToString("0.##", CultureInfo.InvariantCulture); } } And then you just have to call .ToHappyString() wherever you use it. For example, post.Min.ToHappyString()
{ "pile_set_name": "StackExchange" }
Q: Why won't HTML5 video play in firefox? I'm building a web page and want to add HTML video. It works fine in Chrome etc., but not in Firefox. I can hear the sound, but firefox is unable to show the picture, I get grey screen instead. I've got Firefox 25.0.1 Here is my code: <figure id="video"> <video width="320" height="240" controls> <source src="vid/asd.mp4" type="video/mp4"> <source src="vid/asd.ogg" type="video/ogg"> Sorry Your browser cannot play HTML5 video. </video><br/> <img src="img/pic.jpg" alt="Pics"/> <figcaption>Some text here <br/>size: 6,95MB</figcaption> </figure> A: This was a school project, just found out that the school's servers are not able to auto-get the MIME type under firefox. I had to add .htacces file
{ "pile_set_name": "StackExchange" }
Q: Alamofire: how to handle and classify errors? One example for Alamofire is given as: Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]) .validate() .responseJSON { response in switch response.result { case .Success: print("Validation Successful") case .Failure(let error): print(error) } } How can I handle errors like "network in down", "404", "server not found", to give informative excuses to the user for why their stuff isn't loading? A: You can get http status code and handler it like this: Alamofire.request(.GET, USERS_URL, headers: headers, encoding: .JSON) .responseJSON { response in debugPrint(response) switch response.result { case .Success(let data): if response.response!.statusCode == 200 { //do things }else if response.response!.statusCode == 401 { //do things } case .Failure(let error): print("Request failed with error: \(error)") } }
{ "pile_set_name": "StackExchange" }
Q: Google Maps: "This API project is not authorized to use this API." Recently I started coding a Google Maps service integration. I went ahead and generated an API Key associated with my business email account on bronze level. When I use the service sans API Key everything works swimmingly. If I use the API Key parameter, with my API key generated in my developer console I get the error message: This API project is not authorized to use this API. The URL used to access maps is below: https://maps.googleapis.com/maps/api/distancematrix/xml?origins={origin_address}&destinations={destination_addresses}&mode=driving&language=en-US&sensor=false&key={APIKey} How does one get the API Key to be authorized for v3 Maps JavaScript API. I am making the call as a raw post in the ASPX code behind to that address. It seems to me this used to work fine when I first started all this, now today all of the sudden I'm getting this error. I need this to work since I will also be using places and that service seems to only work with the API Key. I would like to be able to have the key configured once and be done with it. A: You'll need to enable each API you want to use. The maps-javascript-API is one API, the DistanceMatrix-API(Webservice) another. Go to the developer-console->API's and enable the Distance Matrix API Note: this is only related to the DistanceMatrix-Webservice, when you use the DistanceMatrix-Service of the Javascript-API you don't need to enable this service.
{ "pile_set_name": "StackExchange" }
Q: Get parameter value that didn't match original intent in a follow-up intent Coding in NodeJS - Google Cloud Functions and actions-on-google library. All intents are fulfilled from the back-end. I have an "Add to List" intent that matches to a "product" entity. When the user says something that does not match one of the entries in the entity list, it defaults to an "Add to List Fallback" fallback intent which asks the user "Do you want us to follow up with you about this unlisted product?", which has a fallback intent of "Add to List Fallback - Yes" for a "yes" answer. My question - how in that final intent can I access what the user said in the first place? It never matched as the "product" parameter. I'm thinking it's something to do with the context, but not sure how to set that up in DialogFlow or access it in JS. Thanks. A: Since you are using fulfillment for everything, including that Fallback Intent, the easiest solution would be to store the value of what they said in the Fallback Intent in either a context or in the Assistant's session storage and access it from the Intent Handler for the "yes" Followup Intent.
{ "pile_set_name": "StackExchange" }
Q: What happened to the Stack Exchange Store? There used to be a place where you could buy Stack Exchange branded gear, what happened to it? A: Unfortunately, it no longer exists. The short story is that it was just too much work for the amount of sales we had. The long story is, we have a lot of remote employees in different states. Our sales tax burden for selling tangible goods started to become an administration nightmare. We also couldn't justify the costs of either having someone at the office ship swag or paying a fulfillment house to do it for us (we were doing both). It also was complicated by the fact that a few months ago, a group of people defrauded us for a few thousand dollars in merchandise before we caught it. We only averaged maybe $20-$50 a day in sales. Sometimes a week would go by without an order. We also felt like allowing anyone to purchase our swag made it a bit less awesome when we sent it out for free to people for being awesome on our sites. So we closed the shop. We'll continue to make swag, and continue to gift it to people in special circumstances, but you won't be able to purchase it anymore. I apologize to everyone who is upset by this news. We should have foreseen a lot of these problems beforehand, and we didn't, so it's my fault.
{ "pile_set_name": "StackExchange" }
Q: Filter a dataframe column based on values in a second column being within a tolerance value of any rows in a second dataframe I am dealing with experimental measurements of time-correlated gamma-ray emissions with a pair of detectors. I have a long-form dataframe which lists every gamma-ray detected and displays its energy, the timestamp of the event, and the detector channel. Here is the sample structure of this dataframe: df Energy Timestamp Channel 0 639 753437128196030 1 1 798 753437128196010 2 2 314 753437131148580 1 3 593 753437131148510 2 4 2341 753437133607800 1 I must filter these data and according to the following conditions: Return the energies of all events detected in Channel 1 which occur within one user-selectable timing_window of events detected in Channel 2. Furthermore, only the events in Channel 2 that are within the energy range [E_lo, E_hi] should be considered when evaluating the timing window conditions. So far, I have tried the following: Separate the energy data of each detector into individual dataframes: d1_all = df[(df["Channel"] == 1)] d2_all = df[(df["Channel"] == 2)] Reset the indices of d1_all: d1_all = d1_all.reset_index() d1_all = d1_all.drop(['index'], axis=1) d1_all.head() Retain only the events in d2_all which occur in the range [E_lo=300, E_hi=600] d2_gate = d2_all[(d2_all["Energy"] >= 300) & (d2_all["Energy"] <=600)] Reset the indices of d2_all: d2_gate = d2_gate.reset_index() d2_gate = d2_gate.drop(['index'], axis=1) d2_gate.head() Everything up to this point works fine. Here is the biggest problem. The following code evaluates each event in detector 1 to determine if its timestamp is within one timing_window of the timestamp corresponding to ANY event within the energy range E_lo to E_hi in detector 2. The problem is that this dataframe can have on the order of 10's to 100's of thousands of entries for each detector, and the current code takes essentially forever to run. This code uses nested for loops. for i in range(0, d1_all.shape[0]): coincidence = False for j in range(0, d2_gate.shape[0]): if ((d1_all.iloc[i]["Timestamp"]) >= (d2_gate.iloc[j]["Timestamp"] - coin_window)) and ((d1_all.iloc[i] ["Timestamp"]) <= (d2_gate.iloc[j]["Timestamp"] + coin_window)): coincidence = True break else: pass if coincidence == True: pass elif coincidence == False: d1_all = d1_all.drop([i]) Any help identifying a faster implementation of evaluating for coincidences would be greatly appreciated! Thank you! A: Perhaps this will work? As you have done, it first splits the data into two dataframes corresponding to the channel. The second dataframe also filters for the energy between the max and min levels. I then create a numpy array of start and end times, corresponding to the timestamps in df2 -/+ the window. window = 10000 # For example. min_energy = 300 max_energy = 600 df1 = df[df['Channel'].eq(1)] df2 = df.loc[df['Channel'].eq(2) & df['Energy'].ge(min_energy) & df['Energy'].le(max_energy)] start = np.array(df2['Timestamp'] - window) end = np.array(df2['Timestamp'] + window) df1[df1['Timestamp'].apply(lambda ts: ((start <= ts) & (ts <= end)).any())] To explain the lambda function, I'll provide the following sample data (timestamps units are to make them more readable): df = pd.DataFrame({ 'Energy': [639, 798, 314, 593, 2341, 550, 625], 'Timestamp': [10, 20, 28, 30, 40, 50, 51], 'Channel': [1, 2, 1, 2, 1, 2, 1] }) After applying the code above: >>> df1 Energy Timestamp Channel 0 639 10 1 2 314 28 1 4 2341 40 1 6 625 51 1 >>> df2 Energy Timestamp Channel 3 593 30 2 5 550 50 2 I use a window of 3 for this example, which gives the following start and end times based on the timestamps from df2 -/+ the window. window = 3 >>> start array([27, 47]) >>> end array([33, 53]) Now let's look at the result from applying the first part of the lambda expression. For each timestamp in df1, it provides a boolean array indicating if that time stamp is greater than each start time based on the timestamps in df2. >>> df1['Timestamp'].apply(lambda ts: (start <= ts)) 0 [False, False] # 27 <= 10, 47 <= 10 2 [True, False] # 27 <= 28, 47 <= 28 4 [True, False] # 27 <= 40, 47 <= 40 6 [True, True] # 27 <= 51, 47 <= 51 Name: Timestamp, dtype: object We then took at the second part of the lambda expression using the same logic. >>> df1['Timestamp'].apply(lambda ts: (ts <= end)) 0 [True, True] # 10 <= 33, 10 <= 55 2 [True, True] # 28 <= 33, 28 <= 55 4 [False, True] # 40 <= 33, 10 <= 40 6 [False, True] # 51 <= 33, 10 <= 51 Name: Timestamp, dtype: object We then combine the results in parallel using the & operator. >>> df1['Timestamp'].apply(lambda ts: ((start <= ts) & (ts <= end))) 0 [False, False] # False & True, False & True <=> (27 <= 10) & (10 <= 33), (47 <= 10) & (10 <= 55) 2 [True, False] # True & True, False & True 4 [False, False] # True & False, False & True 6 [False, True] # True & False, True & True Name: Timestamp, dtype: object Given that we are looking any event from df1 that falls within any window from df2, we apply .any() to our result from above to create the boolean mask. >>> df1['Timestamp'].apply(lambda ts: ((start <= ts) & (ts <= end)).any()) 0 False 2 True 4 False 6 True Name: Timestamp, dtype: bool Which results in the following selected events: >>> df1[df1['Timestamp'].apply(lambda ts: ((start <= ts) & (ts <= end)).any())] Energy Timestamp Channel 2 314 28 1 6 625 51 1 The timestamp of 28 from the first event falls within the window from the first event in df2, i.e. 30 -/+ 3. The timestamp of 51 from the second event falls within the window from the other event in df2, i.e. 50 -/+ 3.
{ "pile_set_name": "StackExchange" }
Q: How can I format time durations exactly using Moment.js? I would like to do the following, given two dates in UTC formatting: var start = "2014-01-13T06:00:00.0000000Z"; var end = "2014-01-13T14:16:04.0000000Z"; I would like to get the exact time span that passes between these two times, such as 8h 16m I have tried using the following: var duration = moment(moment(end) - moment(start)).format('hh[h] mm[m]'); But this does not work with days. Moreover, it does not work with days, since they are always >=1 even if <24 hours pass. I have also tried twix.js to get the length, but its formatting doesn't support creating the format specified above, or I could not find the way to do so in its documentation. Basically I am looking for an exact version of twix.humanizeLength(). Moment.js's a.diff(b) provides only total durations, it can give me the length of the time span in minutes, hours or days, but not calculated using remainders. My current solution is to use diff to create the ranges and then use modulo to calculate remainders, but this is not very elegant: var days = moment(end).diff(start, 'days'); var hours = moment(end).diff(start, 'hours') % 24; var minutes = moment(end).diff(start, 'minutes') % 60; var duration = ((days > 0) ? days + 'd ' : '') + ((hours > 0) ? hours + 'h ' : '') + ((minutes > 0) ? minutes + 'm ' : ''); The question: Is there any smarter way to do this in either moment.js or twix.js, or should I take my time and develop my own moment.js plugin? A: You can try using Durations, but I'm not sure if those have the capabilities you are looking for http://momentjs.com/docs/#/durations/ Also, you can always user moment's diff to get the difference in milliseconds and then format it to your needs. It is basically the same that you are doing, but you only call diff once. function convertMilliSecondsIntoLegibleString(milliSecondsIn) { var secsIn = milliSecondsIn / 1000; var milliSecs = milliSecondsIn % 1000; var hours = secsIn / 3600, remainder = secsIn % 3600, minutes = remainder / 60, seconds = remainder % 60; return ( hours + "h: " + minutes + "m: " + seconds +"s: " + milliSecs + "ms"); } A: There's a plugin for formatting duration in moment.js : moment-duration-format If it doesn't do what you need, then you should extend moment.duration.fn. If you don't support many locales, it should be easy enough. In any case, I'd recommend to read the thread of this feature request.
{ "pile_set_name": "StackExchange" }
Q: free c++ compiler for mac not using xcode Are there any free c++ compilers for macs that do not need xcode? A: If you install the Developer Tools (which include Xcode), you get GCC installed as well. You can use it from the command line. gcc -o myprogram main.cpp
{ "pile_set_name": "StackExchange" }
Q: Adding an event listener to the markers using gmaps4rails I am developing an application that uses gmaps4rails (https://github.com/apneadiving/Google-Maps-for-Rails). I want to add an event listener to the marker so that it creates a visualization next to the map (as well as displaying an info window on the map). Is it possible to add an event listener for each marker using gmaps4rails? A: Of course it's possible. You should write your code in the gmaps4rails_callback javascript function to be sure it's executed when everything is setup. And then loop the markers js variable: Gmaps4Rails.markers The attributes of each marker in this array are: longitude latitude google_object containing the google marker That said you can do whatever you want. As a side note, the map is also available doing Gmaps4Rails.map. In general, read the gmaps4rails.js file, it's well documented (I hope!). EDIT: The problem you explain in the comments is weird, it works perfectly for me when I use: google.maps.event.addListener(Gmaps4Rails.markers[0].google_object, 'click', function(object){ alert("hello"); }); I guess you should try to use a more traditional for loop like: <script type="text/javascript"> function gmaps4rails_callback() { function say_yo(arg) { return function(){alert('yo '+ arg + '!' );};}; for (var i = 0; i < Gmaps4Rails.markers.length; ++i) { google.maps.event.addListener(Gmaps4Rails.markers[i].google_object, 'click', say_yo(i)); } } </script>
{ "pile_set_name": "StackExchange" }
Q: Comparator for Optional with key extractor, like java.util.Comparator.comparing Consider the following example where we are sorting people based on their last name: public class ComparatorsExample { public static class Person { private String lastName; public Person(String lastName) { this.lastName = lastName; } public String getLastName() { return lastName; } @Override public String toString() { return "Person: " + lastName; } } public static void main(String[] args) { Person p1 = new Person("Jackson"); Person p2 = new Person("Stackoverflowed"); Person p3 = new Person(null); List<Person> persons = Arrays.asList(p3, p2, p1); persons.sort(Comparator.comparing(Person::getLastName)); } } Now, let's assume that getLastName returns an optional: public Optional<String> getLastName() { return Optional.ofNullable(lastName); } Obviously persons.sort(Comparator.comparing(Person::getLastName)); will not compile since Optional (the type getLastName returns) is not a comparable. However, the value it holds is. The first google search points us in this answer. Based on this answer we can sort persons by doing: List<Person> persons = Arrays.asList(p3, p2, p1); OptionalComparator<String> absentLastString = absentLastComparator(); //type unsafe persons.sort((r1, r2) -> absentLastString.compare(r1.getLastName(), r2.getLastName())); My question is, is it possible to have this kind of sorting using a function (key extractor) just like Comparator.comparing? I mean something like (without caring absent values first or last): persons.sort(OptionalComparator.comparing(Person::getLastName)); If we look into Comparator.comparing, we see the following code: public static <T, U extends Comparable<? super U>> Comparator<T> comparing( Function<? super T, ? extends U> keyExtractor) { Objects.requireNonNull(keyExtractor); return (Comparator<T> & Serializable) (c1, c2) -> { return keyExtractor.apply(c1).compareTo(keyExtractor.apply(c2)); }; } I tried multiple ways to make it return an OptionalComparator instead of a simple Comparator, but everything I tried and made sense to me was unable to be compiled. Is it even possible to achieve something like that? I guess type-safety cannot be achieved, since even Oracle's comparing throws a type-safety warning. I am on Java 8. A: You can use Comparator#comparing(Function,Comparator): Accepts a function that extracts a sort key from a type T, and returns a Comparator<T> that compares by that sort key using the specified Comparator. Here's an example based on the code in your question: persons.sort(comparing(Person::getLastName, comparing(Optional::get))); Basically this is using nested key extractors to ultimately compare the String objects representing the last names. Note this will cause a NoSuchElementException to be thrown if either Optional is empty. You can create a more complicated Comparator to handle empty Optionals1: // sort empty Optionals last Comparator<Person> comp = comparing( Person::getLastName, comparing(opt -> opt.orElse(null), nullsLast(naturalOrder()))); persons.sort(comp); If you need to do this a lot then consider creating utility methods in a manner similar to Comparator#nullsFirst(Comparator) and Comparator#nullsLast(Comparator)1: // empty first, then sort by natural order of the value public static <T extends Comparable<? super T>> Comparator<Optional<T>> emptyFirst() { return emptyFirst(Comparator.naturalOrder()); } // empty first, then sort by the value as described by the given // Comparator, where passing 'null' means all non-empty Optionals are equal public static <T> Comparator<Optional<T>> emptyFirst(Comparator<? super T> comparator) { return Comparator.comparing(opt -> opt.orElse(null), Comparator.nullsFirst(comparator)); } // empty last, then sort by natural order of the value public static <T extends Comparable<? super T>> Comparator<Optional<T>> emptyLast() { return emptyLast(Comparator.naturalOrder()); } // empty last, then sort by the value as described by the given // Comparator, where passing 'null' means all non-empty Optionals are equal public static <T> Comparator<Optional<T>> emptyLast(Comparator<? super T> comparator) { return Comparator.comparing(opt -> opt.orElse(null), Comparator.nullsLast(comparator)); } Which can then be used like: persons.sort(comparing(Person::getLastName, emptyLast())); 1. Example code simplified based on suggestions provided by @Holger. Take a look at the edit history to see what the code looked like before, if curious.
{ "pile_set_name": "StackExchange" }
Q: Update table with ajax I'm using Ajax to update table, when I hit the first request to edit or delete data in the system, it's works. After update the table with Ajax, I don't know what happens. The add, edit and delete stop working more. function tabela(dados){ var template = "<thead><tr> <th>ID</th><th>Nome</th><th>Status</th><th>E-mail</th> <th>Editar</th> <th>Excluir</th> </tr></thead><tbody>"; var templateContrato = "<tr><td><i class='fa fa-circle' title='OK'></i><span class='statusicon'>#ID#</span></td><td>#NOME#</td><td>#STATUS#</td><td>#EMAIL#</td><td ><div id='EdContrato'> <div id='#EDITAR#'> Editar </div> </div></td><td class='contrato'> <div id='ExContrato'> <div id='#EXCLUIR#'> Excluir </div> </div></td></tr>"; for (i = 0; i < dados.length; i++) { aux = templateContrato; aux = aux.replace('#ID#',dados[i].id_contrato); aux = aux.replace('#NOME#', dados[i].nome ? dados[i].nome:''); aux = aux.replace('#STATUS#',dados[i].status ? dados[i].status:''); aux = aux.replace('#EMAIL#', dados[i].email ? dados[i].email:''); aux = aux.replace('#EDITAR#', dados[i].id_contrato); aux = aux.replace('#EXCLUIR#', dados[i].id_contrato); template += aux; } template +="</tbody>" $("#idContrato").html(template); } $("#btnAdicionar").click(function(e){ e.preventDefault(); var nome = $("input[name=nome]").val(); var email = $("input[name=email]").val(); var status = $("input[name=status]").val(); $.ajax({ type:'POST', url:'/adicionar', data:{nome:nome, email:email, status:status}, success:function(data){ tabela(data); } }); $("input[name=nome]").val(""); $("input[name=email]").val(""); $("input[name=status]").val(""); }); Doesn't show any error. A: As you are creating the DOM Elements dynamically click event wont work after 1st reload of HTML. You need to use event deligator or jquery "on" click $( "#ExContrato" ).on( "click", function() { // logic here }); $( "#EdContrato" ).on( "click", function() { // logic here }); More detail here
{ "pile_set_name": "StackExchange" }
Q: Customizing Octave I am just starting with Octave and running it on my terminal so far. Everytime I open the prompt, my command line starts with : octave-3.4.0:1> So I use the following to make it shorter and easier to read: PS1('>> ') How can I change my settings to exectute this code automatically everytime I open octave? How top of this, is there a way to change my terminal settings to open Octave when I enter 'Octave'? The way I do it now is by using 'exec 'path/to/octave/ Thanks A: You can create edit ~/.octaverc file that contains all the commands you want to execute when Octave starts up. This file is exactly like a .m Octave script file. Just add PS1('>> ') to your ~/.octaverc file. You can use your favorite text editor or use echo on the command line: $ echo "PS1('>> ')" >> ~/.octaverc After that you can see the ~/.octaverc file : $ more ~/.octaverc It should contain the following line : PS1('>> ') For the second question, I am not sure if you're on OSX or Ubuntu or something else. If octave is in your search-path then you should be able to start Octave by just trying octave. Try these commands to find out what octave points to $ which octave /usr/bin/octave $ type octave octave is /usr/bin/octave If somehow, octave is not your PATH search-path, this could be because you installed Octave at a non-standard location. You can do one of two things: Add the folder containing your Octave executable to your PATH search-path. In bash, you can do this by adding the following line to your ~/.bashrc (or ~/.profile on MacOSX): export PATH=~/path/to/octave/folder:${PATH} You can create a soft symlink to your octave executable. ln -s /path/to/octave/executable octave This will create a symlink in your current folder. Now, as long as you're in the current folder, you'll be able to type in octave and run Octave. If you want to be able to run Octave from anywhere (and not necessarily the current folder), you need to add the current folder to your search-path (see point 1 above). A: Consider using the latest release which is GNU Octave 3.8. It comes with a nice GUI if you're familiar with MATLAB. You can customize the PS1 and any other settings on your ~/.octaverc. Please read the documentation on startup files: http://www.gnu.org/software/octave/doc/interpreter/Startup-Files.html As for calling Octave from anywhere, you need to set the PATH variable in your shell to append the directory where Octave is installed, for instace in Bash: export PATH=$PATH:/path/to/octave-3.8/bin
{ "pile_set_name": "StackExchange" }
Q: Xcode loses syntax highlighting when file is open in multiple tabs I have had an issue with syntax highlighting/coloring since Xcode 9.3.0. I work in multiple tabs a lot. Sometimes I have the same file open in multiple tabs to either have reference to different parts of the file or if I'm using one with the debugger and the other for reference. Since 9.3.0, when I launch my app with a file open in more than one tab, I lose part of the syntax highlighting. It seems to be mostly custom classes, (green in the dusk color scheme). This can be very tedious with debugging as I have Xcode set to open a preset 'Debug' tab when it hits a breakpoint. Essentially I will have a file open, launch the app, hit a breakpoint, Xcode opens the same file in the 'Debug' tab, and I lose syntax highlighting when I need it most, to debug. I have tried the following - Delete derived data folder - Quit Xcode - Restart computer - add $(SRCROOT) to header search paths - cleaned project - cleaned build folders Please note, I have also tried this on a brand new project with only a couple of classes and just a few lines of code. It still happens. Please also note, I have tried installing a fresh version of Xcode on a brand new user account, devoid of ALL my previous xcode settings and preferences. It still happens. I have also downloaded 9.3.1 and tried it. It still happens This is driving me crazy. I would absolutely love to find a solution to this. I'm hoping this gets to a boss source kit expert who can be my hero! Example of working syntax-highlighting: What it looks like after building: Update: 5/18/18 : Here's a video of what is happening https://youtu.be/fpWV_x17J7U Update: 5/18/18 Tested on 9.2.0, doesn't happen, only on 9.3.0 and 9.3.1 Update: 5/18/18 Just tested on a friend's computer and can confirm this is happening for him as well. Steps to reproduce. • Update to Xcode 9.3.0 or 9.3.1 • Download and open this basic sample project : https://github.com/provmusic/syntaxHighlightingBug • Open ViewController.swift • Build -> Syntax coloring still in tact • Open a new tab, now having ViewController.swift in both tabs • Build -> Syntax coloring breaks A: Just got word from Apple. This is finally fixed in Xcode 10 Beta 5
{ "pile_set_name": "StackExchange" }
Q: How to sort list type generic if more than one property? I have a list-generic that has a property (class type). I need a sort method for Z parameters (TrainingSet): public override List<TrainingSet> CalculatedDistancesArray (List<TrainigSet> ts, double x, double y, int k) { for (int i =0; i < ts.Count; i++) { ts[i].Z = (Math.Sqrt(Math.Pow((ts[i].X - x), 2) + Math.Pow((ts[i].Y - y), 2))); } // I want to sort according to Z ts.Sort(); //Failed to compare two elements in the array. List<TrainingSet> sortedlist = new List<TrainingSet>(); for (int i = 0; i < k; i++) { sortedlist.Add(ts[i]); } return ts; } public class TrainigSet { public double X { get; set; } public double Y { get; set; } public double Z { get; set; } public string Risk { get; set; } } A: Just sorting on a single property is easy. Use the overload which takes a Comparison<T>: // C# 2 ts.Sort(delegate (TrainingSet o1, TrainingSet o2) { return o1.Z.CompareTo(o2.Z)); } ); // C# 3 ts.Sort((o1, o2) => o1.Z.CompareTo(o2.Z)); Sorting on multiple properties is a bit trickier. I've got classes to build up comparisons in a compound manner, as well as building "projection comparisons" but if you really only want to sort by Z then the above code is going to be as easy as it gets. If you're using .NET 3.5 and you don't really need the list to be sorted in-place, you can use OrderBy and ThenBy, e.g. return ts.OrderBy(t => t.Z); or for a more complicated comparison: return ts.OrderBy(t => t.Z).ThenBy(t => t.X); These would be represented by orderby clauses in a query expression: return from t in ts orderby t.Z select t; and return from t in ts orderby t.Z, t.X select t; (You can also sort in a descending manner if you want.) A: var sortedList = list.OrderBy(i => i.X).ThenBy(i => i.Y).ThenBy(i => i.Z).ToList();
{ "pile_set_name": "StackExchange" }
Q: What should I put on a math finance cheat sheet? What are the most useful results that I should put on a mathematical finance cheat sheet? Am I missing anything important: https://github.com/daleroberts/math-finance-cheat-sheet A: There is a very famous math finance cheat sheet already (by Prof. Wystup), you can find the content here: https://mathfinance2.com/Products/CheatSheet#Content
{ "pile_set_name": "StackExchange" }
Q: SQL Server 2008 R2 log files filled up the drive So some of us dev's are starting to take over the management of some of our SQL Server boxes as we upgrade to SQL Server 2008 R2. In the past, we've manually reduced the log file sizes by using USE [databaseName] GO DBCC SHRINKFILE('databaseName_log', 1) BACKUP LOG databaseName WITH TRUNCATE_ONLY DBCC SHRINKFILE('databaseName_log', 1) and I'm sure you all know how the truncate only has been deprecated. So the solutions that I've found so far are setting the recovery = simple, then shrink, then set it back... however, this one got away from us before we could get there. Now we've got a full disk, and the mirroring that is going on is stuck in a half-completed, constantly erroring state where we can't alter any databases. We can't even open half of them in object explorer. So from reading about it, the way around this happening in the future is to have a maintenance plan set up. (whoops. :/ ) but while we can create one, we can't start it with no disk space and SQL Server stuck in its erroring state (event viewer is showing it recording errors about 5 per second... this has been going on since last night.) Anyone have any experience with this? A: So you've kind of got a perfect storm of bad circumstances here in that you've already reached the point where SQL Server is unable to start. Normally at this point it's necessary to detach a database and move it to free space, but if you're unable to do that you're going to have to start breaking things and rebuilding. If you have a mirror and a backup that is up to date, you're going to need to blast one unlucky database on the disk to get the instance back online. Once you have enough space, then take emergency measures to break any mirrors necessary to get the log files back to a manageable size and get them shrunk. The above is very much emergency recovery and you've got to triple check that you have backups, transaction log backups, and logs anywhere you can so you don't lose any data. Long term to manage the mirror you need to make sure that your mirrors are remaining synchronized, that full and transaction log backups are being taken, and potentially reconfiguring each database on the instance with a maximum file size where the sum of all log files does not exceed the available volume space. Also, I would double check that your system databases are not on the same volume as your database data and log files. That should help with being able to start the instance when you have a full volume somewhere. Bear in mind, if you are having to shrink your log files on a regular basis then there's already a problem that needs to be addressed. Update: If everything is on the C: drive then consider reducing the size of the page file to get enough space to online the instance. Not sure what your setup is here.
{ "pile_set_name": "StackExchange" }
Q: Flattern Dictionary> I have been messing around with this for some days now, and I can't wrap my head around it: I have the following structure: Dictionary<string, HashSet<string>> Containing the following data: P1 S1, S2 P2 S1, S2 Where the P-prefixed values are dictionary keys and S-prefixed values are the HashSet values. What I need is the following output List, P1, P2, S1, S2 In the case I would have the following startvalues : P1 S1, S2 P2 S1 The output List should be : P1, P2, S1, P1, S2 If there similar values in the HashSet of several dictionary items, it should group them together, that's why P1, P2, have S1, P1 has only S2 Here's a little TestApp that clarifies more: static void Main(string[] args) { var start = new Dictionary<string, HashSet<string>>(); var output = new List<string>(); //example1 start.Add("P1", new HashSet<string> { "S1", "S2" }); start.Add("P2", new HashSet<string> { "S1", "S2" }); output = HocusPocus(start); PrintResult(output); // should be P1, P2, S1, S2 //example 2 start.Clear(); start.Add("P1", new HashSet<string> { "S1", "S2" }); start.Add("P2", new HashSet<string> { "S1" }); output = HocusPocus(start); PrintResult(output); // should be P1, P2, S1, P1, S2 //example 3 start.Clear(); start.Add("P1", new HashSet<string> { "S1", "S2", "S3" }); start.Add("P2", new HashSet<string> { "S1" }); start.Add("P3", new HashSet<string> { "S1", "S2" }); output = HocusPocus(start); PrintResult(output); // should be P1, P2, P3, S1, P1, P3, S2, P1, S3 Console.ReadKey(); } public static List<string> HocusPocus(Dictionary<string, HashSet<string>> data) { // magic happens here } public static void PrintResult(List<string> result) { result.ForEach(x => Console.Write($"{x},")); Console.WriteLine(); } A: It seems that you for each S want to find all the P's that are associated with that S and furthermore group S values with the same set of P values. If you dataset isn't to big you can do that quite simply if not in the most efficient way. Your data: var start = new Dictionary<string, HashSet<string>> { { "P1", new HashSet<string> { "S1", "S2", "S3" } }, { "P2", new HashSet<string> { "S1" } }, { "P3", new HashSet<string> { "S1", "S2" } } }; First all the S values are needed for the next iteration: var allSValues = start.SelectMany(kvp => kvp.Value).Distinct(); To be able to group by sequences of P values an IEqualityComparer<IEnumerable<string>> is required: class SequenceEqualityComparer : IEqualityComparer<IEnumerable<string>> { // Does not handle null values correctly. public bool Equals(IEnumerable<string> x, IEnumerable<string> y) => x.SequenceEqual(y); public int GetHashCode(IEnumerable<string> obj) { unchecked { return obj.Aggregate(17, (hash, @string) => hash * 23*@string.GetHashCode()); } } } (The comparison should treat the input as sets, not sequences, but for this purpose the ordering is stable so it will work.) The P values for each S value is found and this is then grouped into a lookup which is like a dictionary except there can be multiple values (S values) for each key (sequence of P values): var lookup = allSValues.Select(s => new { S = s, PValues = start .Where(kvp => kvp.Value.Contains(s)) .Select(kvp => kvp.Key) .ToList() }) .ToLookup(item => item.PValues, item => item.S, new SequenceEqualityComparer()); You can print the lookup: foreach (var items in lookup) { Console.Write(string.Join(" ", items.Key)); Console.Write(" "); Console.WriteLine(string.Join(" ", items)); } A: Here's a version of Martin's that walks the primary dictionary once to build the inverted dictionary, and uses sets instead of sequences (it also works inside your original method signatures): public static List<string> HocusPocus(Dictionary<string, HashSet<string>> data) { var invert = new Dictionary<string, HashSet<string>>(); foreach (var kvp in data) { foreach (var s in kvp.Value) { if (!invert.TryGetValue(s, out var pvalues)) { pvalues = new HashSet<string>(); invert[s] = pvalues; } pvalues.Add(kvp.Key); } } var lookup = invert .ToLookup(_ => _.Value, _ => _.Key, new SetComparer()); var flat = new List<string>(); foreach (var item in lookup) { flat.AddRange(item.Key); flat.AddRange(item); } return flat; } public class SetComparer : IEqualityComparer<ISet<string>> { public bool Equals(ISet<string> x, ISet<string> y) { return x.SetEquals(y); } public int GetHashCode(ISet<string> obj) { unchecked { int hash = 19; foreach (var foo in obj) { hash = hash * 31 + foo.GetHashCode(); } return hash; } } }
{ "pile_set_name": "StackExchange" }
Q: Databind a value to a gridviewcolumn header? Is it possible? I have a listview with several gridviewcolumns. The last column has a dynamic header. I dont know what the column header will be at design time. It's actually a number I want to display as a string. <GridViewColumn Header="{Binding Path=SomeValue}" DisplayMemberBinding="{Binding Path=OtherValue}"/> This doesn't seem to work. The data will bind fine just the header remains blank. Stepping through the code and it doesn't even break on the SomeValue property. A: I think your problem is the source of the "SomeValue" property. If you are binding to a list of objects, it wouldn't make sense to have the header determined by a property on that object, because then you could have a different header for every object. Essentially what you are saying is "Bind the header of the column to the 'SomeValue' property which lives on the same object that my 'OtherValue' property does." The "SomeValue" needs to come from a different source other than the list your grid item is bound to. You need to either set the "RelativeSource" or the "ElementName" property in the binding.
{ "pile_set_name": "StackExchange" }
Q: How to add cart icon react native action bar? I am using react-native-action-bar for my app header and here is I need to add cart icon... I tried everything in right but can't get any solution for adding cart icon with counted items... if anyone has an idea for the same please let me know. I used rightIcons but there are limited icons and the cart icon is missing also I need to add cart count with the icon. <ActionBar containerStyle={{height:60}} backgroundColor={'#d7b655'} title={'Home'} titleStyle={styles.pageTitle} leftIconName={'menu'} onLeftPress={() => this.props.navigation.dispatch(DrawerActions.openDrawer()) } rightIcons={[ { name: 'cart', badge: '1', onPress: () => console.log('cart !'), }, ]} rightIconImageStyle={{tintColor: 'green'}} rightIconContainerStyle={{Top:200}} /> It should show a cart icon with a count of total items with a dynamic count result. A: Unfortunately, react-native-action-bar doesn't support a cart icon. The only predefined icons are: back, flag, loading, location, menu, phone, plus, start and star-outline. Check out here. Also, the library doesn't support react-native-vector-icons. In your case I recommend you to use the react-native-elements Header component: <Header centerComponent={{ text: 'Home', style: { color: '#fff' } }} rightComponent={{ icon: 'shopping_cart', color: '#fff' }} /> To add a badge to your Icon, you can use the badge component: import { Badge, Icon, withBadge } from 'react-native-elements' ... const BadgedIcon = withBadge(1)(Icon); In a combination, it will look like this: <Header centerComponent={{ text: 'Home', style: { color: '#fff' } }} rightComponent={<BadgedIcon type="material" name="shopping_cart" />} />
{ "pile_set_name": "StackExchange" }
Q: Android - How use Fragment as Dialog or Activity depending on device I'm very new to Android programming and I'm stuck at a point where I want to finish my UI development. The picture in this question simply explains my problem: Dialog fragment embedding depends on device I want to create a reusable UI component with a Layout (probably LinearLayout or Relative Layout). Depending on the screen size (Tablet vs. Phone) I want to open the UI component in a Dialog or in a separate Activity. Can anyone of you give me an advice how to achieve this? A: In the activity you want to use fragment type : FragmentManager fm = getSupportFragmentManager(); //fragment class name : DFragment DFragment dFragment = new DFragment(); // Show DialogFragment dFragment.show(fm, "Welcome to dialog fragment!!"); Now create a class DFragment and type : public class DFragment extends DialogFragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.dialogfragment, container, false); getDialog().setTitle("DialogFragment Tutorial"); // Do something else return rootView; } } dialogfragment.xml <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:padding="10dp" android:text="@string/welcome" /> </RelativeLayout> Hope it helps!!
{ "pile_set_name": "StackExchange" }
Q: Macintosh HD not using entire drive I have a 2016 15" macbook pro with a 256gb ssd. Only 122gb are used by MacOS. How do I get MacOS to use the entire drive? I believe this happened because of a botched bootcamp uninstall. Disk utility shows the following: Here's the output from diskutil list /dev/disk0 (internal): #: TYPE NAME SIZE IDENTIFIER 0: GUID_partition_scheme 251.0 GB disk0 1: EFI EFI 314.6 MB disk0s1 2: Apple_APFS Container disk1 122.0 GB disk0s2 /dev/disk1 (synthesized): #: TYPE NAME SIZE IDENTIFIER 0: APFS Container Scheme - +122.0 GB disk1 Physical Store disk0s2 1: APFS Volume Macintosh HD 104.0 GB disk1s1 2: APFS Volume Preboot 44.7 MB disk1s2 3: APFS Volume Recovery 510.4 MB disk1s3 4: APFS Volume VM 1.1 GB disk1s4 Thanks! A: I just needed to resize the container (because apparently that's a simple thing to do). I first had to restart into recovery mode and run firstaid on the container. I ran it on all 3 of the drive, the container, and the volume to be safe, but I'm certain only the run on the container did anything. Then I restarted and logged in and in a terminal ran the following: diskutil apfs resizeContainer /dev/disk1 0
{ "pile_set_name": "StackExchange" }
Q: Aviary Editor Loads blank image until screen is resized So I have an instance of aviary editor on my site, it pulls images from filepicker and then resubmits them. The problem I am having is that when I load an image, it initially has a thumbnail I have loaded appear, then the screen goes blank...until I resize the screen and the image appears normally. Here is what it looks like, notice the image dimensions in the bottom. They go from the already loaded thumbnail to a blank image, with the correct dimensions displayed until I slightly change the windows size. While it is loading, dimensions of the thumbnail in bottom After it has loaded, correct dimensions in bottom After slightly changing window dimensions, the image appears Here is my initialization code: function initEditor( apiKey ){ var tools = ['enhance', 'orientation', 'focus', 'resize', 'crop', 'effects']; var featherEditor = new Aviary.Feather({ apiKey: apiKey, apiVersion: 3, displayImageSize: true, tools: tools, maxSize: 800, theme: 'minimum', onSave: function(image, newUrl){ //onSave function, sends to external filePicker source }, onError: function(errorObj){ console.log(errorObj); }, onLoad: function(){ //load only if there is an img if (typeof img !== 'undefined'){ openEditor(img, src, featherEditor); } } }); return featherEditor; } Opening Code: image = "img-id_image_relations-0-image" src = "https://www.filepicker.io/api/file/mX42P6fLRS6YDP58moIH" function openEditor(image, src, editor){ editor.launch({ image: image, url: src }); //return false; } Things I have tried: Loading the image into a div before opening, Simplifying the feather initialization to the bare minimum, Test on external facing server and localhost, What stinks is when I test it on jsFiddle it works perfectly. http://jsfiddle.net/TD4Ud/ A: It's very dirty, but I found a temporary solution of firing the window resize event when the image loads. I would love there to be a better answer, but this will work in the interim. Add this as the onReady event in the initialization: onReady: function(){ //this is an abomination but it works window.dispatchEvent(new Event('resize')); }
{ "pile_set_name": "StackExchange" }
Q: 'as I've done something I guess something' I'm kind of confused whether the following sentence is correct or not. I'm specifically not sure about the As I've done something I guess that.. part. As I've completed all lectures, all quizzes and the final project as well I guess the course is over for me. Thus, I'd like to thank you for your time... I'm not aware of any grammar rule the sentence would brake but I wanted to be 100 % sure. A: There’s nothing especially wrong with the sentence as speech goes. However, in writing, it would be kinder on your reader to introduce a few commas for a clearer parse: As I’ve completed all lectures, all quizzes, and the final project as well, I guess the course is over for me.
{ "pile_set_name": "StackExchange" }
Q: What is the practical difference between “ignorant” and “naïve”? As these terms are defined in online dictionaries, ignorant means a lack of education, while naïve means a lack of worldly experience. What is the practical difference between these two? When would I use one and not the other? We could consider education to be the acquisition of knowledge, and experience to be knowledge acquired first-hand. In that case, these two words would have no practical difference, yet I have had people strongly disagree with me in some discussions. One person tried to explain that ignorant is when a person doesnt know about something, whereas naïve is when a person does or should know about something but fails to act on the knowledge or fails to acquire the knowledge before acting. Could someone please clarify? A: There is good discussion of the semantic differences in other answers, but the most important practical difference is that ignorant is a very insulting word that you should be careful about using, whereas naïve is not such. In general naïve makes me picture a hopeful child who has unrealistic dreams and has not thought about the real world enough, whereas ignorant makes me picture a dumb, racist old man who won’t change his worldview in the face of overwhelming evidence. So, for instance: “I think you are being naïve, because...” is appropriate way to disagree with someone's theory at, say, a business meeting. It’s still a strong thing to say, and possibly condescending or belittling of your colleague’s theory. On the other hand, “I think you are being ignorant, because...” is quite rude and aggressive. It's not practically very different from saying stupid even though the semantics differ. A: "naive" (often naïve when just the adjective) emphasizes the immaturity of the person in that state. It implies that they lack experience that would make them aware. In other words, the expectation is that they are capable of knowing but do not yet. She's naive, so she does not know he's toying with her. "ignorant" implies an incapacity to know such that you don't expect them to learn. He's so ignorant. That's why he doesn't understand French people.
{ "pile_set_name": "StackExchange" }
Q: Query to find by calculated date I would like to create a query in mongoose to achieve this functionality: Mongoose models: Planted_crop: owner: id, date_planted: Date, crop: id, quantity: Number Crop: name: String, water_consumption: Number, grow_time: Number (means hours) And now I would like to get all planted crops that aren't fully grown yet, In semi code this would be it: if (plantedCrop.date_planted < plantedCrop.date_planted + plantedCrop.crop.grow_time) { // this crop should be selected } And now I need to translate this to mongodb: var PlantedCrop = mongoose.model("planted_crop"); PlantedCrop.find({ date_planted: { $lt: { date_planted + crop.grow_time * 3600 } } }).populate("crop").exec(function(err, crops) { // calculate water consumption var consumption = 0, planted; for (var i = 0; i < crops.length; i++) { planted = crops[i]; consumption += planted.crop.water_consumption * planted.quantity; } console.log("Water consumption of planted crops is " + consumption + " liters. }); I am stuck at creating such query, could anyone help me? A: You should not do this, and therefore the best part of an answer will explain why you don't want this approach. Instead you should calculate the time a grop will be grown at the time of creation, and this is really just maintaining an extra field as in ( just showing the required fields ): var date = new Date(); PlantedCrop.create({ "owner": ownerId, "crop": cropId, "date"_planted": date, "grow_time": ( 1000 * 60 * 60 ) * 2, // "milliseconds" for two hours "ready_time": new Date( date.valueOf() + ( 1000 * 60 * 60 ) * 2) }); Then finding if that crop is not currently "fully grown" from the current time is as simple as: PlantedCrop.find({ "ready_time": { "$gte": new Date() } },function(err,crops) { }); And if you wanted things that are "ready" one hour from the current date then you just do: PlantedCrop.find({ "ready_time": { "$gte": new Date( Date.now + ( 1000 * 60 * 60 ) ) } },function(err,crops) { }); That is functionally simple and not confusing as all of the information is recorded when written and you simply look it up to set if it is grown yet. The "danger" with thinking about this in terms of calculation is that you start moving towards using a $where type of query with JavaScript evaluation of the fields: PlantedCrop.find({ "$where": function() { return this.date_planted.valueOf() + grow_time > Date.now; } },function(err,crops) { }); And this is very bad as such a test cannot use an index for the search and will "brute force" try to match every document in the collection. That is what you want to avoid and what you want to keep clean in the processing logic, but the other alternative is just work the math on the client when creating the request. Simply work backwards and check that the crop was planted "less than one hour" ago, and the grow time is in fact greater: PlantedCrop.find({ "date_planed": { "$lte": new Date( Date.now - ( 1000 * 60 * 60 ) ) }, "grow_time": { "$gte": ( 1000 * 60 * 60 ) } },function(err,crops) { }); And that will find you all crops "not fully grown" within the timeframe that you ask. But as to the original point, it just looks clunky and ugly, and is simply fixed by just storing the final calculated date and querying for that alone instead. Also please make sure that all this data is in the one collection, just as suggested at the begining. You cannot reference values from populated items in such a query as that is called a "join", which MongoDB does not do. Population merely "prettfies" object references by performing another query to replace those object references with whole objects, "after" initial queries are done.
{ "pile_set_name": "StackExchange" }
Q: Handle Exceptions from Thread in Global Exception Handler? I have a main application with a global exception handler installed. Now, for some specific exceptions being raised within another thread I want the global exception handler to be invoked. But it does only handle exceptions from the main thread. I also tried the following from within the thread but it does not work either: RunInMainThread (procedure begin raise EExceptionFromWithinThread.Create; end); where RunInMainThread just executes the anonymous method given as a parameter in the context of the main thread. Why doesn't this work? What's the proper way to handle such a situation? A: How about this: send a message to the main thread which exception should be raised.
{ "pile_set_name": "StackExchange" }
Q: Jquery add and remove DIV tag row based on select value I found this great stackoverflow post that does what I need: add and remove rows based on a select value, but the only difference is that in my case, I don't have a table but blocks of divs. In the table example it works fine, but with divs it fails. I've been using the console to try to fix it to no avail. It seems there are problems with the index value and the increment, but I don't undertand why with a table row works but with divs it doesnot. Could anyone take a look? Here's a jsfiddle that shows the issue: http://jsfiddle.net/njes3w1a/1/ This is my script: if ($('#returnRequest').length) { var row_i = 0; function emptyRow() { row_i++; this.obj = $('<div class="return-row control-group row"></div>'); this.obj.append('<div class="col-md-6"><label class="control-label">Serial number</label><input type="text" class="form-control" value=""/></div><div class="col-md-4"><label class="control-label">Item is</label><select class="form-control"><option value="">Select</option><option value="1">New and unopened</option><option value="2">Defective</option></select></div>'); } function refresh(new_count) { //how many applications we have drawed now ? console.log("New count= " + new_count); if (new_count > 0) { $("#noa_header").show(); } else { $("#noa_header").hide(); } var old_count = parseInt($('#productRowWrapper').children().length); console.log("Old count= " + old_count); //the difference, we need to add or remove ? var rows_difference = parseInt(new_count) - old_count; console.log("Rows diff= " + rows_difference); //if we have rows to add if (rows_difference > 0) { console.log('enetered a'); for (var i = 0; i < rows_difference; i++) $('#productRowWrapper').append((new emptyRow()).obj); } else if (rows_difference < 0) //we need to remove rows .. { console.log('enetered b'); var index_start = old_count + rows_difference + 1; console.log("Index start= " + index_start); $('.return-row:gt(' + index_start + ')').remove(); console.log(row_i); console.log(rows_difference); row_i += rows_difference; console.log(row_i); } } $('#quantityReturn').change(function () { refresh($(this).val()); }); } A: I would use this code: if ($('#returnRequest').length) { function emptyRow() { this.obj = $('<div class="return-row control-group row"></div>'); this.obj.append( '<input type="text" class="form-control" value=""/>' + '<select class="form-control">' + '<option value="">Select</option>' + '<option value="1">New and unopened</option>' + '<option value="2">Defective</option>' + '</select>'); } function refresh(count) { if (count > 0) { $("#noa_header").show(); } else { $("#noa_header").hide(); } var wrapper = $('#productRowWrapper'); while (wrapper.children().length > count) wrapper.children().last().remove(); while (wrapper.children().length < count) wrapper.append((new emptyRow()).obj); } $('#quantityReturn').change(function () { refresh(parseInt($(this).val())); }); } It does not introduce unnecessary variables and it a bit shorter. Updated fiddle at http://jsfiddle.net/njes3w1a/6/.
{ "pile_set_name": "StackExchange" }
Q: Package/Device for a component with duplicated pins I have a L79L05 from ST Microelectronics, which has the following pinout: I have created a symbol and package in Eagle for that component. The symbol has three pins - IN, OUT and GND, while the package has 8 pads. When creating device, I connected pads 2, 3, 6 and 7 to the IN pin. As a result, in board editing mode, Eagle adds airwires that asks me to connect all these pins on PCB: Of course I can overcome these airwires by either ignoring it, or by creating a symbol which has 8 (or 6, as two marked as NC) pins, and assign some of them to a same swap network. But I would like to find a better solution, if there is one. A: You should solder all the pins and use both in and both out pins for the connection to your traces on the PCB. Combining multiple adjacent pins, especially on thin-pitch ICs, is done to allow for better thermal and inductive behaviour of the respective connection. A Quote from the L79L datasheet: Our SO-8 package used for Voltage Regulators is modified inter nally to have pins 2, 3, 6 and 7 electrically communed to the die attach flag. This particular frame decreases the total thermal resistance of the package and increases its ability to dissipate power when an appropriate area of copper on the printed circuit board is available for heat-sinking. The external dimensions are the same as for the standard SO-8.
{ "pile_set_name": "StackExchange" }
Q: Is there a way of finding position of element when searching a char array with bsearch() First time using bsearch() and i was wondering is there a way of finding the position of the element or return the element?? I have bsearch() working and it returns a pointer but from this i am not able to use it to print the element. void choose_food_item(){ char food[20]; int qty; int size = sizeof (food_stuff_choices) / sizeof (*fs); char * ptr_item; do{ printf("\nPlease Choose Your Food Items!!! When finished enter display to view plan\n"); fflush(stdout); gets(food); // searchkey /* sort the elements of the array */ qsort(food_stuff_choices,size,sizeof(*fs),(int(*)(const void*,const void*)) strcmp); /* search for the searchkey */ ptr_item = (char*) bsearch (food,food_stuff_choices,size,sizeof(*fs),(int(*)(const void*,const void*)) strcmp); if (ptr_item!=NULL){ //printf("%d\n",(int)*ptr_item); printf("Please Enter Quantity\n"); fflush(stdout); scanf("%d",&qty); food_plan_item item = {food_stuff_choices[0], qty}; add_food_plan_item(item); } else printf ("%s not found in the array.\n",food); }while(strcmp("display",food) != 0); } A: bsearch returns a pointer to the found element. Subtract that address from the address of the zeroth element. Then divided by the length of the element. That gives you the subscript to the element.
{ "pile_set_name": "StackExchange" }
Q: Why use LUV color space to present objects in object detection? In this paper,Fast feature pyramids for object detection,they use LUV color space to present pedestrians.After I searched more papers, i found many of papers used LUV color space. My questions: 1)what's the advantages of LUV color space over RGB in object detection? 2)what's the characteristic of LUV color space? Thanks. A: A non-technical answer: There are two reasons we might use non-RGB colorspaces, including LUV, in computer vision. The first reason is that differences in RGB space do not correspond well to perceived differences in color. That is, two colors can be close in RGB space but appear very different to humans and vice versa. The second reason (and I would say the more important one for object detection) is that spaces like LUV decouple the "color" (chromaticity, the UV part) and "lightness" (luminance, the L part) of color. Thus in object detection, it is common to match objects just based on the UV part, which gives invariance to changes in lighting condition.
{ "pile_set_name": "StackExchange" }
Q: C# IEnumerable and IList difference private static void Main(string[] args) { var query = Data(); } private static IList<Employee> Data() { List<Employee> list = new List<Employee>(); list.Add(new Employee { Name = "test0", Age = 19 }); list.Add(new Employee { Name = "test1", Age = 33 }); list.Add(new Employee { Name = "test2", Age = 25 }); return list; } private static IEnumerable<Employee> Data() { List<Employee> list = new List<Employee>(); list.Add(new Employee { Name = "test0", Age = 19 }); list.Add(new Employee { Name = "test1", Age = 33 }); list.Add(new Employee { Name = "test2", Age = 25 }); return list; } When I run code above, I didn't see any different result when result type in IEnumerable or IList. Is there any different using both of them? How to decide which type to use? A: IList inherits from IEnummerable so they are essentially the same just IList has extra functionality. It depends on what you are doing with that data once its created as to whether you should use an IEnummerable or IList. IEnumerable is good if you only want to iterate over the collections content as its readonly. IList allows adding and removing of content (so does ICollection) and allows direct access to elements with an index
{ "pile_set_name": "StackExchange" }
Q: Install j2me application in samsung mobile We developing j2me application for low end mobile devices (like Nokia s40 mobiles) which supports java. In our application we used JSR75 and JSR135 its working in nokia and sony ericsson but while trying to install the same application in Samsung devices(GT-S3310 ) we getting error like "File Format not supported". Please help how to install the jar file in samsung mobiles. A: How are you installing the app? Side-loading the jar directly on to the device via USB or Bluetooth? Some handsets don't support that. Try installing it over the air instead, by pointing the web browser to the JAD which should be online somewhere. A: I already checked on some samsung mobiles. They could not allow direct installation through with bluetooth or with USB cable. Because they following certain security norms of java apps installation. You need to install it from WAP sites.
{ "pile_set_name": "StackExchange" }
Q: Are all vegetarian products Halal? Can Muslims safely consider all vegetarian products as Halal? If not then what are the things that are required to be looked at carefully before purchasing such products? A: No, all vegetarian products need not be halal. For example, Vanilla in liquid form may contain alcohol. It is vegetarian but not halal. A: A food/drink being vegetarian eliminates the extra preclusions when consuming meat and animal products (Qur'an 2:173, 5:3, 6:121, 6:145). A food/drink being vegetarian makes is much easier for it to be halal, although there's some exceptions: Alcohol, marijuana, and other intoxicants not created from animals are vegetarian are are not haram. This includes: Vanilla extract ordinarily contains 35% alcohol, which should be considered haram to drink (or own) even if only in small amounts: "The Prophet [SAW] forbade a small amount of whatever intoxicates in large amounts." [grade: hasan] (sunnah.com). However, vanilla itself is ordinarily okay; see Islam Q&A. Some brands of soy sauce contain sufficient alcohol to render it haram. Kikkoman Soy Sauces contain greater than 2% alcohol by volume. -- FAQs About Sauces and Mixes I wrote about alcohol-containing condiments in this answer. Pig milk is vegetarian. Vegetarian food might also be cooked using the same equipment that is used to cook pork, etc., which would render them haram. Vegetarian foods relating to other religions, such as hot cross buns, easter eggs, communion wafers, may be considered haram to eat; see e.g. AskImam. Also, there's some ingredients which a less-strict vegetarian may not pay much attention to (possibly for practical reasons): Some ice creams contain geletin, which might be derived from pig, rending it haram. Some cheese contain rennet which comes from animals, which might make the cheese haram. There's a difference of opinion as to whether this renders cheese haram; see Islam Q&A. Various animal-based cooking oils.
{ "pile_set_name": "StackExchange" }
Q: e.Row.RowIndex throwing Argument out of Range Exception This doesn't make sense to me: if I run this code: protected void viewStoryTime_OnRowDataBound(Object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { var obj = ((DataRowView)e.Row.DataItem)["ActivityDate"]; if (DateTime.Parse(obj.ToString()) < DateTime.Now.StartOfWeek(DayOfWeek.Monday)) { System.Diagnostics.Debug.WriteLine(e.Row.RowIndex); } } } My output is: 4 Now if I try to use this to clear a cell: protected void viewStoryTime_OnRowDataBound(Object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { var obj = ((DataRowView)e.Row.DataItem)["ActivityDate"]; if (DateTime.Parse(obj.ToString()) < DateTime.Now.StartOfWeek(DayOfWeek.Monday)) { viewStoryTime.Rows[e.Row.RowIndex].Cells[3].Controls.Clear(); } } } I get: A first chance exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll Additionally, I get this exception if I manually input 4: viewStoryTime.Rows[e.Row.RowIndex].Cells[3].Controls.Clear(); If I input 3 however it removes the control from the column directly before the one that it should: Why am I getting this exception and what can I do about it? A: Based on everything you've tried, the only way you're getting this exception is for e.Row.RowIndex to be out of range: viewStoryTime.Rows[e.Row.RowIndex]... However, it's unclear to me why you don't simply do this: e.Row.Cells[3].Controls.Clear(); You could have issues accessing the rows on viewStoryTime depending on where the page is in the event life cycle.
{ "pile_set_name": "StackExchange" }
Q: How to move subfolder with files to another directory? I use this code to move files from one folder to another. $src = path_a; $dest = path_b; // get files $files = scandir($src); // movin files foreach ($files as $file){ if (in_array($file, array(".",".."))) continue; if (copy($src.$file, $dest.$file)){ $delete[] = $src.$file; } } // del files foreach ($delete as $file) { unlink($file); } It works, but i have one subfolder with some files in source foulder ("path_a"). How i can move this subfolder with files to "path_b" and delete path_a directory? A: The easiest way: foreach ($files as $file){ if (in_array($file, array(".",".."))) continue; rename($src.$file, $dest.file); } For more details, have a look to rename.
{ "pile_set_name": "StackExchange" }
Q: Evaluating $\int_{} \frac{xe^{2x}}{(1+2x)^2}dx$ via integration by parts $\int_{} \frac{xe^{2x}}{(1+2x)^2}dx$ I am having trouble picking the correct $u/dv$ before integrating by parts. I felt like L.I.A.T.E. did not really help me here... This is what I tried, but it ended up with integration spiraling into an endless evaluation of an integral... $$ \begin{align} u &= (1 + 2x)^2 & dv &= xe^{2x}dx \\ du &= 2(1+2x)dx & v &= \frac{1}{2}x^2 \frac{1}{2}e^{2x} \\ &= 2 + 4xdx & &= \frac{1}{4}x^2e^{2x} \end{align} $$ Am I at least correct in choosing the right $u/du$ values? That is all I really want to know, if I am allowed to choose the $u/du$ like how I did A: Hint: Let $u=xe^{2x}$, $\text dv=\dfrac{\text dx}{(1+2x)^2}$. Result: $$\dfrac{\mathrm{e}^{2x}}{8x+4} + C$$ EDIT: More steps. \begin{eqnarray*} \int \frac{xe^{2x}}{(1+2x)^2} \ \text dx &=& \left|\begin{array}{2} u=xe^{2x} & \text dv=\dfrac{\text d x}{(1+2x)^2} \\ \text du = (1+2x)e^{2x}\ \text dx & v=-\dfrac{1}{2(1+2x)} \end{array}\right| = \\ &=& -\frac{xe^{2x}}{2(1+2x)} + \frac{1}{2} \int e^{2x}\ \text dx = \\ &=&-\frac{xe^{2x}}{2(1+2x)} + \frac{1}{4}e^{2x} + C = \\ &=& e^{2x}\left( -\frac{x}{2(1+2x)}+\frac{1}{4} \right) + C = \boxed{\frac{e^{2x}}{8x+4} + C} \end{eqnarray*}
{ "pile_set_name": "StackExchange" }
Q: How to restore single directory in a Fossil repo? Some commits ago, I deleted a directory in my Fossil repo. How do I get it back? A: The simplest way would be: open fossil ui go to the last commit in which your directory existed click on “zip file” to download a zip of the repository at that time decompress only the right folder.
{ "pile_set_name": "StackExchange" }
Q: How to use FloatingPoint generic type for Float/Double I'd like to make the function below work both with Float and Double values: func srgb2linear(_ S: Float) -> Float { if S <= 0.04045 { return S / 12.92 } else { return pow((S + 0.055) / 1.055, 2.4) } } The Swift 4 Documentation says that what I need is a FloatingPoint generic, to represent both Float and Double classes, like: func srgb2linear<T: FloatingPoint>(_ S: T) -> T However when I try to do this, it doesn't compile with the following errors: Error: binary operator '<=' cannot be applied to operands of type 'T' and 'Double' Error: binary operator '/' cannot be applied to operands of type 'T' and 'Double' Error: binary operator '+' cannot be applied to operands of type 'T' and 'Double' How is it possible that for a generic representing floating point numbers such operators are not implemented? And if not like this, how can I write this function in Swift? A: One problem is that FloatingPoint is not a subprotocol of ExpressibleByFloatLiteral, so your floating-point literals cannot necessarily be converted to T. You can solve this either by changing FloatingPoint to BinaryFloatingPoint (which is a subprotocol of ExpressibleByFloatLiteral) or by adding ExpressibleByFloatLiteral as a separate requirement. Then you will run into the problem that there is no pow function that is generic over FloatingPoint, and no member of FloatingPoint or BinaryFloatingPoint that performs exponentiation. You can solve this by creating a new protocol and conforming the existing floating-point types to it: protocol Exponentiatable { func toPower(_ power: Self) -> Self } extension Float: Exponentiatable { func toPower(_ power: Float) -> Float { return pow(self, power) } } extension Double: Exponentiatable { func toPower(_ power: Double) -> Double { return pow(self, power) } } extension CGFloat: Exponentiatable { func toPower(_ power: CGFloat) -> CGFloat { return pow(self, power) } } Note that there is also a Float80 type, but the standard library doesn't provide a pow function for it. Now we can write a working generic function: func srgb2linear<T: FloatingPoint>(_ S: T) -> T where T: ExpressibleByFloatLiteral, T: Exponentiatable { if S <= 0.04045 { return S / 12.92 } else { return ((S + 0.055) / 1.055).toPower(2.4) } }
{ "pile_set_name": "StackExchange" }
Q: Remove XML namespaces with XML::LibXML I'm converting an XML document into HTML. One of the things that needs to happen is the removal of namespaces, which cannot be legally declared in HTML (unless it's the XHTML namespace in the root tag). I have found posts from 5-10 years ago about how difficult this is to do with XML::LibXML and LibXML2, but not as much recently. Here's an example: use XML::LibXML; use XML::LibXML::XPathContext; use feature 'say'; my $xml = <<'__EOI__'; <myDoc> <par xmlns:bar="www.bar.com"> <bar:foo/> </par> </myDoc> __EOI__ my $parser = XML::LibXML->new(); my $doc = $parser->parse_string($xml); my $bar_foo = do{ my $xpc = XML::LibXML::XPathContext->new($doc); $xpc->registerNs('bar', 'www.bar.com'); ${ $xpc->findnodes('//bar:foo') }[0]; }; $bar_foo->setNodeName('foo'); $bar_foo->setNamespace('',''); say $bar_foo->nodeName; #prints 'bar:foo'. Dang! my @namespaces = $doc->findnodes('//namespace::*'); for my $ns (@namespaces){ # $ns->delete; #can't find any such method for namespaces } say $doc->toStringHTML; In this code I tried a few things that didn't work. First I tried setting the name of the bar:foo element to an unprefixed foo (the documentation says that that method is aware of namespaces, but apparently not). Then I tried setting the element namespace to null, and that didn't work either. Finally, I looked through the docs for a method for deleting namespaces. No such luck. The final output string still has everything I want to remove (namespace declarations and prefixes). Does anyone have a way to remove namespaces, setting elements and attributes to the null namespace? A: Here's my own gymnasticsy answer. If there is no better way, it will do. I sure wish there were a better way... The replace_without_ns method just copies nodes without the namespace. Any children elements that need the namespace get the declaration on them, instead. The code below moves the entire document into the null namespace: use strict; use warnings; use XML::LibXML; my $xml = <<'__EOI__'; <myDoc xmlns="foo"> <par xmlns:bar="www.bar.com" foo="bar"> <bar:foo stuff="junk"> <baz bar:thing="stuff"/> fooey <boof/> </bar:foo> </par> </myDoc> __EOI__ my $parser = XML::LibXML->new(); my $doc = $parser->parse_string($xml); # remove namespaces for the whole document for my $el($doc->findnodes('//*')){ if($el->getNamespaces){ replace_without_ns($el); } } # replaces the given element with an identical one without the namespace # also does this with attributes sub replace_without_ns { my ($el) = @_; # new element has same name, minus namespace my $new = XML::LibXML::Element->new( $el->localname ); #copy attributes (minus namespace namespace) for my $att($el->attributes){ if($att->nodeName !~ /xmlns(?::|$)/){ $new->setAttribute($att->localname, $att->value); } } #move children for my $child($el->childNodes){ $new->appendChild($child); } # if working with the root element, we have to set the new element # to be the new root my $doc = $el->ownerDocument; if( $el->isSameNode($doc->documentElement) ){ $doc->setDocumentElement($new); return; } #otherwise just paste the new element in place of the old element $el->parentNode->insertAfter($new, $el); $el->unbindNode; return; } print $doc->toStringHTML;
{ "pile_set_name": "StackExchange" }
Q: Why is 二十歳 pronounced はたち? 二十歳 is a (to me) bizarre exception to the usual number+さい rule for discussing age. Is this rooted in 20 being the Japanese age of majority? Added: To be more specific: why isn't it pronounced にじゅうさい like the rest of the さい words for age? A: The はた there is part of the same series of Japanese readings for numbers as ひとつ、ふたつ、みっつ and so on. Where the ち comes from - that I do not know. It also makes an appearance in some other common words, such as 二十日(はつか), although in a slightly mangled form. There are readings for the tens after that as well - for instance 三十(みそ) makes an appearance in words such as 三十日(みそか) and 三十路(みそじ). The rest of the tens are formed by adding そ to the corresponding "ones" stem: よそ いそ むそ ななそ やそ ここのそ. Although rarely used these days, the old way of counting was quite flexible. Here's a Chiebukuro question that explains the old way pretty nicely - including how to count hundreds, thousands and tens of thousands! A: Some theories from http://gogen-allguide.com/ha/hatachi.html Please forgive and correct any mistakes I made. Theory: はた means 20. For example: 二十歳 はたち、二十人 はたとり、二十年 はたとせ。 ち (個)is a counter for the ひと、ふた、み counting system. Theory (folklore): The 旗乳 (はたち)folktale. During the Warring States period, a young soldier who turned 20 years old wore a banner (旗 はた)of his lords family crest on his back into battle. On that banner he put 20 decorative things (乳 - ち) to match his age. So the theory associates the age of 20 with being old enough to risk your life at war, an adult. Theory (folklore): If you count your fingers and toes you end up with 20. Deriving from 果て (はて), you reach the end (はて) at 20. There are more on that site.
{ "pile_set_name": "StackExchange" }
Q: Google Sheets API - Python - Constructing Body for BatchUpdate I need to create the body for multiple updates to a Google Spreadsheet using Python. I used the Python dictionary dict() but that doesn't work for multiple values that are repeated as dict() doesn't allow multiple keys. My code snippet is: body = { } for i in range (0,len(deltaListcolNames) ): rangeItem = deltaListcolNames[i] batch_input_value = deltaListcolVals[i] body["range"] = rangeItem body["majorDimension"] = "ROWS" body["values"] = "[["+str(batch_input_value)+"]]" batch_update_values_request_body = { # How the input data should be interpreted. 'value_input_option': 'USER_ENTERED', # The new values for the input sheet... to apply to the spreadsheet. 'data': [ dict(body) ] } print(batch_update_values_request_body) request = service.spreadsheets().values().batchUpdate( spreadsheetId=spreadsheetId, body=batch_update_values_request_body) response = request.execute() A: Thanks for the answer, Graham. I doubled back and went away from using the dict paradigm and found that by using this grid, I was able to make the data structure. Here is how I coded it... perhaps a bit quirky but it works nicely: range_value_data_list = [] width = 1 # height = 1 for i in range (0,len(deltaListcolNames) ): rangeItem = deltaListcolNames[i] # print(" the value for rangeItem is : ", rangeItem) batch_input_value = str(deltaListcolVals[i]) print(" the value for batch_input_value is : ", batch_input_value) # construct the data structure for the value grid = [[None] * width for i in range(height)] grid[0][0] = batch_input_value range_value_item_str = { 'range': rangeItem, 'values': (grid) } range_value_data_list.append(range_value_item_str)
{ "pile_set_name": "StackExchange" }
Q: S3 NodeJS -ListObjects always returns 0 The code for this question is already here: Does writing to S3(aws-sdk nodeJS) conflict with listing objects in a bucket? Please be sympathetic, I've been on this problem for days and I'm a complete rookie. I am trying to poll for a list of objects(haveFilesBeenWrittenToBucket method) and then read the file when there are objects (readFile method). If I place a breakpont on the callback(items) in the haveFilesBeenWrittenToBucket, everything works fine. If I don't, I always get 'number of items 0' written out to the console. It is not predictable exactly when the stuff will be written to S3, but it should be within a minute. There appears to be a race condition, and I would be very grateful if anyone could help me out here. I'm desperate for ideas. Thanks so much. P.S. I was advised to make this a separate question to the one asked in the link. A: In the end, I was barking up the wrong tree- my error had nothing to do with node.
{ "pile_set_name": "StackExchange" }
Q: prove unique minimal normal subgroup of soluble group by $ P_{G}(M) > M $ Let $ G $ be a soluble group. If $ P_{G}(M) = \langle y\in G | \langle y \rangle M = M\langle y \rangle \rangle > M $for any subgroup $ M $ of prime power index in $ G $, then every chief factor of $ G $ has order $ 4 $ or a prime. For proof let $ G $ be a counterexample of minimal order and choose a minimal normal subgroup $ A $ of $ G $. Hence $ A $ is elementary abelian group of prime power order. since $ G/A $ is a soluble group and $ \vert G/A \vert < \vert G \vert $, so each chief factor of $ G/A $ has order $ 4 $ or a prime. Now i need to prove $ A $ is the unique minimal normal subgroup of $ G $. Suppose $ A_{1} $ and $ A_{2} $ are minimal normal subgroups of $ G $ that $ A_{1} \neq A_{2} $. So $ A_{1} \cap A_{2} = 1 $ and each chief factor of $ G/A_{1} $ and $ G/A_{2} $ have order $ 4 $ or prime. Since $ G/A_{1} \times G/A_{2} = G/A_{1} \cap A_{2} \cong G $, now can say every chief factor of $ G $ has order $ 4 $ or a prime? If it is true, then it is contradiction. A: In general, if $H \le G$, and $K/L$ is a chief factor of $G$, then $(H \cap K)/(H \cap L) \cong (H \cap K)L/L$ is a subgroup of $K/L$. So, if every chief factor of $G$ has order $4$ or prime, then the same is true of any subgroup $H$ of $G$. So, in your situation, every chief factor of $G/A_1$ and of $G/A_2$ has order $4$ or prime, so the same is true of $G/A_1 \times G/A_2$, and hence the same is true of $G \cong G/A_1 \cap A_2$, which is isomorphic to a subgroup of $G/A_1 \times G/A_2$.
{ "pile_set_name": "StackExchange" }
Q: iPad Retina Launch Image -- Only top half of the image is displayed I've added launch images for the iPad retina display. I use the required sizes. When the app is run on the simulator, the launch images look fine. When run on actual devices (tested 2 devices, both New iPad (3rd generation)), only the top half of the image shows up, the bottom half of the screen is black. Once the launch image is dismissed, everything is displayed properly. If I assign the smaller (non-Retina) launch images, they display properly (though the image is not crisp, obviously). Any thoughts? Note: these are 2.4 MB png files. Thanks for any help! A: Apparently the image files were corrupted. Oddly, they opened fine in Preview and Safari, but not in the app for some reason. Anyway, I recreated the images, and all was well.
{ "pile_set_name": "StackExchange" }
Q: New line character as function parameter in Javascript From Test.html I include a test.js that runs function d(). This function has a parameter a string that might contain "new line" characters (10 in ASCII), as per example below. However, when I am debugging this function, vars s and data include all characters except the new line, i.e., they contain string "HelloWorld" (length 10) instead of "Hello[charNewLine]World" (length 11). Is there a way to pass a string with new line characters as parameter to a function in Javascript? Thank you. Test.html <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=x-user-defined"> <title>JavaScript Scripting</title> </head> <body> <script type="text/javascript" charset="x-user-defined" src="test.js"> </script> </body> </html> test.js function d(s) { var data = (s + "").split(""); var dataLength = data.length; var t = [dataLength],n; for(n=0;n<dataLength;n++) t[n]=data[n].charCodeAt(0); } d("Hello\ World"); A: d("Hello\ World"); contains a "line continuation". The language specification says The String value (SV) of the literal is described in terms of character values (CV) contributed by the various parts of the string literal. ... The SV of LineContinuation :: \ LineTerminatorSequence is the empty character sequence. which means that it contributes no characters to the value of the string literal. To embed a newline in a string, just use \n as in d("Hello\nWorld")
{ "pile_set_name": "StackExchange" }
Q: Magento 2 Upgrade 404 Error (document root set to PUB folder) As I'm sure you are aware, there is a new version of Magento 2 (2.0.3 at the time of writing). I can not follow the update instructions given in the Magento developer docs (using the System Upgrade utility) as my document root points to the pub folder, not the main Magento installation folder. The setup wizard is not in the pub directory for security reasons and the best practice is to use the pub folder as the document root. The only way I can think of using the setup wizard to upgrade the system is to change the doc root to the main Magento installation folder, upgrade the system, change the doc root back to the pub folder. Does anyone know of any other work around or a way to upgrade with the setup wizard? I installed Magento via the command line using the compressed package (decompressed and installed via the command line tool) A: For a Magento install initially via the zip/gzip method, where pub is the document root, the procedure we're following to upgrade is: Edit the composer.json file in the main directory, and change the "magento/product-community-edition" to 2.0.3 run: "composer update" chmod a+x bin/magento run: bin/magento setup:upgrade run: bin/magento cache:flush This seems to work well from what we've found so far. It's not officially documented in the dev guide, but seems to be an accepted method for now...
{ "pile_set_name": "StackExchange" }
Q: Can You build a DockPanel like Visual Studio in WPF In Visual Studio, we can add various panels like SolutionExplorer Panel, Properties Panel,etc. Also we can minimize these panels and maximize these panels. I want to design a dockpanel similar to what I have mentioned in WPF. ( I should be able to pin the panel, unpin the panel, etc) Does DockPanel support this by default? Or should I do something to support this feature. A sample illustration of code will be great!!! A: DockPanel is just a common Panel for arranging elements around the edges of the container with the option of having the last element fill the remaining space. It does not do any sort of VS type docking/undocking/pinning/unpinning. For something like that you would need a custom control. You could try a free one like AvalonDock or purchase ones like Infragistics XamDockManager or from the other component vendors.
{ "pile_set_name": "StackExchange" }
Q: How to translate 哪有农村热闹? 北京城里禁止随便放鞭炮,城里人过春节越来越简单, 哪有农村热闹? I don't understand the last part of this sentence, marked in bold. I guess it's a rhetorical question? My attempt: Beijing City banned setting off fireworks, so the city dwellers' celebration of the Spring Festival has become more and more simple. The city is not as lively as the countryside? I can provide more of the dialogue if necessary. A: Yes, it is a rhetorical question, the emphasis is on the lively and noisy fashion the village dwellers can celebrate compared to Beijingers. It is a good way to contrast difference. I would translate it (second sentence only) as 'How can you compare that to the lively manner of celebration in the countryside!' PS. My English is not the best, native speakers can put it right, but I think the idea is clear.
{ "pile_set_name": "StackExchange" }
Q: Open source project for downloading mailing list archives preferably in Python I am interested in knowing if there are any open source projects (preferably in Python) which can be used to download (crawl?) the mailing list archives of open source projects such as Lucene/Hadoop (such as http://mail-archives.apache.org/mod_mbox/lucene-java-user/). I am specially looking for a crawler/downloader customized for (Apache) mailing list archives (not a generic crawler such as Scrappy). Any pointers are highly appreciated. Thank you. A: There's usually facilities for downloading mbox files. In the link you provided, you can for example append the mbox name and get the mail archive directly. Example, the mbox for October 2012: http://mail-archives.apache.org/mod_mbox/lucene-java-user/201210.mbox So getting the archives programmatically is pretty straightforward. Once you have them: import mailbox mails = mailbox.mbox(filename.mbox) for message in mails: print message['subject']
{ "pile_set_name": "StackExchange" }
Q: Memory Address and values in memory address I have a little confusion. struct node *p; and if(p==NULL) Now what I have gathered based upon my studies is that NULL is not a memory address but a value (i.e 0) in the memory address. When I use if(*p==NULL) it gives an error - no match for 'operator=='. But doesn't *p gives the value in the memory address. If we just use p aren't we comparing a memory address with a value in the memory address. Why is p==NULL correct while *p=NULL is not. A: Yes, *p gives the value in a memory address. But in this case, that value is a struct node because p is of type "pointer to struct node". You can't compare a structure's value to NULL. A: If we just use p aren't we comparing a memory address with a value in the memory address No. When we talk about NULL, as per the C11 standard, chapter §7.19, <stddef.h>, (emphasis mine) NULL which expands to an implementation-defined null pointer constant;[...] So, NULL is a pointer and in your code, so is p. So, you can compare them. OTOH, *p is a value, and you cannot compare that with NULL.
{ "pile_set_name": "StackExchange" }
Q: Serve multiple static files and make a post request in golang I just started using Golang 2 days ago, so this is probably pretty simple, but nevertheless hard for me. The first step of my question was to serve multiple files under the directory "/static", which I already know how to do ( func main() { fs := http.FileServer(http.Dir("./static")) http.Handle("/", fs) log.Println("Listening on :3000...") err := http.ListenAndServe(":3000", nil) if err != nil { log.Fatal(err) } }) ), but I want to make POST requests too (to save information to a MongoDB database) which is the part that stumps me. There is a code sample that does allow to serve one static file and a POST request, but I couldn't modify with my abilities. This sample can be found here:https://www.golangprograms.com/example-to-handle-get-and-post-request-in-golang.html. Can I make it somehow to serve multiple static files (under the directory "static" preferably)? A: Write a handler that calls through to fs for non-POST requests: type handler struct { next http.Handler } func (h handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { if r.Method != "POST" { h.next.ServeHTTP(w, r) return } // write post code here } Use the handler like this: func main() { fs := http.FileServer(http.Dir("./static")) http.Handle("/", handler{fs}) log.Println("Listening on :3000...") err := http.ListenAndServe(":3000", nil) if err != nil { log.Fatal(err) } }
{ "pile_set_name": "StackExchange" }
Q: VB.net rearrange string data from 20171019 to 19/10/2017 Can anyone assist me with learning how to rearrange data from a format of (example) 20171019 to 19/10/2017? The 20171019 is obtained from a SQL query as a string, the data type being nvarchar(255), but I then want to display it as a standard date format. Do I somehow assign each character of the string a position (value) and then rearrange those values, or is there a formatting tool built within VB? Thank you very much for your time and assistance in this matter. A: On clientside you have to parse the string to DateTime, then you can use ToString(format) to apply a specific format. But the important question is why you need that, why you get a DateTime as string from your database? Why you don't store it as DateTime or Date? However, here is how you parse and convert: Dim dt = DateTime.ParseExact("20171019", "yyyyMMdd", Nothing) Dim result = dt.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture)
{ "pile_set_name": "StackExchange" }
Q: jQuery not behaving as expected in reference to clicks I have an element that I grab the content of and swap for an input, I then want to user to be able to click on the input (to enter text as normal), but if they click anywhere else to swap it back to the text. However the click event seems to fire even the very first time the user clicks anywhere on the page. My code is below, have I misunderstood something? $(document).ready(function(){ $("#thingy").css('cursor', 'pointer'); $("#thingy").one("click", function() { var element = $(this); element.css('cursor', 'auto'); element.css('display', 'inline-block'); element.fadeOut(100, function(){element.html('<input type="text" size="25" value="' + element.text() + '" style="width:' + element.width() + 'px;height:' + element.height() + 'px;border:none;padding:0px;margin:0px;">')}).fadeIn(100); $("#thingy").click(function() { return false; }); $(document).click(function() { alert("You clicked off the text-box"); element.html(element.children('input:text').val()); }); }); }); A: The reason it alerts even the first time is the first click handler (the .one() doesn't itself return false; or .stopPropgaton(), like this: $(document).ready(function(){ $("#thingy").css('cursor', 'pointer'); $("#thingy").one("click", function() { var element = $(this); element.css('cursor', 'auto'); element.css('display', 'inline-block'); element.fadeOut(100, function(){element.html('<input type="text" size="25" value="' + element.text() + '" style="width:' + element.width() + 'px;height:' + element.height() + 'px;border:none;padding:0px;margin:0px;">')}).fadeIn(100); $("#thingy").click(function() { return false; }); $(document).click(function() { alert("You clicked off the text-box"); element.html(element.children('input:text').val()); }); return false; }); }); ​ You can test it out here. A better approach would be to use the blur event instead, replacing this: $("#thingy").click(function() { return false; }); $(document).click(function() { alert("You clicked off the text-box"); element.html(element.children('input:text').val()); }); return false; With this: $(element).delegate("input", "blur", function() { element.html(element.children('input:text').val()); }); You can try that version here.
{ "pile_set_name": "StackExchange" }
Q: Base64 Encoding in objective-c IOS-App I am using this function in Java to generated a secrect URL Parameter: new String(Base64Encoding.encode(String.valueOf(vendorId), Bean.getSessionId())) And i need to do the same in my ios app, can someone help? Only found examples for base64 encoding. But not how to say this is my "salt". (Sessionid). A: There is no ready to use function for Base64 in iOS. However you can use one of existing implementations and libraries. You can check on of those: https://github.com/nicklockwood/Base64/ https://gist.github.com/0xced/1901480 Salt is just concatenated to the String. So if your Salt is "MySalt" than it's combining Salt with your string and do Base64 on concatenated String. You need to make salt value equal on both devices - just define it as your secret on both platforms.
{ "pile_set_name": "StackExchange" }
Q: Extends Android APIs I work with Eclipse and implement some applications using the Android Emulator. I'd like to know: is it possible to extend Android APIs with other .jar file? If it's possible, how can I extend the APIs? I just have to add libraries to the project or do I copy it to the $ANDROID_HOME/platforms/android-8/tools/lib A: If you want to use thirdparty jars you just need to include them in your Android application. You can do that putting them in a lib directory under your android project or adding them to your build path. You do not need to add anything to the SDK.
{ "pile_set_name": "StackExchange" }
Q: FireDAC: How to avoid "Cannot describe type" error? (on a postgres geometry column) I have read in the documentation (http://docwiki.embarcadero.com/RADStudio/Tokyo/en/Defining_Connection_(FireDAC)) that one must set the connection parameter "UnknownFormat" to "BYTEA", to avoid this error. However, I have set that parameter and still get that error. Details: A simple VCL forms application with an FDConnection and an FDQuery. Tested the FDConnection and set the UnknownFormat parameter to ufBYTEA. Put an SQL select statement in the FDQuery which selects a geometry field from a table. On Execute I get the error. A: Reproduced in Delphi Tokyo 10.2.3 with PostgreSQL 10.1, PostGIS 2.4.3. Issue report RSP-20251. But I believe it's irrelevant as I guess you've simply returned raw geometry data (as they are stored by PostGIS) without proper geometry output. It's because when you returned your data e.g. in the WKB format by using the ST_AsBinary function, the column would be described by the statement. So review your SQL command and check if you're not returning raw geometry. If so, return proper geometry output instead.
{ "pile_set_name": "StackExchange" }
Q: Activemq not start in linux mint17 Please see the following console output after executing activemq console command: /opt/apache-activemq-5.5.1/bin $ sudo activemq console sudo: /var/lib/sudo/vivek writable by non-owner (040777), should be mode 0700 [sudo] password for vivek: INFO: Loading '/usr/share/activemq/activemq-options' INFO: Using java '/usr/bin/java' INFO: Starting in foreground, this is just for debugging purposes (stop process by pressing CTRL+C) INFO: changing to user 'activemq' to invoke java mkdir: missing operand Try 'mkdir --help' for more information. Java Runtime: Oracle Corporation 1.8.0_45 /usr/lib/jvm/java-8-oracle/jre Heap sizes: current=502784k free=492256k max=502784k JVM args: -Xms512M -Xmx512M -Dorg.apache.activemq.UseDedicatedTaskRunner=true -Dcom.sun.management.jmxremote -Djava.io.tmpdir=/var/lib/activemq/tmp -Dactivemq.classpath=/var/lib/activemq/conf; -Dactivemq.home=/usr/share/activemq -Dactivemq.base=/var/lib/activemq/ -Dactivemq.conf=/var/lib/activemq/conf -Dactivemq.data=/var/lib/activemq/data ACTIVEMQ_HOME: /usr/share/activemq ACTIVEMQ_BASE: /var/lib/activemq ACTIVEMQ_CONF: /var/lib/activemq/conf ACTIVEMQ_DATA: /var/lib/activemq/data Loading message broker from: xbean:activemq.xml log4j:WARN No appenders could be found for logger (org.apache.activemq.xbean.XBeanBrokerFactory). log4j:WARN Please initialize the log4j system properly. log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info. ERROR: java.lang.RuntimeException: Failed to execute start task. Reason: org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [activemq.xml]; nested exception is java.io.FileNotFoundException: class path resource [activemq.xml] cannot be opened because it does not exist java.lang.RuntimeException: Failed to execute start task. Reason: org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [activemq.xml]; nested exception is java.io.FileNotFoundException: class path resource [activemq.xml] cannot be opened because it does not exist at org.apache.activemq.console.command.StartCommand.runTask(StartCommand.java:98) at org.apache.activemq.console.command.AbstractCommand.execute(AbstractCommand.java:57) at org.apache.activemq.console.command.ShellCommand.runTask(ShellCommand.java:148) at org.apache.activemq.console.command.AbstractCommand.execute(AbstractCommand.java:57) at org.apache.activemq.console.command.ShellCommand.main(ShellCommand.java:90) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:497) at org.apache.activemq.console.Main.runTaskClass(Main.java:257) at org.apache.activemq.console.Main.main(Main.java:111) Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [activemq.xml]; nested exception is java.io.FileNotFoundException: class path resource [activemq.xml] cannot be opened because it does not exist at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:341) at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:302) at org.apache.xbean.spring.context.ResourceXmlApplicationContext.loadBeanDefinitions(ResourceXmlApplicationContext.java:111) at org.apache.xbean.spring.context.ResourceXmlApplicationContext.loadBeanDefinitions(ResourceXmlApplicationContext.java:104) at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:130) at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:467) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:397) at org.apache.xbean.spring.context.ResourceXmlApplicationContext.(ResourceXmlApplicationContext.java:64) at org.apache.xbean.spring.context.ResourceXmlApplicationContext.(ResourceXmlApplicationContext.java:52) at org.apache.activemq.xbean.XBeanBrokerFactory$1.(XBeanBrokerFactory.java:108) at org.apache.activemq.xbean.XBeanBrokerFactory.createApplicationContext(XBeanBrokerFactory.java:108) at org.apache.activemq.xbean.XBeanBrokerFactory.createBroker(XBeanBrokerFactory.java:72) at org.apache.activemq.broker.BrokerFactory.createBroker(BrokerFactory.java:71) at org.apache.activemq.broker.BrokerFactory.createBroker(BrokerFactory.java:54) at org.apache.activemq.console.command.StartCommand.startBroker(StartCommand.java:115) at org.apache.activemq.console.command.StartCommand.runTask(StartCommand.java:74) ... 10 more Caused by: java.io.FileNotFoundException: class path resource [activemq.xml] cannot be opened because it does not exist at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:158) at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:328) ... 25 more ERROR: java.lang.Exception: org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [activemq.xml]; nested exception is java.io.FileNotFoundException: class path resource [activemq.xml] cannot be opened because it does not exist java.lang.Exception: org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [activemq.xml]; nested exception is java.io.FileNotFoundException: class path resource [activemq.xml] cannot be opened because it does not exist at org.apache.activemq.console.command.StartCommand.runTask(StartCommand.java:99) at org.apache.activemq.console.command.AbstractCommand.execute(AbstractCommand.java:57) at org.apache.activemq.console.command.ShellCommand.runTask(ShellCommand.java:148) at org.apache.activemq.console.command.AbstractCommand.execute(AbstractCommand.java:57) at org.apache.activemq.console.command.ShellCommand.main(ShellCommand.java:90) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:497) at org.apache.activemq.console.Main.runTaskClass(Main.java:257) at org.apache.activemq.console.Main.main(Main.java:111) Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [activemq.xml]; nested exception is java.io.FileNotFoundException: class path resource [activemq.xml] cannot be opened because it does not exist at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:341) at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:302) at org.apache.xbean.spring.context.ResourceXmlApplicationContext.loadBeanDefinitions(ResourceXmlApplicationContext.java:111) at org.apache.xbean.spring.context.ResourceXmlApplicationContext.loadBeanDefinitions(ResourceXmlApplicationContext.java:104) at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:130) at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:467) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:397) at org.apache.xbean.spring.context.ResourceXmlApplicationContext.(ResourceXmlApplicationContext.java:64) at org.apache.xbean.spring.context.ResourceXmlApplicationContext.(ResourceXmlApplicationContext.java:52) at org.apache.activemq.xbean.XBeanBrokerFactory$1.(XBeanBrokerFactory.java:108) at org.apache.activemq.xbean.XBeanBrokerFactory.createApplicationContext(XBeanBrokerFactory.java:108) at org.apache.activemq.xbean.XBeanBrokerFactory.createBroker(XBeanBrokerFactory.java:72) at org.apache.activemq.broker.BrokerFactory.createBroker(BrokerFactory.java:71) at org.apache.activemq.broker.BrokerFactory.createBroker(BrokerFactory.java:54) at org.apache.activemq.console.command.StartCommand.startBroker(StartCommand.java:115) at org.apache.activemq.console.command.StartCommand.runTask(StartCommand.java:74) ... 10 more Caused by: java.io.FileNotFoundException: class path resource [activemq.xml] cannot be opened because it does not exist at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:158) at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:328) ... 25 more A: You need to deploy the configuration file in the activemq/conf path. You can download the last configuration file: http://activemq.apache.org/xml-configuration.html . I had the same issue deploying activemq on Ubuntu using apt-get. A configuration file was stored in a different path: /etc/activemq/instances-available/main/activemq.xml I linked this file into a /var/lib/activemq/conf folder sudo su - su activemq mkdir /var/lib/activemq/conf ln -s /etc/activemq/instances-available/main/activemq.xml /var/lib/activemq/conf/
{ "pile_set_name": "StackExchange" }
Q: select option (html 5 tag) position over next input (html 5 tag) in IE 10, 9 I have drop down select --> option "id="select_proptype" whose values are dynamically generating in jquery function... i have other select---> options are as well but the dynamic select position comes on top of following input (html 5) tag... this behaviour is only in IE 10 and IE 9 .... here is my code .... <div class="criteria_block"> <span><label class="search_form_Label" for="proptype">Property Type</label></span> <span><select class="inputStyle_class" id="select_proptype" name="type" style="width:165px;"></select></span> </div> <div class="criteria_block"> <span><label class="search_form_Label default_font" for="postcodes">Post Codes</label></span> <span><input class="inputStyle_class form_search_textbox" id="postcodes" style="width:160px;" name="postcodes" type="text" /></span> </div> in html i am calling function to get all values... $(document).ready(function () { $(this).SearchForm(); }); jquery plugin function .......... $.fn.SearchForm = function () { //process the code// //generate option values for (var val in plugin_Global_Variables.F_property_Type) { $("#select_proptype").append('<option value="' + plugin_Global_Variables.F_property_Type[val] + '">' + plugin_Global_Variables.F_property_Type[val] + '</option>'); } } css---------------- .criteria_block { display:block; width:300px; height:40px; margin-top:10px; color:#4E4E4E; border:thin; border-color:grey; } .search_form_Label { display:inline-block; width:100px; font-weight:500; margin-left:10px; line-height:40px; } A: the width in your css for .search_form_Label is set to 100px where has you label <span><label class="search_form_Label" for="proptype">Property Type</label></span> need more width to display "Property Type" in once line that is why your select option position over the following input tag... change your width to 100px+ to fit within frame.... .search_form_Label { display:inline-block; width:100px; // change width here to 100px + font-weight:500; margin-left:10px; line-height:40px; }
{ "pile_set_name": "StackExchange" }
Q: This expression was expected to have type 'double' but here has type 'unit' Ive an array of integers, and want to do the following operation: s += array(index+1) - array(index) so, I tried the below: let mutable s =0 for i in 0 .. slen-1 do s <- series.[i+1] - series.[i] + s but I goy an error: This expression was expected to have type 'double' but here has type 'unit' UPDATE The full code let series = [|30;21;29;31;40;48;53;47;37;39;31;29;17;9;20;24;27;35;41;38; 27;31;27;26;21;13;21;18;33;35;40;36;22;24;21;20;17;14;17;19; 26;29;40;31;20;24;18;26;17;9;17;21;28;32;46;33;23;28;22;27; 18;8;17;21;31;34;44;38;31;30;26;32|] let initialTrend series slen : double= let mutable s = 0 for i in 0 .. slen-1 do s <- series.[i+1] - series.[i] + s A: Well, you are telling that the function will return a double and the error message is telling you that it doesn't return anything, that's correct. Either, remove the return type: let initialTrend series slen : unit = let mutable s = 0 for i in 0 .. slen-1 do s <- series.[i+1] - series.[i] + s or change the way the function works: let initialTrend (series: _ list) slen : double= let mutable s = 0 for i in 0 .. slen-1 do s <- series.[i+1] - series.[i] + s float s But, looking at your recent questions, you are still sticking to mutability. I would suggest to use a higher order function here instead: let initialTrend (series: float []) : double = Array.pairwise series |> Array.fold (fun s (x0, x1) -> x1 - x0 + s) 0.
{ "pile_set_name": "StackExchange" }
Q: What is the FIREWALLD equivalent to IPTABLES -NOTRACK I recently converted to centos 7 and so far I am beginning to like the simplicity of zones in my firewall structure, however I can't seem to find a configuration parameter for firewalld like the iptables "NOTRACK" which essentially ignores the status of the incoming connections. In other words I need a stateless firewalld setup in order to keep up with the volume of Queries coming into my DNS Caching server. This is the syntax I was using with iptables: iptables -t raw -I OUTPUT -p udp --dport 53 -j NOTRACK iptables -t raw -I OUTPUT -p udp --sport 53 -j NOTRACK iptables -t raw -I PREROUTING -p udp --dport 53 -j NOTRACK iptables -t raw -I PREROUTING -p udp --sport 53 -j NOTRACK iptables -I INPUT -p udp --dport 53 -j ACCEPT iptables -I INPUT -p udp --sport 53 -j ACCEPT iptables -I OUTPUT -p udp --dport 53 -j ACCEPT ip6tables -t raw -I OUTPUT -p udp --dport 53 -j NOTRACK ip6tables -t raw -I OUTPUT -p udp --sport 53 -j NOTRACK ip6tables -t raw -I PREROUTING -p udp --sport 53 -j NOTRACK ip6tables -t raw -I PREROUTING -p udp --dport 53 -j NOTRACK ip6tables -I INPUT -p udp --dport 53 -j ACCEPT ip6tables -I INPUT -p udp --sport 53 -j ACCEPT ip6tables -I OUTPUT -p udp --dport 53 -j ACCEPT A: I don't remember the syntax for marking the traffic as NOTRACK, but doing it in the raw table is correct. You'll need a rule like iptables -A INPUT -m state --state NOTRACK -j ACCEPT to actually let the traffic through. (and a corresponding rule for IPv6).
{ "pile_set_name": "StackExchange" }
Q: Spring Webflow: No actions were executed I'm trying to implement an Action in SWF but I get the same error even in the simplest example. Error: "java.lang.IllegalStateException: No actions were executed, thus I cannot execute any state transition" import org.springframework.webflow.execution.Action; import org.springframework.webflow.execution.Event; import org.springframework.webflow.execution.RequestContext; public class HelloAction implements Action { @Override public Event execute(RequestContext rc) throws Exception { return new Event(this, "success"); } I've declared the bean. <bean id="helloAction" class="app.action.HelloAction"/> And in flow.xml.. <action-state id="intermedio"> <action bean="helloAction"/> <transition on="success" to="fin"/> </action-state> <end-state id="fin" view="final" /> It works fine if I don't use "HelloAction". But if I want to use Action in SWF, I always get the previous error. Is something else needed? Thanks in advance. A: <action-state id="intermedio"> <evaluate expression="helloAction.execute()"> <transition on="success" to="fin"/> </action-state>
{ "pile_set_name": "StackExchange" }
Q: Pyqt5 How to avoid freezing program by an infinite while loop? I want to know, how can I stop the process of the function iniciar every time I click on the button self.runButton.clicked.connect(self.iniciar) the program freezes and I can not do another action. I want the timer to continue working while the function iniciar keeps repeating infinitely. also that the button self.runButton1 stops the function iniciar . my code: #!/usr/bin/env python3 # Program created for play audios of time in zapoteco' # # Created by: Python 3.6, PyQt5 5.9.2. # # Author: Raul Espinosa [email protected] # # WARNING! All changes made in this file will be lost! # # Version 0.2 GUI import time import subprocess from PyQt5 import QtCore, QtGui, QtWidgets class Ui_Form(object): def setupUi(self, Form): Form.setObjectName("Form") Form.resize(383, 263) palette = QtGui.QPalette() brush = QtGui.QBrush(QtGui.QColor(164, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Button, brush) brush = QtGui.QBrush(QtGui.QColor(138, 226, 52)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Light, brush) brush = QtGui.QBrush(QtGui.QColor(164, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush) brush = QtGui.QBrush(QtGui.QColor(173, 127, 168)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Base, brush) brush = QtGui.QBrush(QtGui.QColor(114, 159, 207)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Window, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Shadow, brush) brush = QtGui.QBrush(QtGui.QColor(164, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Button, brush) brush = QtGui.QBrush(QtGui.QColor(138, 226, 52)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Light, brush) brush = QtGui.QBrush(QtGui.QColor(164, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush) brush = QtGui.QBrush(QtGui.QColor(173, 127, 168)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Base, brush) brush = QtGui.QBrush(QtGui.QColor(114, 159, 207)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Window, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Shadow, brush) brush = QtGui.QBrush(QtGui.QColor(46, 52, 54)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Button, brush) brush = QtGui.QBrush(QtGui.QColor(138, 226, 52)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Light, brush) brush = QtGui.QBrush(QtGui.QColor(190, 190, 190)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush) brush = QtGui.QBrush(QtGui.QColor(114, 159, 207)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Base, brush) brush = QtGui.QBrush(QtGui.QColor(114, 159, 207)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Window, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Shadow, brush) Form.setPalette(palette) Form.setPalette(palette) self.label = QtWidgets.QLabel(Form) self.label.setGeometry(QtCore.QRect(10, 0, 361, 181)) self.label.setObjectName("label") self.horizontalSlider = QtWidgets.QSlider(Form) self.horizontalSlider.setGeometry(QtCore.QRect(110, 240, 160, 16)) self.horizontalSlider.setOrientation(QtCore.Qt.Horizontal) self.horizontalSlider.setObjectName("horizontalSlider") self.horizontalSlider.setRange(0,100) self.horizontalSlider.setSingleStep(1) self.horizontalSlider.valueChanged.connect(self.valueHandler) self.runButton = QtWidgets.QPushButton(Form) self.runButton.setGeometry(QtCore.QRect(50, 180, 80, 25)) self.runButton.setObjectName("runButton") self.runButton.clicked.connect(self.iniciar) self.runButton1 = QtWidgets.QPushButton(Form) self.runButton1.setGeometry(QtCore.QRect(250, 180, 80, 25)) self.runButton1.setObjectName("runButton1") self.label_2 = QtWidgets.QLabel(Form) self.label_2.setGeometry(QtCore.QRect(160, 220, 55, 17)) self.label_2.setObjectName("label_2") self.timer = QtCore.QTimer(Form) self.timer.timeout.connect(self.Time) self.timer.start(1000) self.lcdNumber = QtWidgets.QLCDNumber(Form) self.lcdNumber.setGeometry(QtCore.QRect(280, 0, 101, 61)) self.lcdNumber.setInputMethodHints(QtCore.Qt.ImhNone) self.lcdNumber.setFrameShape(QtWidgets.QFrame.NoFrame) self.lcdNumber.setFrameShadow(QtWidgets.QFrame.Raised) self.lcdNumber.setSmallDecimalPoint(True) self.lcdNumber.setDigitCount(5) self.lcdNumber.setMode(QtWidgets.QLCDNumber.Dec) self.lcdNumber.setSegmentStyle(QtWidgets.QLCDNumber.Flat) self.lcdNumber.display(time.strftime("%H"+":"+"%M")) #tiempo = time.strftime("%H"+":"+"%M") #print (tiempo) #self.lcdNumber.setProperty("value", 12:20) self.lcdNumber.setObjectName("lcdNumber") self.retranslateUi(Form) QtCore.QMetaObject.connectSlotsByName(Form) def Time(self): self.lcdNumber.display(time.strftime("%H"+":"+"%M")) def valueHandler(self,value): scaledValue = float(value)/100 print (scaledValue) , type(scaledValue) return scaledValue def retranslateUi(self, Form): _translate = QtCore.QCoreApplication.translate Form.setWindowTitle(_translate("Form", "XIGABA")) Form.setToolTip(_translate("Form", "<html><head/><body><pre style=\" margin-top:0px; margin-bottom:15px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; background-color:#ffffff;\"><span style=\" font-family:\'monospace\'; background-color:#ffffff;\">Creado con Software Libre.</span></pre></body></html>")) self.label.setToolTip(_translate("Form", "<html><head/><body><p>Dictador de horario.</p></body></html>")) self.label.setText(_translate("Form", "<html><head/><body><pre align=\"center\" style=\" margin-top:15px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; background-color:#729fcf;\"><a name=\"taag_output_text\"/><span style=\" font-family:\'monospace\'; color:#555753; background-color:#729fcf;\">)</span><span style=\" font-family:\'monospace\'; color:#555753; background-color:#729fcf;\"> ( </span></pre><pre align=\"center\" style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; background-color:#729fcf;\"><span style=\" font-family:\'monospace\'; color:#555753; background-color:#729fcf;\"> ( /( )\\ ) ( ( ( ( </span></pre><pre align=\"center\" style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; background-color:#729fcf;\"><span style=\" font-family:\'monospace\'; color:#555753; background-color:#729fcf;\"> )\\()|()/( )\\ ) )\\ ( )\\ )\\ </span></pre><pre align=\"center\" style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; background-color:#729fcf;\"><span style=\" font-family:\'monospace\'; color:#555753; background-color:#729fcf;\">((_)\\ /(_)|()/( ((((_)( )((_|(((_)( </span></pre><pre align=\"center\" style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; background-color:#729fcf;\"><span style=\" font-family:\'monospace\'; color:#555753; background-color:#729fcf;\">__((_|_)) /(_))_)\\ _ )((_)_ )\\ _ )\\ </span></pre><pre align=\"center\" style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; background-color:#729fcf;\"><span style=\" font-family:\'monospace\'; color:#555753; background-color:#729fcf;\">\\ \\/ /_ _|(_)) __(_)_\\(_) _ )(_)_\\(_) </span></pre><pre align=\"center\" style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; background-color:#729fcf;\"><span style=\" font-family:\'monospace\'; color:#555753; background-color:#729fcf;\"> &gt; &lt; | | | (_ |/ _ \\ | _ \\ / _ \\ </span></pre><pre align=\"center\" style=\" margin-top:0px; margin-bottom:15px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; background-color:#729fcf;\"><span style=\" font-family:\'monospace\'; color:#555753; background-color:#729fcf;\">/_/\\_\\___| \\___/_/ \\_\\|___//_/ \\_\\ </span></pre><pre align=\"center\" style=\" margin-top:0px; margin-bottom:15px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; background-color:#729fcf;\"><span style=\" font-family:\'monospace\'; font-size:6pt; color:#555753; background-color:#729fcf;\">version 0.2 GUI</span></pre></body></html>")) self.runButton.setText(_translate("Form", "Iniciar")) self.runButton1.setText(_translate("Form", "Detener")) self.label_2.setText(_translate("Form", "<html><head/><body><pre align=\"center\" style=\" margin-top:0px; margin-bottom:15px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; background-color:#000000;\"><a name=\"taag_output_text\"/><span style=\" font-family:\'monospace\'; color:#ef2929; background-color:#000000;\">VOLUMEN</span></pre></body></html>")) def iniciar(self): self.runButton1.setEnabled(True) position = self.horizontalSlider.value() scaledValue = float(position)/100 print (scaledValue) , type(scaledValue) while (True): time.sleep(0.5) second_test = time.strftime('%S') minute_test = time.strftime('%M') hour_test = time.strftime('%H') tiempo = time.strftime("%H"+":"+"%M") print (tiempo) self.lcdNumber.setProperty("value", tiempo) if int(minute_test) == int(00) and int(second_test) == int(00): print ('llego al hora exacta') filen = 'HRS' + hour_test + '_O.mp3.mp3' print (filen) subprocess.Popen(["play", filen, "vol", scaledValue]).communicate() elif int(second_test) == int(00): print ('llego al minuto') filen = 'HRS' + hour_test + '.mp3' filen2 = 'MIN' + minute_test + '.mp3.mp3' print (filen) print (filen2) subprocess.Popen(["play", filen, "vol", str(scaledValue)]).communicate() subprocess.Popen(["play", filen2, "vol", str(scaledValue)]).communicate() if __name__ == "__main__": import sys app = QtWidgets.QApplication(sys.argv) Form = QtWidgets.QWidget() ui = Ui_Form() ui.setupUi(Form) Form.show() sys.exit(app.exec_()) I am used python3.6 and pyqt5 A: Blocking loops like the while true that you use are not suitable for a GUI because they do not let you do the typical tasks of a GUI like checking events, signals and slots. In Qt, and therefore also PyQt, there are methods to avoid those problems, a possible solution for your case is to use threads, and a simple way to implement them is using QRunnable and QThreadPool, but before that it is advisable to reform your code. Qt Designer offers a class that can implement a design in widget but it is not a widget, it is appropriate to create a class that inherits from the appropriate widget and use the initial class to fill it. class Widget(QtWidgets.QWidget, Ui_Form): def __init__(self, *args, **kwargs): QtWidgets.QWidget.__init__(self, *args, **kwargs) self.setupUi(self) self.runButton.clicked.connect(self.iniciar) self.timer.timeout.connect(self.update_time) self.horizontalSlider.valueChanged.connect(self.valueHandler) def update_time(self): self.lcdNumber.display(time.strftime("%H" + ":" + "%M")) def valueHandler(self, value): scaledValue = float(value) / 100 print(scaledValue), type(scaledValue) return scaledValue def iniciar(self): self.runButton1.setEnabled(True) position = self.horizontalSlider.value() scaledValue = float(position) / 100 print(scaledValue), type(scaledValue) self.runnable = Runnable(self) QtCore.QThreadPool.globalInstance().start(self.runnable) In the next section I implement the QRunnable and we pass the widget, this widget will be used to communicate and update the GUI data, since a rule of Qt is that the GUI should not be updated from another thread, a solution for this is use QMetaObject.invokeMethod: class Runnable(QtCore.QRunnable): def __init__(self, w, *args, **kwargs): QtCore.QRunnable.__init__(self, *args, **kwargs) self.w = w self.position_initial = self.w.horizontalSlider.value() def run(self): scaledValue = float(self.position_initial) / 100 print(scaledValue) while True: time.sleep(0.5) second_test = time.strftime('%S') minute_test = time.strftime('%M') hour_test = time.strftime('%H') tiempo = time.strftime("%H" + ":" + "%M") print(tiempo) QtCore.QMetaObject.invokeMethod(self.w.lcdNumber, "display", QtCore.Qt.QueuedConnection, QtCore.Q_ARG(str, tiempo)) if int(minute_test) == int(00) and int(second_test) == int(00): print('llego al hora exacta') filen = 'HRS' + hour_test + '_O.mp3.mp3' print(filen) subprocess.Popen(["play", filen, "vol", scaledValue]).communicate() elif int(second_test) == int(00): print('llego al minuto') filen = 'HRS' + hour_test + '.mp3' filen2 = 'MIN' + minute_test + '.mp3.mp3' print(filen) print(filen2) subprocess.Popen(["play", filen, "vol", str(scaledValue)]).communicate() subprocess.Popen(["play", filen2, "vol", str(scaledValue)]).communicate() Then, as implemented in the iniciar method, we call the runnable through QThreadPool: self.runnable = Runnable(self) QtCore.QThreadPool.globalInstance().start(self.runnable) The complete code can be found at the following link. PS: If you want to add a stop we must change some things for example instead of while True you should use a flag, and change the state of the flag: class Runnable(QtCore.QRunnable): def __init__(self, w, *args, **kwargs): QtCore.QRunnable.__init__(self, *args, **kwargs) self.w = w self.position_initial = self.w.horizontalSlider.value() self.m_stopped = False def run(self): scaledValue = float(self.position_initial) / 100 print(scaledValue) while not self.m_stopped: [...] def stop(self): self.m_stopped = True and then we created the detener method: def detener(self): self.runButton.setEnabled(True) self.runButton1.setEnabled(False) self.runnable.stop()
{ "pile_set_name": "StackExchange" }
Q: Antiforgery token not set in the cookie when deployed in azure I have two app services, one is an angular app and the other is a .NET core 2.0 app. I create Antiforgery token from the latter and attach to a header for each request, so that it is set as a cookie in the former. Startup.cs public void ConfigureServices(IServiceCollection services) { services.AddCors(); services.AddAntiforgery(options => { options.HeaderName = "X-XSRF-TOKEN"; options.Cookie.SecurePolicy = CookieSecurePolicy.Always; options.Cookie.HttpOnly = false; options.Cookie.SameSite = SameSiteMode.None; }); ... public void Configure(IApplicationBuilder app, IHostingEnvironment env) { app.UseCookiePolicy(new CookiePolicyOptions { MinimumSameSitePolicy = SameSiteMode.None }); app.UseAntiforgeryTokenMiddleware("X-XSRF-TOKEN"); .... AntiForgeryMiddleware.cs public async Task Invoke(HttpContext context, IAntiforgery antiforgery, ILogger<AntiForgeryMiddleware> logger) { string path = context.Request.Path.Value; if (path != null && path.ToLower().Contains("/api/account/authorizeview")) { if (httpVerbs.Contains(context.Request.Method, StringComparer.OrdinalIgnoreCase)) { var tokens = antiforgery.GetAndStoreTokens(context); context.Response.Cookies.Append(requestTokenCookieName, tokens.RequestToken, new CookieOptions() { HttpOnly = false, Secure = true }); } } context.Response.Headers.Add("Access-Control-Allow-Credentials", "true"); await next.Invoke(context); } In Angular app withCredentials: true is set. This works in localhost but when deployed to azure cookies are not set in Chrome. In Microsoft Edge, cookies are displayed as the screenshot in the response but not in application storage. A: We cannot access cookies from sub-domains where the top domain is azurewebsites.net since it is listed in public prefix list. Further details : ASP.NET5, MVC 6 Cookies not being shared across sites
{ "pile_set_name": "StackExchange" }
Q: Node calling postgres function with temp tables causing "memory leak" I have a node.js program calling a Postgres (Amazon RDS micro instance) function, get_jobs within a transaction, 18 times a second using the node-postgres package by brianc. The node code is just an enhanced version of brianc's basic client pooling example, roughly like... var pg = require('pg'); var conString = "postgres://username:password@server/database"; function getJobs(cb) { pg.connect(conString, function(err, client, done) { if (err) return console.error('error fetching client from pool', err); client.query("BEGIN;"); client.query('select * from get_jobs()', [], function(err, result) { client.query("COMMIT;"); done(); //call `done()` to release the client back to the pool if (err) console.error('error running query', err); cb(err, result); }); }); } function poll() { getJobs(function(jobs) { // process the jobs }); setTimeout(poll, 55); } poll(); // start polling So Postgres is getting: 2016-04-20 12:04:33 UTC:172.31.9.180(38446):XXX@XXX:[5778]:LOG: statement: BEGIN; 2016-04-20 12:04:33 UTC:172.31.9.180(38446):XXX@XXX:[5778]:LOG: execute <unnamed>: select * from get_jobs(); 2016-04-20 12:04:33 UTC:172.31.9.180(38446):XXX@XXX:[5778]:LOG: statement: COMMIT; ... repeated every 55ms. get_jobs is written with temp tables, something like this CREATE OR REPLACE FUNCTION get_jobs ( ) RETURNS TABLE ( ... ) AS $BODY$ DECLARE _nowstamp bigint; BEGIN -- take the current unix server time in ms _nowstamp := (select extract(epoch from now()) * 1000)::bigint; -- 1. get the jobs that are due CREATE TEMP TABLE jobs ON COMMIT DROP AS select ... from really_big_table_1 where job_time < _nowstamp; -- 2. get other stuff attached to those jobs CREATE TEMP TABLE jobs_extra ON COMMIT DROP AS select ... from really_big_table_2 r inner join jobs j on r.id = j.some_id ALTER TABLE jobs_extra ADD PRIMARY KEY (id); -- 3. return the final result with a join to a third big table RETURN query ( select je.id, ... from jobs_extra je left join really_big_table_3 r on je.id = r.id group by je.id ); END $BODY$ LANGUAGE plpgsql VOLATILE; I've used the temp table pattern because I know that jobs will always be a small extract of rows from really_big_table_1, in hopes that this will scale better than a single query with multiple joins and multiple where conditions. (I used this to great effect with SQL Server and I don't trust any query optimiser now, but please tell me if this is the wrong approach for Postgres!) The query runs in 8ms on small tables (as measured from node), ample time to complete one job "poll" before the next one starts. Problem: After about 3 hours of polling at this rate, the Postgres server runs out of memory and crashes. What I tried already... If I re-write the function without temp tables, Postgres doesn't run out of memory, but I use the temp table pattern a lot, so this isn't a solution. If I stop the node program (which kills the 10 connections it uses to run the queries) the memory frees up. Merely making node wait a minute between polling sessions doesn't have the same effect, so there are obviously resources that the Postgres backend associated with the pooled connection is keeping. If I run a VACUUM while polling is going on, it has no effect on memory consumption and the server continues on its way to death. Reducing the polling frequency only changes the amount of time before the server dies. Adding DISCARD ALL; after each COMMIT; has no effect. Explicitly calling DROP TABLE jobs; DROP TABLE jobs_extra; after RETURN query () instead of ON COMMIT DROPs on the CREATE TABLEs. Server still crashes. Per CFrei's suggestion, added pg.defaults.poolSize = 0 to the node code in an attempt to disable pooling. The server still crashed, but took much longer and swap went much higher (second spike) than all the previous tests which looked like the first spike below. I found out later that pg.defaults.poolSize = 0 may not disable pooling as expected. On the basis of this: "Temporary tables cannot be accessed by autovacuum. Therefore, appropriate vacuum and analyze operations should be performed via session SQL commands.", I tried to run a VACUUM from the node server (as some attempt to make VACUUM an "in session" command). I couldn't actually get this test working. I have many objects in my database and VACUUM, operating on all objects, was taking too long to execute each job iteration. Restricting VACUUM just to the temp tables was impossible - (a) you can't run VACUUM in a transaction and (b) outside the transaction the temp tables don't exist. :P EDIT: Later on the Postgres IRC forum, a helpful chap explained that VACUUM isn't relevant for temp tables themselves, but can be useful to clean up the rows created and deleted from pg_attributes that TEMP TABLES cause. In any case, VACUUMing "in session" wasn't the answer. DROP TABLE ... IF EXISTS before the CREATE TABLE, instead of ON COMMIT DROP. Server still dies. CREATE TEMP TABLE (...) and insert into ... (select...) instead of CREATE TEMP TABLE ... AS, instead of ON COMMIT DROP. Server dies. So is ON COMMIT DROP not releasing all the associated resources? What else could be holding memory? How do I release it? A: Use CTEs to create partial result sets instead of temp tables. CREATE OR REPLACE FUNCTION get_jobs ( ) RETURNS TABLE ( ... ) AS $BODY$ DECLARE _nowstamp bigint; BEGIN -- take the current unix server time in ms _nowstamp := (select extract(epoch from now()) * 1000)::bigint; RETURN query ( -- 1. get the jobs that are due WITH jobs AS ( select ... from really_big_table_1 where job_time < _nowstamp; -- 2. get other stuff attached to those jobs ), jobs_extra AS ( select ... from really_big_table_2 r inner join jobs j on r.id = j.some_id ) -- 3. return the final result with a join to a third big table select je.id, ... from jobs_extra je left join really_big_table_3 r on je.id = r.id group by je.id ); END $BODY$ LANGUAGE plpgsql VOLATILE; The planner will evaluate each block in sequence the way I wanted to achieve with temp tables. I know this doesn't directly solve the memory leak issue (I'm pretty sure there's something wrong with Postgres' implementation of them, at least the way they manifest on the RDS configuration). However, the query works, it is query planned the way I was intending and the memory usage is stable now after 3 days of running the job and my server doesn't crash. I didn't change the node code at all.
{ "pile_set_name": "StackExchange" }
Q: Vim: Shortcuts specific to a file extension? In Vim, it is possible to attach syntax highlighter to a file extension. Is it possible to do the same with keyboard shortcuts? I.e. the shortcuts would switch on only if a file with particular extension is being edited. A: The association is not directly to file extensions, but filetypes (which can be detected based on file extensions, but also other file patterns or even its contents). :setl filetype? shows you the current buffer's. To define a filetype-specific mapping, just append the <buffer> attribute after the :map command. (Same for custom commands, use -buffer after :command.) You can define that for certain filetypes by prepending :autocmd Filetype {filetype} ..., and put that into your ~/.vimrc. But that gets unwieldy as you add mappings and other settings for various filetypes. Better put the commands into ~/.vim/ftplugin/{filetype}_mappings.vim. (This requires that you have :filetype plugin on.)
{ "pile_set_name": "StackExchange" }
Q: Vanishing Gaussian curvature So let us assume that we have a surface in $\mathbb{R}^3$ with its first fundamental form $ds^2=E(u)du^2+G(v)dv^2$. Does its Gaussian curvature vanish? The answer is supposed to be yes, and I tried computing the Gaussian curvature using the intrinsic formula $K=R_{121}^\ell g_{\ell2}/g$ where $g$ is the determinant of the metric tensor, but I wasn't able to get everything to cancel. I was hoping someone could do the computation so I can identify where I'm going wrong. EDIT Here is what I got. Let us assume the chart were working in is $x(u,v)$. $$ \begin{align} \Gamma_{11}^1&=\frac{\partial_1E}{2}E^{-1}\\ \Gamma_{12}^1&=0\\ \Gamma_{22}^1&=0\\ \Gamma_{11}^2&=\langle x_{11},x_2\rangle g^{22}\\ \Gamma_{12}^2&=0\\ \Gamma_{22}^2&=\frac{\partial_2G}{2}G^{-1} \end{align} $$ Using the intrinsic formula I got $$K=\frac{\partial_2\langle x_{11},x_2\rangle G}{G^2}-\frac{\langle x_{11},x_2\rangle \langle x_{22},x_2\rangle}{G^2}$$ A: I think in your case you should use Brioschi Formula. Since $E=E(u)$ and $G=G(v)$ and $F=0$, hence by the above formula, Gaussian Curvature, $K=0$.
{ "pile_set_name": "StackExchange" }