Dataset Viewer
Auto-converted to Parquet Duplicate
text
stringlengths
138
33.6k
meta
dict
Q: How can I merge several hashes into one hash in Perl? In Perl, how do I get this: $VAR1 = { '999' => { '998' => [ '908', '906', '0', '998', '907' ] } }; $VAR1 = { '999' => { '991' => [ '913', '920', '918', '998', '916', '919', '917', '915', '912', '914' ] } }; $VAR1 = { '999' => { '996' => [] } }; $VAR1 = { '999' => { '995' => [] } }; $VAR1 = { '999' => { '994' => [] } }; $VAR1 = { '999' => { '993' => [] } }; $VAR1 = { '999' => { '997' => [ '986', '987', '990', '984', '989', '988' ] } }; $VAR1 = { '995' => { '101' => [] } }; $VAR1 = { '995' => { '102' => [] } }; $VAR1 = { '995' => { '103' => [] } }; $VAR1 = { '995' => { '104' => [] } }; $VAR1 = { '995' => { '105' => [] } }; $VAR1 = { '995' => { '106' => [] } }; $VAR1 = { '995' => { '107' => [] } }; $VAR1 = { '994' => { '910' => [] } }; $VAR1 = { '993' => { '909' => [] } }; $VAR1 = { '993' => { '904' => [] } }; $VAR1 = { '994' => { '985' => [] } }; $VAR1 = { '994' => { '983' => [] } }; $VAR1 = { '993' => { '902' => [] } }; $VAR1 = { '999' => { '992' => [ '905' ] } }; to this: $VAR1 = { '999:' => [ { '992' => [ '905' ] }, { '993' => [ { '909' => [] }, { '904' => [] }, { '902' => [] } ] }, { '994' => [ { '910' => [] }, { '985' => [] }, { '983' => [] } ] }, { '995' => [ { '101' => [] }, { '102' => [] }, { '103' => [] }, { '104' => [] }, { '105' => [] }, { '106' => [] }, { '107' => [] } ] }, { '996' => [] }, { '997' => [ '986', '987', '990', '984', '989', '988' ] }, { '998' => [ '908', '906', '0', '998', '907' ] }, { '991' => [ '913', '920', '918', '998', '916', '919', '917', '915', '912', '914' ] } ]}; A: I think this is closer than anybody else has gotten: This does most of what you want. I did not store things in arrays of singular hashes, as I don't feel that that is useful. Your scenario is not a regular one. I've tried to genericize this to some extent, but was not possible to overcome the singularity of this code. First of all because it appears you want to collapse everything with the same id into a merged entity (with exceptions), you have to descend through the structure pulling the definitions of the entities. Keeping track of levels, because you want them in the form of a tree. Next, you assemble the ID table, merging entities as possible. Note that you had 995 defined as an empty array one place and as a level another. So given your output, I wanted to overwrite the empty list with the hash. After that, we need to move the root to the result structure, descending that in order to assign canonical entities to the identifiers at each level. Like I said, it's not anything that regular. Of course, if you still want a list of hashes which are no more than pairs, that's an exercise left to you. use strict; use warnings; # subroutine to identify all elements sub descend_identify { my ( $level, $hash_ref ) = @_; # return an expanding list that gets populated as we desecend return map { my $item = $hash_ref->{$_}; $_ => ( $level, $item ) , ( ref( $item ) eq 'HASH' ? descend_identify( $level + 1, $item ) : () ) ; } keys %$hash_ref ; } # subroutine to refit all nested elements sub descend_restore { my ( $hash, $ident_hash ) = @_; my @keys = keys %$hash; @$hash{ @keys } = @$ident_hash{ @keys }; foreach my $h ( grep { ref() eq 'HASH' } values %$hash ) { descend_restore( $h, $ident_hash ); } return; } # merge hashes, descending down the hash structures. sub merge_hashes { my ( $dest_hash, $src_hash ) = @_; foreach my $key ( keys %$src_hash ) { if ( exists $dest_hash->{$key} ) { my $ref = $dest_hash->{$key}; my $typ = ref( $ref ); if ( $typ eq 'HASH' ) { merge_hashes( $ref, $src_hash->{$key} ); } else { push @$ref, $src_hash->{$key}; } } else { $dest_hash->{$key} = $src_hash->{$key}; } } return; } my ( %levels, %ident_map, %result ); #descend through every level of hash in the list # @hash_list is assumed to be whatever you Dumper-ed. my @pairs = map { descend_identify( 0, $_ ); } @hash_list; while ( @pairs ) { my ( $key, $level, $ref ) = splice( @pairs, 0, 3 ); $levels{$key} |= $level; # if we already have an identity for this key, merge the two if ( exists $ident_map{$key} ) { my $oref = $ident_map{$key}; my $otyp = ref( $oref ); if ( $otyp ne ref( $ref )) { # empty arrays can be overwritten by hashrefs -- per 995 if ( $otyp eq 'ARRAY' && @$oref == 0 && ref( $ref ) eq 'HASH' ) { $ident_map{$key} = $ref; } else { die "Uncertain merge for '$key'!"; } } elsif ( $otyp eq 'HASH' ) { merge_hashes( $oref, $ref ); } else { @$oref = sort { $a <=> $b || $a cmp $b } keys %{{ @$ref, @$oref }}; } } else { $ident_map{$key} = $ref; } } # Copy only the keys that do not appear at higher levels to the # result hash if ( my @keys = grep { !$levels{$_} } keys %ident_map ) { @result{ @keys } = @ident_map{ @keys } if @keys; } # then step through the hash to make sure that the entries at # all levels are equal to the identity descend_restore( \%result, \%ident_map );
{ "pile_set_name": "StackExchange" }
Q: change space between ticks in first y-axis in plt.imshow Hey I have used the following code: import matplotlib.pyplot as plt import numpy as np Class1=np.array([[1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [1., 1., 1., 1., 1., 1., 1., 0., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [0., 0., 1., 0., 0., 0., 1., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.], [1., 1., 1., 0., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 0., 1., 0., 1.], [1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0.], [1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [0., 0., 0., 0., 0., 0., 1., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.], [1., 1., 1., 1., 1., 1., 1., 1., 0., 1., 1., 1., 0., 1., 0., 1., 0., 1.], [0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 1., 0., 0., 1., 1., 1., 0.]]) Unique=np.array([ 0., 1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 12., 13., 14., 15., 16., 17., 18., 19., 20., 21., 22., 23., 24., 25., 26., 27., 28., 29., 30., 31., 32., 33., 34., 35., 36., 37., 38.]) counts=np.array([56184982, 2904400, 4950837, 114746, 4270, 182052, 844444, 106292, 47007, 68480, 23522, 13838, 23990, 301704, 50462, 21345, 12263, 7217, 64194, 251, 885, 2947045, 4895643, 102992, 4401, 180136, 844872, 281, 107200, 48703, 69791, 22651, 50295, 22772, 7020, 62543, 43, 1103, 48]) list_y2=[] list_x=[] list_y1=[] for i in np.arange(len(Unique)): list_y2.append( np.array2string(round(counts[i]/Class1.sum(axis=1)[i],2))) if i < 9: list_x.append(str(i+1)) else: list_x.append( str(i+1)) list_y1.append( str(38-int(Unique[i]))) fig, ax1 = plt.subplots() F=16 ax1.set_xlabel('Brain image',fontsize=F) ax1.set_yticks(np.arange(len(list_y1))) ax1.set_yticklabels(list_y1) ax1.set_xticks(np.arange(len(list_x))) ax1.set_xticklabels(list_x) ax1.set_ylabel('class',fontsize=F) ax2 = ax1.twinx() ax2.set_yticks(np.arange(len(list_y2))) ax2.set_yticklabels(list_y2, va='baseline') ax2.set_ylabel('size',fontsize=F) #Rotate the tick labels and set their alignment. plt.setp(ax1.get_xticklabels(), rotation=45, ha="right", rotation_mode="anchor") plt.imshow(Class1, aspect='auto') fig.tight_layout() plt.show() which makes the following plot: The problem with this is that the first y-axis doesn't fit the plot properly. The length between the ticks in the first y-axis should be the same as in the second y-axis and the 0 in the top and the 38 in bottom should be moved a bit inward on the y-axis. Hope one of you can help me. A: I had the same problem recently and found the following workaround: Setting the same limits for the twin axis ax2 as for the parent axis (ax1). This aligns the ticks on both y-axes and then you proceed by setting the ticks and the labels as desired as you are doing. ax2 = ax1.twinx() ax2.set_ylim(ax1.get_ylim()) # This was the fix for me ax2.set_yticks(np.arange(len(list_y2))) ax2.set_yticklabels(list_y2, va='baseline') ax2.set_ylabel('size',fontsize=F) Let me know if it works.
{ "pile_set_name": "StackExchange" }
Q: Why ListList is List> but not List> I have a generic interface interface ListList<E> extends List<List<E>>. For some reasons, I can't cast ListList<? super T> to List<List<? super T>>. Is there any way of doing it and why it doesn't work? By this moment I've already tried the following: Simple assignment, this way I've managed to assign ListList<? super T> to List<? extends List<? super T>> (1), but when I try to assign ListList<? super T> to List<List<? super T>> I get Incompatible types compile-time error (1.1). Explicit type conversion, it doesn't work because of the same Incompatible types compile-time error (2). Casting to raw type ListList, it works (3), but I don't like raw types. Adding all elements from ListList<? super T> to List<? extends List<? super T>>, it works (4), but I need a more general solution which works not only with ListList<E>, but with any generic type. Here is my code: ListList<? super T> var = new ArrayListList<>(); List<? extends List<? super T>> work = var; // (1) List<List<? super T>> notWork = var; // (1.1) List<List<? super T>> explicit = (List<List<? super T>>) var; // (2) List<List<? super T>> raw = (ListList) var; // (3) List<List<? super T>> copy = new ArrayList<>(); // (4) copy.addAll(var); // (4) I've expected ListList<? super T> to be List<List<? super T>>, but it appeared to be List<? extends List<? super T>>. I need to know why it is and how I can cast it to List<List<? super T>> without raw types and copying of elements. A: At first, it looks like these assignments should all succeed, but they don't because of the inner wildcard ? super T. If we remove those wildcards, then all the assignments compile. public static <T> void test() { ListList<T> var = new ArrayListList<>(); List<? extends List<T>> work = var; // Compiles List<List<T>> notWork = var; // Compiles List<List<T>> explicit = (List<List<T>>) var; // Compiles List<List<T>> raw = (ListList) var; // Compiles with warning List<List<T>> copy = new ArrayList<>(); // Compiles copy.addAll(var); // Compiles } I still get the unchecked conversion warning for (3), but they all still compile. At first glance it looks like declaring the interface ListList<E> extends List<List<E>> makes a ListList equivalent to a List of Lists. However what you have done is take a nested type parameter and made it the main type parameter. The reason that that makes a difference is nested wildcards don't perform wildcard capture. A nested wildcard here means "a list of lists of any type matching the bound", but a main-level wildcard here means "a 'listlist' of a specific yet unknown type matching the bound". One cannot add an object that is a supertype of the lower bound to a collection, because the type parameter -- a specific yet unknown type -- may be the actual bound. List<? super Integer> test2 = new ArrayList<>(); test2.add(2); // Compiles; can add 2 if type parameter is Integer, Number, or Object test2.add((Number) 2); // Error - Can't add Number to what could be Integer test2.add(new Object()); // Error - Can't add Object to what could be Integer Because Java's generics are invariant, the types must match exactly when type parameters are involved, so similar cases for ListList all fail to compile. // My assumption of how your ArrayListList is defined. class ArrayListList<E> extends ArrayList<List<E>> implements ListList<E> {} ListList<? super Integer> llOfSuperI = new ArrayListList<>(); llOfSuperI.add(new ArrayList<Integer>()); // capture fails to match Integer llOfSuperI.add(new ArrayList<Number>()); // capture fails to match Number llOfSuperI.add(new ArrayList<Object>()); // capture fails to match Object However, a List of List compiles with all 3 cases. List<List<? super Integer>> lOfLOfSuperI = new ArrayList<>(); lOfLOfSuperI.add(new ArrayList<Integer>()); // no capture; compiles lOfLOfSuperI.add(new ArrayList<Number>()); // no capture; compiles lOfLOfSuperI.add(new ArrayList<Object>()); // no capture; compiles Your ListList is a different type than a List of Lists, but the differing generics behavior of where the type parameter is defined means that there is different generics behavior. This is why you cannot directly assign a ListList<? super T> to a List<List<? super T>> (1.1), and also why you can't cast it (2). You can cast to a raw type to get it to compile (3), but that introduces the possibilities of ClassCastException in future use of the casted object; that is what the warning is about. You can assign it to a List<? extends List<? super T>> (1), introducing another wildcard to capture a subtype relationship, but that introduces a wildcard to be captured; you won't be able to add anything useful to that list. These differences have arisen only because a wildcard introduces wildcard capture and the associated differences. Without using a wildcard, a ListList<E> is equivalent to a List<List<E>> and as shown at the top of this answer, shows no problems compiling the code. If you want all of your sub-lists to use the same exact type parameter, then go ahead and use your ListList interface, but don't use any wildcards. This forces the exact same type parameter for all lists that are added to your ListList, i.e. a ListList<Integer> can only hold List<Integer>s. If you want all of your sub-lists to simply match a wildcard, e.g. contain a List<Number>, List<Integer>, and List<Object> in the same list, then just use a List<List<? super T>> to avoid wildcard capture.
{ "pile_set_name": "StackExchange" }
Q: C linked list implementation For the following C linked list implementation, please give me some suggestions for improved efficiency, style and design. This implementation is not 100% complete, please give some suggestions for additional features. Notice the data type for the list is void*, I want it to be as generic as possible. accList.h: #ifndef ACCLIST_H #define ACCLIST_H #include <stdio.h> #include <stdlib.h> struct accListNode //the nodes of a linked-list for any data type { void *data; //generic pointer to any data type struct accListNode *next; //the next node in the list }; struct accList //a linked-list consisting of accListNodes { struct accListNode *head; struct accListNode *tail; int size; }; void accList_allocate(struct accList *theList); //allocate the accList and set to NULL void appendToEnd(void *data, struct accList *theList); //append data to the end of the accList void removeData(void *data, struct accList *theList); //removes data from accList #endif accList.c: #include "accList.h" #include "cmpsc311.h" void accList_allocate(struct accList *theList) //allocate and initialize to NULL values { theList = Malloc(sizeof(struct accList)); theList->head = NULL; theList->tail = NULL; theList->size = 0; } void appendToEnd(void *data, struct accList *theList) { struct accListNode *newNode = Malloc(sizeof(struct accListNode)); newNode->data = data; newNode->next = NULL; if(theList->head == NULL) //the list is empty { theList->head = theList->tail = newNode; } else //the list is not empty { theList->tail->next = newNode; theList->tail = newNode; } } void removeData(void *data, struct accList *theList) { if(theList->head == NULL) //the list is empty return; else if(theList->head == theList->tail) //there is one element in the list { free(theList->head); theList->head = NULL; } else if(data == theList->head->data) //the element to be removed is the head { struct accListNode *temp = theList->head->next; free(theList->head); theList->head = temp; } else if(data == theList->tail->data) //the element to be removed is the tail { struct accListNode *cur; struct accListNode *prev = NULL; for(cur = theList->head; cur->next != NULL; prev = cur, cur = cur->next); free(theList->tail); prev->next = NULL; theList->tail = prev; } else //any other node { struct accListNode *prev = NULL; struct accListNode *cur; for(cur = theList->head; cur != NULL; prev = cur, cur = cur->next) { if(cur->data == data) //this is the node we must free { prev->next = cur->next; free(cur); } } } } I think the remove function needs the most work. I did post that function on this site, however I think I needed to include the whole implementation to get the best feedback. Will this work on an embedded system? A: Several problems I see: accList_allocate accList_allocate doesn't do what you probably think. It creates a new accList, yes, but this new one will not be visible to the caller (and thus, will be lost as memory leakage). If you want to initialize the pointer passed to it, use a pointer-to-pointer: void accList_allocate(struct accList **outList) //allocate and initialize to NULL values { struct accList* theList = Malloc(sizeof(struct accList)); theList->head = NULL; theList->tail = NULL; theList->size = 0; *outList = theList; } Also, you should really check the return value of Malloc. Especially on embedded systems, there's a real possibility of running out of memory. Let the caller handle the error, but tell him that something's wrong. appendToEnd Same as with accList_allocate, check Malloc's return value and return some kind of error code if it's NULL. What you're writing there is library code that should always handle errors gracefully and let the caller decide whether to crash and burn or recover and try again. removeData Please refer to my answer in your other thread. A: I see two issues with the removeData function. The first is in the "single item list" section: else if(theList->head == theList->tail) //there is one element in the list { free(theList->head); theList->head = NULL; } What happens if I have a list with a single item in it, and I ask the removeData() function to remove a piece of data that isn't in the list? It'll remove the wrong item instead of ignoring the function call. It should really look like this: else if(theList->head == theList->tail) //there is one element in the list { if (theList->head->data == data) { free(theList->head); theList->head = NULL; theList->tail = NULL; } } Note that I also set the tail pointer to NULL, which you've missed. Secondly, the section of the function that deals with searching for the data within the list should really exit once it finds a match, unless you are specifically intending to remove all instances of data from the list. Here's the code: if(cur->data == data) //this is the node we must free { prev->next = cur->next; free(cur); } Here's what I'd do: if(cur->data == data) //this is the node we must free { prev->next = cur->next; free(cur); return; } To make it more obvious what's going on, I'd probably rename the function to removeFirstInstance(), and maybe have another function called removeAllInstances() that followed your current design, but that's somewhat anathema to the terseness of idiomatic C (I like descriptive names rather than obtuse names that encourage me constantly to have the API docs open). I can also see an opportunity for a tiny optimisation: for(cur = theList->head; cur != NULL; prev = cur, cur = cur->next) You already know that the data isn't stored in the head node from earlier if statements, so you can skip the first item in the search loop: for(cur = theList->head->next; cur != NULL; prev = cur, cur = cur->next) If I were to rewrite this method it'd probably look like this: void removeData(void *data, struct accList *list) { struct accListNode *previous = NULL; struct accListNode *current = list->head; while (current != NULL) { if (current->data == data) { if (list->head == current) list->head = current->next; if (list->tail == current) list->tail = previous; if (previous != NULL) previous->next = current->next; free(current); --size; return; } previous = current; current = current->next; } } I'd forgo the micro-optimsation of all of the guard clauses in favour of a shorter method. One more problem that applies generally: you have a size value in the list struct but you never change its value. Either increase it in the append function and decrease it in the remove function or remove it from the struct. As it stands it is misleading. A: Isn't this an issue? void appendToEnd(void *data, struct accList *theList) { struct accListNode *newNode = Malloc(sizeof(struct accListNode)); newNode->data = data; <=== What happens if the input is freed. The linked list will also lose the value. I think the value should be copied here.
{ "pile_set_name": "StackExchange" }
Q: auto height for a html div auto scrolling - Div to take remaining height i have a very simple but confusing problem what issue i am having is that i have some div. first div which is fixed to top right with height 100% and this div has 2 more div inside div2 and div3 both should be scrolled . one the uper div2 varies height from 100px to 200px after that it should be scrolling and the div with id div3 should take the remaining height and should be scrolling if data is increased. i can achieve till div2 but the div3 is not taking the remaining height my code is <div style="width:200px;height:100%;position:fixed;top:0px;right:0px;background:red;overflow:auto;"> <div style="width:100%;min-height:100px;max-height:200px;background:blue;overflow:auto;float:left;"> ggdhhd<br/>ggdhhd<br/>ggdhhd<br/>ggdhhd<br/><br/>ggdhhd<br/>ggdhhd<br/>ggdhhd<br/>ggdhhd<br/><br/>ggdhhd<br/>ggdhhd<br/>ggdhhd<br/>ggdhhd<br/><br/>ggdhhd<br/>ggdhhd<br/>ggdhhd<br/>ggdhhd<br/><br/>ggdhhd<br/>ggdhhd<br/>ggdhhd<br/>ggdhhd<br/><br/>ggdhhd<br/>ggdhhd<br/>ggdhhd<br/>ggdhhd<br/><br/>ggdhhd<br/>ggdhhd<br/>ggdhhd<br/>ggdhhd<br/><br/> </div> <div style="width:100%;height:300px;background:yellow;float:left;overflow:auto;"> ggdhhd<br/>ggdhhd<br/>ggdhhd<br/>ggdhhd<br/><br/>ggdhhd<br/>ggdhhd<br/>ggdhhd<br/>ggdhhd<br/><br/>ggdhhd<br/>ggdhhd<br/>ggdhhd<br/>ggdhhd<br/><br/>ggdhhd<br/>ggdhhd<br/>ggdhhd<br/>ggdhhd<br/><br/>ggdhhd<br/>ggdhhd<br/>ggdhhd<br/>ggdhhd<br/><br/>ggdhhd<br/>ggdhhd<br/>ggdhhd<br/>ggdhhd<br/><br/>ggdhhd<br/>ggdhhd<br/>ggdhhd<br/>ggdhhd<br/><br/>ggdhhd<br/>ggdhhd<br/>ggdhhd<br/>ggdhhd<br/><br/>ggdhhd<br/>ggdhhd<br/>ggdhhd<br/>ggdhhd<br/><br/>ggdhhd<br/>ggdhhd<br/>ggdhhd<br/>ggdhhd<br/><br/>ggdhhd<br/>ggdhhd<br/>ggdhhd<br/>ggdhhd<br/><br/>ggdhhd<br/>ggdhhd<br/>ggdhhd<br/>ggdhhd<br/><br/>ggdhhd<br/>ggdhhd<br/>ggdhhd<br/>ggdhhd<br/><br/>ggdhhd<br/>ggdhhd<br/>ggdhhd<br/>ggdhhd<br/><br/> </div> i need something which is browser friendly.. if you can suggest me something it would be very helpful.. this is demo http://www.reurl.in/f84acc961 https://jsfiddle.net/fy727tLL/ A: Here is the updated fiddle: Fiddle <div style="width:200px;height:100%;position:fixed;top:0px;right:0px;background:red;overflow:auto;"> <div style="width:100%;height:20%;background:blue;overflow:auto;float:left;"> ggdhhd <br/>ggdhhd <br/>ggdhhd <br/>ggdhhd <br/> <br/>ggdhhd <br/>ggdhhd <br/>ggdhhd <br/>ggdhhd <br/> <br/>ggdhhd <br/>ggdhhd <br/>ggdhhd <br/>ggdhhd <br/> <br/>ggdhhd <br/>ggdhhd <br/>ggdhhd <br/>ggdhhd <br/> <br/>ggdhhd <br/>ggdhhd <br/>ggdhhd <br/>ggdhhd <br/> <br/>ggdhhd <br/>ggdhhd <br/>ggdhhd <br/>ggdhhd <br/> <br/>ggdhhd <br/>ggdhhd <br/>ggdhhd <br/>ggdhhd <br/> <br/> </div> <div style="width:100%;height:80%;background:yellow;float:left;overflow:auto;"> ggdhhd <br/>ggdhhd <br/>ggdhhd <br/>ggdhhd <br/> <br/>ggdhhd <br/>ggdhhd <br/>ggdhhd <br/>ggdhhd <br/> <br/>ggdhhd <br/>ggdhhd <br/>ggdhhd <br/>ggdhhd <br/> <br/>ggdhhd <br/>ggdhhd <br/>ggdhhd <br/>ggdhhd <br/> <br/>ggdhhd <br/>ggdhhd <br/>ggdhhd <br/>ggdhhd <br/> <br/>ggdhhd <br/>ggdhhd <br/>ggdhhd <br/>ggdhhd <br/> <br/>ggdhhd <br/>ggdhhd <br/>ggdhhd <br/>ggdhhd <br/> <br/>ggdhhd <br/>ggdhhd <br/>ggdhhd <br/>ggdhhd <br/> <br/>ggdhhd <br/>ggdhhd <br/>ggdhhd <br/>ggdhhd <br/> <br/>ggdhhd <br/>ggdhhd <br/>ggdhhd <br/>ggdhhd <br/> <br/>ggdhhd <br/>ggdhhd <br/>ggdhhd <br/>ggdhhd <br/> <br/>ggdhhd <br/>ggdhhd <br/>ggdhhd <br/>ggdhhd <br/> <br/>ggdhhd <br/>ggdhhd <br/>ggdhhd <br/>ggdhhd <br/> <br/>ggdhhd <br/>ggdhhd <br/>ggdhhd <br/>ggdhhd <br/> <br/> </div> </div>
{ "pile_set_name": "StackExchange" }
Q: Python : error when insert mysql database I'm using Ejabberd xmpp/jabber server and I'm trying to insert data into mysql database using Python What I'm doing is : username = "user1" email = "user1@domain.tld" vCard = ("<vCard xmlns='vcard-temp'><VERSION>3.0</VERSION><ADR><HOME/></ADR><ADR><WORK/></ADR><TEL><HOME/></TEL><TEL><WORK/></TEL><TEL><FAX/></TEL><TEL><CELL/></TEL><EMAIL><HOME/><USERID>%s</USERID></EMAIL><EMAIL><WORK/></EMAIL><JABBERID></JABBERID><ORG><ORGUNIT/></ORG><PRODID></PRODID></vCard>" % (email)) import MySQLdb as mdb db = mdb.connect('localhost', 'test1', 'test1', 'test1') try: cur = db.cursor() cur.execute("INSERT INTO vcard(username,vcard) VALUES('%s', '%s')" % (username, vCard)) except Exception as why: print why db.close() showed to me this error : (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '<vCard xmlns='vcard-temp'><VERSION>3.0</VERSION><ADR><HOME/></ADR><ADR><WORK/></' at line 1") but when I'm trying to connect to mysql via terminal and insert it, it's work 100% what I'm doing in terminal : mysql -u test1 -p test1 INSERT INTO vcard(username,vcard) VALUES("user1", "<vCard xmlns='vcard-temp'><VERSION>3.0</VERSION><ADR><HOME/></ADR><ADR><WORK/></ADR><TEL><HOME/></TEL><TEL><WORK/></TEL><TEL><FAX/></TEL><TEL><CELL/></TEL><EMAIL><HOME/><USERID>user1@domain.tld</USERID></EMAIL><EMAIL><WORK/></EMAIL><JABBERID></JABBERID><ORG><ORGUNIT/></ORG><PRODID></PRODID></vCard>"); How can I do it? A: You don't need to put %s within quotations : cur.execute("INSERT INTO vcard(username,vcard) VALUES(%s, %s)"%(username, vCard)) You can also remove the % at the leading of your values tuple : cur.execute("INSERT INTO vcard(username,vcard) VALUES(%s, %s)",(username, vCard))
{ "pile_set_name": "StackExchange" }
Q: C# wpf calculator I'm making a calculator but I get an exception when I try to make a calculation with a decimal number. There is something wrong with with all sum1 += double.Parse(numEnt.Text); But I'm a bit lost now:P public partial class MainWindow : Window { double sum1 = 0; double sum2 = 0; string dotSign = ""; bool plusButtonClicked = false; bool subButtonClicked = false; bool multButtonClicked = false; bool divButtonClicked = false; public MainWindow() { InitializeComponent(); } private void NumberValidationTextBox(object sender, TextCompositionEventArgs e) { Regex regex = new Regex("[^0-9]+"); e.Handled = regex.IsMatch(e.Text); } private void one_Click(object sender, RoutedEventArgs e) { numEnt.Text += one.Content; } private void two_Click(object sender, RoutedEventArgs e) { numEnt.Text += two.Content; } private void three_Click(object sender, RoutedEventArgs e) { numEnt.Text += three.Content; } private void four_Click(object sender, RoutedEventArgs e) { numEnt.Text += four.Content; } private void five_Click(object sender, RoutedEventArgs e) { numEnt.Text += five.Content; } private void six_Click(object sender, RoutedEventArgs e) { numEnt.Text += six.Content; } private void seven_Click(object sender, RoutedEventArgs e) { numEnt.Text += seven.Content; } private void eight_Click(object sender, RoutedEventArgs e) { numEnt.Text += eight.Content; } private void nine_Click(object sender, RoutedEventArgs e) { numEnt.Text += nine.Content; } private void zero_Click(object sender, RoutedEventArgs e) { numEnt.Text += zero.Content; } private void add_Click(object sender, RoutedEventArgs e) { sum1 += double.Parse(numEnt.Text); numEnt.Clear(); plusButtonClicked = true; subButtonClicked = false; multButtonClicked = false; divButtonClicked = false; } private void sub_Click(object sender, RoutedEventArgs e) { sum1 += double.Parse(numEnt.Text); numEnt.Clear(); plusButtonClicked = false; subButtonClicked = true; multButtonClicked = false; divButtonClicked = false; } private void mult_Click(object sender, RoutedEventArgs e) { sum1 += double.Parse(numEnt.Text); numEnt.Clear(); plusButtonClicked = false; subButtonClicked = false; multButtonClicked = true; divButtonClicked = false; } private void div_Click(object sender, RoutedEventArgs e) { sum1 = Convert.ToDouble(dotSign); sum1 += double.Parse(numEnt.Text); numEnt.Clear(); plusButtonClicked = false; subButtonClicked = false; multButtonClicked = false; divButtonClicked = true; } public void deci_Click(object sender, RoutedEventArgs e) { double currentInput = numEnt.Text.Length; bool pointFound = false; /*for (int i = 0; i < currentInput.Length; i++) { if (currentInput[i] == '.') pointFound = true; }*/ if (pointFound == false) numEnt.Text += "."; } private void equal_Click(object sender, RoutedEventArgs e) { if (plusButtonClicked == true) { sum2 = sum1 + double.Parse(numEnt.Text); result.Text = sum2.ToString(); sum1 = 0; } if (subButtonClicked == true) { sum2 = sum1 - double.Parse(numEnt.Text); result.Text = sum2.ToString(); sum1 = 0; } if (multButtonClicked == true) { sum2 = sum1 * double.Parse(numEnt.Text); result.Text = sum2.ToString(); sum1 = 0; } if (divButtonClicked == true) { sum2 = sum1 / double.Parse(numEnt.Text); result.Text = sum2.ToString(); sum1 = 0; } numEnt.Clear(); } private void clear_Click(object sender, RoutedEventArgs e) { numEnt.Clear(); calculations.Clear(); result.Clear(); } private void change_Click(object sender, RoutedEventArgs e) { double signchange = numEnt.Text.Length; signchange = -signchange; numEnt.Text = signchange.ToString(); } } } A: double.Parse(string) Only three possible exceptions with double.Parse(string), and since it doesn't seem you played with its parameter, you're getting a FormatException. You were talking about decimal numbers, so I'm guessing it all comes down to the decimal and groups separators you're using. By defaults, I think you can use '.' as a decimal separator and ',' or ' ' as a groups one. You should consider using double.Parse(string, NumberStyle) to define more precisely the separators you wish to use in your calculator.
{ "pile_set_name": "StackExchange" }
Q: ACUMATICA BQL QUERIES I need to return records from the database using BQL. I have tried writing the BQL query like this TaxZone zone = PXSelectJoin<TaxZone, InnerJoin<LocationExtAddress, On<TaxZone.taxZoneID, Equal<LocationExtAddress.cTaxZoneID>>, InnerJoin<Customer, On<Customer.bAccountID, Equal<LocationExtAddress.bAccountID>>, Where<Customer.bAccountID, Equal<Current<Customer.BAccountID>>>; and I get errors \App_RuntimeCode\SOOrderEntry.cs(387): error CS1002: ; expected \App_RuntimeCode\SOOrderEntry.cs(387): error CS1525: Invalid expression term '<' \App_RuntimeCode\SOOrderEntry.cs(387): error CS1002: ; expected \App_RuntimeCode\SOOrderEntry.cs(387): error CS1002: ; expected \App_RuntimeCode\SOOrderEntry.cs(387): error CS1525: Invalid expression term ',' \App_RuntimeCode\SOOrderEntry.cs(387): error CS1002: ; expected \App_RuntimeCode\SOOrderEntry.cs(387): error CS1002: ; expected \App_RuntimeCode\SOOrderEntry.cs(387): error CS1525: Invalid expression term ',' \App_RuntimeCode\SOOrderEntry.cs(387): error CS1002: ; expected \App_RuntimeCode\SOOrderEntry.cs(387): error CS1002: ; expected \App_RuntimeCode\SOOrderEntry.cs(387): error CS1525: Invalid expression term ',' \App_RuntimeCode\SOOrderEntry.cs(387): error CS1002: ; expected \App_RuntimeCode\SOOrderEntry.cs(387): error CS1002: ; expected \App_RuntimeCode\SOOrderEntry.cs(387): error CS1525: Invalid expression term ',' \App_RuntimeCode\SOOrderEntry.cs(387): error CS1002: ; expected \App_RuntimeCode\SOOrderEntry.cs(387): error CS1002: ; expected I have also tried using one DAC like this Customer cust = PXSelect<Customer, Where<Customer.bAccountID, Equal<Current<Customer.bAccountID>>>; I am still getting the error \App_RuntimeCode\SOOrderEntry.cs(383): error CS1002: ; expected \App_RuntimeCode\SOOrderEntry.cs(383): error CS1525: Invalid expression term '<' \App_RuntimeCode\SOOrderEntry.cs(383): error CS1002: ; expected \App_RuntimeCode\SOOrderEntry.cs(383): error CS1002: ; expected \App_RuntimeCode\SOOrderEntry.cs(383): error CS1525: Invalid expression term ',' \App_RuntimeCode\SOOrderEntry.cs(383): error CS1002: ; expected \App_RuntimeCode\SOOrderEntry.cs(383): error CS1525: Invalid expression term '>' \App_RuntimeCode\SOOrderEntry.cs(383): error CS1002: ; expected Compiler time, in seconds: 21.1134712 Any help on the issue would be really appreciated because I have gone through the documentation, that is the format that is supporsed to be written A: TaxZone zone = PXSelectJoin<TaxZone, InnerJoin<LocationExtAddress, On<TaxZone.taxZoneID, Equal<LocationExtAddress.cTaxZoneID>>, InnerJoin<Customer, On<Customer.bAccountID, Equal<LocationExtAddress.bAccountID>>>>, Where<Customer.bAccountID, Equal<Current<Customer.bAccountID>>>>.Select(graph); To Construct BQL Statements
{ "pile_set_name": "StackExchange" }
Q: Transform a 9x9 Matrix so that each row is a 3x3 Block I have the following example data: [0] = {01,02,03, 04,05,06, 07,08,09} [1] = {11,12,13, 14,15,16, 17,18,19} [2] = {21,22,23, 24,25,26, 27,28,29} [3] = {31,32,33, 34,35,36, 37,38,39} [4] = {41,42,43, 44,45,46, 47,48,49} [5] = {51,52,53, 54,55,56, 57,58,59} [6] = {61,62,63, 64,65,66, 67,68,69} [7] = {71,72,73, 74,75,76, 77,78,79} [8] = {81,82,83, 84,85,86, 87,88,89} To create the new matrix I did this, Knowing it static 9x9 var grid2=[[],[]]; grid2.push([grid[0][0],grid[0][1], grid[0][2],grid[1][0],grid[1][1], grid[1][2],grid[2][0],grid[2][1], grid[2][2]]); grid2.push([grid[3][0],grid[3][1], grid[3][2],grid[4][0],grid[4][1], grid[4][2],grid[5][0],grid[5][1], grid[5][2]]); grid2.push([grid[6][0],grid[6][1], grid[6][2],grid[7][0],grid[7][1], grid[7][2],grid[8][0],grid[8][1], grid[8][2]]); grid2.push([grid[0][3],grid[0][4], grid[0][5],grid[1][3],grid[1][4], grid[1][5],grid[2][3],grid[2][4], grid[2][5]]); grid2.push([grid[3][3],grid[3][4], grid[3][5],grid[4][3],grid[4][4], grid[4][5],grid[5][3],grid[5][4], grid[5][5]]); grid2.push([grid[6][3],grid[6][4], grid[6][5],grid[7][3],grid[7][4], grid[7][5],grid[8][3],grid[8][4], grid[8][5]]); grid2.push([grid[0][6],grid[0][7], grid[0][8],grid[1][6],grid[1][7], grid[1][8],grid[2][6],grid[2][7], grid[2][8]]); grid2.push([grid[3][6],grid[3][7], grid[3][8],grid[4][6],grid[4][7], grid[4][8],grid[5][6],grid[5][7], grid[5][8]]); grid2.push([grid[6][6],grid[6][7], grid[6][8],grid[7][6],grid[7][7], grid[7][8],grid[2][6],grid[8][7], grid[8][8]]); This works, but my question is, can this be done more efficiently / elegantly. The point of this, is part of a larger code base, that takes the matrix and validates if it is a Sudoku solution. A: You can use a simple algorithm for this let idx = [0, 1, 2], idy = [0, 1, 2]; let result = []; for(let i=0; i<9; i+=3){ for(let j=0; j<9; j+=3){ idx.forEach(e => { idy.forEach(f => { result.push(arr[i+e][j+f]); }) }) } }
{ "pile_set_name": "StackExchange" }
Q: Anim Zemiros is highly anthropomorphic; how come we sing it in public? Shir HaKovod - Anim Zemiros. This is amazingly anthropomorphic and all that without even once the word כביכול (= as if such a thing could be true). Admittedly the references come from texts such as Shir HaShirim but to make a poem from it, how come it’s allowed? A: The poet makes it very clear, before launching into these descriptions, that they are not literal: אֲסַפְּרָה כְבודְךָ וְלא רְאִיתִיךָ. אֲדַמְּךָ אֲכַנְּךָ וְלא יְדַעְתִּיךָ:‏ בְּיַד נְבִיאֶיךָ בְּסוד עֲבָדֶיךָ. דִּמִּיתָ הֲדַר כְּבוד הודֶךָ:‏ גְּדֻלָּתְךָ וּגְבוּרָתֶךָ. כִּנּוּ לְתוקֶף פְּעֻלָּתֶךָ:‏ דִּמּוּ אותְךָ וְלא כְּפִי יֶשְׁךָ. וַיַּשְׁווּךָ לְפִי מַעֲשיךָ:‏ הִמְשִׁילוּךָ בְּרוב חֶזְיונות. הִנְּךָ אֶחָד בְּכָל דִּמְיונות:‏ I shall relate Your glory, though I see You not; I shall allegorize You, I shall describe You, though I know You not. Through the hand of Your prophets, through the counsel of Your servants; You allegorized the splendrous glory of Your power. Your greatness and Your strength, they described the might of Your works. They allegorized You, but not according to Your reality, and they portrayed You according to your deeds. They symbolized You in many varied visions; yet You are a Unity containing all the allegories. (Hebrew text of lines 5 - 9 copy/pasted from Sefaria. English Translation from the Artscroll Siddur.) That sounds to me like five lines of "כביכול ."
{ "pile_set_name": "StackExchange" }
Q: Java 8 streams maintain specific map key order return from group by operation I have a list with collections of TitleIsbnBean objects. I wrote the following code snippet to group by this collection by learning area type as below. titleListByLearningArea = nonPackageIsbnList.stream() .collect(groupingBy(TitleIsbnBean::getKeylearningarea, LinkedHashMap::new,Collectors.toList()) ); but I want to preserve the following specific order in the map return from the above stream. titleListByLearningArea.put("Commerce", new ArrayList<TitleIsbnBean>() {}); titleListByLearningArea.put("English", new ArrayList<TitleIsbnBean>() {}); titleListByLearningArea.put("Health & PE", new ArrayList<TitleIsbnBean>() {}); titleListByLearningArea.put("Humanities", new ArrayList<TitleIsbnBean>() {}); titleListByLearningArea.put("Mathematics", new ArrayList<TitleIsbnBean>() {}); titleListByLearningArea.put("Music & the Arts", new ArrayList<TitleIsbnBean>() {}); titleListByLearningArea.put("Science", new ArrayList<TitleIsbnBean>() {}); titleListByLearningArea.put("Others", new ArrayList<TitleIsbnBean>() {}); but I'm getting a different order once I group by the collections using streams. How can I maintain a specific order when stream group by operation using. class TitleIsbnBean { private String titleName; private String isbn; private int status; private String keylearningarea; public TitleIsbnBean(String titleName, String isbn, int status, String keylearningarea){ super(); this.titleName = titleName; this.isbn = isbn; this.status = status; this.setKeylearningarea(keylearningarea); } } ArrayList<TitleIsbnBean> nonPackageIsbnList = new ArrayList<>(); Map<String,List<TitleIsbnBean>> titleListByLearningArea = new LinkedHashMap<>(); titleListByLearningArea.put("Commerce", new ArrayList<TitleIsbnBean>() {}); titleListByLearningArea.put("English", new ArrayList<TitleIsbnBean>() {}); titleListByLearningArea.put("Health & PE", new ArrayList<TitleIsbnBean>() {}); titleListByLearningArea.put("Humanities", new ArrayList<TitleIsbnBean>() {}); titleListByLearningArea.put("Mathematics", new ArrayList<TitleIsbnBean>() {}); titleListByLearningArea.put("Music & the Arts", new ArrayList<TitleIsbnBean>() {}); titleListByLearningArea.put("Science", new ArrayList<TitleIsbnBean>() {}); titleListByLearningArea.put("Others", new ArrayList<TitleIsbnBean>() {}); titleListByLearningArea = nonPackageIsbnList.stream() .collect(Collectors.groupingBy(TitleIsbnBean::getKeylearningarea, LinkedHashMap::new,Collectors.toList())); A: Considering you need a desired order of keys for the Map you are collecting in, you can collect to a TreeMap with a Comparator based on index specified such as: Collection<TitleIsbnBean> nonPackageIsbnList = .... //initialisation List<String> orderedKeys = List.of("Commerce", "English", "Health & PE", "Humanities", "Mathematics", "Music & the Arts", "Science", "Others"); Map<String, List<TitleIsbnBean>> titleListByLearningArea = nonPackageIsbnList.stream() .collect(Collectors.groupingBy(TitleIsbnBean::getKeylearningarea, () -> new TreeMap<>(Comparator.comparingInt(orderedKeys::indexOf)), Collectors.toList()));
{ "pile_set_name": "StackExchange" }
Q: Horizontal list element evenly spaced and responsive I am creating an unordered list that contains images and text, and would like each item to be 1/3rd the width with a margin, evenly spaced. I can't figure out how to ensure, in a responsive website, the items are always exactly 1/3rd the width, including margins. Percentages seem to not remain consistent across browsers. HTML <ul> <li><img>Text</li> <li><img>Text</li> <li><img>Text</li> <li><img>Text</li> <li><img>Text</li> <li><img>Text</li> </ul> CSS ul {list-style:none; text-align:center; margin:0;} ul li {display:inline-block; zoom:1; *display:inline; vertical-align:top; width:32%; margin:10px 1%;} If I want two rows of three columns here, it will sometimes look fine and other times push the third item down to the next row--almost as if some browsers are adding a pixel or two somewhere. Is there CSS that I can use to just space it evenly across the entire width of the parent element? Note that the site is responsive so calculating exact pixels isn't going to work. I'd also rather avoid writing separate CSS for different browsers, if possible. A: There's a couple of ways to tackle this, but the easiest CSS solution is to use inline-blocks for the li elements. Now the issue with inline-block is, they will take whitespace into account, breaking your layout, but there are two easy solutions for this in the markup: HTML comments between the li elements; Compressed HTML code. Example with HTML comments: <ul> <li><img>Text</li><!-- --><li><img>Text</li><!-- --><li><img>Text</li><!-- --><li><img>Text</li><!-- --><li><img>Text</li><!-- --><li><img>Text</li> </ul> Example with compressed HTML: <ul><li><img>Text</li><li><img>Text</li><li><img>Text</li><li><img>Text</li><li><img>Text</li><li><img>Text</li></ul> For the CSS, this should do the trick (you can modify the width of the 'columns' in media queries). ul { list-style-type: none; margin: 0; padding: 0; } li { display: inline-block; width: 50%; } @media screen and (min-width: 20em) { li { width: 33.33333%; } } Another thing to note is that you can't use margins on the left and right of these items, as they will not be part of the original width, but you can use padding on the inside to "space" elements apart. This is also how some of the repsonsive grid systems are built (a little more advanced, but same principle). Here's the live code: http://codepen.io/TheDutchCoder/pen/zxxwom
{ "pile_set_name": "StackExchange" }
Q: No new line before form First my code: <?php echo 'Hello <FORM ACTION="uebung3.php" METHOD="post"> <P> <LABEL FOR="vorname">Vorname: </LABEL> <INPUT TYPE="text" NAME="vorname"> <LABEL FOR="nachname">Nachname: </LABEL> <INPUT TYPE="textarea" NAME="nachname"> <LABEL FOR="email">E-Mail: </LABEL> <INPUT TYPE="text" NAME="email"> <INPUT TYPE="radio" NAME="geschlecht" VALUE="Maskulin"> Maskulin <INPUT TYPE="checkbox" NAME="geschlecht" VALUE="Feminin"> Feminin <input type="password" for="pw" NAME="PW"> <INPUT TYPE="submit" VALUE="Absenden"> <INPUT TYPE="reset" VALUE="Zurücksetzen"> </P> </FORM> '; ?> So if i run that on my xampp-Server, it shows a "Hello" and the Form in a new line. What must I do that all this is written in one line? Thanks A: You need to remove the <p> element and display the form inline. <?php echo 'Hello <FORM ACTION="uebung3.php" METHOD="post" style="display:inline"> <LABEL FOR="vorname">Vorname: </LABEL> <INPUT TYPE="text" NAME="vorname"> <LABEL FOR="nachname">Nachname: </LABEL> <INPUT TYPE="textarea" NAME="nachname"> <LABEL FOR="email">E-Mail: </LABEL> <INPUT TYPE="text" NAME="email"> <INPUT TYPE="radio" NAME="geschlecht" VALUE="Maskulin"> Maskulin <INPUT TYPE="checkbox" NAME="geschlecht" VALUE="Feminin"> Feminin <input type="password" for="pw" NAME="PW"> <INPUT TYPE="submit" VALUE="Absenden"> <INPUT TYPE="reset" VALUE="Zurücksetzen"> </FORM> '; ?>
{ "pile_set_name": "StackExchange" }
Q: ¿Cómo se puede usar las dos columnas de resultado de un SELECT en un UPDATE en SQL? Basicamente mi problema es que tengo una consulta bastante compleja para poder obtener la suma de productos que vendio cada empleado, la cual es la siguiente: SELECT SUM(Quantity)AS productosven, EmployeeID FROM(SELECT Orders.OrderID,Orders.EmployeeID,[Order Details].Quantity FROM Orders INNER JOIN DimEmployee ON Orders.EmployeeID=DimEmployee.EmployeeID INNER JOIN [Order Details] ON [Order Details].OrderID=Orders.OrderID)AS X GROUP BY EmployeeId El resultado de la consulta anterior es: Y es necesaria que sea así de compleja, ya que en la tabla Orders tengo el OrderID y el EmployeeID y en la tabla [Order Detail] tengo el OrderID y la cantidad de producto. Lo que hace es obtenerme dos columnas en las cuales de un lado tengo todos los productos que ese empleado vendió y del otro obtengo el id de ese empleado, y ahora intento meter eso en un update, de la siguiente manera: UPDATE DimEmployee SET N_Productos =(SELECT SUM(Quantity)AS productosven, EmployeeID FROM(SELECT Orders.OrderID,Orders.EmployeeID,[Order Details].Quantity FROM Orders INNER JOIN DimEmployee ON Orders.EmployeeID=DimEmployee.EmployeeID INNER JOIN [Order Details] ON [Order Details].OrderID=Orders.OrderID)AS X GROUP BY EmployeeId) WHERE EmployeeID=(SELECT EmployeeID FROM(SELECT Orders.OrderID,Orders.EmployeeID,[Order Details].Quantity FROM Orders INNER JOIN DimEmployee ON Orders.EmployeeID=DimEmployee.EmployeeID INNER JOIN [Order Details] ON [Order Details].OrderID=Orders.OrderID)AS X GROUP BY EmployeeId) Pero me dice que no es posible ya que devuelve varios resultados, me imagino que es por que uso la misma consulta dos veces, una en el set y otra en el where, pero no se. UPDATE DimEmployee SET N_Productos =(SELECT SUM(Quantity)AS productosven, EmployeeID FROM(SELECT Orders.OrderID,Orders.EmployeeID,[Order Details].Quantity FROM Orders INNER JOIN DimEmployee ON Orders.EmployeeID=DimEmployee.EmployeeID INNER JOIN [Order Details] ON [Order Details].OrderID=Orders.OrderID)AS X GROUP BY EmployeeId) Y de esta forma me aparece este error: Mens. 116, Nivel 16, Estado 1, Línea 7 Sólo se puede especificar una expresión en la lista de selección cuando la subconsulta no se especifica con EXISTS. A: En SQLServer puedes hacer una consulta de actualización, algo bastante útil, conceptualmente es algo así: UPDATE Tabla1 SET Columna = T2.OtraColumna FROM Tabla1 T1 INNER JOIN Tabla2 T2 ON T1.AlgunId = T2.AlgunId Si te fijas bien es casi una consulta habitual a la que se le ha agregado las sentencias de UPDATE. Adaptando un poco tu consulta, podrías hacer algo así: UPDATE DimEmployee SET N_Productos = G.productosven FROM DimEmployee E INNER JOIN (SELECT SUM(Quantity) AS productosven, EmployeeID FROM (SELECT Orders.OrderID, Orders.EmployeeID, [Order Details].Quantity FROM Orders INNER JOIN DimEmployee ON Orders.EmployeeID=DimEmployee.EmployeeID INNER JOIN [Order Details] ON [Order Details].OrderID=Orders.OrderID ) X GROUP BY EmployeeId ) G ON E.EmployeeID = G.EmployeeID
{ "pile_set_name": "StackExchange" }
Q: Replace path with another path with sed I have a file with following lines: some /foo/foo/foo some some=/foo/foo/foo some some /foo/foo/foo/ some some=/foo/foo/foo/ some some "/foo/foo/foo" some some="/foo/foo/foo" some some "/foo/foo/foo/" some some="/foo/foo/foo/" some some '/foo/foo/foo' some some='/foo/foo/foo' some some '/foo/foo/foo/' some some='/foo/foo/foo/ some some (/foo/foo/foo) some some=(/foo/foo/foo) some How can I find and replace this pathS with path with 'frame' like: some [p]/foo/foo/foo[;p] some some=[p]/foo/foo/foo[;p] some some [p]/foo/foo/foo/[;p] some some=[p]/foo/foo/foo/[;p] some some "[p]/foo/foo/foo[;p]" some some="[p]/foo/foo/foo[;p]" some some "[p]/foo/foo/foo/[;p]" some some="[p]/foo/foo/foo/[;p]" some some '[p]/foo/foo/foo[;p]' some some='[p]/foo/foo/foo[;p]' some some '[p]/foo/foo/foo/[;p]' some some='[p]/foo/foo/foo/[;p] some some ([p]/foo/foo/foo[;p]) some some=([p]/foo/foo/foo[;p]) some I wrote almost all of the examples, if someone might have wanted to set up sub-question. Note: Paths are completely arbitrary. I do not know what are paths. I should only know that they should be replaced with a path with 'frame' A: you mentioned: Note: Paths are completely arbitrary. I do not know what are paths. I assume the path should be in format \w (a-z A-Z 0-9 or _). then this sed line: sed -r 's#(/[a-zA-Z0-9_/]+)#[p]\1[;p]#g' yourFile will do the job. see the test with your example. (note I did some changes on the input, to make it "arbitrary") kent$ cat t some /foo/foo/fo3o some some=/foo/foo/fdoo some some /foo/foo/fxoo/ some some=/foo/fofo/foo/ some some "/foxo/foo/foo" some some="/foo/ffoo/foo" some some "/foo/foxo/foo/" some some="/foo/f6oo/foo/" some some '/foo/fo7o/foo' some some='/foo/foo7/foo' some some '/foxo/foo/foo/' some some='/fo0o/f_oo/foo/ some some (/foo/f99oox/foo) some some=(/fo234o/fdoo/fd_oo) some' kent$ sed -r 's#(/[a-zA-Z0-9_/]+)#[p]\1[;p]#g' t some [p]/foo/foo/fo3o[;p] some some=[p]/foo/foo/fdoo[;p] some some [p]/foo/foo/fxoo/[;p] some some=[p]/foo/fofo/foo/[;p] some some "[p]/foxo/foo/foo[;p]" some some="[p]/foo/ffoo/foo[;p]" some some "[p]/foo/foxo/foo/[;p]" some some="[p]/foo/f6oo/foo/[;p]" some some '[p]/foo/fo7o/foo[;p]' some some='[p]/foo/foo7/foo[;p]' some some '[p]/foxo/foo/foo/[;p]' some some='[p]/fo0o/f_oo/foo/[;p] some some ([p]/foo/f99oox/foo[;p]) some some=([p]/fo234o/fdoo/fd_oo[;p]) some'
{ "pile_set_name": "StackExchange" }
Q: c++, "Error: initialization with '{...}' expected for aggregate object" When compiling this code I get the error, "Error: initialization with '{...}' expected for aggregate object" at my function calls. I am compiling using Visual Studio 11. #include <iostream> #include <string> #include <array> using namespace std; typedef std::array<string, 5> string_t; string_t centerString(std::array<string, 5> (&tempArray),unsigned short int length); string_t evenString(std::array<string, 5> (&tempArray),unsigned short int length); int main(){ std::array<string, 5> aArray = {"a","aa","aaa","aaaa","aaaaa"}; std::array<string, 5> evenStr[5] = evenString(aArray,5); std::array<string, 5> centerStr[5] = centerStr(aArray,5); } string_t evenString(std::array<string, 5> (&srcArray),unsigned short int length){ std::array<string, (sizeof(srcArray)/sizeof(srcArray[0]))> trgtArray= {}; for(unsigned short int x = 0; x < (sizeof(srcArray)/sizeof(srcArray[0]));x++){ trgtArray[x] = srcArray[x]; for(unsigned short int y = 0; y < (length-trgtArray[x].length()); y++){ trgtArray[x] += " "; } } return(trgtArray); } string_t centerString(std::array<string, 5> (&srcArray),unsigned short int length){ std::array<string, (sizeof(srcArray)/sizeof(srcArray[0]))> trgtArray= {}; unsigned short int remainder; string spacer = ""; for(unsigned short int x = 0; x < (sizeof(srcArray)/sizeof(srcArray[0]));x++){ remainder = length - srcArray[x].length(); if((remainder % 2) == 0){ trgtArray[x] = srcArray[x]; for(unsigned short int y = 0; y < (length-srcArray[x].length()); y++){ trgtArray[x] += " "; } }else{ for(unsigned short int z = 0; z < (remainder/2); z++){ spacer += " "; } trgtArray[x] = spacer + srcArray[x] + spacer + " "; } } return(trgtArray); } A: You are returning temporary reference in centerString string_t& centerString(std::array<string, 5> (&tempArray),unsigned short int length); centerStr is array, can't use it as function std::array<string, 5> centerStr = centerStr(aArray,5); I guess you mean std::array<string, 5> centerStr = centerString(aArray,5); You could try below sample function, just return array out, RVO should kick in. std::array<string,5> evenString(std::array<string, 5> (&srcArray), unsigned short length){ std::array<string,5> trgtArray = {}; //.... return trgtArray; } std::array<string, 5> evenStr = evenString(aArray,5); std::array<string, 5> centerStr = centerString(aArray,5);
{ "pile_set_name": "StackExchange" }
Q: Xml code in my database <?xml version="1.0" standalone="yes"?> <NewDataSet> <ColSettings> <Column1>Column1</Column1> <Column2>Column2</Column2> <Column3>Column3</Column3> <Column4>Column4</Column4> <Column5>Column5</Column5> <Column6>Column6</Column6> <Column7>Column7</Column7> <Column8>Column8</Column8> <Column9>Column9</Column9> <Column10>Column10</Column10> </ColSettings> <ColSettings> <Column1>Symbol</Column1> <Column2>Bid</Column2> <Column3>Ask</Column3> <Column4>DHS</Column4> <Column5>PKR</Column5> <Column6>High</Column6> <Column7>Low</Column7> <Column8>TTRate</Column8> <Column9>Comm</Column9> <Column10>SelRate</Column10> </ColSettings> <ColSettings> <Column1>1</Column1> <Column2>2</Column2> <Column3>3</Column3> <Column4>4</Column4> <Column5>5</Column5> <Column6>6</Column6> <Column7>7</Column7> <Column8>8</Column8> <Column9>9</Column9> <Column10>10</Column10> </ColSettings> <ColSettings> <Column1>#FFFFFF</Column1> <Column2>#214488</Column2> <Column3>#D8FF7C</Column3> <Column4>#BE7400</Column4> <Column5>#FFFFFF</Column5> <Column6>#FFFFFF</Column6> <Column7>#FFFFFF</Column7> <Column8>#FFFFFF</Column8> <Column9>#000000</Column9> <Column10>#000000</Column10> </ColSettings> <ColSettings> <Column1>#FFFFFF</Column1> <Column2>#FFFFFF</Column2> <Column3>#32CD32</Column3> <Column4>#214488</Column4> <Column5>#000000</Column5> <Column6>#127332</Column6> <Column7>#FF2121</Column7> <Column8>#32CD32</Column8> <Column9>#FF4800</Column9> <Column10>#FF4800</Column10> </ColSettings> </NewDataSet> hi Friends i want to store given code in my Database column suggest me how can i do either by store procedure or c#.net code give me some code or related web site so that store it in my database i am trying from 2 days ... A: Read the xml in datatable. ds.ReadXml(xmlPath); Then you can refer following post How to insert multiple records with table param in sql server 2008
{ "pile_set_name": "StackExchange" }
Q: Exercise about conditional expectation I have to show that for sigma-algebras $\mathcal{F, G}$ with $\mathcal{F}\subseteq \mathcal{G}$ and $X, Y$ real random variables with $\Bbb E[X^2] < \infty$ the following holds: $$\Bbb{E}\bigl[(X-\Bbb{E}[X \mid \mathcal{G}])^2\bigr] + \Bbb E\bigl[(\Bbb E[X \mid \mathcal{G}]-\Bbb E[X \mid \mathcal{F}])^2\bigr]=\Bbb E\bigl[(X-\Bbb E[X \mid \mathcal{F}])^2\bigr] \, .$$ Can you give me some hints? A: Expanding the squares on both sides, we find that the claim is equivalent to $$-2 \mathbb{E}(X \mathbb{E}(X \mid \mathcal{G})) + 2 \mathbb{E}(\mathbb{E}(X \mid \mathcal{G})^2) - 2 \mathbb{E}(\mathbb{E}(X \mid \mathcal{F}) \mathbb{E}(X \mid \mathcal{G})) = -2 \mathbb{E}(X \mathbb{E}(X \mid \mathcal{F})). \tag{1}$$ It follows from the very definition that $X-\mathbb{E}(X \mid \mathcal{G})$ and $\mathbb{E}(X \mid \mathcal{G})$ are orthogonal, i.e. $$\mathbb{E}(\mathbb{E}(X- \mathbb{E}(X \mid \mathcal{G})) \mathbb{E}(X \mid \mathcal{G}))=0,$$ or, equivalently, $$\mathbb{E}(X \mathbb{E}(X \mid \mathcal{G})) = \mathbb{E}(\mathbb{E}(X \mid \mathcal{G})^2). \tag{2}$$ This shows that the first two terms on the left-hand side in $(1)$ cancel. Finally, we note that by the tower property $$\begin{align*}\mathbb{E}(X \mathbb{E}(X \mid \mathcal{F}) &= \mathbb{E} \left( \mathbb{E} \left[ X \mathbb{E}(X \mid \mathcal{F}) \mid \mathcal{G} \right] \right) \\ &= \mathbb{E}(\mathbb{E}(X \mid \mathcal{G}) \mathbb{E}(X \mid \mathcal{F})) \end{align*}$$ where we have used in the last step that $\mathcal{F} \subseteq \mathcal{G}$ (which implies that $\mathbb{E}(X \mid \mathcal{F})$ is measurable with respect to $\mathcal{G}$).
{ "pile_set_name": "StackExchange" }
Q: JNI Unsatisfied link error in distributed jar I have a java project that connects to a fingerprint scanner through a JNI library. I have the project running perfectly in netbeans with the jni files in the root directory of the java project. The problem occurs when I try and package it as a jar. Im having this error: C:\Users\dwake\Desktop\OnceAgain\TestJob\dist>java -jar TestJob.jar Exception in thread "AWT-EventQueue-0" java.lang.UnsatisfiedLinkError: no scannerJNI in java.library.path at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1860) at java.lang.Runtime.loadLibrary0(Runtime.java:845) at java.lang.System.loadLibrary(System.java:1084) at scanner.scannerGUI.<clinit>(Unknown Source) at scanner.main$1.run(Unknown Source) at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:251) at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:701) at java.awt.EventQueue.access$000(EventQueue.java:102) at java.awt.EventQueue$3.run(EventQueue.java:662) at java.awt.EventQueue$3.run(EventQueue.java:660) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76) at java.awt.EventQueue.dispatchEvent(EventQueue.java:671) at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:244) at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:163) at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:151) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:147) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:139) at java.awt.EventDispatchThread.run(EventDispatchThread.java:97) I know this is caused by a library file not being in the correct directory or not being found by the java virtual machine. How would I get my JNI libraries to compile with the jar? P.S. I have tried opening the jar with 7zip and placing the .dll files in the jar but this hasnt helped. A: Try this: java -Djava.library.path=/path/to/dlls/ -jar TestJob.jar
{ "pile_set_name": "StackExchange" }
Q: Parsing JSON in Flutter / Dart: () => Map , NoSuchMethodError - (array problem?) Im still a bit new to Flutter / Dart and Ive struggled with parsing JSON for quite some time now. It seems like a daunting task to me, even though I think my JSON structure is not that complicated. Your help would be greatly appreciated. This is the JSON I want to parse: { "predictionICL":{ "openingTimeToday":"8:00 - 23:00", "openingTimeTomorrow":"8:00 - 23:00", "percentagesToday":[ 3, 5, 11, 17, 20, 23, 25, 26, 25, 29, 30, 32, 31, 35, 40, 43, 44, 46, 49, 53, 50, 56, 54, 60, 62, 61, 69, 70, 75, 76, 84, 90, 94, 100, 93, 81, 72, 70, 73, 71, 63, 59, 55, 56, 51, 49, 50, 45, 43, 40, 38, 35, 31, 27, 25, 23, 20, 20, 19, 17, 12, 9, 8, 2, 1 ], "percentagesTomorrow":[ 0, 0, 1, 7, 14, 20, 22, 21, 21, 22, 20, 25, 27, 31, 30, 31, 32, 33, 30, 34, 35, 33, 35, 37, 39, 40, 40, 39, 38, 40, 41, 38, 34, 37, 34, 35, 33, 32, 31, 30, 33, 30, 31, 30, 29, 30, 27, 28, 26, 23, 20, 19, 16, 17, 15, 12, 10, 7, 5, 1, 1, 0, 0, 0, 0 ] }, "predictionRandwyck":{ "openingTimeToday":"8:00 - 23:00", "openingTimeTomorrow":"8:00 - 23:00", "percentagesToday":[ 3, 5, 11, 17, 20, 23, 25, 26, 25, 29, 30, 32, 31, 35, 40, 43, 44, 46, 49, 53, 50, 56, 54, 60, 62, 61, 69, 70, 75, 76, 84, 90, 94, 100, 93, 81, 72, 70, 73, 71, 63, 59, 55, 56, 51, 49, 50, 45, 43, 40, 38, 35, 31, 27, 25, 23, 20, 20, 19, 17, 12, 9, 8, 2, 1 ], "percentagesTomorrow":[ 0, 0, 1, 7, 14, 20, 22, 21, 21, 22, 20, 25, 27, 31, 30, 31, 32, 33, 30, 34, 35, 33, 35, 37, 39, 40, 40, 39, 38, 40, 41, 38, 34, 37, 34, 35, 33, 32, 31, 30, 33, 30, 31, 30, 29, 30, 27, 28, 26, 23, 20, 19, 16, 17, 15, 12, 10, 7, 5, 1, 1, 0, 0, 0, 0 ] }, "predictionTapijn":{ "openingTimeToday":"8:00 - 23:00", "openingTimeTomorrow":"8:00 - 23:00", "percentagesToday":[ 3, 5, 11, 17, 20, 23, 25, 26, 25, 29, 30, 32, 31, 35, 40, 43, 44, 46, 49, 53, 50, 56, 54, 60, 62, 61, 69, 70, 75, 76, 84, 90, 94, 100, 93, 81, 72, 70, 73, 71, 63, 59, 55, 56, 51, 49, 50, 45, 43, 40, 38, 35, 31, 27, 25, 23, 20, 20, 19, 17, 12, 9, 8, 2, 1 ], "percentagesTomorrow":[ 0, 0, 1, 7, 14, 20, 22, 21, 21, 22, 20, 25, 27, 31, 30, 31, 32, 33, 30, 34, 35, 33, 35, 37, 39, 40, 40, 39, 38, 40, 41, 38, 34, 37, 34, 35, 33, 32, 31, 30, 33, 30, 31, 30, 29, 30, 27, 28, 26, 23, 20, 19, 16, 17, 15, 12, 10, 7, 5, 1, 1, 0, 0, 0, 0 ] }, "message":"optionalmessageString" } Its basically just three instances of the datatype LibraryPrediction and one optional Message string. The datatype LibraryPrediction consists of one String "openingTimeToday", one String "openingTimeTomorrow" and two double Arrays "percentagesToday" and "percentagesTomorrow". Right now, I am trying to parse the json from above from disk, as my Server is not running yet. This is my code so far: I have one service file: import 'dart:convert'; import 'package:flutter/services.dart'; import 'package:test_app/models/predictions_update_model.dart'; PredictionsUpdate parseUpdate(String responseBody) { final jsonResponse = json.decode(responseBody).cast<Map<String, dynamic>>(); PredictionsUpdate update = jsonResponse.map<PredictionsUpdate>((json) => PredictionsUpdate.fromJson(json)); return update; } Future<PredictionsUpdate> fetchUpdate() async { final response = await rootBundle.loadString('lib/testJson/data.json'); return parseUpdate(response); } And one model file: class PredictionsUpdate { final LibraryPrediction predictionICL; final LibraryPrediction predictionRandwyck; final LibraryPrediction predictionTapijn; final String message; PredictionsUpdate({ this.predictionICL, this.predictionRandwyck, this.predictionTapijn, this.message, }); factory PredictionsUpdate.fromJson(Map<String, dynamic> parsedJson){ return PredictionsUpdate( predictionICL: LibraryPrediction.fromJson(parsedJson['predictionICL']), predictionRandwyck: LibraryPrediction.fromJson(parsedJson['predictionRandwyck']), predictionTapijn: LibraryPrediction.fromJson(parsedJson['predictionTapijn']), message: parsedJson['message'] as String, ); } } class LibraryPrediction { final String openingTimeToday; final String openingTimeTomorrow; final List<double> percentagesToday; final List<double> percentagesTomorrow; LibraryPrediction({ this.openingTimeToday, this.openingTimeTomorrow, this.percentagesToday, this.percentagesTomorrow, }); factory LibraryPrediction.fromJson(Map<String, dynamic> json){ return LibraryPrediction( openingTimeToday: json['openingTimeToday'] as String, openingTimeTomorrow: json['openingTimeTomorrow'] as String, percentagesToday: json['percentagesToday'] as List<double>, percentagesTomorrow: json['percentagesTomorrow'] as List<double>, ); } } This is how I call the function: Row( children: <Widget>[ RaisedButton( child: Text('update'), onPressed: () { Future<PredictionsUpdate> futureUpdate = fetchUpdate(); futureUpdate.then((update)=> widget.currentNumbers = update) .catchError((error) => print(error)); }, ), ], ), whenever I try to parse the JSON, I get the following error: flutter: NoSuchMethodError: Class '_InternalLinkedHashMap<String, dynamic>' has no instance method 'cast' with matching arguments. Receiver: _LinkedHashMap len:4 Tried calling: cast<Map<String, dynamic>>() Found: cast<RK, RV>() => Map<RK, RV> I have this feeling that the error originates somewhere when im trying to parse the double arrays "percentagesToday" or "percentagesTomorrow", but I can't say for sure and Im not able to get more clues from the error message. I would be very grateful for any help in figuring out where I went wrong. A: You can copy paste run full code below You can do like this List<double>.from(json["percentagesToday"].map((x) => x.toDouble())), code snippet factory LibraryPrediction.fromJson(Map<String, dynamic> json) => LibraryPrediction( openingTimeToday: json["openingTimeToday"], openingTimeTomorrow: json["openingTimeTomorrow"], percentagesToday: List<double>.from( json["percentagesToday"].map((x) => x.toDouble())), percentagesTomorrow: List<double>.from( json["percentagesTomorrow"].map((x) => x.toDouble())), ); ... futureUpdate.then((update) { print('${update.predictionIcl.openingTimeToday.toString()}'); print('${update.message}'); print('${update.predictionRandwyck.openingTimeTomorrow}'); }).catchError((error) => print(error)); output I/flutter ( 7344): 8:00 - 23:00 I/flutter ( 7344): optionalmessageString I/flutter ( 7344): 8:00 - 23:00 full code import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; import 'dart:convert'; PredictionsUpdate predictionsUpdateFromJson(String str) => PredictionsUpdate.fromJson(json.decode(str)); class PredictionsUpdate { LibraryPrediction predictionIcl; LibraryPrediction predictionRandwyck; LibraryPrediction predictionTapijn; String message; PredictionsUpdate({ this.predictionIcl, this.predictionRandwyck, this.predictionTapijn, this.message, }); factory PredictionsUpdate.fromJson(Map<String, dynamic> json) => PredictionsUpdate( predictionIcl: LibraryPrediction.fromJson(json["predictionICL"]), predictionRandwyck: LibraryPrediction.fromJson(json["predictionRandwyck"]), predictionTapijn: LibraryPrediction.fromJson(json["predictionTapijn"]), message: json["message"], ); } class LibraryPrediction { String openingTimeToday; String openingTimeTomorrow; List<double> percentagesToday; List<double> percentagesTomorrow; LibraryPrediction({ this.openingTimeToday, this.openingTimeTomorrow, this.percentagesToday, this.percentagesTomorrow, }); factory LibraryPrediction.fromJson(Map<String, dynamic> json) => LibraryPrediction( openingTimeToday: json["openingTimeToday"], openingTimeTomorrow: json["openingTimeTomorrow"], percentagesToday: List<double>.from( json["percentagesToday"].map((x) => x.toDouble())), percentagesTomorrow: List<double>.from( json["percentagesTomorrow"].map((x) => x.toDouble())), ); } void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(title: 'Flutter Demo Home Page'), ); } } class MyHomePage extends StatefulWidget { MyHomePage({Key key, this.title}) : super(key: key); final String title; @override _MyHomePageState createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { int _counter = 0; Future<PredictionsUpdate> fetchUpdate() async { String jsonString = ''' { "predictionICL":{ "openingTimeToday":"8:00 - 23:00", "openingTimeTomorrow":"8:00 - 23:00", "percentagesToday":[ 3, 5, 11, 17, 20, 23, 25, 26, 25, 29, 30, 32, 31, 35, 40, 43, 44, 46, 49, 53, 50, 56, 54, 60, 62, 61, 69, 70, 75, 76, 84, 90, 94, 100, 93, 81, 72, 70, 73, 71, 63, 59, 55, 56, 51, 49, 50, 45, 43, 40, 38, 35, 31, 27, 25, 23, 20, 20, 19, 17, 12, 9, 8, 2, 1 ], "percentagesTomorrow":[ 0, 0, 1, 7, 14, 20, 22, 21, 21, 22, 20, 25, 27, 31, 30, 31, 32, 33, 30, 34, 35, 33, 35, 37, 39, 40, 40, 39, 38, 40, 41, 38, 34, 37, 34, 35, 33, 32, 31, 30, 33, 30, 31, 30, 29, 30, 27, 28, 26, 23, 20, 19, 16, 17, 15, 12, 10, 7, 5, 1, 1, 0, 0, 0, 0 ] }, "predictionRandwyck":{ "openingTimeToday":"8:00 - 23:00", "openingTimeTomorrow":"8:00 - 23:00", "percentagesToday":[ 3, 5, 11, 17, 20, 23, 25, 26, 25, 29, 30, 32, 31, 35, 40, 43, 44, 46, 49, 53, 50, 56, 54, 60, 62, 61, 69, 70, 75, 76, 84, 90, 94, 100, 93, 81, 72, 70, 73, 71, 63, 59, 55, 56, 51, 49, 50, 45, 43, 40, 38, 35, 31, 27, 25, 23, 20, 20, 19, 17, 12, 9, 8, 2, 1 ], "percentagesTomorrow":[ 0, 0, 1, 7, 14, 20, 22, 21, 21, 22, 20, 25, 27, 31, 30, 31, 32, 33, 30, 34, 35, 33, 35, 37, 39, 40, 40, 39, 38, 40, 41, 38, 34, 37, 34, 35, 33, 32, 31, 30, 33, 30, 31, 30, 29, 30, 27, 28, 26, 23, 20, 19, 16, 17, 15, 12, 10, 7, 5, 1, 1, 0, 0, 0, 0 ] }, "predictionTapijn":{ "openingTimeToday":"8:00 - 23:00", "openingTimeTomorrow":"8:00 - 23:00", "percentagesToday":[ 3, 5, 11, 17, 20, 23, 25, 26, 25, 29, 30, 32, 31, 35, 40, 43, 44, 46, 49, 53, 50, 56, 54, 60, 62, 61, 69, 70, 75, 76, 84, 90, 94, 100, 93, 81, 72, 70, 73, 71, 63, 59, 55, 56, 51, 49, 50, 45, 43, 40, 38, 35, 31, 27, 25, 23, 20, 20, 19, 17, 12, 9, 8, 2, 1 ], "percentagesTomorrow":[ 0, 0, 1, 7, 14, 20, 22, 21, 21, 22, 20, 25, 27, 31, 30, 31, 32, 33, 30, 34, 35, 33, 35, 37, 39, 40, 40, 39, 38, 40, 41, 38, 34, 37, 34, 35, 33, 32, 31, 30, 33, 30, 31, 30, 29, 30, 27, 28, 26, 23, 20, 19, 16, 17, 15, 12, 10, 7, 5, 1, 1, 0, 0, 0, 0 ] }, "message":"optionalmessageString" } '''; //final response = await rootBundle.loadString('lib/testJson/data.json'); final http.Response response = http.Response(jsonString, 200); PredictionsUpdate payload = predictionsUpdateFromJson(response.body); return payload; } void _incrementCounter() { Future<PredictionsUpdate> futureUpdate = fetchUpdate(); futureUpdate.then((update) { print('${update.predictionIcl.openingTimeToday.toString()}'); print('${update.message}'); print('${update.predictionRandwyck.openingTimeTomorrow}'); }).catchError((error) => print(error)); setState(() { _counter++; }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.title), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text( 'You have pushed the button this many times:', ), Text( '$_counter', style: Theme.of(context).textTheme.headline4, ), ], ), ), floatingActionButton: FloatingActionButton( onPressed: _incrementCounter, tooltip: 'Increment', child: Icon(Icons.add), ), ); } }
{ "pile_set_name": "StackExchange" }
Q: Exception in thread "AWT-EventQueue-0" java.lang.NoSuchMethodError: setControlKeepAliveTimeout(J)V I have created a runnable jar for my project and when I try to execute it I am getting exception, but from eclipse it is executing fine Exception in thread "AWT-EventQueue-0" java.lang.NoSuchMethodError: com.FTP.setControlKeepAliveTimeout(J)V at com.FTP.<init>(FTP.java:64) at com.build.Build.GetFtp(Build.java:71) at com.build.MainFile.step1(MainFile.java:79) at com.build.ui.ScreenL.jButton2MouseClicked(ScreenL.java:240) at com.build.ui.ScreenL.access$1(ScreenL.java:215) at cm21.build.ui.ScreenL$2.mouseClicked(ScreenL.java:88) at java.awt.AWTEventMulticaster.mouseClicked(Unknown Source) at java.awt.Component.processMouseEvent(Unknown Source) at javax.swing.JComponent.processMouseEvent(Unknown Source) at java.awt.Component.processEvent(Unknown Source) at java.awt.Container.processEvent(Unknown Source) at java.awt.Component.dispatchEventImpl(Unknown Source) at java.awt.Container.dispatchEventImpl(Unknown Source) at java.awt.Component.dispatchEvent(Unknown Source) at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source) at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source) at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source) at java.awt.Container.dispatchEventImpl(Unknown Source) at java.awt.Window.dispatchEventImpl(Unknown Source) at java.awt.Component.dispatchEvent(Unknown Source) at java.awt.EventQueue.dispatchEventImpl(Unknown Source) at java.awt.EventQueue.access$200(Unknown Source) at java.awt.EventQueue$3.run(Unknown Source) at java.awt.EventQueue$3.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source) at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source) at java.awt.EventQueue$4.run(Unknown Source) at java.awt.EventQueue$4.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source) at java.awt.EventQueue.dispatchEvent(Unknown Source) at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source) at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source) at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source) at java.awt.EventDispatchThread.pumpEvents(Unknown Source) at java.awt.EventDispatchThread.pumpEvents(Unknown Source) at java.awt.EventDispatchThread.run(Unknown Source) where i find out that setControlKeepAliveTimeout is a method from one of the Jar's included in the project. am not still resolve this issue. A: Your com.FTP library version in your OS environment differs from the one in the Eclipse environment. Make sure classpath references same JAR on both environments.
{ "pile_set_name": "StackExchange" }
Q: Scrollbar horizontal sendo rolada pela scrollbar vertical Estou fazendo um pequeno teste com a scrollbar do Chrome Canary 74 no Android. Li muito a respeito, mas não obtive resultados para o dispositivo mobile, e como não tenho pc, eu uso o Aide Web para programar. No meu projeto, há apenas dois arquivos, um css e o outro html. Parece spam de h, mas não é: <!DOCTYPE html> <html> <head> <meta name="viewport" content="user-scalable=no,width=device-width"> <link href="css/styles.css" rel="stylesheet"> </head> <body> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> </body> </html> CSS: ::-webkit-scrollbar { -webkit-appearance: none; } ::-webkit-scrollbar:vertical { width: 12px; } ::-webkit-scrollbar:horizontal { height: 12px; } ::-webkit-scrollbar-thumb { background-color: rgba(0, 0, 0, .5); border-radius: 10px; border: 2px solid #f00; } ::-webkit-scrollbar-track { border-radius: 10px; background-color: #000; } body { margin: 0; padding: 0; border: 0; position: relative; width:100%; } html,body { overflow-x: scroll; overflow-y: scroll; } Quando eu dou um RUN no projeto, fica basicsmente deste modo: [Inicio] [Fim] A: Acredito que o seu problema é que vc não colocou uma altura determinada no html e body, eu usei height: 100vh; nesse exepmplo, pode ser que isso deixe a barra no lugar esperado. ::-webkit-scrollbar { -webkit-appearance: none; } ::-webkit-scrollbar:vertical { width: 12px; } ::-webkit-scrollbar:horizontal { height: 12px; } ::-webkit-scrollbar-thumb { background-color: rgba(0, 0, 0, .5); border-radius: 10px; border: 2px solid #f00; } ::-webkit-scrollbar-track { border-radius: 10px; background-color: #000; } body { margin: 0; padding: 0; border: 0; position: relative; width:100%; } html,body { overflow-x: scroll; overflow-y: scroll; height: 100vh; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="user-scalable=no,width=device-width"> <link href="css/styles.css" rel="stylesheet"> </head> <body> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> h<br> </body> </html>
{ "pile_set_name": "StackExchange" }
Q: Dynamic row range when calculating moving sum/average using window functions (SQL Server) I'm currently working on a sample script which allows me to calculate the sum of the previous two rows and the current row. However, I would like to make the number '2' as a variable. I've tried declaring a variable, or directly casting in the query, yet a syntax error always pops up. Is there a possible solution? DECLARE @myTable TABLE (myValue INT) INSERT INTO @myTable ( myValue ) VALUES ( 5) INSERT INTO @myTable ( myValue ) VALUES ( 6) INSERT INTO @myTable ( myValue ) VALUES ( 7) INSERT INTO @myTable ( myValue ) VALUES ( 8) INSERT INTO @myTable ( myValue ) VALUES ( 9) INSERT INTO @myTable ( myValue ) VALUES ( 10) SELECT SUM(myValue) OVER (ORDER BY myValue ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) FROM @myTable A: DECLARE @test VARCHAR = 1 DECLARE @sqlCommand VARCHAR(1000) DECLARE @myTable TABLE (myValue INT) INSERT INTO @myTable ( myValue ) VALUES ( 5) INSERT INTO @myTable ( myValue ) VALUES ( 6) INSERT INTO @myTable ( myValue ) VALUES ( 7) INSERT INTO @myTable ( myValue ) VALUES ( 8) INSERT INTO @myTable ( myValue ) VALUES ( 9) INSERT INTO @myTable ( myValue ) VALUES ( 10) SET @sqlCommand = 'SELECT SUM(myValue) OVER (ORDER BY myValue ROWS BETWEEN ' + @test + ' PRECEDING AND CURRENT ROW) FROM #temp' EXEC (@sqlCommand) A: You can try something like this which does not use dynamic SQL. DECLARE @myTable TABLE (myValue INT) INSERT INTO @myTable ( myValue ) VALUES ( 5) INSERT INTO @myTable ( myValue ) VALUES ( 6) INSERT INTO @myTable ( myValue ) VALUES ( 7) INSERT INTO @myTable ( myValue ) VALUES ( 8) INSERT INTO @myTable ( myValue ) VALUES ( 9) INSERT INTO @myTable ( myValue ) VALUES ( 10) DECLARE @prev_records INT = 2 ;WITH CTE as ( SELECT ROW_NUMBER() OVER(ORDER BY myValue) rn,myValue FROM @myTable ) SELECT (SELECT SUM(myValue) FROM CTE t2 WHERE t2.rn BETWEEN (t1.rn - @prev_records) AND t1.rn ) FROM CTE t1 SUM(myValue) OVER() is best option however it does not allow you to pass previous N rows using a variable.
{ "pile_set_name": "StackExchange" }
Q: AngularJS - Remove custom event listener I have a non AngularJS snippet that is communicating with my AngularJS modules via custom events. Each of these AngularJS modules represents a different route. When I am leaving each route $onDestroy is triggered but does not remove the event listener. What am I missing to un-register my custom event? Non AngularJS HTML Snippet <script> function sendEvent() { const payload = getPayload(); const event = new CustomEvent('myCustomEvent', { payload }); window.dispatchEvent(event); } </script> <button onclick="sendEvent()">Send Custom Event</button> AngularJS Component Class ModuleA { $onInit() { this.$window.addEventListener('myCustomEvent', this.onCustomEventClick.bind(this)); } $onDestroy() { this.$window.removeEventListener('myCustomEvent', this.onCustomEventClick.bind(this), false); } } Class ModuleB { $onInit() { this.$window.addEventListener('myCustomEvent', this.onCustomEventClick.bind(this)); } $onDestroy() { this.$window.removeEventListener('myCustomEvent', this.onCustomEventClick.bind(this), false); } } A: Every time you call bind it will create a new function and return it instead of modifying the function itself. So the even listeners you provide to addEventListener and removeEventListener are different functions, thus the registered ones are not removed. To solve it, call bind once in $onInit and keep a reference to the returned function and always use that reference: Class ModuleB { $onInit() { this.onCustomEventClick = this.onCustomEventClick.bind(this) this.$window.addEventListener('myCustomEvent', this.onCustomEventClick); } $onDestroy() { this.$window.removeEventListener('myCustomEvent', this.onCustomEventClick, false); } }
{ "pile_set_name": "StackExchange" }
Q: Graph Implementation in Java using adjacency list - v2 Updated version from Graph Implementation in Java using adjacency list public class MyGraph { // add vertex name as key, and neighbors as values in set HashMap<String, HashSet<String>> adjList = new HashMap<>(); public void addVertex(String name) { if (adjList.containsKey(name)) { throw new IllegalArgumentException(); } adjList.put(name, new HashSet<>()); } public void addEdge(String source, String destination) { // are both vertexes already in the graph? if (!adjList.containsKey(source) || !adjList.containsKey(destination)) { throw new IllegalArgumentException(); } // does edge already exist? if (adjList.get(source).contains(destination)) { throw new IllegalArgumentException(); } else { adjList.get(source).add(destination); } } public HashSet<String> getNeighbors(String name) { return adjList.get(name); } // return true if there is an edge from source -> destination public boolean isNeighbor(String source, String destination) { if (!adjList.containsKey(source) || !adjList.containsKey(destination)) { throw new IllegalArgumentException(); } return adjList.get(source).contains(destination); } public void removeEdge(String source, String destination) { if (!adjList.containsKey(source) || !adjList.containsKey(destination)) { throw new IllegalArgumentException(); } adjList.get(source).remove(destination); } public void removeVertex(String name) { if (!adjList.containsKey(name)) { throw new IllegalArgumentException(); } // remove vertex and its neighbors, if any adjList.remove(name); // remove vertex as a neighbors from other vertexes Set vertexes = adjList.keySet(); Iterator i = vertexes.iterator(); while (i.hasNext()) { String vertex = (String) i.next(); if (adjList.get(vertex).contains(name)) { adjList.get(vertex).remove(name); } } } // removes all vertexes/edges from graph public void clear() { adjList = new HashMap<>(); } // returns the number of vertexes public int size() { return adjList.size(); } public boolean isEmpty() { return adjList.isEmpty(); } } A: You should make your class final unless you're explicitly intending it to be extended. adjList should be private. You don't want other classes in your package reaching into a MyGraph and messing with its adjacencies. It would also be reasonable to make it final. Map defines a clear method you can use. In general, prefer using interfaces where possible. Within your code, the fact that adjList is a HashMap and not a TreeMap is irrelevant. So just refer to it as a Map. Most of your comments are noise. If the purpose of a block of code isn't obvious, you can usually create a new method with a name that makes it obvious. There's no charge for extra characters, and it's easier to read adjacencyLists than adjList. Is it really necessary to throw an error if the user asks you to do something you've already done for them? If they need to know if the edge already existed, you can return a boolean. This is how the Collections API works, and I think it's a good model. You can't safely return a Set from your adjList, because if a user mucks with that, they're changing the internals of your graph. Use a new Set instance. For isNeighbor and removeEdge, do those need to be exceptions? Remember to use generics consistently. There's no need to call contains in removeVertex. Sets don't break if you try to remove a non-existent element. In removeVertex, it's a lot easier to just loop over the values in the map, rather than the keys. If I were to refactor your code, a first pass might look something like: import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; public final class MyGraph { // add vertex name as key, and neighbors as values in set private final Map<String, Set<String>> adjacencyLists = new HashMap<>(); public void addVertex(final String name) { if (this.adjacencyLists.containsKey(name)) { throw new IllegalArgumentException(); } this.adjacencyLists.put(name, new HashSet<>()); } public boolean addEdge(final String source, final String destination) { if (!this.adjacencyLists.containsKey(source) || !this.adjacencyLists.containsKey(destination)) { throw new IllegalArgumentException(); } return this.adjacencyLists.get(source).add(destination); } public Set<String> getNeighbors(final String name) { return new HashSet<>(this.adjacencyLists.get(name)); } /** * @return true if there is an edge from source -> destination */ public boolean isNeighbor(final String source, final String destination) { if (!this.adjacencyLists.containsKey(source) || !this.adjacencyLists.containsKey(destination)) { throw new IllegalArgumentException(); } return this.adjacencyLists.get(source).contains(destination); } public boolean removeEdge(final String source, final String destination) { if (!this.adjacencyLists.containsKey(source)) { return false; } return this.adjacencyLists.get(source).remove(destination); } public boolean removeVertex(final String name) { if (!this.adjacencyLists.containsKey(name)) { return false; } this.adjacencyLists.remove(name); for (final Set<String> adjacencies : this.adjacencyLists.values()) { adjacencies.remove(name); } return true; } /** * removes all vertexes/edges from graph */ public void clear() { this.adjacencyLists.clear(); } /** * @return the number of vertexes */ public int size() { return this.adjacencyLists.size(); } public boolean isEmpty() { return this.adjacencyLists.isEmpty(); } }
{ "pile_set_name": "StackExchange" }
Q: On the coincidence (or non-coincidence) of two norms defined on the quotient of a given Hilbert $ C^{\ast} $-module by a certain linear subspace Let $ A $ be a $ C^{\ast} $-algebra, $ I $ a closed two-sided ideal of $ A $, and $ \mathcal{E} $ a Hilbert $ A $-module. Let $$ \mathcal{E}_{I} \stackrel{\text{df}}{=} \{ x \in \mathcal{E} \mid \langle x,x \rangle_{\mathcal{E}} \in I \}. $$ Using the Cauchy-Schwarz Inequality for Hilbert $ C^{\ast} $-modules, it is not difficult to show that $$ \mathcal{E}_{I} = \{ x \in \mathcal{E} \mid (\forall y \in \mathcal{E})(\langle x,y \rangle_{\mathcal{E}} \in I) \}. $$ This implies that $ \mathcal{E}_{I} $ is a linear subspace of $ \mathcal{E} $. Furthermore, as the $ A $-valued inner product on $ \mathcal{E} $ is continuous, $ \mathcal{E}_{I} $ is a $ \| \cdot \|_{\mathcal{E}} $-closed subset of $ \mathcal{E} $. All of this implies that $ \mathcal{E}_{I} $ is a Hilbert $ I $-module. Now, the quotient space $ \mathcal{E} / \mathcal{E}_{I} $ is a Banach space w.r.t. the quotient norm $ \| \cdot \|_{\text{q}} $ defined by $$ \forall x \in \mathcal{E}: \qquad \| x + \mathcal{E}_{I} \|_{\text{q}} \stackrel{\text{df}}{=} \inf_{y \in \mathcal{E}_{I}} \| x + y \|_{\mathcal{E}}. $$ It is also a right $ (A / I) $-module equipped with an $ (A / I) $-valued pre-inner product $ [\cdot,\cdot] $ defined by $$ \forall x_{1},x_{2} \in \mathcal{E}: \qquad [x_{1} + \mathcal{E}_{I},x_{2} + \mathcal{E}_{I}] \stackrel{\text{df}}{=} \langle x_{1},x_{2} \rangle_{\mathcal{E}} + I. $$ Question. Is the norm on $ \mathcal{E} / \mathcal{E}_{I} $ that is induced by $ [\cdot,\cdot] $ the same as $ \| \cdot \|_{\text{q}} $, i.e., $$ \forall x \in \mathcal{E}: \qquad \| x + \mathcal{E}_{I} \|_{\text{q}} = \sqrt{\| \langle x,x \rangle_{\mathcal{E}} + I \|_{A / I}}? $$ Thank you for your help! A: Here are a couple of supplements to Omar's answer. The first thing to note is that the module $\mathcal{E}_I$ is equal to the module $\mathcal{E}I=\{ei\ |\ e\in \mathcal{E},\ i\in I\}$. The inclusion $\mathcal{E}I\subset \mathcal{E}_I$ follows easily from the linearity of the inner product and from the fact that $I$ is an ideal. For the reverse inclusion, let $i_\lambda$ be an approximate unit for $I$, and then show (by expressing the norm in terms of the inner product) that for each $e\in \mathcal{E}_I$ one has $\| e-ei_\lambda\|\to 0$ as $\lambda\to\infty$. This gives $\mathcal{E}_I\subset \overline{\mathcal{E}I}$, and the latter is equal to $\mathcal{E}I$ by the Cohen factorisation theorem. For full details see Lemma 3.23 in: Raeburn, Iain; Williams, Dana P., Morita equivalence and continuous-trace $C^*$-algebras, Mathematical Surveys and Monographs. 60. Providence, RI: American Mathematical Society (AMS). xiv, 327 p. (1998). ZBL0922.46050. Now, turning to the inner product on $\mathcal{E}/\mathcal{E}_I$: here are three arguments showing that the norm defined by the inner product is equal to the quotient norm. (1) A short direct computation is given in Lemma 3.1 in: Zettl, Heinrich H., Ideals in Hilbert modules and invariants under strong Morita equivalence of C*-algebras, Arch. Math. 39, 69-77 (1982). ZBL0498.46034. (2) An argument based on the uniqueness of the $C^*$-norm on the linking algebra is given in Proposition 3.25 in the book of Raeburn-Williams cited above. (The authors attribute the argument to Siegfried Echterhoff.) (3) Here is a third proof, using ideas around operator modules and the Haagerup tensor product. All of the necessary background can be found in Blecher, David P.; Le Merdy, Christian, Operator algebras and their modules -- an operator space approach, London Mathematical Society Monographs. New Series 30; Oxford Science Publications. Oxford: Oxford University Press (ISBN 0-19-852659-8/hbk). x, 387~p. (2004). ZBL1061.47002. Consider $I\to A\to A/I$ as an exact sequence of operator $A$-bimodules. Taking the Haagerup tensor product with $\mathcal E$ (viewed as a right operator module over $A$) gives $$ \mathcal E\otimes_A I \to \mathcal E\otimes_A A \to \mathcal E\otimes_A (A/I). $$ By the exactness property of the Haagerup tensor product over a $C^*$-algebra (a theorem of Anantharaman-Delaroche and Pop), the first map in the display is a (completely) isometric embedding, and the second map induces a (completely) isometric isomorphism $$ (\mathcal E\otimes_A A)/ (\mathcal E\otimes_A I) \cong \mathcal E\otimes_A (A/I)\qquad (*) $$ where the left-hand side carries its canonical quotient operator space structure (and in particular, the usual Banach-space quotient norm). The module action gives a (completely) isometric isomorphism $\mathcal E\otimes_A A \to \mathcal E$, which restricts to an isomorphism $\mathcal E\otimes_A I \to \mathcal E I=\mathcal E_I$. Making these identifications, the isomorphism $(*)$ is given by the formula $$ \mathcal E/\mathcal E_I\to \mathcal E\otimes_A (A/I),\qquad (ea+\mathcal E_I)\mapsto e\otimes(a+I).\qquad (**) $$ Now, $A/I$ is a (right) Hilbert $C^*$-module over itself, and the quotient map $A\to A/I$ gives a (left) action of $A$ on this $C^*$-module by adjointable operators. We can thus form the Hilbert $C^*$-module tensor product $\mathcal E\otimes^{C^*}_A (A/I)$, which will be a Hilbert $C^*$-module over $A/I$. A theorem of Blecher asserts that the identity map on the algebraic tensor products extends to a (completely) isometric isomorphism between $\mathcal E\otimes^{C^*}_A (A/I)$ and the Haagerup tensor product $\mathcal E\otimes_A (A/I)$. A straightforward computation shows that the map $(**)$ is isometric with respect to the inner product $[\cdot,\cdot]$ on $\mathcal E/\mathcal E_I$, and the canonical inner product on $\mathcal E\otimes^{C^*}_A (A/I)$. Since $(**)$ is also isometric for the quotient norm, the latter must coincide with the norm induced by $[\cdot,\cdot]$. A: Yes, I think this is true. Here is an argument to show why. First for $E=A$, then this is just the standard theorem saying that the quotient norm on $A/I$ is the $C^*$-algebra norm. (any ref on $C^*$-algebras has a proof) Then you argue directly that the case $E=A$ implies that it is also true for $E=l^2(\mathbb{N})\otimes A$. Then you could use Kasparov stabilization theorem to prove it for coutably generated $C^*$-modules. To prove it for all modules, you might argue that both norms calcuated at a fixed element, only needed a countably generated submodule to be computed on. (Both are infimum of something so you take the submodules generated by a sequence reaching the infimum) Edit: Here some more details, I will use $E'$ to denote the module $E\oplus l^2(\mathbb{N})\otimes A$. We directly see that $E'_I=E_I\oplus l^2(\mathbb{N})\otimes I$, hence $E'/E'_I=E/E_I\oplus l^2(\mathbb{N})\otimes A/I.$ Hence the inclusion map $i:E/E_I\to E'/E'_I$ preserves the two norms defined in the question. Theorem(Kasparov's Specialization theorem)(reference in a comment) Let $E$ be a countably generated $A$-module, then $E\oplus l^2(\mathbb{N})\otimes A\simeq l^2(\mathbb{N})\otimes A$. Here the isomorphism is a unitary isomorphism. Since the module $E'$ is untarly equivalent to $l^2(\mathbb{N})\otimes A$ it follows that the two norms are equal on $E'/E'_I$ and hence on $E/E_I$.
{ "pile_set_name": "StackExchange" }
Q: Scala collection of dates and group by week import java.time.LocalDate case class Day(date: LocalDate, other: String) val list = Seq( Day(LocalDate.of(2016, 2, 1), "text"), Day(LocalDate.of(2016, 2, 2), "text"), // Tuesday Day(LocalDate.of(2016, 2, 3), "text"), Day(LocalDate.of(2016, 2, 4), "text"), Day(LocalDate.of(2016, 2, 5), "text"), Day(LocalDate.of(2016, 2, 6), "text"), Day(LocalDate.of(2016, 2, 7), "text"), Day(LocalDate.of(2016, 2, 8), "text"), Day(LocalDate.of(2016, 2, 9), "text"), Day(LocalDate.of(2016, 2, 10), "text"), Day(LocalDate.of(2016, 2, 11), "text"), Day(LocalDate.of(2016, 2, 12), "text"), Day(LocalDate.of(2016, 2, 13), "text"), Day(LocalDate.of(2016, 2, 14), "text"), Day(LocalDate.of(2016, 2, 15), "text"), Day(LocalDate.of(2016, 2, 16), "text"), Day(LocalDate.of(2016, 2, 17), "text") ) // hard code, for example Tuesday def groupDaysBy(list: Seq[Day]): List[List[Day]] = { ??? } val result = Seq( Seq(Day(LocalDate.of(2016, 2, 1), "text")), // Separate Seq(Day(LocalDate.of(2016, 2, 2), "text"), // Tuesday Day(LocalDate.of(2016, 2, 3), "text"), Day(LocalDate.of(2016, 2, 4), "text"), Day(LocalDate.of(2016, 2, 5), "text"), Day(LocalDate.of(2016, 2, 6), "text"), Day(LocalDate.of(2016, 2, 7), "text"), Day(LocalDate.of(2016, 2, 8), "text")), Seq(Day(LocalDate.of(2016, 2, 9), "text"), // Tuesday Day(LocalDate.of(2016, 2, 10), "text"), Day(LocalDate.of(2016, 2, 11), "text"), Day(LocalDate.of(2016, 2, 12), "text"), Day(LocalDate.of(2016, 2, 13), "text"), Day(LocalDate.of(2016, 2, 14), "text"), Day(LocalDate.of(2016, 2, 15), "text")), Seq(Day(LocalDate.of(2016, 2, 16), "text"), // Tuesday Day(LocalDate.of(2016, 2, 17), "text")) ) assert(groupDaysBy(list) == result) I have a list of Day object, and I want to group every 7 days together and the start date can be any day (from Monday to Sunday, I give Tuesday as an example). Above is the function and expected result for my requirement. I am wondering how can I take advantage of Scala collection API to achieve without tail recursive? A: Here's what you can do: // hard code, for example Tuesday def groupDaysBy(list: Seq[Day]): Seq[Seq[Day]] = { val (list1,list2)= list.span(_.date.getDayOfWeek != DayOfWeek.TUESDAY) Seq(list1) ++ list2.grouped(7) } I would recommend taking day as a parameter instead of hardcoding though, so it becomes // hard code, for example Tuesday def groupDaysBy(list: Seq[Day], dayOfWeek: DayOfWeek): Seq[Seq[Day]] = { val (list1,list2)= list.span(_.date.getDayOfWeek != dayOfWeek) Seq(list1) ++ list2.grouped(7) } ... assert(groupDaysBy(list, DayOfWeek.TUESDAY) == result)
{ "pile_set_name": "StackExchange" }
Q: Error while configuring multiple Navigation Properties to same table I am having a weird issue with multiple navigation Properties to the same table. My FuelBunkerType POCO class is configured like the following: public class FuelBunkerType : IEventReportElement { public long Id { get; set; } public string TypeKey { get; set; } public string TypeValue { get; set; } public decimal? Sulphur { get; set; } public decimal? Water { get; set; } public decimal? Viscosity { get; set; } public decimal? Density { get; set; } public string BdnNumber { get; set; } public long? IdEventReport { get; set; } public long? DeactivatedByIdEventReport { get; set; } public IList<FuelBunkerQuantity> FuelBunkerQuantitys { get; set; } public EventReport EventReport { get; set; } public EventReport DeactivatedByEventReport { get; set; } } In the DbContext, my class is configured like: modelBuilder.Entity<FuelBunkerType>().HasKey(x => x.Id); if (_writeversion) modelBuilder.Entity<FuelBunkerType>().Property(x => x.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None); else modelBuilder.Entity<FuelBunkerType>().Property(x => x.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity); modelBuilder.Entity<FuelBunkerType>().HasRequired(x => x.EventReport).WithMany().HasForeignKey(x => x.IdEventReport); modelBuilder.Entity<FuelBunkerType>().HasOptional(x => x.DeactivatedByEventReport).WithMany().HasForeignKey(x => x.DeactivatedByIdEventReport); So far, so good. It actually worked like this until friday. However, when I try to fetch data from the table now, the resulting Query looks like {SELECT 1 AS [C1], [Extent1].[Id] AS [Id], [Extent1].[TypeKey] AS [TypeKey], [Extent1].[TypeValue] AS [TypeValue], [Extent1].[Sulphur] AS [Sulphur], [Extent1].[Water] AS [Water], [Extent1].[Viscosity] AS [Viscosity], [Extent1].[Density] AS [Density], [Extent1].[BdnNumber] AS [BdnNumber], [Extent1].[IdEventReport] AS [IdEventReport], [Extent1].[DeactivatedByIdEventReport] AS [DeactivatedByIdEventReport], [Extent1].[EventReport_Id] AS [EventReport_Id] FROM [FuelBunkerType] AS [Extent1]} which obviously results in a "column name is not valid" error, so my first Configuration line (Entity().HasRequired(x=>x.EventReport)...) is ignored. I tried out commenting out the Configuration for DeactivatedByEventReport, it resulted in the same query except for DeactivatedByEventReport_Id (like expected), it only happens with multiple Navigation Properties to the same table. However, when I add more navigation properties to EventReport, it only mistakenly queries for EventReport_Id, so only the first one seems to be ignored when there are multiple navigation properties. Any ideas why this happens, and what to do to solve this? Greetings EDIT: For the other classes corresponding to this, there are the following Fluent API configs: if (_writeversion) modelBuilder.Entity<EventReport>().Property(x => x.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None); else modelBuilder.Entity<EventReport>().Property(x => x.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity); modelBuilder.Entity<EventReport>().HasKey(x => x.Id); modelBuilder.Entity<EventReport>().Property(x => x.Id).HasColumnName("Id"); modelBuilder.Entity<EventReport>().Ignore(x => x.MaxEventTimeLt); modelBuilder.Entity<EventReport>().Ignore(x => x.MaxEventTimeUtc); modelBuilder.Entity<EventReport>().Ignore(x => x.MinEventTimeLt); modelBuilder.Entity<EventReport>().Ignore(x => x.MinEventTimeUtc); modelBuilder.Entity<EventReport>().Ignore(x => x.EventReportElementTyps); modelBuilder.Entity<EventReport>().Ignore(x => x.EventsWithUpdatedSortNumber); modelBuilder.Entity<EventReport>().Ignore(x => x.EventTimeUtcLoaded); modelBuilder.Entity<EventReport>().Ignore(x => x.HasChanged); modelBuilder.Entity<FuelBunkerQuantity>().HasKey(x => x.Id); if (_writeversion) modelBuilder.Entity<FuelBunkerQuantity>().Property(x => x.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None); else modelBuilder.Entity<FuelBunkerQuantity>().Property(x => x.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity); modelBuilder.Entity<FuelBunkerQuantity>().HasOptional(x => x.FuelBunkerType).WithMany().HasForeignKey(x => x.IdFuelBunkerType); //modelBuilder.Entity<FuelBunkerQuantity>().HasOptional(x => x.EventReport).WithMany().HasForeignKey(x => x.IdEventReport); modelBuilder.Entity<FuelBunkerQuantity>().Ignore(x => x.EventReport); The Configs on EventReport shouldn't effect anything, as you can see I disabled the navigation property on FuelBunkerQuantity to try if this was causing the error, but it didn't change the Error or the resulting Query in the slightest. EDIT2: The class EventReport: public class EventReport { public long Id { get; set; } public long? SortNumber { get; set; } public string ReportType { get; set; } public DateTime? CreationTimeUtc { get; set; } public DateTime? EventTimeUtc { get; set; } public DateTime? EventTimeUtcLoaded { get; set; } public DateTime? EventTimeLt { get; set; } public long? EventDuration { get; set; } public DateTime? LastSendAtUtc { get; set; } public DateTime? LastSendAtLt { get; set; } public DateTime? FirstSendAtUtc { get; set; } public DateTime? FirstSendAtLt { get; set; } public string EventQualityState { get; set; } public bool IsDraft { get; set; } [IgnoreOnEqualCheck] public IEnumerable<FuelBunkerRob> FuelRoB { get; set; } [IgnoreOnEqualCheck] public IEnumerable<OilBunkerRob> OilRoB { get; set; } [IgnoreOnEqualCheck] public List<FuelBunkerType> ActiveFuelTypes { get; set; } [IgnoreOnEqualCheck] public DateTime? MaxEventTimeUtc { get; set; } [IgnoreOnEqualCheck] public DateTime? MaxEventTimeLt { get; set; } [IgnoreOnEqualCheck] public DateTime? MinEventTimeUtc { get; set; } [IgnoreOnEqualCheck] public DateTime? MinEventTimeLt { get; set; } public List<EventReport> EventsWithUpdatedSortNumber {get; set;} public long? ConfigurationId { get; set; } public bool HasChanged { get; set; } public List<IEventReportElement> EventReportElements { get; set; } } EDIT3: I just skipped the Statement which was causing the error. Turns out FuelBunkerQuantity has wrong Translation as well (see configuration in Edit): {SELECT 1 AS [C1], [Extent1].[Id] AS [Id], [Extent1].[IdFuelBunkerType] AS [IdFuelBunkerType], [Extent1].[MassDelta] AS [MassDelta], [Extent1].[MassAbsolut] AS [MassAbsolut], [Extent1].[IdEventReport] AS [IdEventReport], [Extent1].[FuelBunkerType_Id] AS [FuelBunkerType_Id] FROM [FuelBunkerQuantity] AS [Extent1]} Seems like something is broken, but I have no idea what. A: As you are configuring two one-to-may relationships between EventReport and FuelBunkerType and there is only one collection on the many side EF can't match the relationships. Depending on which relationship the collection property ActiveFuelTypes belongs to you can explicitly map it like this: modelBuilder.Entity<FuelBunkerQuantity>(). HasOptional(x => x.FuelBunkerType). WithMany(e => e.ActiveFuelTypes). HasForeignKey(x => x.IdFuelBunkerType);
{ "pile_set_name": "StackExchange" }
Q: Android: Simple XML SAX Parser - Displays Same Data Over and Over I've created an XML parser which populates a listView with data obtained from an XML file. The problem is for some reason the listView shows the same data over and over instead of unique data for each listView item. I'm not sure exactly what is causing this issue - any insight is greatly appreciated. Screenshot: XML Data: <response> <cmd>getVideos</cmd> <success>1</success> <NumberOfVideos>4</NumberOfVideos> <Videos> <Video> <VideoName>sample_iPod</VideoName> <VideoDesc/> <VideoUrl> http://mobile.example.com/api/wp-content/uploads/sites/6/2014/01/api/1/06087297988b.m4v </VideoUrl> <VideoTags/> </Video> <Video> <VideoName>sample_mpeg4</VideoName> <VideoDesc/> <VideoUrl> http://mobile.example.com/api/wp-content/uploads/sites/6/2014/01/api/1/b5ed9e7100e2.mp4 </VideoUrl> <VideoTags/> </Video> <Video> <VideoName>sample_sorenson</VideoName> <VideoDesc/> <VideoUrl> http://mobile.example.com/api/wp-content/uploads/sites/6/2014/01/api/1/2a8e64b24997.mov </VideoUrl> <VideoTags/> </Video> <Video> <VideoName>sample_iTunes</VideoName> <VideoDesc/> <VideoUrl> http://mobile.example.com/api/wp-content/uploads/sites/6/2014/01/api/1/6c7f65254aad.mov </VideoUrl> <VideoTags/> </Video> </Videos> </response> Example/Tutorial: http://theopentutorials.com/tutorials/android/xml/android-simple-xml-sax-parser-tutorial/ SAXXMLHandler.java public class SAXXMLHandler extends DefaultHandler { private List<Cmd> videos; private String tempVal; // to maintain context private Cmd cmd; public SAXXMLHandler() { videos = new ArrayList<Cmd>(); } public List<Cmd> getResponse() { return videos; } // Event Handlers public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { // reset tempVal = ""; if (qName.equalsIgnoreCase("Video")) { // create a new instance of cmd cmd = new Cmd(); } } public void characters(char[] ch, int start, int length) throws SAXException { tempVal = new String(ch, start, length); } public void endElement(String uri, String localName, String qName) throws SAXException { if (qName.equalsIgnoreCase("videos")) { // add it to the list } else if (qName.equalsIgnoreCase("success")) { cmd.setSuccess(tempVal); } else if (qName.equalsIgnoreCase("numberofvideos")) { cmd.setNumberOfVideos(tempVal); } else if (qName.equalsIgnoreCase("videos")) { cmd.setVideos(videos); } else if (qName.equalsIgnoreCase("video")) { cmd.setVideo(tempVal); } else if (qName.equalsIgnoreCase("videoname")) { cmd.setVideoName(tempVal); } else if (qName.equalsIgnoreCase("videourl")) { cmd.setVideoURL(tempVal); videos.add(cmd); //You only need store an instance of your Cmd } } } CustomListViewAdapter.java public class CustomListViewAdapter extends ArrayAdapter<Cmd> { Activity context; List<Cmd> videos; public CustomListViewAdapter(Activity context, List<Cmd> videos) { super(context, R.layout.list_item2, videos); this.context = context; this.videos = videos; } /*private view holder class*/ private class ViewHolder { ImageView imageView; TextView txtSuccess; TextView txtCmd; TextView txtPrice; } public Cmd getItem(int position) { return videos.get(position); } public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; LayoutInflater inflater = context.getLayoutInflater(); if (convertView == null) { convertView = inflater.inflate(R.layout.list_item2, null); holder = new ViewHolder(); holder.txtSuccess = (TextView) convertView.findViewById(R.id.success); holder.txtCmd = (TextView) convertView.findViewById(R.id.cmd); holder.txtPrice = (TextView) convertView.findViewById(R.id.price); holder.imageView = (ImageView) convertView.findViewById(R.id.thumbnail); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } Cmd cmd = (Cmd) getItem(position); holder.txtSuccess.setText(cmd.getSuccess()); holder.txtCmd.setText(cmd.getCmd()); // holder.imageView.setImageBitmap(cmd.getImageBitmap()); holder.txtPrice.setText(cmd.getVideoName() + ""); return convertView; } } SAXParserAsyncTaskActivity.java public class SAXParserAsyncTaskActivity extends Activity implements OnClickListener, OnItemClickListener { Button button; ListView listView; List<Cmd> videos = new ArrayList<Cmd>(); CustomListViewAdapter listViewAdapter; static final String URL = "http://mobile.example.com/api/xmlrpc.php?cmd=getVideos&username=fake&password=credential"; public static final String LIBRARY = "Library"; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.parser_main); findViewsById(); button.setOnClickListener(this); listView.setOnItemClickListener(this); GetXMLTask task = new GetXMLTask(this); task.execute(new String[] { URL }); } private void findViewsById() { button = (Button) findViewById(R.id.button); listView = (ListView) findViewById(R.id.cmdList); } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { } @Override public void onClick(View view) { // GetXMLTask task = new GetXMLTask(this); // task.execute(new String[] { URL }); } // private inner class extending AsyncTask private class GetXMLTask extends AsyncTask<String, Void, List<Cmd>> { private Activity context; public GetXMLTask(Activity context) { this.context = context; } protected void onPostExecute(List<Cmd> videos) { listViewAdapter = new CustomListViewAdapter(context, videos); listView.setAdapter(listViewAdapter); } /* * uses HttpURLConnection to make Http request from Android to download * the XML file */ private String getXmlFromUrl(String urlString) { StringBuffer output = new StringBuffer(""); try { InputStream stream = null; URL url = new URL(urlString); URLConnection connection = url.openConnection(); HttpURLConnection httpConnection = (HttpURLConnection) connection; httpConnection.setRequestMethod("GET"); httpConnection.connect(); if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) { stream = httpConnection.getInputStream(); BufferedReader buffer = new BufferedReader( new InputStreamReader(stream)); String s = ""; while ((s = buffer.readLine()) != null) output.append(s); } } catch (Exception ex) { ex.printStackTrace(); } return output.toString(); } @Override protected List<Cmd> doInBackground(String... urls) { List<Cmd> videos = null; String xml = null; for (String url : urls) { xml = getXmlFromUrl(url); InputStream stream = new ByteArrayInputStream(xml.getBytes()); videos = SAXXMLParser.parse(stream); if ( videos == null) { Toast.makeText(getApplicationContext(), "Videos is null!)", Toast.LENGTH_LONG).show(); } for (Cmd cmd : videos) { String videoName = cmd.getVideoName(); // String getVideos = cmd.getVideos(); // String getVideo = cmd.getVideo(); // String getVideoURL = cmd.getVideoURL(); // String getNumberOfVideos = cmd.getNumberOfVideos(); // // Bitmap bitmap = null; // BitmapFactory.Options bmOptions = new BitmapFactory.Options(); // bmOptions.inSampleSize = 1; // // try { // bitmap = BitmapFactory.decodeStream( // new URL(videoName).openStream(), null, // bmOptions); // } catch (MalformedURLException e) { // e.printStackTrace(); // } catch (IOException e) { // e.printStackTrace(); // } } } // stream.close(); return videos; } } } A: You are creating only one instance of Cmd() that is overriding itself, because you have only one <cmd> element. Change: if (qName.equalsIgnoreCase("cmd")) { // create a new instance of cmd cmd = new Cmd(); } to: if (qName.equalsIgnoreCase("Video")) { // create a new instance of cmd cmd = new Cmd(); } You need to create an instance of Cmd() when your parser read every <Video> element. and change your endElement(String uri, String localName, String qName) method to: public void endElement(String uri, String localName, String qName) throws SAXException { if (qName.equalsIgnoreCase("videos")) { // add it to the list /*} else if (qName.equalsIgnoreCase("success")) { cmd.setSuccess(tempVal); } else if (qName.equalsIgnoreCase("numberofvideos")) { cmd.setNumberOfVideos(tempVal); } else if (qName.equalsIgnoreCase("videos")) { cmd.setVideos(videos); } else if (qName.equalsIgnoreCase("video")) { cmd.setVideo(tempVal);*/ } else if (qName.equalsIgnoreCase("videoname")) { cmd.setVideoName(tempVal); } else if (qName.equalsIgnoreCase("videourl")) { cmd.setVideoURL(tempVal); videos.add(cmd); //You only need store an instance of your Cmd } }
{ "pile_set_name": "StackExchange" }
Q: SQLite3 performance with OR of BETWEEN ranges I have a quite big SQLite3 database table with a numeric indexed field on which I have to search for a list of ranges of values. As the numeric values are huge 64-bit numbers, a IN clause would not an option. The queries typically look like this: SELECT * FROM sometable WHERE ID BETWEEN 10 AND 11 OR ID BETWEEN 20 AND 21 OR ID BETWEEN 30 AND 31; I have experienced a strange performance limit. With up to 9 BETWEEN terms, the query is extremely fast (ID field is indexed). But starting with 10 terms, the query becomes several orders or magnitude slower! I do not have found any explanation to that limit in the documentation. I found that the EXPLAIN QUERY PLAN instruction can be used to see the change of behavior. I made my experiments with SQLite 3.7.12 in case that matters. For the sake of demonstration, let's create a very simple and empty table: CREATE TABLE sometable(name TEXT, ID INTEGER); CREATE INDEX id_idx ON sometable (ID ASC); This query: EXPLAIN QUERY PLAN SELECT * FROM sometable WHERE ID BETWEEN 10 AND 11 OR ID BETWEEN 20 AND 21 OR ID BETWEEN 30 AND 31 OR ID BETWEEN 40 AND 41 OR ID BETWEEN 50 AND 51 OR ID BETWEEN 60 AND 61 OR ID BETWEEN 70 AND 71 OR ID BETWEEN 80 AND 81 OR ID BETWEEN 90 AND 91; produces that result: 0|0|0|SEARCH TABLE sometable USING INDEX id_idx (ID>? AND ID<?) (~31250 rows) 0|0|0|SEARCH TABLE sometable USING INDEX id_idx (ID>? AND ID<?) (~31250 rows) 0|0|0|SEARCH TABLE sometable USING INDEX id_idx (ID>? AND ID<?) (~31250 rows) 0|0|0|SEARCH TABLE sometable USING INDEX id_idx (ID>? AND ID<?) (~31250 rows) 0|0|0|SEARCH TABLE sometable USING INDEX id_idx (ID>? AND ID<?) (~31250 rows) 0|0|0|SEARCH TABLE sometable USING INDEX id_idx (ID>? AND ID<?) (~31250 rows) 0|0|0|SEARCH TABLE sometable USING INDEX id_idx (ID>? AND ID<?) (~31250 rows) 0|0|0|SEARCH TABLE sometable USING INDEX id_idx (ID>? AND ID<?) (~31250 rows) 0|0|0|SEARCH TABLE sometable USING INDEX id_idx (ID>? AND ID<?) (~31250 rows) While that query: EXPLAIN QUERY PLAN SELECT * FROM sometable WHERE ID BETWEEN 10 AND 11 OR ID BETWEEN 20 AND 21 OR ID BETWEEN 30 AND 31 OR ID BETWEEN 40 AND 41 OR ID BETWEEN 50 AND 51 OR ID BETWEEN 60 AND 61 OR ID BETWEEN 70 AND 71 OR ID BETWEEN 80 AND 81 OR ID BETWEEN 90 AND 91 OR ID BETWEEN 100 AND 101; produces that result: 0|0|0|SCAN TABLE sometable (~500000 rows) SCAN TABLE means that the index is not used and the whole original table is searched, resulting in poor performance. Is there a way (pragma / compilation switch / trick) to avoid that limit? A: As you can see, SQLite tries to split up the query into multiple subqueries so that each range can be looked up individually in the index. However, when there are too many ranges, the query optimizer assumes that the sum of the cost of all the individual subqueries is larger than just going once through the table. If your ranges contain less than 31250 rows, or if your table has more than 1000000 rows, you can try to use the ANALYZE command to improve the cost estimates. As a last resort, you can split up the query manually to force separate lookups: SELECT * FROM sometable WHERE ID BETWEEN 10 AND 11 UNION ALL SELECT * FROM sometable WHERE ID BETWEEN 20 AND 21 UNION ALL SELECT * FROM sometable WHERE ID BETWEEN 30 AND 31 ...
{ "pile_set_name": "StackExchange" }
Q: DatagridView Event To allow Numbers, Backspace & Delete Keys Only VB.Net How to alter the below code to accept Delete and BackSpace Keys also?? Private Sub DataGridView1_EditingControlShowing(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles DataGridView1.EditingControlShowing Select Case DataGridView1.CurrentCell.ColumnIndex Case Is = 0, 1 AddHandler CType(e.Control, TextBox).KeyPress, AddressOf TextBox_keyPress End Select End Sub Private Sub TextBox_keyPress(ByVal sender As Object, ByVal e As KeyPressEventArgs) If Not (Char.IsDigit(CChar(CStr(e.KeyChar))) Or e.KeyChar = ".") Then e.Handled = True End If End Sub Current Code After Modification - Not Working Private Sub DataGridView1_EditingControlShowing(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles DataGridView1.EditingControlShowing Select Case DataGridView1.CurrentCell.ColumnIndex Case Is = 0, 1 AddHandler CType(e.Control, TextBox).KeyPress, AddressOf TextBox_keyDown End Select End Sub Private Sub TextBox_keyDown(ByVal sender As Object, ByVal e As KeyPressEventArgs) If Not (Char.IsDigit(CChar(CStr(e.KeyChar))) Or e.KeyChar = ".") Then e.Handled = True End If End Sub EDIT - 2 Code Private Sub DataGridView1_EditingControlShowing(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles DataGridView1.EditingControlShowing Select Case DataGridView1.CurrentCell.ColumnIndex Case Is = 0, 1 AddHandler CType(e.Control, TextBox).KeyPress, AddressOf TextBox_keyDown End Select End Sub Private Sub TextBox_keyDown(ByVal sender As Object, ByVal e As KeyEventArgs) If Not (Char.IsDigit(CChar(CStr(e.KeyValue))) Or e.KeyValue = ".") Then e.Handled = True End If End Sub Now getting error in TextBox_keyDown Word this line... AddressOf TextBox_keyDown Error Text Severity Code Description Project File Line Suppression State Error BC31143 Method 'Private Sub TextBox_keyDown(sender As Object, e As KeyEventArgs)' does not have a signature compatible with delegate 'Delegate Sub KeyPressEventHandler(sender As Object, e As KeyPressEventArgs)'. A: Change the DataGridview EditMode Property to EditOnEnter and use the below code. Private Sub DataGridView1_EditingControlShowing(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles DataGridView1.EditingControlShowing Select Case DataGridView1.CurrentCell.ColumnIndex Case Is = 0, 1 AddHandler CType(e.Control, TextBox).KeyPress, AddressOf TextBox_keyPress End Select End Sub Private Sub TextBox_keyPress(ByVal sender As Object, ByVal e As KeyPressEventArgs) If e.KeyChar <> ControlChars.Back Then e.Handled = Not (Char.IsDigit(e.KeyChar)) End If End Sub
{ "pile_set_name": "StackExchange" }
Q: MySQL "Foreign key constraint is incorrectly formed" I have the follwing SQL commands: CREATE TABLE IF NOT EXISTS `users` ( `id` INTEGER NOT NULL auto_increment, `username` VARCHAR(255) NOT NULL UNIQUE, `password` VARCHAR(255) NOT NULL, `root` TINYINT(1) DEFAULT 0, `createdat` DATETIME NOT NULL, `updatedat` DATETIME NOT NULL, UNIQUE `username_unique` (`username`), PRIMARY KEY (`id`) ) engine=innodb; CREATE TABLE IF NOT EXISTS `domains` ( `id` INTEGER NOT NULL auto_increment, `domain` VARCHAR(255) NOT NULL UNIQUE, `createdat` DATETIME NOT NULL, `updatedat` DATETIME NOT NULL, `userid` INTEGER, UNIQUE `domain_unique` (`domain`), PRIMARY KEY (`id`), FOREIGN KEY (`userid`) REFERENCES `users` (`id`) ON DELETE SET NULL ON UPDATE CASCADE ) engine=innodb; CREATE TABLE IF NOT EXISTS `aliases` ( `id` INTEGER NOT NULL auto_increment, `source_username` VARCHAR(255) NOT NULL, `source_domain` VARCHAR(255) NOT NULL, `destination_username` VARCHAR(255) NOT NULL, `destination_domain` VARCHAR(255) NOT NULL, `enabled` TINYINT(1) NOT NULL DEFAULT 1, `createdat` DATETIME NOT NULL, `updatedat` DATETIME NOT NULL, PRIMARY KEY (`id`), FOREIGN KEY (`source_domain`) REFERENCES `domains` (`domain`) ) engine=innodb; CREATE TABLE IF NOT EXISTS `accounts` ( `id` INTEGER NOT NULL auto_increment, `username` VARCHAR(255) NOT NULL, `domain` VARCHAR(255) NOT NULL, `password` VARCHAR(255) NOT NULL, `quota` INTEGER NOT NULL DEFAULT 500, `enabled` TINYINT(1) NOT NULL DEFAULT 1, `sendonly` TINYINT(1) NOT NULL DEFAULT 0, `createdat` DATETIME NOT NULL, `updatedat` DATETIME NOT NULL, PRIMARY KEY (`id`), FOREIGN KEY (`domain`) REFERENCES `domains` (`domain`) ) engine=innodb; if i try to run these i get the message: "Foreign key constraint is incorrectly formed" for the tables Alias and Accounts. Its not possible to use primary keys in alias and accounts Im using MariaDB 10.2 I hope somebody can tell me what is wrong with these statements. A: You need to add a key/index to the domain field of the domains table, in order for it to be used as Foreign Key by another table. If the table is already created and you want to add an index, use this. CREATE INDEX domain ON domains(domain); OR add the index while creating the table - CREATE TABLE IF NOT EXISTS `domains` ( `id` INTEGER NOT NULL auto_increment, `domain` VARCHAR(255) NOT NULL UNIQUE, `createdat` DATETIME NOT NULL, `updatedat` DATETIME NOT NULL, `userid` INTEGER, UNIQUE `domain_unique` (`domain`), PRIMARY KEY (`id`), INDEX domain (domain), FOREIGN KEY (`userid`) REFERENCES `users` (`id`) ON DELETE SET NULL ON UPDATE CASCADE ) engine=innodb; For further reading (official documentation) regarding Foreign Key Contraint Errors on MariaDB this URL
{ "pile_set_name": "StackExchange" }
Q: cocoa - screen not refreshing after CGEventPost mouse click I am programatically generating mouse clicks when a user clicks a certain keyboard key (CapsLock). So I do a left mouse down when CapsLock is switched on, then a left mouse up when CapsLock is switched off. This behaves correctly in that if I for example place the mouse over a window title bar, click CapsLock, then move the mouse, then click CapsLock, the window correctly moves. i.e. I correctly 'drag' the window as if I had held the left mouse button down whilst moving the mouse. However there is one problem - the window does not move whilst I am moving the mouse, it only moves to the final position after I have clicked CapsLock a second time. i.e. after I have 'released' the mouse button. What do I need to do to ensure the screen is refreshed during the mouse move? Interestingly, I also hooked to [NSEvent addGlobalMonitorForEventsMatchingMask:NSLeftMouseDraggedMask and found that my NSLog statement only output after I released the left mouse button (the real left mouse button) Mouse click code is below, I can post all the code if necessary, there isn't much of it.. // simulate mouse down // get current mouse pos CGEventRef ourEvent = CGEventCreate(NULL); CGPoint point = CGEventGetLocation(ourEvent); NSLog(@"Location? x= %f, y = %f", (float)point.x, (float)point.y); CGEventSourceRef source = CGEventSourceCreate(kCGEventSourceStateCombinedSessionState); CGEventRef theEvent = CGEventCreateMouseEvent(source, kCGEventLeftMouseDown, point, kCGMouseButtonLeft); CGEventSetType(theEvent, kCGEventLeftMouseDown); CGEventPost(kCGHIDEventTap, theEvent); CFRelease(theEvent); // simulate mouse up // get current mouse pos CGEventRef ourEvent = CGEventCreate(NULL); CGPoint point = CGEventGetLocation(ourEvent); NSLog(@"Location? x= %f, y = %f", (float)point.x, (float)point.y); CGEventSourceRef source = CGEventSourceCreate(kCGEventSourceStateCombinedSessionState); CGEventRef theEvent = CGEventCreateMouseEvent(source, kCGEventLeftMouseUp, point, kCGMouseButtonLeft); CGEventSetType(theEvent, kCGEventLeftMouseUp); CGEventPost(kCGHIDEventTap, theEvent); CFRelease(theEvent); A: If you want to be able to drag windows, the problem is that you also need to post a LeftMouseDragged event. Simply call beginEventMonitoring to start listening for caps lock key events and mouse move events. The event handlers will simulate a left mouse press and movement just as you wanted. Here is a link to my blog where you can download a full working example for Xcode 4: http://www.jakepetroules.com/2011/06/25/simulating-mouse-events-in-cocoa The example is in the public domain, do whatever you like with it. :) According to Apple (NSEvent documentation), "Enable access for assistive devices" needs to be checked in System Preferences > Universal Access for this to work, but I have it unchecked and it wasn't an issue. Just a heads up. Please let me know if you have any further issues and I will try my best to help. // Begin listening for caps lock key presses and mouse movements - (void)beginEventMonitoring { // Determines whether the caps lock key was initially down before we started listening for events wasCapsLockDown = CGEventSourceKeyState(kCGEventSourceStateHIDSystemState, kVK_CapsLock); capsLockEventMonitor = [NSEvent addGlobalMonitorForEventsMatchingMask:(NSFlagsChangedMask) handler: ^(NSEvent *event) { // Determines whether the caps lock key was pressed and posts a mouse down or mouse up event depending on its state bool isCapsLockDown = [event modifierFlags] & NSAlphaShiftKeyMask; if (isCapsLockDown && !wasCapsLockDown) { [self simulateMouseEvent: kCGEventLeftMouseDown]; wasCapsLockDown = true; } else if (wasCapsLockDown) { [self simulateMouseEvent: kCGEventLeftMouseUp]; wasCapsLockDown = false; } }]; mouseMovementEventMonitor = [NSEvent addGlobalMonitorForEventsMatchingMask:(NSMouseMovedMask) handler:^(NSEvent *event) { [self simulateMouseEvent: kCGEventLeftMouseDragged]; }]; } // Cease listening for caps lock key presses and mouse movements - (void)endEventMonitoring { if (capsLockEventMonitor) { [NSEvent removeMonitor: capsLockEventMonitor]; capsLockEventMonitor = nil; } if (mouseMovementEventMonitor) { [NSEvent removeMonitor: mouseMovementEventMonitor]; mouseMovementEventMonitor = nil; } } -(void)simulateMouseEvent:(CGEventType)eventType { // Get the current mouse position CGEventRef ourEvent = CGEventCreate(NULL); CGPoint mouseLocation = CGEventGetLocation(ourEvent); // Create and post the event CGEventRef event = CGEventCreateMouseEvent(CGEventSourceCreate(kCGEventSourceStateHIDSystemState), eventType, mouseLocation, kCGMouseButtonLeft); CGEventPost(kCGHIDEventTap, event); CFRelease(event); }
{ "pile_set_name": "StackExchange" }
Q: Array List Java Please can somebody help me? I'm learning about Array List in Java, I found interesting things in this lesson (Stanford CS106a) https://www.youtube.com/watch?v=YJ9FlCFi3c8&feature=youtu.be&list=PL84A56BC7F4A1F852&t=1385 But when I tried to run this program in Eclipse it gives me many errors :( What's wrong with this? (Why is void invalid type for the variable printList?) import java.util.ArrayList; import acm.program.*; class ArrayListEx extends ConsoleProgram { public void run () { ArrayList<String> sList = new ArrayList <String>(); readList (sList); printList (sList); readList (sList); printList (sList); private void readList (ArrayList list) { while (true) { String line = readLine("Unesi tekst"); if (line.equals("")) break; list.add(line); } } private void printList (ArrayList lista) { println ("List contains: " + lista.size() + " elements."); for (int i = 0; i< lista.size(); i++) { println(lista.get(i)); } } } } A: The issue was no } bracket on your run function and an extra } at the end of your printList function. Also have changed run() to init(). This should hopefully work for you. import java.util.ArrayList; import acm.program.*; public class ArrayListEx extends ConsoleProgram { public void init () { ArrayList<String> sList = new ArrayList <String>(); readList (sList); printList (sList); readList (sList); printList (sList); } private void readList (ArrayList list) { while (true) { String line = readLine("Unesi tekst"); if (line.equals("")) break; list.add(line); } } private void printList (ArrayList lista) { println ("List contains: " + lista.size() + " elements."); for (int i = 0; i< lista.size(); i++) { println(lista.get(i)); } } }
{ "pile_set_name": "StackExchange" }
Q: LINK : fatal error LNK1181:cannot open input file 'C:\OpenSSL-Win64\lib\libeay32.lib' I have windows 7 - 64 bit with Visual studio 2013 ultimate. I am running npm install command and getting below errors: npm info it worked if it ends with ok npm info using npm@3.8.3 npm info using node@v5.10.0 npm info attempt registry request try #1 at 10:01:07 AM npm http request GET http://registry.npmjs.org/fsevents npm http 304 http://registry.npmjs.org/fsevents npm info attempt registry request try #1 at 10:01:09 AM npm http request GET http://registry.npmjs.org/ursa npm http 304 http://registry.npmjs.org/ursa npm info lifecycle ursa@0.9.4~preinstall: ursa@0.9.4 npm info linkStuff ursa@0.9.4 npm info lifecycle ursa@0.9.4~install: ursa@0.9.4 > ursa@0.9.4 install C:\Users\sudhir_kumar05\mockingbird\node_modules\ursa > node-gyp rebuild C:\Users\sudhir_kumar05\mockingbird\node_modules\ursa>if not defined npm_config_node_gyp (node "C:\Program Files\nodejs\node_modules\npm\bin\node-gyp-bin\\..\..\node_modules\node-gyp\bin\node-gyp.js" rebuild ) else (node "" rebuild ) gyp info it worked if it ends with ok gyp info using node-gyp@3.3.1 gyp info using node@5.10.0 | win32 | x64 gyp info spawn C:\Python27\python.EXE gyp info spawn args [ 'C:\\Program Files\\nodejs\\node_modules\\npm\\node_modules\\node-gyp\\gyp\\gyp_main.py', gyp info spawn args 'binding.gyp', gyp info spawn args '-f', gyp info spawn args 'msvs', gyp info spawn args '-G', gyp info spawn args 'msvs_version=2013', gyp info spawn args '-I', gyp info spawn args 'C:\\Users\\sudhir_kumar05\\mockingbird\\node_modules\\ursa\\build\\config.gypi', gyp info spawn args '-I', gyp info spawn args 'C:\\Program Files\\nodejs\\node_modules\\npm\\node_modules\\node-gyp\\addon.gypi', gyp info spawn args '-I', gyp info spawn args 'C:\\Users\\sudhir_kumar05\\.node-gyp\\5.10.0\\include\\node\\common.gypi', gyp info spawn args '-Dlibrary=shared_library', gyp info spawn args '-Dvisibility=default', gyp info spawn args '-Dnode_root_dir=C:\\Users\\sudhir_kumar05\\.node-gyp\\5.10.0', gyp info spawn args '-Dnode_gyp_dir=C:\\Program Files\\nodejs\\node_modules\\npm\\node_modules\\node-gyp', gyp info spawn args '-Dnode_lib_file=node.lib', gyp info spawn args '-Dmodule_root_dir=C:\\Users\\sudhir_kumar05\\mockingbird\\node_modules\\ursa', gyp info spawn args '--depth=.', gyp info spawn args '--no-parallel', gyp info spawn args '--generator-output', gyp info spawn args 'C:\\Users\\sudhir_kumar05\\mockingbird\\node_modules\\ursa\\build', gyp info spawn args '-Goutput_dir=.' ] gyp info spawn C:\Program Files (x86)\MSBuild\12.0\bin\msbuild.exe gyp info spawn args [ 'build/binding.sln', gyp info spawn args '/clp:Verbosity=minimal', gyp info spawn args '/nologo', gyp info spawn args '/p:Configuration=Release;Platform=x64' ] Building the projects in this solution one at a time. To enable parallel build, please add the "/m" switch. ursaNative.cc ..\src\ursaNative.cc(157): warning C4244: 'argument' : conversion from 'ssize_t' to 'int', possible loss of data [C:\Users\sudhir_kumar05\mockingbird\node_modules\ursa\build\ursaNative.vcxproj] ..\src\ursaNative.cc(172): warning C4244: 'argument' : conversion from 'ssize_t' to 'int', possible loss of data [C:\Users\sudhir_kumar05\mockingbird\node_modules\ursa\build\ursaNative.vcxproj] ..\src\ursaNative.cc(378): warning C4267: 'initializing' : conversion from 'size_t' to 'int', possible loss of data [C:\Users\sudhir_kumar05\mockingbird\node_modules\ursa\build\ursaNative.vcxproj] ..\src\ursaNative.cc(379): warning C4267: 'initializing' : conversion from 'size_t' to 'int', possible loss of data [C:\Users\sudhir_kumar05\mockingbird\node_modules\ursa\build\ursaNative.vcxproj] ..\src\ursaNative.cc(686): warning C4267: 'argument' : conversion from 'size_t' to 'int', possible loss of data [C:\Users\sudhir_kumar05\mockingbird\node_modules\ursa\build\ursaNative.vcxproj] ..\src\ursaNative.cc(734): warning C4267: 'argument' : conversion from 'size_t' to 'int', possible loss of data [C:\Users\sudhir_kumar05\mockingbird\node_modules\ursa\build\ursaNative.vcxproj] ..\src\ursaNative.cc(779): warning C4267: 'argument' : conversion from 'size_t' to 'int', possible loss of data [C:\Users\sudhir_kumar05\mockingbird\node_modules\ursa\build\ursaNative.vcxproj] ..\src\ursaNative.cc(826): warning C4267: 'argument' : conversion from 'size_t' to 'int', possible loss of data [C:\Users\sudhir_kumar05\mockingbird\node_modules\ursa\build\ursaNative.vcxproj] ..\src\ursaNative.cc(945): warning C4267: 'argument' : conversion from 'size_t' to 'unsigned int', possible loss of data [C:\Users\sudhir_kumar05\mockingbird\node_modules\ursa\build\ursaNative.vcxproj] ..\src\ursaNative.cc(1003): warning C4267: 'argument' : conversion from 'size_t' to 'unsigned int', possible loss of data [C:\Users\sudhir_kumar05\mockingbird\node_modules\ursa\build\ursaNative.vcxproj] win_delay_load_hook.c LINK : fatal error LNK1181: cannot open input file 'C:\OpenSSL-Win64\lib\libeay32.lib' [C:\Users\sudhir_kumar05\mockingbird\node_modules\ursa\build\ursaNative.vcxproj] gyp ERR! build error gyp ERR! stack Error: `C:\Program Files (x86)\MSBuild\12.0\bin\msbuild.exe` failed with exit code: 1 gyp ERR! stack at ChildProcess.onExit (C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\build.js:276:23) gyp ERR! stack at emitTwo (events.js:100:13) gyp ERR! stack at ChildProcess.emit (events.js:185:7) gyp ERR! stack at Process.ChildProcess._handle.onexit (internal/child_process.js:204:12) gyp ERR! System Windows_NT 6.1.7601 gyp ERR! command "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\node_modules\\node-gyp\\bin\\node-gyp.js" "rebuild" gyp ERR! cwd C:\Users\sudhir_kumar05\mockingbird\node_modules\ursa gyp ERR! node -v v5.10.0 gyp ERR! node-gyp -v v3.3.1 gyp ERR! not ok npm info lifecycle ursa@0.9.4~install: Failed to exec install script npm WARN install:ursa@0.9.4 ursa@0.9.4 install: `node-gyp rebuild` npm WARN install:ursa@0.9.4 Exit status 1 npm info lifecycle mockingbird@1.0.150~preinstall: mockingbird@1.0.150 npm info linkStuff mockingbird@1.0.150 npm info lifecycle mockingbird@1.0.150~install: mockingbird@1.0.150 npm info lifecycle mockingbird@1.0.150~postinstall: mockingbird@1.0.150 npm info lifecycle mockingbird@1.0.150~prepublish: mockingbird@1.0.150 npm WARN optional Skipping failed optional dependency /chokidar/fsevents: npm WARN notsup Not compatible with your operating system or architecture: fsevents@1.0.14 npm WARN mongodb-core@1.2.32 requires a peer of kerberos@~0.0 but none was installed. npm info ok I tried running same project in IntelliJ ultimate trial version but getting same error. A: I've had the same trouble and the answer is to read the documentation. OpenSSL (normal, not light) in the same bitness as your Node.js installation. OpenSSL must be installed in the a specific install directory (C:\OpenSSL-Win32 or C:\OpenSSL-Win64) If you get Error: The specified module could not be found., copy libeay32.dll from the OpenSSL bin directory to this module's bin directory, or to Windows\System32. One problem with this - you need 1.0.2 (got here). Version 1.1.0 has no libea32.dll. And successively I've faced following problems installing ursa: node-gyp. Think it was not a real problem, but rebuilt was successful after this compiler. I had VS2010express and again error, but now when installing ursa MSBUILD : error MSB3428: Could not load the Visual C++ component "VCBuild.exe Tried out some recipes but only after VS2013express installation I've gor success and another error SSL. Use Open-SSL 64 1.0.2
{ "pile_set_name": "StackExchange" }
Q: Equivalence definition for convergence in probability Let $(X_n)$ be a sequnce of random variables in the probability space $(\Omega, \mathscr{F}, \mathbb{P}).$ Then $X_n \rightarrow X$ in probability if and only if $\mathbb{E} \min(|X_n - X|, 1) \rightarrow 0$ as $n \uparrow \infty.$ ($\rightarrow)$ Let $Y_n = \min(|X_n - X|,1).$ Then $|Y_n| \leq 1$. So by Dominated convergence thm, $$\lim \mathbb{E}Y_n = \mathbb{E} \lim Y_n.$$ Since $X_n \rightarrow X$ in probability, almost every $x$, $$Y_n(x) = |X_n-X|(x)$$ for $n$ large. So it should be like $$Y(x) = \lim |X_n - X|(x)$$ almost every $x$. I feel that $\lim |X_n - X|$ should be $0$, but I cannot find a good reason to support this (I know just $X_n \rightarrow X$ in probability, but not $X_n \rightarrow X$ in usual sequence sence.) Any help for this direction ? A: Note that convergence in probiability does not give you that for almost every $x$ that $|X_n - X|$ is small almost surely. It just guarantees that the set where $|X_n - X|$ is large has small (not zero!) probiability. Recall that $X_n - X$ in probiability means $$ \forall \epsilon > 0: \def\P{\mathbf P}\def\E{\mathbf E}\P\bigl(|X_n - X| > \epsilon\bigr) \to 0 $$ Suppose this is true and we want to prove $\E(Y_n) \to 0$. Let $\epsilon \in(0, 1)$. Choose $N \in \mathbf N$ such that $$ \P\bigl(|X_n - X| > \epsilon\bigr) < \epsilon, \qquad n \ge N.$$ We have \begin{align*} Y_n &= \min(1, |X_n - X|)\\ &\le \epsilon \chi_{\{|X_n - X|\le \epsilon\}} + 1\chi_{\{|X_n - X| > \epsilon\}} \end{align*} Taking the expected value, we have \begin{align*} \E Y_n &\le \epsilon \P(|X_n - X| \le \epsilon) + \P(|X_n - X| > \epsilon)\\ &\le \epsilon + \epsilon\\ &= 2\epsilon \end{align*} Hence $\E Y_n \to 0$. For the other direction suppose $\E Y_n \to 0$, let $\epsilon \in (0,1)$. We have by Markov \begin{align*} \P(|X_n - X| > \epsilon) &= \P(\min\{1,|X_n - X|\}> \epsilon)\\ &= \P(Y_n > \epsilon)\\ &\le \frac 1\epsilon \E Y_n\\ &\to 0. \end{align*}
{ "pile_set_name": "StackExchange" }
Q: Compilation error when passing Integer into generic method with Function> I have some code with 3 overriding methods that perform the same operation ( code is identically for each method) on the Inputs, the only difference between them is the input parameter type private List<String> extractDoubleValues(Function<MyClass, List<Double>> extractions) private List<String> extractLongValues(Function<MyClass List<Long>> extractions) private List<String> extractIntegerValues(Function<MyClass, List<Integer>> extractions) I was trying to attempt to replace these 3 methods with a single method that makes us of generic wildcards as follows private List<String> extractNumberValues(Function<MyClass, List<? extends Number>> extractions) When I attempt to use the above generic method in place of one of the 3 type specific methods Function<MyClass, List<Integer>> intExtractions; List<String> extractedValues = extractNumberValues(intExtractions); I get a the following compilation error on the second line of code above Error:(59, 80) java: incompatible types: java.util.function.Function<MyClass,java.util.List<java.lang.Double>> cannot be converted to java.util.function.Function<MyClass,java.util.List<? extends java.lang.Number>> I've successfully replaced duplicate methods with the wildcard before, as bellow List<String> convertNumberListToStringList(List<Integer> numberList) List<String> convertNumberListToStringList(List<Double> numberList) with List<String> convertNumberListToStringList(List<? extends Number> numberList) I'm new to the idea of generics so I was curious as why the above would fail to compile? I do not quite understand why it would fail to compile A: Major problem(or i should say feature?) here is generic are used only during compilation. During runtime you do not have any information about generic. In other words you have to consider List<Integer> and List<Double> and completelly different types. If you see inside Fucntion class you will see <T, R> without wildcard. So even Function use List<Integer> and List<Double> as completelly different types. If y ou want to say to Function that R will be something of List type, you have to code it like: Function<SomeClass, ? extends List<? extends SomeOtherClass>> By code above you are telling that R will be List for sure and list will contain instances of SomeOtherClass. Main point during work with generic is that generic changes original class to some other class...
{ "pile_set_name": "StackExchange" }
Q: How to merge data? I have some group of data with different classes,in the form of below: {{2, 3} -> 1, {1, 5} -> 1, {1, 1} -> 2, {2, 2} -> 2} I need to merge the data of same class.Like this: {1->{ {2,3},{1,5}},2->{{1,1},{2,2}} } Merge[#[[2]] -> #[[1]] & /@ a, List] This doesn't work well. A: Using the straightforward way GroupBy Normal@GroupBy[{{2, 3} -> 1, {1, 5} -> 1, {1, 1} -> 2, {2, 2} -> 2}, Last -> First] (* {1 -> {{2, 3}, {1, 5}}, 2 -> {{1, 1}, {2, 2}}} *) Using SequenceCases: list = {{2, 3} -> 1, {1, 5} -> 1, {1, 1} -> 2, {2, 2} -> 2}; Map[# -> SequenceCases[list, {pat : PatternSequence[_ -> #]} :> First@pat] &, Union@list[[All, 2]]] (* {1 -> {{2, 3}, {1, 5}}, 2 -> {{1, 1}, {2, 2}}} *) Using pattern in ReplaceRepeated (this will work if at most two entries per index i.e. 1 -> or 2 -> are present) {{2, 3} -> 1, {1, 5} -> 1, {1, 1} -> 2, {2, 2} -> 2} //. {w___, pat1_ -> x_, y___, pat2_ -> x_, z___} :> {w, x -> {pat1, pat2} y, z} (* {1 -> {{2, 3}, {1, 5}}, 2 -> {{1, 1}, {2, 2}}} *) More general form of ReplaceRepeated (works with more than two entries) list= {{2, 3} -> 2, {1, 5} -> 1, {1, 1} -> 2, {2, 2} -> 1, {3, 3} -> 2}; list//. {{w___, pat1_ -> x_, y___, pat2_ -> x_, z___} :> {w, x -> {pat1, pat2}, y, z}, {w___, x_ -> {pat1 : {__} ..}, y___, pat2_ -> x_, z___} :> {w, x -> {pat1, pat2}, y, z}} (* {2 -> {{2, 3}, {1, 1}, {3, 3}}, 1 -> {{1, 5}, {2, 2}}} *) A: data = {{2, 3} -> 1, {1, 5} -> 1, {1, 1} -> 2, {2, 2} -> 2}; #[[1, -1]] -> #[[All, 1]] & /@ GatherBy[data, Last] (* {1 -> {{2, 3}, {1, 5}}, 2 -> {{1, 1}, {2, 2}}} *) A: a = {{2, 3} -> 1, {1, 5} -> 1, {1, 1} -> 2, {2, 2} -> 2} Merge[Reverse /@ a, Apply[List]]
{ "pile_set_name": "StackExchange" }
Q: Issue with Json file for Highstock I'm actually be doing a project in my studies and i will take json data from webservice for set it in highstock. My webservice (file in php language) return actually this json format [{"jour":"22","mois":"1","an":"10","heure":"10","minute":"0","p_ac":"143"},{"jour":"22","mois":"1","an":"10","heure":"11","minute":"0","p_ac":"827"},{"jour":"22","mois":"1","an":"10","heure":"12","minute":"0","p_ac":"965"},{"jour":"22","mois":"1","an":"10","heure":"13","minute":"0","p_ac":"1025"},{"jour":"22","mois":"1","an":"10","heure":"14","minute":"0","p_ac":"1003"},{"jour":"22","mois":"1","an":"10","heure":"15","minute":"0","p_ac":"635"},{"jour":"22","mois":"1","an":"10","heure":"16","minute":"0","p_ac":"385"},{"jour":"22","mois":"1","an":"10","heure":"17","minute":"0","p_ac":"54"},{"jour":"22","mois":"1","an":"10","heure":"18","minute":"0","p_ac":"0"},{"jour":"22","mois":"1","an":"10","heure":"19","minute":"0","p_ac":"0"},{"jour":"22","mois":"1","an":"10","heure":"20","minute":"0","p_ac":"0"},{"jour":"23","mois":"1","an":"10","heure":"9","minute":"0","p_ac":"204"},{"jour":"23","mois":"1","an":"10","heure":"10","minute":"0","p_ac":"468"},{"jour":"23","mois":"1","an":"10","heure":"11","minute":"0","p_ac":"815"},{"jour":"23","mois":"1","an":"10","heure":"12","minute":"0","p_ac":"933"},{"jour":"23","mois":"1","an":"10","heure":"13","minute":"0","p_ac":"1062"},{"jour":"23","mois":"1","an":"10","heure":"14","minute":"0","p_ac":"332"},{"jour":"23","mois":"1","an":"10","heure":"15","minute":"0","p_ac":"536"},{"jour":"23","mois":"1","an":"10","heure":"16","minute":"0","p_ac":"348"},{"jour":"23","mois":"1","an":"10","heure":"17","minute":"0","p_ac":"73"},{"jour":"23","mois":"1","an":"10","heure":"18","minute":"0","p_ac":"0"},{"jour":"23","mois":"1","an":"10","heure":"19","minute":"0","p_ac":"0"},{"jour":"23","mois":"1","an":"10","heure":"20","minute":"0","p_ac":"0"},{"jour":"23","mois":"1","an":"10","heure":"21","minute":"0","p_ac":"0"}] I need to re-format it for Highstock The correct and complete file for highstock : Here's the correct code How can i do it please ? Ps : Sorry for my bad english A: This code resolve my problem ! :)
{ "pile_set_name": "StackExchange" }
Q: Eliminate duplication in similar fake data access classes Can I combine this two classes and have one fake db class? public class FakeDb : Dictionary<string, List<string>> { public const string Table1 = "Table1"; public void AddToTable(string tableName, string line) { if(!ContainsKey(tableName)) Add(tableName, new List<string>()); List<string> rows = GetTableData(tableName); rows.Add(line); } internal List<string> GetTableData(string tableName) { return this[tableName]; } } public class FakeComplexDb : Dictionary<string, List<Dictionary<string,List<string>>>> { public void AddToTable(string tableName, Dictionary<string, List<string>> line) { if (!ContainsKey(tableName)) Add(tableName, new List<Dictionary<string, List<string>>>()); List<Dictionary<string, List<string>>> rows = GetTableData(tableName); rows.Add(line); } internal List<Dictionary<string, List<string>>> GetTableData(string tableName) { return this[tableName]; } } A: Why not use generics: public class FakeDb<TList> : Dictionary<string, List<TList>> { public const string Table1 = "Table1"; public void AddToTable(string tableName, TList line) { if (!ContainsKey(tableName)) { Add(tableName, new List<TList>()); } List<TList> rows = GetTableData(tableName); rows.Add(line); } private List<TList> GetTableData(string tableName) { return this[tableName]; } } Then to use: var simpleDB = new FakeDb<string>(); var complexDb = new FakeDb<Dictionary<string, List<string>>>();
{ "pile_set_name": "StackExchange" }
Q: Detect Shift + Enter on physical keyboard in Android In preparing my Android App for Chromebooks and use with physical keyboards I want to distinguish in an EditText between receiving an "Enter" (keyEvent 66) and an "Shift+Enter" (also keyEvent 66 apparently) from a physical keyboard. I have tried a number of different solutions, such as dispatchKeyEvent(KeyEvent event) in the activity. The event.getModifiers() however always return 0, as do event.getMetaState(). keyEvent.isShiftPressed() always returns false. onKeyDown(int keyCode, KeyEvent keyEvent) in the activity with the same result. keyEvent.isShiftPressed() always returns false as well. I have not found a way either using onKeyUp(), onKeyPreIme(), editText.setOnKeyListener(...), or with a editText.addTextChangedListener(new TextWatcher() {...}). I have not had any problems acquiring the Enter event, however a Shift+Enter is in all the ways I have tried indistinguishable from the Enter event. So my question is this: did any other Android Dev find a way to properly capture the Shift+Enter from a physical keyboard? A: i had the same problem and I fixed it by detecting "Shift" down and "Shift" up events, and define a boolean that store the state. this is my code, hope help you. final boolean[] isPressed = {false}; inputEditText.setOnKeyListener(new View.OnKeyListener() { public boolean onKey(View v, int keyCode, KeyEvent event) { // If the event is a key-down event on the "enter" button if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { if (isPressed[0]) { // Shift + Enter pressed return false; } else { // Enter pressed return true; } } if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_SHIFT_RIGHT)) { isPressed[0] = true; return false; } if ((event.getAction() == KeyEvent.ACTION_UP) && (keyCode == KeyEvent.KEYCODE_SHIFT_RIGHT)) { isPressed[0] = false; return false; } return false; } });
{ "pile_set_name": "StackExchange" }
Q: Stripping all '\n' from HTMLCalendar() import calendar def websiteCalendar(month, year): return calendar.HTMLCalendar().formatmonth(year, month).rstrip("\n") returns: "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" class=\"month\">\n<tr><th colspan=\"7\" class=\"month\">November 2016</th></tr>\n<tr><th class=\"mon\">Mon</th><th class=\"tue\">Tue</th><th class=\"wed\">Wed</th><th class=\"thu\">Thu</th><th class=\"fri\">Fri</th><th class=\"sat\">Sat</th><th class=\"sun\">Sun</th></tr>\n<tr><td class=\"noday\">&nbsp;</td><td class=\"tue\">1</td><td class=\"wed\">2</td><td class=\"thu\">3</td><td class=\"fri\">4</td><td class=\"sat\">5</td><td class=\"sun\">6</td></tr>\n<tr><td class=\"mon\">7</td><td class=\"tue\">8</td><td class=\"wed\">9</td><td class=\"thu\">10</td><td class=\"fri\">11</td><td class=\"sat\">12</td><td class=\"sun\">13</td></tr>\n<tr><td class=\"mon\">14</td><td class=\"tue\">15</td><td class=\"wed\">16</td><td class=\"thu\">17</td><td class=\"fri\">18</td><td class=\"sat\">19</td><td class=\"sun\">20</td></tr>\n<tr><td class=\"mon\">21</td><td class=\"tue\">22</td><td class=\"wed\">23</td><td class=\"thu\">24</td><td class=\"fri\">25</td><td class=\"sat\">26</td><td class=\"sun\">27</td></tr>\n<tr><td class=\"mon\">28</td><td class=\"tue\">29</td><td class=\"wed\">30</td><td class=\"noday\">&nbsp;</td><td class=\"noday\">&nbsp;</td><td class=\"noday\">&nbsp;</td><td class=\"noday\">&nbsp;</td></tr>\n</table>" For some reason it keeps '\n', is there an easy way to strip out all the '\n' from the returned text? I successfully stripped the '\n' element at the end, but there is still the one before the tag that I can't seem to get rid of. A: If you want just to remove all '\n' occurrences from string you should try calendar.HTMLCalendar().formatmonth(year, month).replace("\n", "")
{ "pile_set_name": "StackExchange" }
Q: Default generic on dynamic component (ReactTS) My question is kinda to my previous one: ReactTS extend type by dynamic Component Props? So lets say I've got the next lines: type Base = { baseProp: ... } type Extend = { extendProp: ... } // use this if "as" undefined type DefaultPropsToExtend = { defaultToExtendProp: ... } declare const ExtendedComponent: React.FC<Extend> declare const DefaultExtendedComponent: React.FC<DefaultPropsToExtend> function Base<T = DefaultPropsToExtend>(props: BaseProps & { as: React.ComponentType<T> } & T): React.ReactElement { const Wrapper = props.as return <Wrapper /> } So what I expect when I call the next lines are: <Base /> // props can be => { baseProp, defaultToExtendProp } What props actually I am seeing => { baseProp } If I am doing the next then things working property, but this way I need to be explicit about the default "as" every time. <Base as={DefaultToExtendComponent} /> // => { baseProp, defaultToExtendProp } A: Probably the best option is to use overloads. One overload can be generic and accept any component. The other overload can have the default: type BaseProps = { baseProp: string } type Extend = { extendProp: number } // use this if "as" undefined type DefaultPropsToExtend = { defaultToExtendProp: number } declare const ExtendedComponent: React.FC<Extend> declare const DefaultExtendedComponent: React.FC<DefaultPropsToExtend> function Base(props: BaseProps & DefaultPropsToExtend): React.ReactElement function Base<T>(props: BaseProps & { as: React.ComponentType<T> } & T): React.ReactElement function Base<T = DefaultPropsToExtend>(props: BaseProps & { as?: React.ComponentType<T> } & T): React.ReactElement { const Wrapper = props.as || (DefaultExtendedComponent as unknown as React.ComponentType<T>) return <Wrapper {...props as T}/> } let a = <Base baseProp="" defaultToExtendProp={0} /> let a2 = <Base as={DefaultExtendedComponent} defaultToExtendProp={0} baseProp="" />
{ "pile_set_name": "StackExchange" }
Q: Print a string in as few distinct characters as possible The task is simple: print The quick brown fox jumps over the lazy dog using as few distinct characters in your source code as possible. print "The quick brown fox jumps over the lazy dog" has a score of 29 characters, as all 26 lowercase letters appear at least once, as well as an uppercase T, spaces, and quote characters. I'm sure you can get more creative than that, though! Brainfuck, Whitespace, and similar languages (at my discretion) are disallowed. Line breaks count as one character. The code may be as long as necessary. I'll accept a solution on April 21, 11:59 PM EST. In the event of a tie, the shorter answer will be accepted. A: 64-bit Intel machine code for Linux in binary: 2 distinct characters 01111111010001010100110001000110000000100000000100000001000000000000000000000000 00000000000000000000000000000000000000000000000000000010000000000011111000000000 00000001000000000000000000000000011110000000000001000000000000000000000000000000 00000000000000000100000000000000000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000000000000000000000000000000000 00000000000000000100000000000000001110000000000000000001000000000000000000000000 00000000000000000000000000000000000000010000000000000000000000000000010100000000 00000000000000000000000000000000000000000000000000000000000000000000000000000000 00000000000000000100000000000000000000000000000000000000000000000000000000000000 01000000000000000000000000000000000000000000000011001011000000000000000000000000 00000000000000000000000000000000110010110000000000000000000000000000000000000000 00000000000000000000000000000000001000000000000000000000000000000000000000000000 10111000000000010000000000000000000000001011111100000001000000000000000000000000 01001000101111101001111100000000010000000000000000000000000000000000000000000000 10111010001011000000000000000000000000000000111100000101101110000011110000000000 00000000000000001011111100000000000000000000000000000000000011110000010101010100 01101000011001010010000001110001011101010110100101100011011010110010000001100010 01110010011011110111011101101110001000000110011001101111011110000010000001101010 01110101011011010111000001110011001000000110111101110110011001010111001000100000 01110100011010000110010100100000011011000110000101111010011110010010000001100100 011011110110011100001010 I refuse to rewrite it in unary. A: Lua, 8 distinct characters load"load\"load\\\"load\\\\\\\"load\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\5\50\\5\55\\\\0 \\5\50\\05\55\50\\\\\\\\\\\\\\5\50\\5\55\\\\0\\5\50\\5\55\\5\50\\\\\\\\\\\\0\\5\ 50\\05\05505\\\\\\\\\\\\\\5\50\\5\55\\\\0\\5\50\\05\0550\\\\\\\\\\\\\\5\50\\5\55 \\\\\\5\50\\5\55\\\\5\\5\50\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\\\\\\\ \\\05\\\\05\\5\50\\5\50\\\\\\\\\\\\0\\5\50\\05\0550\\5\50\\\\\\\\\\\\0\\5\50\\05 \0550\\\\\\5\50\\5\55\\\\\\\\\\\\\\\\\\\\\\\\05\\\\0\\5\50\\05\55\50\\\\\\\\\\\\ \\\\\\\\\\5\50\\5\55\\\\\\5\50\\5\55\\\\\\\\5\\\\\\5\50\\5\55\\\\\\\\\\\\\\5\50\ \5\55\\\\0\\5\50\\05\55\55\\\\\\\\\\\\0\\5\50\\05\05505\\\\\\5\55\\5\55\\\\\\\\\ \\\0\\5\50\\05\0550\55\\\\\\\\\\\\\\\\\\\\\\\\05\\\\0\\5\50\\05\55\50\\\\\\\\\\\ \\\\\\\5\55\\\\\\\\5\\\\5\\5\50\\\\\\\\\\\\\\5\50\\5\55\\\\0\\5\50\\5\55\\5\50o\ \\\\\\\\\\\\\5\50\\5\55\\\\0\\5\50\\5\55\\5\55\\\\\\\\\\\\\\5\50\\5\55\\\\0\\5\5 0\\05\0550\\\\\\\\\\\\\\\\\\\\\\\\05\\\\0\\5\50\\05\55\50\\\\\\\\\\\\0\\5\50\\05 \0550\50o\\\\\\\\\\\\0\\5\50\\05\55\0500\\\\\\\\\\\\\\\\\\\\\\\\05\\\\0\\5\50\\0 5\55\50\\\\\\\\\\\\0\\5\50\\05\0550\\\\5\\5\50\\\\\\\\\\\\\\5\50\\5\55\\\\0\\5\5 0\\05\55\55\\\\\\\\\\\\0\\5\50\\05\0550\\5\55\\\\\\\\\\\\\\5\50\\5\55\\\\0\\5\50 \\05\55\50\\\\\\\\\\\\\\5\50\\5\55\\\\0\\5\50\\05\0555\\\\\\\\\\\\\\\\\\\\\\\\05 \\\\0\\5\50\\05\55\50o\\\\\\\\\\\\\\\\\\\\\\5\50\\5\55\\\\\\5\50\\5\55\\\\\\\\5\ \\\5\\5\50\\\\\\\\\\\\0\\5\50\\05\0550\\\\\\5\50\\5\55\\\\\\\\\\\\\\5\50\\5\55\\ \\0\\5\50\\5\55\\5\50\\\\\\\\\\\\\\\\\\\\\\\\05\\\\0\\5\50\\05\55\50\\\\\\\\\\\\ \\5\50\\5\55\\\\\\5\50\\5\55\\\\5\\5\50\\\\\\\\\\\\0\\5\50\\05\0550\\5\50\\\\\\\ \\\\\0\\5\50\\05\0550\\\\\\5\50\\5\55\\\\\\\\\\\\\\\\\\\\\\\\05\\\\0\\5\50\\05\5 5\50la\\\\\\\\\\\\0\\5\50\\05\55\50\50\\\\\\\\\\\\0\\5\50\\05\55\50\\\\\\5\50\\5 \55\\\\\\\\\\\\\\\\\\\\\\\\05\\\\0\\5\50\\05\55\50do\\\\\\\\\\\\\\\\\\\\0\\5\50\ \05\0550\\\\\\\\5\\\\\\5\50\\5\55\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\ "\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\"\\\\\\\"\\\\\\\"\\\"\\\"\\\"\"\"\"""" All newline characters must be removed from this code to get single line of length 1998. Lua 5.2 required How arbitrary Lua program could be written using only 8 characters load"\05 Having chars 05\, it is possible to write string literal for any string consisting of chars 0257\. Indeed, "\\" means backslash, "2" == "\50" and "7" == "\55" ("\ddd" in Lua means char with decimal code ddd). Having chars 0257\, it is possible to write string literal for any string consisting of chars 024579\ (as "4" == "\52" and "9" == "\57") On the next step chars 01245679\ will become available. One more step is required to get all decimal digits. Lua has function load which treats a string as Lua code and converts it to a function. E.g., load("print\"Hello\"")() prints Hello. It could be written without parentheses: load"print\"Hello\"""" (last two quotes mean empty string which is passed as optional parameter to the function). Any Lua program could be converted to reduced alphabet within at most 5 steps. Example: If our program consists of single digit 9, then only two steps are required: step 0: 9 step 1: load"\57""" step 2: load"load\"\\5\55\"\"\"""" A: Python, 9 Using this idea. (The line breaks are there for readability and can be removed.) exec(chr(111+1)+chr(111+1+1+1)+chr(11+11+11+11+11+11+11+11+11+1+1+1+1+1+1)+chr(11 +11+11+11+11+11+11+11+11+11)+chr(111+1+1+1+1+1)+chr(11+11+11+1)+chr(11+11+11+11 +11+11+11+1+1+1+1+1+1+1)+chr(11+11+11+11+11+11+11+11+11+1+1+1+1+1)+chr(11+11+11+ 11+11+11+11+11+11+1+1)+chr(11+11+1+1+1+1+1+1+1+1+1+1)+chr(111+1+1)+chr(111+1+1+1 +1+1+1)+chr(11+11+11+11+11+11+11+11+11+1+1+1+1+1+1)+chr(11+11+11+11+11+11+11+11+ 11)+chr(11+11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1)+chr(11+11+1+1+1+1+1+1+1+1+1+ 1)+chr(11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1+1)+chr(111+1+1+1)+chr(111)+chr( 111+1+1+1+1+1+1+1+1)+chr(11+11+11+11+11+11+11+11+11+11)+chr(11+11+1+1+1+1+1+1+1+ 1+1+1)+chr(11+11+11+11+11+11+11+11+11+1+1+1)+chr(111)+chr(111+1+1+1+1+1+1+1+1+1) +chr(11+11+1+1+1+1+1+1+1+1+1+1)+chr(11+11+11+11+11+11+11+11+11+1+1+1+1+1+1+1)+chr (111+1+1+1+1+1+1)+chr(11+11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1+1)+chr(111+1 )+chr(111+1+1+1+1)+chr(11+11+1+1+1+1+1+1+1+1+1+1)+chr(111)+chr(111+1+1+1+1+1+1+1 )+chr(11+11+11+11+11+11+11+11+11+1+1)+chr(111+1+1+1)+chr(11+11+1+1+1+1+1+1+1+1+1 +1)+chr(111+1+1+1+1+1)+chr(11+11+11+11+11+11+11+11+11+1+1+1+1+1)+chr(11+11+11+11 +11+11+11+11+11+1+1)+chr(11+11+1+1+1+1+1+1+1+1+1+1)+chr(11+11+11+11+11+11+11+11+ 11+1+1+1+1+1+1+1+1+1)+chr(11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1)+chr(111+11) +chr(111+1+1+1+1+1+1+1+1+1+1)+chr(11+11+1+1+1+1+1+1+1+1+1+1)+chr(11+11+11+11+11+ 11+11+11+11+1)+chr(111)+chr(11+11+11+11+11+11+11+11+11+1+1+1+1)+chr(11+11+11+1)) This builds the string 'print"The quick brown fox jumps over the lazy dog"' and executes it.
{ "pile_set_name": "StackExchange" }
Q: If $Y_i$ are the irr. components of $Y$, then $\overline{Y_i}$ are the irr. componens of $\overline{Y}$. Got a real dumb question for ya. Suppose $Y$ is a subset of a topological space with irreducible components $Y_1, ... , Y_n$. Then $\overline{Y_1}, ... , \overline{Y_n}$ should be the irreducible components of $\overline{Y}$, and they are all distinct. Why is this? Certainly the $\overline{Y_i}$ are irreducible. I don't understand why $\overline{Y_i}$ is still a maximal irreducible subset of $\overline{Y}$, or why the $\overline{Y_i}$ should be distinct if the $Y_i$ are. I would appreciate a hint on this. Note this is not the same question as If $Y$ has irreducible components $Y_1, \cdots, Y_n$, then the $\overline{Y_i}$ are the irreducible components of $\overline{Y}$ because I am confused on a different part. A: Write $\bar Y=\cup_j P_j$ where $P_i$ are irreducible components. You have $Y_i=\cup_j Y_i\cap P_j$. Note that $P_i$ are closed subsets of the closed set $\bar Y$ so $Y_i\cap P_j$ is closed in $Y$ since $Y_i$ is irreducible, there exists $j_i$ such that $Y_i\cap P_{j_i}=Y_i$. Let $Y_{j_1},...Y_{j_l}$ the connected components of $Y$ contained in $P_j$, since $P_j$ is closed, $\bar Y_{j_l}\subset P_j$ so $P_j=\cup \bar Y_{j_l}$. Since $P_j$ is irreducible, there exists $l$ such that $P_j=\bar Y_{j_l}$. Suppose that $P_j=\bar Y_{j_l}=\bar Y_{j_m}$. Remark that since $Y_{j_l}$ is closed, $Y_{j_l}=F_l\cap Y$ where $F_l$ is a closed subset. $F_l\cap P_j$ is also a closed subset of $\bar Y$ which contains $Y_{j_l}$, since $\bar Y_{j_l}=P_j$ we deduce that $F_l \cap P_j=P_j$ thus $Y_{j_l}\cup Y_{j_m} \subset F_l\cap Y=Y_{j_l}$. This implies $Y_{j_l}=Y_{j_m}$.
{ "pile_set_name": "StackExchange" }
Q: python find second occurence of a set in a column I have a dataframe: ID Status 100 X 100 Y 100 Y 100 Z 100 A 100 Y 100 Y 100 Y 100 X 100 X 100 Y 100 Y 200 A 200 B 200 Y 200 Y 200 C 200 Y 200 Y 200 Z For every non-consecutive occurence of the element Y, I want the Status to change based on the number of times Y appears. My expected output is: ID Status 100 X 100 Y 100 Y 100 Z 100 A 100 Y1 100 Y1 100 Y1 100 X 100 X 100 Y2 100 Y2 200 A 200 B 200 Y 200 Y 200 C 200 Y1 200 Y1 200 Z I've tried the following: df['index'] = pd.np.where(df['Status']==Y, df.groupby(['ID']).cumcount(),0) which indexes every occurence of Y. Then I count the difference like so: df['diff'] = df['index'] - df['index'].shift(1) Then I choose every point df['diff'] >1 becomes a new Status value, 'Y1'. df['Status']=pd.np.where(df['diff']>1, 'Y1', df['Status']) The above, however, identifies every point where Y occurs. I need to filter out the first time that Y occurs and solve for subsequent occurrences. I am ok even with the following output: ID Status 100 X 100 Y 100 Y 100 Z 100 A 100 Y1 100 Y1 100 Y1 100 X 100 X 100 Y1 100 Y1 200 A 200 B 200 Y 200 Y 200 C 200 Y1 200 Y1 200 Z A: Here's one way via groupby + transform: def enum(x): mask = x.eq('Y') y = mask & x.ne(x.shift()) z = y.cumsum().sub(1).where(mask).fillna(0).astype(int).astype(str) return z.mask(z == '0', '') df['Status'] += df.groupby('ID')['Status'].transform(enum) print(df) ID Status 0 100 X 1 100 Y 2 100 Y 3 100 Z 4 100 A 5 100 Y1 6 100 Y1 7 100 Y1 8 100 X 9 100 X 10 100 Y2 11 100 Y2 12 200 A 13 200 B 14 200 Y 15 200 Y 16 200 C 17 200 Y1 18 200 Y1 19 200 Z
{ "pile_set_name": "StackExchange" }
Q: Nested wildcards with lower bounds So I read through the main Java Generic FAQ and the single thing which is holding me up are nested wildcards with lower bounds. I want to give you an example of what I do understand, something specifically which works and how I view it. Maybe you could tell me the way I am thinking about this is wrong even though the compiler isn't complaining in the "good" case. Example 1 (makes sense): static void WildcardsMethod(List<? extends Pair<? extends Number>> list) { System.out.println("It worked"); } static void TestWildcardsMethod() { List<Pair<Integer>> list = null; WildcardsMethod(list); } I first look at the deepest wildcard and bound in WildcardMethod's signature. It is looking for Pair<? extends Number>. Therefore, I could use Pair<Integer>, Pair<Double> and so on. Now I have something which looks like the below code in my mind if I decided to substitute Pair<Integer> for Pair<? extends Number>: List<? extends Pair<Integer>> Now, the wildcard represents a type/subtype of the parametrized type Pair<Integer>. Therefore, I can either pass a Pair<Integer> or SubPair<Integer> to WildcardsMethod. Example 2 (makes sense): static void WildcardsMethod(List<? extends Pair<? super Number>> list) { System.out.println("It worked"); } static void TestWildcardsMethod() { List<Pair<Number>> list = null; WildcardsMethod(list); } I look and see that I first need a Pair<? super Number> so I decide to pass in Pair<Number> resulting in the following code: ? extends Pair<Number> I then look at the leftmost wildcard and see that I can use either Pair<Number> or SubPair<Number>. I end up passing List<Pair<Number>>. So in other words, I see the deepest wildcard as asking for a subtype or supertype of the innermost bound (Number). I then go to the top level wildcard and look for a subtype/supertype of the generic type (Pair). Example 3 (doesn't make sense): static void WildcardsMethod(List<? super Pair<? super Number>> list) { System.out.println("It worked"); } static void TestWildcardsMethod() { List<Pair<Object>> list = null; WildcardsMethod(list); } Well, in terms of Pair<? super Number>, Object is definitely a supertype of Number so Pair<Object> should work just as it did for the previous examples. The following is what I think of when trying to understand this: ? super Pair<Object> So I am limited to either Pair<Object> or SuperPair<Object>. However, none of this works. Example 4 (doesn't make sense): static void WildcardsMethod(List<? super Pair<? extends Number>> list) { System.out.println("It worked"); } static void TestWildcardsMethod() { List<Pair<Integer>> list = null; WildcardsMethod(list); } It's the same thing here. Pair<Integer> belongs to the family of Pair<? extends Number> resulting in the following: ? super Pair<Integer> I can then pass in either Pair<Integer> or SuperPair<Integer> However, this too does not work. So I am either thinking of this wrong and somehow that model works for extends but not for super or I am simply missing something about lowerbounds and nested wildcards. A: Example 1: Is List<Pair<Integer>> a subtype of List<? extends Pair<? extends Number>>? It would be if Pair<Integer> is a subtype of Pair<? extends Number>. Is it? Yes, because Integer is a subtype of Number. Example 2: Is List<Pair<Number>> a subtype of List<? extends Pair<? super Number>>? It would be if Pair<Number> is a subtype of Pair<? super Number>. Is it? Yes, because Number is a supertype of Number. Example 3: Is List<Pair<Object>> a subtype of List<? super Pair<? super Number>>? It would be if Pair<Object> is a supertype of Pair<? super Number>. Is it? No, it is not. A parameterized type with a specific parameter can never be a supertype of a parameterized type with a wildcard. Example 4: Is List<Pair<Integer>> a subtype of List<? super Pair<? extends Number>>? It would be if Pair<Integer> is a supertype of Pair<? extends Number>. Is it? No, it is not. A parameterized type with a specific parameter can never be a supertype of a parameterized type with a wildcard.
{ "pile_set_name": "StackExchange" }
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
4