text
stringlengths
64
81.1k
meta
dict
Q: swapping adjacent nodes of a LinkedList I have to swap two adjacent node(not their data) in a linked list. e.g. 1) Input a->b->c->d->e->f, Output : b->a->d->c->f->e 2) Input a->b->c->d->e, Output : b->a->d->c->e I have writen the following code is there any more efficient way (maybe with two temporary pointers) or simple logic? node* swap(node* head) { node *first = head; node *second,*third,*result; if(head == NULL || head->next == NULL) { return head; } result = second = first->next; third = second->next; while(second != NULL) { second->next=first; first->next=(third->next==NULL ? third : third->next); first=third; second=(third->next==NULL ? third : third->next); third=(second==NULL ? second : second->next); } return result; } A: Looks good. I added one correctness check (third==NULL) and removed one redundant expression. You are going through the whole list only once, which you have to do. So I think we can be pretty certain that this is the fastest way to do it. node* swap(node* head) { node *first = head; node *second,*third,*result; if(head == NULL || head->next == NULL) { return head; } result = second = first->next; third = second->next; while(second != NULL) { second->next=first; second = first->next=((third==NULL || third->next==NULL) ? third : third->next); first=third; third=(second==NULL ? second : second->next); } return result; } A: You can do this fairly simply with a recursion: // Swaps node b and c. void swapTwo(node* a, node* b, node* c) { if (a != NULL) a->next = c; b->next = c->next; c->next = b; } void swapEveryTwo(node* prev, node* node) { if (node != null && node->next != null) { swapTwo(prev, node, node->next); swapEveryTwo(node->next, node->next->next); } } Every call of swapEveryTwo swaps pairs of nodes, and then sets up the recursion for the next pair. Also, because this function is tail recursive, the compiler will undoubtedly optimize it to a while loop, ensuring no extra stack frames are allocated, and thus will be optimal. If you need further explanation, feel free to ask. Edited to add swap function as in original post: node* swap(node *head) { if (head != NULL && head->next != NULL) { node *newHead = head->next; swapEveryTwo(NULL, head); return newHead; } else { return head; } }
{ "pile_set_name": "StackExchange" }
Q: Error when i deploying Laravel project on free host (000webhostapp.com) When I deploying my Laravel project on free host called 000webhostapp.com, I got this error: SQLSTATE[HY000] [2002] Connection refused (SQL: select * from posts order by created_at desc limit 10) I tried by creating a database there and also I connected with phpmyadmin. My config/database.php file is : <?php return [ /* |-------------------------------------------------------------------------- | Default Database Connection Name |-------------------------------------------------------------------------- | | Here you may specify which of the database connections below you wish | to use as your default connection for all database work. Of course | you may use many connections at once using the Database library. | */ 'default' => env('DB_CONNECTION', 'mysql'), /* |-------------------------------------------------------------------------- | Database Connections |-------------------------------------------------------------------------- | | Here are each of the database connections setup for your application. | Of course, examples of configuring each database platform that is | supported by Laravel is shown below to make development simple. | | | All database work in Laravel is done through the PHP PDO facilities | so make sure you have the driver for your particular database of | choice installed on your machine before you begin development. | */ 'connections' => [ 'sqlite' => [ 'driver' => 'sqlite', 'database' => env('DB_DATABASE', database_path('database.sqlite')), 'prefix' => '', ], 'mysql' => [ 'driver' => 'mysql', 'host' => 'DB_HOST', 'localhost', 'database' => 'DB_DATABASE', 'id5155399_laravel', 'username' => 'DB_USERNAME', 'id5155399_victorhugoe', 'password' => 'DB_PASSWORD', 'ay942006', 'unix_socket' => 'DB_SOCKET', '', 'charset' => 'utf8mb4', 'collation' => 'utf8mb4_unicode_ci', 'prefix' => '', 'strict' => true, 'engine' => null, ], 'pgsql' => [ 'driver' => 'pgsql', 'host' => env('DB_HOST', '127.0.0.1'), 'port' => env('DB_PORT', '5432'), 'database' => env('DB_DATABASE', 'forge'), 'username' => env('DB_USERNAME', 'forge'), 'password' => env('DB_PASSWORD', ''), 'charset' => 'utf8', 'prefix' => '', 'schema' => 'public', 'sslmode' => 'prefer', ], 'sqlsrv' => [ 'driver' => 'sqlsrv', 'host' => env('DB_HOST', 'localhost'), 'port' => env('DB_PORT', '1433'), 'database' => env('DB_DATABASE', 'forge'), 'username' => env('DB_USERNAME', 'forge'), 'password' => env('DB_PASSWORD', ''), 'charset' => 'utf8', 'prefix' => '', ], ], /* |-------------------------------------------------------------------------- | Migration Repository Table |-------------------------------------------------------------------------- | | This table keeps track of all the migrations that have already run for | your application. Using this information, we can determine which of | the migrations on disk haven't actually been run in the database. | */ 'migrations' => 'migrations', /* |-------------------------------------------------------------------------- | Redis Databases |-------------------------------------------------------------------------- | | Redis is an open source, fast, and advanced key-value store that also | provides a richer set of commands than a typical key-value systems | such as APC or Memcached. Laravel makes it easy to dig right in. | */ 'redis' => [ 'client' => 'predis', 'default' => [ 'host' => env('REDIS_HOST', '127.0.0.1'), 'password' => env('REDIS_PASSWORD', null), 'port' => env('REDIS_PORT', 6379), 'database' => 0, ], ], ]; And my .env file is : APP_NAME=Laravel APP_ENV=local APP_KEY=base64:vSPcSzSYn5vSsZ0m5caAdG7QSGNltPbsHe/6a8tmWms= APP_DEBUG=true APP_LOG_LEVEL=debug APP_URL=http://localhost DB_CONNECTION=mysql DB_HOST=localhost DB_PORT=3306 DB_DATABASE=id5155399_laravel DB_USERNAME=id5155399_victorhugo DB_PASSWORD=******* BROADCAST_DRIVER=log CACHE_DRIVER=file SESSION_DRIVER=file QUEUE_DRIVER=sync REDIS_HOST=127.0.0.1 REDIS_PASSWORD=null REDIS_PORT=6379 MAIL_DRIVER=smtp MAIL_HOST=smtp.mailtrap.io MAIL_PORT=2525 MAIL_USERNAME=null MAIL_PASSWORD=null MAIL_ENCRYPTION=null PUSHER_APP_ID= PUSHER_APP_KEY= PUSHER_APP_SECRET= If someone can address my problem, you welcome. Thanks A: Please use the following 'mysql' => [ 'driver' => 'mysql', 'host' => env('DB_HOST', '127.0.0.1'), 'port' => env('DB_PORT', '3306'), 'database' => env('DB_DATABASE', ''), 'username' => env('DB_USERNAME', ''), 'password' => env('DB_PASSWORD', ''), 'unix_socket' => env('DB_SOCKET', ''), 'charset' => 'utf8mb4', 'collation' => 'utf8mb4_unicode_ci', 'prefix' => '', 'strict' => true, 'engine' => null, ], and in env file DB_CONNECTION=mysql DB_HOST=localhost DB_PORT=3306 DB_DATABASE=id5155399_laravel DB_USERNAME=id5155399_victorhugo DB_PASSWORD=ay942006
{ "pile_set_name": "StackExchange" }
Q: Is the time complexity of `std::vector::clear` *really* not specified? During the proceedings of this question, it came to light that there appear to be no time complexity requirements placed on std::vector<T>::clear by the C++ standard. Table 100 under 23.2.3 says: Destroys all elements in a. Invalidates all references, pointers, and iterators referring to the elements of a and may invalidate the past-the-end iterator. post: a.empty() returns true And... that's it. There's no entry for it specifically under 23.3.6, and no explicit indication that the following applies to clear: [C++11: 23.3.6.1/1]: A vector is a sequence container that supports random access iterators. In addition, it supports (amortized) constant time insert and erase operations at the end; insert and erase in the middle take linear time. Storage management is handled automatically, though hints can be given to improve efficiency. [..] So... is this really true? Or have I simply missed it? A: This seems to be an unintended consequence of DR 704 (and the related DR 1301) which removed the wording saying clear() was equivalent to erase(begin(), end()) because erase() requires MoveAssignable, which isn't needed when erasing every element. Removing the definition in terms of erase() also removes the complexity requirement. That can probably be handled editorially; I've raised it with the committee. N.B. std::deque::clear() and std::forward_list::clear() are also affected. std::list::clear() does have a complexity guarantee. Edit: this is now http://cplusplus.github.com/LWG/lwg-active.html#2231
{ "pile_set_name": "StackExchange" }
Q: Multi-tiered Spring application dependency resolution I am trying to create a three-tier application with Spring, view, logic, data, more or less. The view depends on logic which depends on data. How can I configure the Spring application in the view project such that the dependency graph is able to be resolved? For example: In the view layer: @Controller public class SomeView { private final SomeService someService; @Autowired public SomeView(SomeService someService) { this.someService = someService; } } @Configuration @EnableAutoConfiguration @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } In the logic layer: @Component public class SomeService { private final SomeData someData; @Autowired public SomeService(SomeData someData){ this.someData = someData; } } In the data layer: @Component public class SomeData { } This configuration is not able to boot because SomeService can't resolve SomeData because SomeData is not scanned in the view layers Application.java A: when using @SpringBootApplication Spring boot uses default values. If you take a look at the @SpringBootApplication definition you will see that : Many Spring Boot developers always have their main class annotated with @Configuration, @EnableAutoConfiguration and @ComponentScan. Since these annotations are so frequently used together (especially if you follow the best practices above), Spring Boot provides a convenient @SpringBootApplication alternative. The @SpringBootApplication annotation is equivalent to using @Configuration, @EnableAutoConfiguration and @ComponentScan with their default attributes: [...] That means : @SpringBootApplication // same as @Configuration @EnableAutoConfiguration @ComponentScan public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } Also, it means that when using default values for @ComponentScan your packages sturctures shloud be as following : com.example.model -> your entities com.example.repositoriy -> your repositories com.example.controller -> controllers com.example -> MainApplication class If not following this structure you should tell to the @ComponentScan the package where to find the components : Example 1: @Configuration @EnableAutoConfiguration @ComponentScan({"com.my.package.controller","com.my.package.domain"}) public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } Exemple 2 : @Configuration @EnableAutoConfiguration @ComponentScan(basePackageClasses = {SomeService.class, SomeData.class}) public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } Also, i advice you to check this guide on how to structuring your code in a Spring Boot Application.
{ "pile_set_name": "StackExchange" }
Q: Ex 3.3.5 from Tao analysis book Let $f:X \to Y$ and $g:Y \to Z$ be functions. Given that their composition $g\circ f :X \to Z$ is injective prove that $f$ must be injective while $g$ need not to be. How do I proof that $g$ need not to be injective? Without giving a counter example. Is there a constructive proof? A: Let $g \circ f$ be injective. If $f$ weren't injective, then there would be $a,b \in X$ such that $f(a) = f(b)$, implying $(g \circ f)(a) = (g \circ f)(b)$, which is a contradiction. So $f$ must be injective. Now suppose $f(X)$ is a proper subset of $Y$, meaning that there exists $c \in Y$ such that $c \notin f(X)$, i.e. there is no element of $X$ that is mapped to $c$ by $f$. Then pick $d := f(a)$ and suppose $g(c) = g(d)$. The map $g$ is clearly not injective, but this does not contradict the injectivity of $g \circ f$. An example of this phenomenon is: $$ \begin{split} f : [0,1] \to [0,2] &\qquad f(x) := \sqrt{x}, \\ g : [0,2] \to [0,1] &\qquad g(x) := [x], \end{split} $$ where $[x] := x - \lfloor x \rfloor $ indicates the decimal part of $x$.
{ "pile_set_name": "StackExchange" }
Q: Can a constant name be composed? Is there any way to call/compose a constant name in PHP, which does not require the use of eval? I mean, I have several constant names following this schema: define("CONSTANT_0", "foo 0"); define("CONSTANT_1", "foo 1"); define("CONSTANT_2", "foo 2"); and I want to be able to go through those values in a loop, something like this: for ($i=0; $i<3; $i++) echo CONSTANT_$i; I can't use variables here because I'm using a pre-defined shared class, which already contains those values. Thanks in advance A: This would help - define("CONSTANT_0", "foo 0"); define("CONSTANT_1", "foo 1"); define("CONSTANT_2", "foo 2"); for ($i=0; $i<3; $i++) { echo constant('CONSTANT_' . $i); } Output foo 0foo 1foo 2 constant()
{ "pile_set_name": "StackExchange" }
Q: Can't you install socket.io as a global package? I tried to install socket.io with the -g switch npm install -g socket.io and it installed correctly I think. but running the app it throws the cannot find module error. Local install, i.e. if socket.io is present in node_modules in my project/package, works though. So can't it be installed globally? A: You misunderstood the meaning of global installation. It allows you to access packages directly from your console. But if you want to require package into your own application, you should add it as a dependency into your packaje.json and install it locally. Here is the quotation from npm documentation: Install it locally if you're going to require() it. Install it globally if you're going to run it on the command line.
{ "pile_set_name": "StackExchange" }
Q: How to derive the formula for $\sum_{n=0}^{\infty}\tan^{-1}(\frac{x^{2}}{n^{2}})$ How to derive the formula $$\sum_{n=1}^{\infty}\tan^{-1}\left(\frac{x^{2}}{n^{2}}\right)=\tan^{-1}\left[\frac{\tan\left(\frac{x\pi}{\sqrt{2}}\right)-\tanh\left(\frac{x\pi}{\sqrt{2}}\right)}{\tan\left(\frac{x\pi}{\sqrt{2}}\right)+\tanh\left(\frac{x\pi}{\sqrt{2}}\right)}\right]$$ Is the formula correct? How do I derive the above formula? I tried to apply the formula integral as the limit of sum formula. A: I'd start that sum at $n=1$ if I were you. Now, up to multiples of $\pi$, $$\sum_{n=1}^\infty\tan^{-1}\frac{x^2}{n^2} $$ is the argument of the complex number $$\prod_{n=1}^\infty\left(1+\frac{ix^2}{n^2}\right).$$ But $$\prod_{n=1}^\infty\left(1-\frac{z^2}{n^2}\right)=\frac{\sin\pi z}{\pi z}$$ so how about choosing $z$ to make $-z^2=ix^2$?
{ "pile_set_name": "StackExchange" }
Q: Issue with Dynamic View Panel and onColumnClick (CSJS) event Using the Dynamic View Panel and trying in the onColumnClick event with client side JS to get the UNID or NoteID of the row the user clicked on. However, the XPage does not load with the error shown below Error while executing JavaScript action expression Script interpreter error, line=1, col=9: [ReferenceError] 'rowData' not found JavaScript code 1: rowData.getNoteID() The complete XPage code is shown below. Is there a way to get a handle on the row information to build this event handler? Goal is to use client side JS to open a new tab to show the document the user clicked on. Howard <xe:dynamicViewPanel id="dynamicViewPanel1" var="rowData" indexVar="index"> <xe:this.data> <xp:dominoView var="view1" viewName="testview"> </xp:dominoView> </xe:this.data> <xp:eventHandler event="onColumnClick" submit="false"> <xe:this.script><![CDATA[alert('#{javascript:rowData.getNoteID()}');]]></xe:this.script> </xp:eventHandler></xe:dynamicViewPanel></xp:view> A: You can't calculate row's noteId with alert('#{javascript:rowData.getNoteID()}') in CSJS code as this is executed on server side before all the rows get rendered. Use rowAttrs property instead. It allows you to add an attribute to rendered table row. You'd add an attribute "noteId": <xe:this.rowAttrs> <xp:attr name="noteId" value="#{javascript:rowData.getNoteID()}"> </xp:attr> </xe:this.rowAttrs> The rendered html looks like this then: The onColumnClick event is fired on rendered <a id="view:_id1:dynamicViewPanel1:0:_id3:_internalColumnLink" href="#" ... You can get this element/node in onColumnClick's CSJS code with thisEvent.target. From there you "walk" upwards with .parentNode twice and get the element <tr ..> with attribute "noteId". Finally, read the attribute with .getAttribute("noteId"). This is your example with all changes: <xe:dynamicViewPanel id="dynamicViewPanel1" var="rowData" indexVar="index"> <xe:this.data> <xp:dominoView var="view1" viewName="testview"> </xp:dominoView> </xe:this.data> <xe:this.rowAttrs> <xp:attr name="noteId" value="#{javascript:rowData.getNoteID()}"> </xp:attr> </xe:this.rowAttrs> <xp:eventHandler event="onColumnClick" submit="false"> <xe:this.script><![CDATA[ alert(thisEvent.target.parentNode.parentNode.getAttribute("noteId")); ]]></xe:this.script> </xp:eventHandler> </xe:dynamicViewPanel>
{ "pile_set_name": "StackExchange" }
Q: How can I remove these screws from shutters? I am trying to pull some wood shutters off vinyl siding. The screws are placed into what looks like a cylinder (I believe it is called an "anchor"), which itself looks attached to the siding. But when you get working on the screws, instead of coming out, they simply spin and make a popping noise every once in awhile. How can I get these shutters off? Note: This is not simply one isolated screw; none of them will come out on any of the shutters. I have also put a crowbar behind the shutter to pull it from the wall so that the screw would "catch", but that didn't work either. A: Have you tried just pulling the screw? If it is a plug anchor it should just pull right out with moderate force. If it is a toggle-like anchor (where something expands behind the wood), try pulling the screw until it feels tight, then hold the anchor with a pair of pliars and try turning the screw. Worst case just cut the screw off with a pair of tin snips, a rotary tool with a cut-off wheel, etc. Once the screw head is off you can probably just push the rest of the screw and anchor into the void behind the wall.
{ "pile_set_name": "StackExchange" }
Q: Why struct size is multiple of 8 when consist a int64 variable In 32 bit system In C Programming language and I use 32 bit system, I have a struct and this struct size is multiple of four. But I look at Linker Map file and size is multiple of eight Example typedef struct _str { U64 var1, U32 var2 } STR; Size of this struct is 16. But typedef struct _str { U32 var1, U32 var2, U32 var3 } STR2; Size of STR2 is 12. I am working on 32 bit ARM microcontroller. I dont know why A: The first structure is padded in order to get it aligned on a U64 boundary: it is equivalent to struct STR { U64 var1; U32 var2; U8 pad[4]; /* sizeof(U64) - sizeof(U32) */ }; So when used in an array of struct STR [], each U64 is well aligned regarding to ABI requirements. Have a look at Procedure Call Standard for ARM Architecture , 4.1 Fundamental Data Types . A: The size of a structure is defined as a multiple of the alignment of a member with the largest alignment requirement. It looks like the alignment requirement of U64 is 8 bytes even in 32-bit mode on your platform. The following code: #include <stdio.h> #include <stdint.h> int main() { printf("alignof(uint64_t) is %zu\n", __alignof(uint64_t)); } Produces the same output when compiled in both 32-bit and 64-bit mode on Linux x86_64: alignof(uint64_t) is 8
{ "pile_set_name": "StackExchange" }
Q: Given $BA+B^2=I-BA^{2}$ what can be said about the matrices A, B? Let $A,B$ be $n\times n$ matrices such that $BA+B^2=I-BA^{2}$ where $I$ is the identity matrix. Which of the following is true: $A$ is nonsingular $B$ is nonsingular $A+B$ is nonsingular $AB$ is nonsingular How do we proceed in this type of problems? A: $I=BA+B^2+BA^{2}=B(A+B+A^2) \Rightarrow |I|=|B||A+B+A^2|=1$ Hence B is nonsingular Counter-examples: For statements 1 and 4 : $A=O,B=I$ For statement 3 : $A=-I,B=I$
{ "pile_set_name": "StackExchange" }
Q: Target Facebook login button I'm newly learning the automation stuff, How can I target the Facebook login button. <div class="fb-btn"> <div class="fb-logo"></div> <div class="fb-text">Log In with Facebook</div> <div> A: You can try this 1 . @browser.div(:class => 'fb-btn').click or @browser.div(:class => 'fb-text').click
{ "pile_set_name": "StackExchange" }
Q: JS download file from the server does not working I am getting from my server a png file. The response looks like this: �PNG IHDR|�<V� IDATx���w�T����ם^����I� v[$��J��bL����oL�&єob���K��QEQ���RDzoK���˽�?f�Sd��ǃ���s���;�����s�����������������-��@DDDDDDDDDDDD� When I'm trying to convert it to a blob and download it, the file is empty. download() { return this.http.get(url).map(res => this.downloadFile(res.text())); } private downloadFile(data) { const blob = new Blob([data], {type: 'image/png'}); const url = window.URL.createObjectURL(blob); return url; } this.download(this.config.guid).subscribe(url => { var link = document.createElement("a"); link.href = url; link.download = "data.png"; document.body.appendChild(link); link.click(); }); What am I doing wrong? A: If you don't need to support IE11, fetch makes it easy to get a Blob for a downloaded resource: fetch(url).then(response => response.blob()).then(blob => { // Use the blob here... const blobUrl = window.URL.createObjectURL(blob); const link = document.createElement("a"); link.href = blobUrl; link.download = "data.png"; document.body.appendChild(link); link.click(); }); That said: I would just make the link an actual link and return the data with the Content-Disposition header set to attachment; filename=data.png. The browser will offer to save the file when the user clicks the link.
{ "pile_set_name": "StackExchange" }
Q: How to permanently add values to python dictionaries I have a script that checks wether the user enters a valid username that corresponds to the correct password and grants access. it also allows them to create a username and password and adds them to the dictionary. However when I run the program and create a new username and password it adds them to the dictionary but not permanently as when the program is run again and the dictionary is printed the values I added before are no longer there. # creates a users dictionary users = { 'Joe': 'juk725', 'Mat': 'axr3', 'Th3_j0k3r': 'bl4z3' } while username not in users and username != 'signup': username = input("enter username(type signup to create an account): ") if username == "signup" or username == "Signup": create_username = input("enter a new username: ") create_password = input("enter a new password: ") if create_password in users: create_password = input("password taken re-enter: ") if create_username==create_password: create_password=input("password cannot be the same as your username re-enter: ") # then adds the new username to the users dictionary if username == 'signup': users[create_username] = create_password else: if username in users: password = input("enter password: ") if password in users: print("access granted") A: Python only has access to the memory assigned to it by the operating system. When the Python process ends, that memory is no longer accessible. If you want more permanent storage you can write to disk. There are lots of ways to do this but here are a couple common ones for dictionaries in Python: pickle json
{ "pile_set_name": "StackExchange" }
Q: Convert RGB camera to infrared, but 3 channels not just 1? A common way to make an infrared camera is to remove a commodity camera's IR-blocking filter (and add another filter to block the visible spectrum). Is there a similarly cheap way to convert an RGB camera to sense three different bands of infrared (three colors), i.e., multispectral? Searching online for 3-channel infrared hits the red herring of remote-control toys. A: Yes. In fact, every thus-modified camera senses three different bands of near-infrared. (This answer is an expansion of Mark Booth's comment.) In Basics of Infrared Photography, the first diagram's shaded areas show the sensitivity to wavelength of the R,G,B sensors of an unmodified camera. The third diagram (copied in this answer) shows the same for a camera whose IR blocker has been removed. Those three shaded areas are identical past 900 nm, but from 700 to 900 they differ enough to be fairly considered as three different "colors." The difference can be augmented by boosting saturation in an image editor. (Note that the blue channel now represents the longest wavelengths, red the shortest.)
{ "pile_set_name": "StackExchange" }
Q: Associate row of datatable to bootstrap switch (using another column field) I'm using datatables and bootstrap switch plugins to enable and disable users. When I click on switch I call a web service throught ajax and my rest web services switch status of user into database. The problem is know whitch user is selected from datatables row and pass it to my web service. This is table initialitanion: if ( ! $.fn.DataTable.isDataTable( '#usersTable' ) ) { userTable = $('#usersTable').DataTable({ responsive: true, //disable order and search on column columnDefs: [ { targets: 1, orderable: false, searchable: false, } ], //fix problem with responsive table "autoWidth": false, "ajax": "table", "columns": [ { "data": "username" }, { data: "enabled", render: function ( data, type, row ) { if (data) { return '<input data=data=row.username type="checkbox" name="my-checkbox" checked>'; } else { return '<input data=data=row.username type="checkbox" name="my-checkbox">'; } } }, { "data": "role.role"}, { "data": "clientVersion.name" }, { data: null, className: "center", defaultContent: '<button type="button" class="btn btn-danger" id="deleteLicense" data-toggle="modal" th:attr="data-href=${license.idClientLicense}" data-target="#deleteLicenseModal">Delete</button>' } ], "fnDrawCallback": function() { //Initialize checkbos for enable/disable user $("[name='my-checkbox']").bootstrapSwitch({size: "small", onColor:"success", offColor:"danger"}); //$('#toggleChecked').bootstrapSwitch({size: "small", onColor:"success", offColor:"danger"}); } }); } else { userTable.ajax.url("table").load(); } And this is bootstrap switch event : $('#usersTable').on('switchChange.bootstrapSwitch', 'input[name="my-checkbox"]', function(event, state) { //CSRF attribute for spring security var token = $("meta[name='_csrf']").attr("content"); var header = $("meta[name='_csrf_header']").attr("content"); $.ajax({ type : "POST", url : "status/" + //username setted above, beforeSend:function(xhr) { xhr.setRequestHeader(header, token); }, // all right with rest call success : function(data) { // No exception occurred if (data.status==true){ // Also the field are right(for e.g. form value) if(data.success==true){ } else{ // code if there are some error into form for example } } else { // code exception notifyMessage(data.result, 'error'); } }, // error during rest call error : function(data) { window.location.href = "/ATS/500"; } }); }); I thought to set username as field for bootstrap switch during its construction but how? I should do something like this: if (data) { return '<input value=username type="checkbox" name="my-checkbox" checked>'; but it doesn't work because set username and not the value returned from ajax call. Can you help me? A: I solved with this code (I hope it is useful for someone) { data: "enabled", render: function ( data, type, row ) { if (data) { return '<input data="'+row.username+'" type="checkbox" name="my-checkbox" checked>'; }else { return '<input data="'+row.username+'" type="checkbox" name="my-checkbox">'; } } and then I get the value with $(this).attr('data')
{ "pile_set_name": "StackExchange" }
Q: passing value from parent to child not working Using Vuu.js, I'm trying to pass a value from parent to child component. I have this working fine with a provided example. But when I change the name, it stops working. I can't figure out what i'm doing wrong. My understanding on props is limited, i'm still trying to get me head around it. Working Example: https://codepen.io/sdras/pen/788a6a21e95589098af070c321214b78 HTML <div id="app"> <child :text="message"></child> </div> JS Vue.component('child', { props: ['text'], template: `<div>{{ text }}</div>` }); new Vue({ el: "#app", data() { return { message: 'hello mr. magoo' } } }); Non Working Example: HTML <div id="app"> <child :myVarName="message"></child> </div> JS Vue.component('child', { props: ['myVarName'], template: `<div>{{ myVarName }}</div>` }); new Vue({ el: "#app", data() { return { message: 'hello mr. magoo' } } }); A: In your parent template <div id="app"> <child :myVarName="message"></child> </div> replace <child :myVarName="message"></child> with <child :my-var-name="message"></child> Additionally you can refer this to get insights of casing. A: Leave everything as is in your updated example EXCEPT in the HTML change "myVarName" to "my-var-name" - this is done by default by Vue and within the js you can use the camelCased version myVarName still.
{ "pile_set_name": "StackExchange" }
Q: What are community answers and why / when to use them? I have seen some community wiki answers laying around the site, I am wondering when should one use it and the main reason for them to exist. Can moderators convert a user answer to community wiki? ie: a user makes a great answer with a lot of votes up, but the answer is outdated and the user in no where to be seen. I know you can downvote and create a new answer but maybe it can be converted to community wiki and edited to best fit the current situation? A: You can edit answers even if they're not community wiki. It just reduces the reputation requirements to be able to edit without approval if a post is CW. The main use of CW is to directly invite others to edit the post. And yes, moderators can convert to community wiki, but I don't think that it necessary just because an answer is outdated. From a more general question on Meta.SO I answered a while ago: From the blog post on Community Wiki from Grace Note: The intent of community wiki in answers is to help share the burden of solving a question. An incomplete “seed” answer is a stepping stone to a complete solution with help from others; an incomplete question is a hindrance and an obstacle to getting a solution as no one understands the inquiry. It is in answers that the goal of community wiki, for the community, by the community, shows its truest colors. If you know that your answer is incomplete and you want to encourage other users to add information to it, you can make it CW to invite others to edit the answer. Since everyone can propose edits, community wiki is not necessary anymore for collaborative answers, so it has lost a lot of its usefulness. It is now more of an invitation for other users to edit, but it is not really a technical necessity anymore. It is rather used as a sign for others that you don't mind, and even encourage other users to edit the post. Many users hesitate to make big changes to posts belonging to other users, CW means you relinquish the sole ownership of the answer and encourage other users to add to the answer.
{ "pile_set_name": "StackExchange" }
Q: Computation between two large columns in a Pandas Dataframe I have a dataframe that has 2 columns of zipcodes, I would like to add another column with their distance values, I am able to do this with a fairly low number of rows, but I am now working with a dataframe that has about 500,000 rows for calculations. The code I have works, but on my current dataframe it's been about 30 minutes of running, and still no completion, so I feel what i'm doing is extremely inefficient. Here is the code import pgeocode dist = pgeocode.GeoDistance('us') def distance_pairing(start,end): return dist.query_postal_code(start, end) zips['distance'] = zips.apply(lambda x: distance_pairing(x['zipstart'], x['zipend']), axis=1) zips I know looping is out of the question, so is there something else I can do, efficiency wise that would make this better? A: Whenever possible, use vectorized operations in pandas and numpy. In this case: zips['distance'] = dist.query_postal_code( zips['zipstart'].values, zips['zipend'].values, ) This won't always work, but in this case, the underlying pgeocode.haversine function is written (in numpy) to accommodate arrays of x and y coordinates. This should speed up your code by several orders of magnitude for a dataframe of this size.
{ "pile_set_name": "StackExchange" }
Q: How do I create a function / procedure in MariaDB to run an update script when the table got accessed? I have some records in my DB with a special Status let's say t_status = 'T' and I want to update each t_status which has an t_moddate older than 45 minutes to t_status = 'X'. How can i put this into a stored procedure in Maria DB? My table looks like below: table name: Test columns: t_id,t_status,t_moddate,t_usr_update I guess my update is like below: UPDATE TEST SET t_status = 'X' where t_status = 'T' and t_moddate <= now()- interval(45 minutes); CREATE PROCEDURE myProc() BEGIN UPDATE TEST SET t_status = REPLACE (first_name, 'T', 'X') WHERE t_status = 'T' and t_moddate <= now()- interval 45 minute; END$$ But how do I get this into a stored procedure to let it run by default? A: You can use an EVENT run hourly or whatever interval you choose. First enable it SET GLOBAL event_scheduler = ON; Then write the event proper CREATE EVENT somename ON SCHEDULE EVERY '1' HOUR STARTS '2017-25-12 00:00:00' DO UPDATE TEST SET t_status = REPLACE (first_name, 'T', 'X') WHERE t_status = 'T' AND t_moddate <= now()- interval(45 minutes);
{ "pile_set_name": "StackExchange" }
Q: Word for large, short, wide, roundish, fat bottle What word would you use to describe a large, short, wide, roundish, fat bottle, the kind used for some wines: tubby or chubby? This kind of flask called growler would match my request, but I'd like to learn what adjectives could describe this shape. A: I would describe it as squat: b : marked by disproportionate shortness or thickness
{ "pile_set_name": "StackExchange" }
Q: Releasing a Team name I started creating a team. I used my company name. When I arrived to the second step I noticed I was logged in as my personal user instead of my work one. I did not finish the team creation. I logged out and logged back in with my work user, tried to create the team using the same name but now it tells me the name is not available. It seems to be reserved for my other user, even if I did not finish the process. Is there a way to release the team name from my personal user so my work user can create the team? Update: I noticed that after a few hours (12 more or less) the name was released. I am not sure if it was automatically (due to the team not being finished) or if it was due to an action taken by the Stack Exchange team. See next point. I contacted the Stack Exchange customer service team about this problem. They confirmed that there is no way of doing so from the user perspective. They mentioned they were going to ask their development team to work on this. After a few hours, they sent an update indicating the team name was release and I could try creating it from my work user. I am very pleased with the customer service response, but since this is not really a solution, I will leave the question open. A: You don't need to release your team name for creating the team on another account. Complete the following steps to create your team without releasing your team name. Create your team on your personal account. Now go to your team page. Click Settings from the sidebar. Go to the Invite tab. Click Invite members. Enter the email that you used sign up with the work account. Click Send invites. Check the mail that you used in step 6. for new messages. Open the new email from Stack Overflow For Teams and click the link to join the team. Log in if needed. Go to your personal account. Go to your team page. Click Settings from the sidebar. Go to the Manage tab. Find your work account from the list. Click the Member link/button near your account's name. Click Make Team Admin Click OK on the dialog box. Now switch to your work account. Click Settings from the sidebar. Go to the Manage tab. Find your personal account from the list. Click the Admin link/button near your account's name. Click Revoke Admin status Click OK on the dialog box. Click the Member link/button near your account's name. Click Deactivate user Click OK on the dialog box. Now you can use the team like if it was created on the work account. Note: The payment information and other contact information that you entered while creating the team will be associated with the team, not the account. But still it will be possible to see your personal account in the Deactivated tab.
{ "pile_set_name": "StackExchange" }
Q: Can the last row be center using isotope or masonry? I have a masonry grid, sometimes the last row has less than 4 items. I want the last row to be centered in the middle of my container. The number of items on the last row can change depending on the responsiveness of my page that's why I can not use CSS to identify the last row items. If someone has a solution please help. https://jsfiddle.net/oaoLuh4f/ $('.masonry').masonry({ itemSelector: '.masonry-brick', isFitWidth: true, animationOptions: { duration: 400 } }); $('.masonry').isotope({ itemSelector: '.masonry-brick', layoutMode: 'fitRows', }); $.each($(".masonry-brick"), function() { var blockHeight = $(this).outerHeight(); $(this).css({ "height": blockHeight }); }); $.each($('.masonry'), function() { var masonryWrapperWidth = $(this).outerWidth(); $('.masonry').css({ "width": masonryWrapperWidth, }); }); .masonry { margin: auto; } .masonry-brick { width: 150px; margin: 5px; color: #262524; } <script src="//cdnjs.cloudflare.com/ajax/libs/masonry/3.3.2/masonry.pkgd.min.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/jquery.isotope/2.2.2/isotope.pkgd.min.js"></script> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div class="masonry"> <div class="masonry-brick"> <img src="http://placehold.it/150x150" alt="" /> </div> <div class="masonry-brick"> <img src="http://placehold.it/150x200" alt="" /> </div> <div class="masonry-brick"> <img src="http://placehold.it/150x250" alt="" /> </div> <div class="masonry-brick"> <img src="http://placehold.it/150x100" alt="" /> </div> <div class="masonry-brick"> <img src="http://placehold.it/150x200" alt="" /> </div> <div class="masonry-brick"> <img src="http://placehold.it/150x250" alt="" /> </div> <div class="masonry-brick"> <img src="http://placehold.it/150x150" alt="" /> </div> <div class="masonry-brick"> <img src="http://placehold.it/150x250" alt="" /> </div> </div> A: I don't believe this is possible with Masonry. The reason is that masonry doesn't really work with "Rows"--it just tries to fit your blocks into free spaces. So while the specific width you used in your example makes it appear that there are two rows, if you change the width slightly you get this instead: If you tried to "center" the final block, it would mean that you're not fitting the pieces into the smallest space possible. This would often end up looking weird, and it would be going against the purpose of masonry. If you prefer evenly-distributed rows, rather than filling in gaps, you can probably use ordinary centered inline:block; elements instead.
{ "pile_set_name": "StackExchange" }
Q: Python and OpenCL issue I'm trying to run the following script: import silx from silx.image import sift from PIL import Image import numpy import scipy.ndimage from silx.opencl import ocl, pyopencl, kernel_workgroup_size img1 = numpy.asarray(Image.open('1.jpg')) img2 = numpy.asarray(Image.open('2.jpg')) alignPlan = sift.LinearAlign(img1, devicetype='GPU') img2_aligned = alignPlan.align(img2) But, get the following error which I'm not pretty sure what it means: X server found. dri2 connection failed! DRM_IOCTL_I915_GEM_APERTURE failed: Invalid argument Assuming 131072kB available aperture size. May lead to reduced performance or incorrect rendering. get chip id failed: -1 [22] param: 4, val: 0 X server found. dri2 connection failed! DRM_IOCTL_I915_GEM_APERTURE failed: Invalid argument Assuming 131072kB available aperture size. May lead to reduced performance or incorrect rendering. get chip id failed: -1 [22] param: 4, val: 0 cl_get_gt_device(): error, unknown device: 0 X server found. dri2 connection failed! DRM_IOCTL_I915_GEM_APERTURE failed: Invalid argument Assuming 131072kB available aperture size. May lead to reduced performance or incorrect rendering. get chip id failed: -1 [22] param: 4, val: 0 X server found. dri2 connection failed! DRM_IOCTL_I915_GEM_APERTURE failed: Invalid argument Assuming 131072kB available aperture size. May lead to reduced performance or incorrect rendering. get chip id failed: -1 [22] param: 4, val: 0 cl_get_gt_device(): error, unknown device: 0 X server found. dri2 connection failed! DRM_IOCTL_I915_GEM_APERTURE failed: Invalid argument Assuming 131072kB available aperture size. May lead to reduced performance or incorrect rendering. get chip id failed: -1 [22] param: 4, val: 0 cl_get_gt_device(): error, unknown device: 0 EDIT: Below is the "clinfo" output: X server found. dri2 connection failed! DRM_IOCTL_I915_GEM_APERTURE failed: Invalid argument Assuming 131072kB available aperture size. May lead to reduced performance or incorrect rendering. get chip id failed: -1 [22] param: 4, val: 0 X server found. dri2 connection failed! DRM_IOCTL_I915_GEM_APERTURE failed: Invalid argument Assuming 131072kB available aperture size. May lead to reduced performance or incorrect rendering. get chip id failed: -1 [22] param: 4, val: 0 cl_get_gt_device(): error, unknown device: 0 X server found. dri2 connection failed! DRM_IOCTL_I915_GEM_APERTURE failed: Invalid argument Assuming 131072kB available aperture size. May lead to reduced performance or incorrect rendering. get chip id failed: -1 [22] param: 4, val: 0 X server found. dri2 connection failed! DRM_IOCTL_I915_GEM_APERTURE failed: Invalid argument Assuming 131072kB available aperture size. May lead to reduced performance or incorrect rendering. get chip id failed: -1 [22] param: 4, val: 0 cl_get_gt_device(): error, unknown device: 0 Number of platforms 3 Platform Name NVIDIA CUDA Platform Vendor NVIDIA Corporation Platform Version OpenCL 1.2 CUDA 8.0.0 Platform Profile FULL_PROFILE Platform Extensions cl_khr_global_int32_base_atomics cl_khr_global_int32_extended_atomics cl_khr_local_int32_base_atomics cl_khr_local_int32_extended_atomics cl_khr_fp64 cl_khr_byte_addressable_store cl_khr_icd cl_khr_gl_sharing cl_nv_compiler_options cl_nv_device_attribute_query cl_nv_pragma_unroll cl_nv_copy_opts cl_nv_create_buffer Platform Extensions function suffix NV Platform Name Clover Platform Vendor Mesa Platform Version OpenCL 1.1 Mesa 17.0.7 Platform Profile FULL_PROFILE Platform Extensions cl_khr_icd Platform Extensions function suffix MESA Platform Name Intel Gen OCL Driver Platform Vendor Intel Platform Version OpenCL 1.2 beignet 1.3 (git-8bd8c3a) Platform Profile FULL_PROFILE Platform Extensions cl_khr_global_int32_base_atomics cl_khr_global_int32_extended_atomics cl_khr_local_int32_base_atomics cl_khr_local_int32_extended_atomics cl_khr_byte_addressable_store cl_khr_3d_image_writes cl_khr_image2d_from_buffer cl_khr_depth_images cl_khr_spir cl_khr_icd cl_intel_accelerator cl_intel_subgroups cl_intel_subgroups_short cl_khr_gl_sharing Platform Extensions function suffix Intel X server found. dri2 connection failed! DRM_IOCTL_I915_GEM_APERTURE failed: Invalid argument Assuming 131072kB available aperture size. May lead to reduced performance or incorrect rendering. get chip id failed: -1 [22] param: 4, val: 0 cl_get_gt_device(): error, unknown device: 0 Platform Name NVIDIA CUDA Number of devices 1 Device Name GeForce GTX 765M Device Vendor NVIDIA Corporation Device Vendor ID 0x10de Device Version OpenCL 1.2 CUDA Driver Version 375.66 Device OpenCL C Version OpenCL C 1.2 Device Type GPU Device Profile FULL_PROFILE Device Topology (NV) PCI-E, 01:00.0 Max compute units 4 Max clock frequency 862MHz Compute Capability (NV) 3.0 Device Partition (core) Max number of sub-devices 1 Supported partition types None Max work item dimensions 3 Max work item sizes 1024x1024x64 Max work group size 1024 Preferred work group size multiple 32 Warp size (NV) 32 Preferred / native vector sizes char 1 / 1 short 1 / 1 int 1 / 1 long 1 / 1 half 0 / 0 (n/a) float 1 / 1 double 1 / 1 (cl_khr_fp64) Half-precision Floating-point support (n/a) Single-precision Floating-point support (core) Denormals Yes Infinity and NANs Yes Round to nearest Yes Round to zero Yes Round to infinity Yes IEEE754-2008 fused multiply-add Yes Support is emulated in software No Correctly-rounded divide and sqrt operations Yes Double-precision Floating-point support (cl_khr_fp64) Denormals Yes Infinity and NANs Yes Round to nearest Yes Round to zero Yes Round to infinity Yes IEEE754-2008 fused multiply-add Yes Support is emulated in software No Correctly-rounded divide and sqrt operations No Address bits 64, Little-Endian Global memory size 2094923776 (1.951GiB) Error Correction support No Max memory allocation 523730944 (499.5MiB) Unified memory for Host and Device No Integrated memory (NV) No Minimum alignment for any data type 128 bytes Alignment of base address 4096 bits (512 bytes) Global Memory cache type Read/Write Global Memory cache size 65536 Global Memory cache line 128 bytes Image support Yes Max number of samplers per kernel 32 Max size for 1D images from buffer 134217728 pixels Max 1D or 2D image array size 2048 images Max 2D image size 16384x16384 pixels Max 3D image size 4096x4096x4096 pixels Max number of read image args 256 Max number of write image args 16 Local memory type Local Local memory size 49152 (48KiB) Registers per block (NV) 65536 Max constant buffer size 65536 (64KiB) Max number of constant args 9 Max size of kernel argument 4352 (4.25KiB) Queue properties Out-of-order execution Yes Profiling Yes Prefer user sync for interop No Profiling timer resolution 1000ns Execution capabilities Run OpenCL kernels Yes Run native kernels No Kernel execution timeout (NV) Yes Concurrent copy and kernel execution (NV) Yes Number of async copy engines 1 printf() buffer size 1048576 (1024KiB) Built-in kernels Device Available Yes Compiler Available Yes Linker Available Yes Device Extensions cl_khr_global_int32_base_atomics cl_khr_global_int32_extended_atomics cl_khr_local_int32_base_atomics cl_khr_local_int32_extended_atomics cl_khr_fp64 cl_khr_byte_addressable_store cl_khr_icd cl_khr_gl_sharing cl_nv_compiler_options cl_nv_device_attribute_query cl_nv_pragma_unroll cl_nv_copy_opts cl_nv_create_buffer Platform Name Clover Number of devices 0 Platform Name Intel Gen OCL Driver Number of devices 0 NULL platform behavior clGetPlatformInfo(NULL, CL_PLATFORM_NAME, ...) NVIDIA CUDA clGetDeviceIDs(NULL, CL_DEVICE_TYPE_ALL, ...) Success [NV] clCreateContext(NULL, ...) [default] Success [NV] clCreateContext(NULL, ...) [other] <error: no devices in non-default plaforms> clCreateContextFromType(NULL, CL_DEVICE_TYPE_CPU) No devices found in platform clCreateContextFromType(NULL, CL_DEVICE_TYPE_GPU) No platform clCreateContextFromType(NULL, CL_DEVICE_TYPE_ACCELERATOR) No devices found in platform clCreateContextFromType(NULL, CL_DEVICE_TYPE_CUSTOM) No devices found in platform clCreateContextFromType(NULL, CL_DEVICE_TYPE_ALL) No platform ICD loader properties ICD loader Name OpenCL ICD Loader ICD loader Vendor OCL Icd free software ICD loader Version 2.2.8 ICD loader Profile OpenCL 1.2 NOTE: your OpenCL library declares to support OpenCL 1.2, but it seems to support up to OpenCL 2.1 too. Do you have an idea on how I can solve this issue? Thanks. A: I had a similar problem and found a solution where removing the Beignet OpenCL driver solved the problem. sudo dnf remove beignet Where I found my solution
{ "pile_set_name": "StackExchange" }
Q: Spring Security 404 page for unauthenticated users I'm using Spring Boot and Thymeleaf. I have a custom 404 template page defined in src/main/resources/templates/error/404.html This works properly when users are logged in. However, when they are logged out, they do not get any type of 404 page, they just get redirected back to /login. I'm thinking my security configuration needs to change but not sure what. @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/","/register*","/resetPassword","/forgotPassword","/login","/404").permitAll() .antMatchers("/admin/**").hasAuthority("ADMIN").anyRequest() .authenticated().and().formLogin().loginPage("/login").failureUrl("/login?error") .defaultSuccessUrl("/dashboard").successHandler(successHandler) .usernameParameter("email").passwordParameter("password") .and().logout() .logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("/login?logout").and() .exceptionHandling().accessDeniedPage("/access-denied"); } @Override public void configure(WebSecurity web) throws Exception { web.ignoring().antMatchers("/error**","/resources/**", "/static/**", "/css/**", "/js/**", "/img/**"); } A: First of all I encourage you to use indentation when using java config to configure your security for your spring application. It helps with readability. Note all top level methods on the first indentation (authRequest,formLogin,logout) all configure/update the HTTP object it self. All these elements are from the org.springframework.security.config.annotation.web.builders.HttpSecurity class. The children of these classes further refine the HTTP security configuration. http .authorizeRequests() .antMatchers("/","/register*","/resetPassword","/forgotPassword","/login","/404") .permitAll() .antMatchers("/admin/**").hasAuthority("ADMIN") .anyRequest().authenticated() // <-------- .and() .formLogin() .loginPage("/login") .failureUrl("/login?error") .defaultSuccessUrl("/dashboard") .usernameParameter("email").passwordParameter("password") .and() .logout() .logoutRequestMatcher(new AntPathRequestMatcher("/logout")) .logoutSuccessUrl("/login?logout") .and() .exceptionHandling() .accessDeniedPage("/access-denied"); Note .anyRequest().authenticated() is specifically stating that any request must be authenticated. So when you attempt to goto any missing url on your domain it will ask you to login rather than goto the 404 page. So if you remove that statement it and then try an goto a missing url page it will redirect you to a 404 page.
{ "pile_set_name": "StackExchange" }
Q: C# How to get a list of defined preprocessor? I know I can check if a preprocessor directive is defined using the #if syntax. But I want to get a list of defined preprocessor directives to pass it over to a realtime compiling using CSharpCodeProvider Thanks for advance. A: I don't think that is possible. Related. The compiler itself doesn't know about preprocessor. It receives already preprocessed code so there is no reason to remember what directives were defined.
{ "pile_set_name": "StackExchange" }
Q: Rails uniq pair I am trying to get a the unique elements from a relation but they are distinguished by pairs of IDs. The following example illustrates what I want to do: array.uniq {|post| post.a_id && post.b_id } Unfortunately, the above will only return me the elements which have both a unique a_id and b_id. That is not want I want. I would like it to return me the unique pairs of those. Therefore, if I had the following posts with a_id and b_id respectively (shown below), I want it to return only post1, post3 and post4. post1 1 2 post2 1 2 post3 1 3 post4 2 3 Thanks in advance for all of the help. A: Is this what you are looking for? array.uniq {|post| [ post.a_id, post.b_id ] }
{ "pile_set_name": "StackExchange" }
Q: Scope Issue Javascript (self, this) //Code starts var self = this; var a=10; function myFunc(){ this.a = 4; var a = 5; console.log("this.a -> " + this.a); //Output: this.a -> 4 console.log("self.a -> " + self.a); //Output: self.a -> undefined console.log("a -> " + a); //Output: a -> 5 } myFunc(); //Code ends Can someone please explain the Output of the above console.log statements. Thank You. A: In Javascript, every scope level has a this. When you save this in the var self outside of any function (top level), it gets the window object. So the first this (stored in self) is different from the one in the function. No property "a" was defined on the top level, so self.a is undefined. Now there is a difference between a variable (var) and a propery (obj.prop). The first one will be resolved from scopes (if a is not defined in the current scope, it will search if it is defined in higher scopes, until it finds window where "global vars" are, and comes undefined if still not found). The second one will search the property through the prototype chain.
{ "pile_set_name": "StackExchange" }
Q: Throttling MSMQ messages / prioritising messages I'm not sure how best to describe this, or the best title, so bear with me! I'm using MSMQ to queue up a large number of commands that will fire off HTTP requests to various websites and APIs. In order to avoid hammering these services (and to stay within certain pre-defined request limits) I need to ensure tasks hitting the same domain are executed only after a minimum time has elapsed from the last request. Previously I was using a database to queue the tasks, and so could perform a query to achieve this, but we rapidly outgrew that solution with the number of tasks (way too many deadlocks on the table). Does anyone have any suggestions as to what approach we could take? I've considered just keeping taking items off the queue until you find one that you can execute - but I'm conscious there's nothing to stop the ordering on the queue meaning we could take off thousands for the same domain before finding one on a different domain. Thanks! A: Erm, I disagree completely with the sentiments Remus Rusanu's answer. MSMQ is not in any way a step down from a database table, and in many ways can be a step up, which if you required them, you'd need to build manually for a table based solution. See MSMQ v Database Table In saying that, for your requirements the database table seems to be the best fit. MSMQ is good for communication between apps you dont own if you dont require immediate results, and need reliable delivery (i.e. you can use MSMQ while disconnected from the DB, whereas to use the table approach you need DB access.) MSMQ can be load balanced A: You 'outgrew' relational database and replace it with MSMQ? This is like 'promoting' from college to kindergarten! 4GB size limitation, no high availability solution, questionable recoverability, no querying of the message queue, you are already running into the very limitations than everyone is claiming when moving away from MSMQ to a relational database based queuing... I highly recommend you go back to the table based queuing. There are ways to avoid deadlocks in table based queuing, specially with the advent of OUTPUT clauses for DELETE (which is the key to write a fast deadlock free dequeue operation from a table based queue). Or you can use an off-the-shelf in database queuing solution like Service Broker. Actually SSB would offer a free lunch with many of its features, like built-in throttling (MAX_QUEUE_READERS), enable/disable processing on a schedule (by enabling/disabling activation), built-in timers for retry, high-availability based on database mirroring or on clustering, or built-in priority handling.
{ "pile_set_name": "StackExchange" }
Q: Check if substring of a string is substring of another string I have two strings $Str1 = "A B C D E F G H I J"; $Str2 = "1 2 C D E P Q R"; Now I have to check that a substring of $Str2 exits in $Str1. For example in this case C D E. This is a basic and simple example. I am having complex cases and data in both strings is dynamic. If I would had to compare complete string the strpos was the solution but what to do in this case? A: This function should work any Strings function test($str1, $str2) { for ($i = strlen($str1); $i != 0; $i--) { for ($x = 0; $x < strlen($str1) - $i; $x++) { if (($pos = strpos($str2, substr($str1, $x, $i + 1))) !== false) { return substr($str1, $x, $i + 1); } } } return null; } It returns the biggest possible match or null. $str1 = "Sed ut perspiciatis unde omnis iste natus error sit voluptatem"; $str2 = "Sed ut perspiciatis undeT omnis iste natus error sit voluptatem"; echo test($str1, $str2); // omnis iste natus error sit voluptatem
{ "pile_set_name": "StackExchange" }
Q: Can't stop animation on last frame I'm trying to play a character jumping animation which I want to stop on last frame, but it does not stop. I tried using animation-fill-mode: forwards; with no result. Below is the code I'm using .kia-jump { width: 320px; height: 464px; position: absolute; top: 1%; left: 41%; background: url('../images/activity/KiaJumpingAnimation.png') left center; animation-fill-mode: forwards; animation: jumpAnim 1.67s steps(24) 1; } @keyframes jumpAnim { 100% { background-position: -7920px; } } Here's the link to the JSFiddle -> https://jsfiddle.net/k4rz5tdy/ A: You actually have one extra step and as your background is set as repeat by default, it just go back to the first frame at the end. .kia-jump { width: 320px; height: 464px; position: absolute; top: 1%; left: 41%; background: url('http://schoolcinema-sconline.rhcloud.com/images/activity/KiaJumpingAnimation.png') left center; animation: jumpAnim 1.67s steps(23) 1 forwards; } @keyframes jumpAnim { 100% { background-position: -7590px; } } Just did 7920 - (7920/24) = 7590 https://jsfiddle.net/RedBreast/k4rz5tdy/2/
{ "pile_set_name": "StackExchange" }
Q: How many puranas are there and is there any full list mentioned in any of the scriptures How many "puranas" are there? Are there any authentic full list of all the puranas (not just 18 mahapuranas) backed by some other puranas or scriptures? A: For the Puranas and Upapuranas- we get their names in the Devi Bhagavata Purana. There are 18 Puranas and 18 Upapuranas. 1-11. Sûta said :-- “O best of the Munis! I am now telling you the names of the Purânas, etc., exactly as 1 have heard from Veda Vyâsa, the son of Satyavati; listen. The Purâna beginning with "ma" are two in number; those beginning with “bha” are two; those beginning with “bra" are three; those beginning with "va” are four; those beginning respectively with “A”, “na”, “pa”, “Ling”, “ga”, “kû” and “Ska” are one each and “ma” means Matsya Purâna, Mârkandeya Purâna; “Bha” signifies Bhavisya, Bhâgavat Purânas; “Bra” signifies Brahmâ, Brahmânda and Brahmâvaivarta Purânas; “va” signifies Vâman, Vayu, Visnu and Varaha Purânas; “A” signifies Agni Purâna; “Na” signifies Narada Purâna; “Pa” signifies Padma Purâna; “Ling” signifies Linga Purânam; “Ga” signifies Govinda Purânam; Kû signifies Kurma Purâna and “Ska” signifies Skanda Purânam. These are the eighteen Purânas. O Saunaka! In the Matsya Purâna there are fourteen thousand slokas; in the wonderfully varied Markandeya Purânam there are nine thousand slokas. In the Bhavisya Purâna fourteen thousand and five hundred slokas are counted by the Munis, the seers of truth. In the holy Bhâgavata there are eighteen thousand S’lokas; in the Brahmâ Purâna there are Ajuta (ten thousand) S’lokas. In the Brahmânda Purâna there are twelve thousand one hundred S’lokas; in the Brahmâ Vaivarta Purânam there are eighteen thousand S’lokas. In the Vaman Purâna there are Ajuta (ten thousand) S’lokas; in the Vayu Purânam there are twenty-four thousand and six hundred S’lokas; in the greatly wonderful Visnu Purâna there are twenty-three thousand S’lokas; in the Agni Purânam there are sixteen thousand S’lokas; in the Brihat Narada Purânam, there are twenty-five thousand S’lokas, in the big Padma Purâna there are fifty-five thousand s'lokas; in the voluminous Linga Purâna eleven thousand s’lokas exist; in the Garuda Purânam spoken by Hari nineteen thousand s'lokas exist; iu the Kurma Purâna, seventeen thousand s'lokas exist and in the greatly wonderful Skanda Purâna there are eighty-one thousand s'lokas, O sinless Risis! Thus I have described to you the names of all the Purânas and the number of verses contained in them. Now hear about the Upa Purânas. Upapuranas' names are as follows: 12-17. The first is the Upapurâna narrated by Sanat Kumâra; next comes Narasimha Purâna; then Naradiya Purâna, S’iva Purâna, Purâna narrated by Durvasa, Kapila Purâna, Manava Purâna, Aus’anasa Purâna, Varuna Purâna. Kalika Purâna, Samva Purâna, Nandi Kes’wara Purâna, Saura Purâna, Purâna spoken by Parâs’ara, Âditya Purâna, Mahesvara Purâna, Bhâgavata and Vasistha Purâna. These Upa Purânas are described by the Mahatmas. From the Purana's Book 1, Chapter 3. For, the Upanishads, a minor Upanishad, called the Muktika (linked to the Shukla Yajurveda), gives a list of 108 of them: The only means by which the final emancipation is at tained is through Mandukya-Upanishad alone, which is enough for the salvation of all aspirants. If Jnana is not attained thereby, study the 10 Upanishads; thou shalt soon attain Jnana, and then My Seat. son of Anjana, if thy Jnana is not made firm, practise (study) well the 32 Upanishads. Thou shalt get release. If thou longest after Videhamukti (or disembodied salvation), study the 108 Upanishads. I will truly state in order the (names of the) Upanishads with their S anti (purificatory Mantras). Hearken to them. (They are:) Is a, Kena, Katha, Prasna, Munda, Alandukya, Tittiri, Aitareya, Chhandogya, Brhadaranyaka, Brahma, Kaivalya, Jabala, S wetas watara, Hamsa, Arum, Garbha, Narayana, (Parama) -Hamsa, (Amrta)-Bindu, (Amrta)- Nada, (Atharva)-Sira, (AtharvaJ-Sikha, Maitrayani, Kaushitaki, (Brhat) Jabala, (Narasihma) -Tapani, Kiilagnirudra, Maitreyi, Subala, Kshurika, Mantrika, Sarvasara, Niralamba, (Suka)- Rahasya, Vajrasuchika, Tejo-(Bindu), Nada-(Bindu), Dhyana- (Bindu), (Brahma) -Vidya, Yoga-Tattwa, Atmabodhaka, Farivrat (Narada-Parivriijaka), (TraS ikhi, Sita, (Yoga)-Chuda-(Mani) Nirvana, Mandala-(Brahmana), pakshina-(Murti), Sarabha, Skanda, (Tripadvibhuti)-Maha-Narayana, Adwaya-(Taraka), (Rama)-Rahasya, (Rama) -Tapani, Vasudeva, Mudgala, S andilya, Paingala, Bhikshu, Mahat-Srariraka, (Yoga)-S ikha, Furiyatlta, Sannyasa, (Paramahamsa)-Parivrajaka, Akshamalika, Avyakta, Ekakshara, (Anna)-Purna, Surya, Akshi, Adhyatma, Kundika, Savitr, lAtma, Pas upata, Parabrahma, Avadhuta, Tripuratapani, Qe vi, Tripura, Kara, Bhavana, (Rudra) -Hrdaya, (Yoga) -Kundalini, Bhasma-(Jabala) Rudraksha, Ganapati, Darsana, Tarasara, Mahavakya, Panchabrahma, (Prana)-Agnihotra, Gopala-Tapani, Krshna, Yajnavalkya, Varaha, Satyayani, Hayagrlva, Dattatreya, Garuda, Kali-(Santarana), Jabala, Soubhagya, Saraswatirahasya, Bahvricha, and Muktika. These 108 (Upanishads) are able to do away with the three Bhavanas [of doubt, vain thought, and false thought] , conferring Jyana and Vairagya, and destroying the three Vasanas [of book-lore, world and body] . From the Muktika Upanishad's 1st chapter.
{ "pile_set_name": "StackExchange" }
Q: LINQ join query returning null I've three tables. Table A id name des table2 table3 1 xyz TableA_des1 null 1 2 abc TableA_des2 1 2 3 hgd TableA_des2 2 3 Table B id name des Active 1 xyz TableB_des1 1 2 abc TableB_des2 1 3 hgd TableB_des2 1 Table C id name des Active 1 xyz TableC_des1 1 2 abc TableC_des2 1 3 hgd TableC_des2 1 LINQ Query var res = (from a in TableA where id = 1 join b in TableB on a.table2 equals b.id into ab from bdata in ab.DefaultIfEmpty() where bdata.Active = true join c in TableC on a.table3 equals c.id into ac from cdata in ac.DefaultIfEmpty() where cdata.Active = true select new { data1 = a.name, data2 = bdata?? string.Empty, data3 = cdata?? string.Empty}) The about query is giving null. On debugging variable res has null. A: You should avoid putting where conditions on range variables coming from the right side of a left outer join, because doing so effectively turns them into inner join. Instead, you should either apply the right side filtering before the join: from a in TableA where id = 1 join b in TableB.Where(x => a.Active) on a.table2 equals b.id into ab from bdata in ab.DefaultIfEmpty() join c in TableC.Where(x => x.Active) on a.table3 equals c.id into ac from cdata in ac.DefaultIfEmpty() ... or include them in the join (when possible): from a in TableA where id = 1 join b in TableB on new { id = a.table2, Active = true } equals new { b.id, b.Active } into ab from bdata in ab.DefaultIfEmpty() join c in TableC on new { id = a.table3, Active = true } equals new { c.id, c.Active } into ac from cdata in ac.DefaultIfEmpty() ... In order to understand why is that, try to evaluate where bdata.Active == true when bdata is null (i.e. there is no matching record). Actually if this was LINQ to Objects, the above criteria will generate NullReferenceException. But LINQ to Entities can handle that w/o exceptions, since databases naturally support null values in queries for a columns which are normally non nullable. So the above simple evaluates to false, hence is filtering the resulting record and effectively removing the effect of a left outer join which by definition should return the left side record regardless of whether a matching right side record exists. Which means that actually there is a third way (althought the first two options are preferable) - include an explicit null checks: from a in TableA where id = 1 join b in TableB on a.table2 equals b.id into ab from bdata in ab.DefaultIfEmpty() where bdata == null || bdata.Active join c in TableC on a.table3 equals c.id into ac from cdata in ac.DefaultIfEmpty() where cdata == null || cdata.Active ...
{ "pile_set_name": "StackExchange" }
Q: How to get flushleft to the page margin within enumerate environment? How do I get the headings to come to the page margin inside of the enumerate envirnoment. \documentclass{article} \usepackage{lipsum} \begin{document} \begin{flushleft} Heading \end{flushleft} \begin{enumerate} \item \lipsum[10] \begin{flushleft} Heading \end{flushleft} \item \lipsum[10] \noindent\begin{flushleft} Heading \end{flushleft} \item \lipsum[10] \end{enumerate} \end{document} A: Try for instance this. \documentclass{article} \usepackage{lipsum} \usepackage{enumitem} \begin{document} \begin{flushleft} Heading \end{flushleft} \begin{enumerate} \item \lipsum[10] \end{enumerate} \begin{flushleft} Heading \end{flushleft} \begin{enumerate}[resume] \item \lipsum[10] \end{enumerate} \begin{flushleft} Heading \end{flushleft} \begin{enumerate}[resume] \item \lipsum[10] \end{enumerate} \end{document} Note also that using flushleft for headings is not necessarily the best possible idea.
{ "pile_set_name": "StackExchange" }
Q: MVVM and Role Based Security I have a silverlight application (MVVM) with a view that will be used by multiple roles within the application, the accessibilty of certain ui controls in the view is dependant on the users role. How should this be managed within the view model? Are there any object patterns that I should be considering? Any ideas/guidance would be greatly appreciated. A: The first idea that comes to mind is to have properties in your ViewModel that correspond to whether or not the current user has the ability to perform certain operations. For example: public bool CanChangeDisplayName { get { bool result = SomeMechanismToDetermineUsersAbilityToPerformAction(); return result; } } Then you could bind the IsEnabled (or IsReadOnly or Visibility) property on the appropriate controls on your View to this property. Like: <TextBox IsReadOnly="{Binding CanChangeDisplayName}" Text="{Binding DisplayName}"/> I hope this helps!
{ "pile_set_name": "StackExchange" }
Q: Existence of Limits, $P_n/P_{n+1}$ and $P_{n+1}/P_n$. Was curious about this question, can't seem to find this on the internet, perhaps my googling skills are rustly lol Let $(P_k)_{k\geq1}$ be the sequence of prime numbers where the $k$-th term represents the $k$-th prime. So we have $(P_k)_{k\geq1}=2,3,5,7,11,13,\dots$ and so on. Now, consider the limits \begin{align*} \lim_{n\to\infty}\dfrac{P_n}{P_{n+1}}\text{ and }\lim_{n\to\infty}\dfrac{P_{n+1}}{P_{n}}. \end{align*} Does either one of these limit exists? I know as number gets larger, the gap between primes gets larger in general but is the gap close enough between consecutive prime numbers in a way that these limits approaches, say $1$? 1, If we can show there exists, say our favorite greek symbol $\delta$, such that between any $n\in\mathbb{N}$, we can always find some prime number $p_i\in(n-\delta,n+\delta)$, then this limit obviously approaches 1. But I don't think we can assume such thing. 2, Recall some theorem showed that between any $n$ and $2n$ (perhaps with some kind of limitation) there is a prime between them, so that means if the limit exists, then $\lim_{n\to\infty}\dfrac{P_n}{P_{n+1}}$ is bounded below by $1/2$ and the other one bounded above by $2$. A: It should exist and should be well-known. Here is a sloppy calculation. Recall that by PNT, $\pi(n)=\frac{n}{\ln n}(1+o(1))$. Thus, $n^{th}$ prime $p_n$ is roughly of order $n\ln n$. It then follows that, $\frac{p_{n+1}}{p_n}= \frac{p_{n+1}}{(n+1)\ln (n+1)}\frac{(n+1)\ln (n+1)}{n\ln n}\frac{n\ln n}{p_n}$ has the limit one, since $\frac{p_{n+1}}{(n+1)\ln(n+1)}=1+o(1)$ and $\frac{n\ln n}{p_n}=1+o(1)$.
{ "pile_set_name": "StackExchange" }
Q: Hidden parent stylesheet? Please follow those steps: CurrentValue[EvaluationNotebook[], ScreenStyleEnvironment] = "SlideShow" SetOptions[ EvaluationNotebook[], StyleDefinitions -> Notebook[{ Cell[StyleData["Notebook"], DockedCells -> {Inherited, Inherited, Cell[TextData["TEST"]]}] }, StyleDefinitions -> "Reference.nb" ]] As you can see, those double slideshow toolbars are inherited from somewhere even though there is no reference to Core/Default in StyleDefinitions. Where are they from? A: The FE always opens the stylesheet named in the DefaultStyleDefinitions option at the global level. In certain failsafe cases, it will fall back to this stylesheet if style definitions can't be found anywhere else. The one case I know for certain(*) where this happens is if the FE followed a stylesheet chain all the way to the end looking for stylename, and that end was not "Core.nb". There might be other cases, too, but if so, they're probably much less interesting for your purposes. (*) To clarify, this means that I reminded myself by looking at the source code...I've not tried to run confirmational experiments, and if you find something slightly different, it's possible there's something I'm overlooking.
{ "pile_set_name": "StackExchange" }
Q: Fill out rest of screen I want a simple page where i have a main section and a left sidebar with two sections. I dont know the height of the top section, and I want to bottom section to fill out the rest of the screen. As you can see on the fiddle below (try to resize the window if you cant see the sidebar), height 100% sets the hight of the bar plus the it own height and I want it to only fill out the rest of the space. I found other questions in here where people propose to use vh minus top bar, but I dont know the hight of the top bar. Is there other options? Notice the bottom section must support scrolling if content exeeds the screen height. https://jsfiddle.net/segato/agprcbg0/2/ html, body, .wrapper, .wrapper-inner, .sidebar, .main { height: 100%; } A: You can do it with the Flexbox. The whole point is to make the #bottom div flexible so that it can take up all the remaining vertical space. Updated Fiddle
{ "pile_set_name": "StackExchange" }
Q: Chiral coupling in string-nets In Xiao-Gang Wen's review of topological order http://arxiv.org/abs/1210.1281 , he states in footnote 52 that string-nets are so far unable to produce the chiral coupling between the SU(2) gauge boson and the fermions. Is it known how this chiral coupling can be expressed in lattice gauge theory, and the remaining question is one of emergence; or is it the case that its expression in lattice gauge theory is unknown, analogous to the chiral fermion question which took many years to solve? A: The chiral-fermion/chiral-gauge-theory problem is solved: any anomaly-free chiral gauge theories can be put on lattice by simply turning on a proper interaction. See my new papers http://arxiv.org/abs/1305.1045 and http://arxiv.org/abs/1303.1803 As a result, the string-net theory can also produce the coupling between the SU(2) gauge boson and the chiral fermions.
{ "pile_set_name": "StackExchange" }
Q: Android: Updating a menu item programmatically results in NullPointerException I am working on a RecylcerView and CardView. The cards contain ImageView. I also have an menu-item that is declared as an action and whose title is set to 0. What I want to achieve is that when I click on the image its position should be added to an array and the title of menu-item should be the size of array. Below is the my menu.xml code: <menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" tools:context=".MainActivity"> ... <item android:id="@+id/action_down_list" android:title="@string/action_down_list" android:orderInCategory="100" app:showAsAction="withText|always" android:icon="@drawable/ic_action_download" /> </menu> Below is the Adapter class code from which I am running the onClickListner code: public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> { List<String> abc = new ArrayList<String>(); ... @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { ... viewHolder.imgView.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View view) { String img_id = images.get(viewHolder.getAdapterPosition()); MenuItem dl_menu = (MenuItem) view.findViewById(R.id.action_down_list); abc.add(img_id); dl_menu.setTitle(Integer.toString(abc.size())); return true; } }); } } But when I run my program it gives an java.lang.NullPointerException. I have different kinds of method but still no solution. A: The problem is in this line. MenuItem dl_menu = (MenuItem) view.findViewById(R.id.action_down_list); You tried to find a menu item in view that does not have it. There is no easy way to get access to menu from adapter. Easiest way in your situation is to create in your adapter a set method for menu, public void setMenu(Menu menu){ this.menu = menu; } and call it for your adapter in onCreateOptionsMenu callback, be sure that your adapter initialized before it. After that you could write: public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> { List<String> abc = new ArrayList<String>(); Menu menu; ... @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { ... viewHolder.imgView.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View view) { String img_id = images.get(viewHolder.getAdapterPosition()); MenuItem dl_menu = menu.findItem(R.id.action_down_list); abc.add(img_id); dl_menu.setTitle(Integer.toString(abc.size())); return true; } }); But a preferred way from my point of view is using smth like LocalBroadcastManager to send to Activity or Fragment an intent with information what should be done with a menu item. So in this way adapter will don't have direct access to menu.
{ "pile_set_name": "StackExchange" }
Q: Are answers hiding marketing considered as spam I stumbled upon this answer: Custom gcc preprocessor. While the answer contains some relevant information, the answer tries to promote a specific product, and could be considered as spam. The moderator did not think so. Is it the phrase DMS is kind a a big hammer for this task. That saves the post? A: We have rules for this. Minimally, you must: Disclosure your affiliation with the product or service. Provide an answer that is relevant to the question and actually solves the problem. Ira is doing both of those things here, so this answer is not spam. It is self-promotion, but it is not unsolicited self-promotion, which is what is required for something to be spam. pachanga asked the question (the solicitation) and Ira provided a relevant solution that he just so happens to have created. The only guideline that you might possibly say is being violated here is the one that cautions, "Don't talk about your product / website / book / job too much." Granted, Ira does tend to post a lot of answers that promote his product(s). This is something that has been discussed previously, ad nauseam, and the moderators have been in contact with him about it. As suraj comments, his profile even indicates that he is aware of the problem. But the answer you have selected here is not emblematic of any sort of a problem, and it is clearly not spam. If you disapprove of it or think it is not helpful, feel free to downvote it. BTW, no, that phrase you quoted has nothing to do with it. If anything, the key phrase is "Our DMS Software Reengineering Toolkit is a such a system", where he discloses that it is his product and says that it solves the problem. The rest of the answer goes on to explain how. (And then, strangely, conclude that this is a relatively poor solution, but oh well.)
{ "pile_set_name": "StackExchange" }
Q: More user data from firebase_auth plugin in Flutter I have implemented firebase auth (through Google) on Flutter, but I cannot seem to be able to retrieve more user data other than email, picture and name. I'm interested in age and sex of users. Also, I don't know why but also on the firebase dashboard those data don't seem to be retrieved after login. A: Unfortunately Firebase doesn't provide these information, for retrieving that, you can use the ID that you retrieved after the login with external services. E.g. for gender you can use https://developers.google.com/people/ API. Flutter seems like a package that is developed by Google Engineers, for Google APIs including people, you can use it. (I haven't done this operation on Flutter, I know it from Android.) If you are familiar with Android you can check this question and answers.
{ "pile_set_name": "StackExchange" }
Q: If "yet" means "and despite that", then what word means "and partially owing to that"? The child is only 4 years old, yet it can already talk. The child is only 4 years old, and, despite this, it can already talk. The child is only 4 years old, and, at least partially owing to its young age, doesn't have such great balance. How do I make the last sentence more concise? As a sidenote, is it not correct to refer to the subject "child" as "it"? A: To be parallel to "The child is only 4 years old, yet it can already talk," I would like to suggest naturally as a hint that at least the consequence is partially owing to the mentioned fact. Thus, for your example, The child is only 4 years old, naturally it doesn't have such great balance. If the consequence is definitive or certain, the words thus, hence, and so, could be used. To tone the certainty down a little, words such as inevitably, unavoidably, and naturally are more appropriate.
{ "pile_set_name": "StackExchange" }
Q: Which of the subsets of $\mathbb{R}^6$ are connected? Let $X$ be the space of all real polynomials $a_5t^5 +a_4t^4 +a_3t^3+a_2t^2+ a_1t +a_0$ of degree at most $5$. We may think of $X$ as a topological space via its identification with $\mathbb{R}^6$ given by: $a_5t^5 +a_4t^4 +a_3t^3+a_2t^2+ a_1t +a_0\to (a_5,a_4,a_3,a_2,a_1,a_0)$. Which of the following subsets of $X$ is connected? (a) All polynomials in X that do not vanish at $t = 2$. (b) All polynomials in X whose derivatives vanish at $t = 3$. (c) All polynomials in X that vanish at both $t = 4$ and $t = 5$. (d) All polynomials in X that are increasing (as functions from $\mathbb{R}$ to $\mathbb{R}$). Answer- Option a is disconnected. Let $A$ be the subset of polynomials in X that do not vanish at $t = 2$. Consider $\psi: X \to \mathbb{R}$ defined by $\psi(f(x))=f(2)$. Clearly $\psi$ is a continuous map being an evaluation map. Note that $\psi(A)=\mathbb{R}/\{0\}$ which is a disconnected set. Therefore, $A$ must be disconnected otherwise $\psi(A)$ is also connected being continuous image. Please help how to solve options b, c and d. A: The set from (b) is connected (and even path-connected): if $f$ and $g$ belong to it and if $t\in[0,1]$, $\bigl((1-t)f+tg\bigr)'(3)=0$ too. For (c), use the fact that that is is $\{(p(t)(t-4)(t-5)\mid\deg p(t)\leqslant 3\}$. And the set from (d) is path-connected, by the same argument that I used for (b).
{ "pile_set_name": "StackExchange" }
Q: While loop in Async task block the execution of another Async task I have started two services in an activity named StartServiceActivity. In the On create method of the StartServiceActivity I have started two services, service 1 and service 2. The services are creates successfully. On the onstart method of service 1 I have started an asynTask1. The asynTask1 executed successfully and entered into the doInBackGround() In the doInbackground() of asynctask1(service1) I have created a while(true){ On start method of service2 I have started an asynTask2. Then I trying to start asynTask2 but it failed to start. The doInBackground() of asynTask2 is not being executed When I comment the while(true){ in asynTask1 both asynTask1 and asynTask2 is started. I want to execute async1 and asyn2 with while(true). A: The reason is because AsyncTasks run in serial order i.e. one after another. Take a look at Order of execution here. So what is happening is: There is a while loop in the task1 which runs first. The while loop doesn't finish so the task2 doesn't get turn to be executed. Solution: You need to set the executor for the AsyncTask manually so that the default (serial) executor is not used. Do something like: if (Build.VERSION.SDK_INT >= 11) { //--post GB use serial executor by default -- task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } else { //--GB uses ThreadPoolExecutor by default-- task.execute(); } Take a look at this link
{ "pile_set_name": "StackExchange" }
Q: Typescript redux connected component type error I am trying to merge state from redux into properties in a react component defined in a tsx file. I have defined the type LoggedInUserState elsewhere, it is exported like this in its file: import { Action, Reducer } from 'redux'; // ----------------- // STATE - This defines the type of data maintained in the Redux store. export interface LoggedInUserState { userName: string, isAdmin: boolean, isUserManager: boolean } This is my tsx file: import * as React from 'react'; import { connect } from 'react-redux'; import { LoggedInUserState } from 'ClientApp/store/LoggedInUser'; import { NavLink } from 'react-router-dom'; export interface LinkProps { routeTo: string, name: string, glyphIcon: string } interface LoginStateProps { isAuthenticated: boolean } type ExpandedAuthProps = LinkProps & LoginStateProps; class AuthenticatedLink extends React.Component<ExpandedAuthProps, null> { public render() { return this.props.isAuthenticated ? <NavLink exact to={this.props.routeTo} activeClassName='active'> <span className={this.props.glyphIcon}></span> {this.props.name} </NavLink> : <NavLink exact to={'/loginUser'} activeClassName='active'> <span className='glyphicon glyphicon-ban-circle'></span> {this.props.name} </NavLink>; } } function mapStateToProps(state: LoggedInUserState, originalProps: LinkProps): ExpandedAuthProps { return { routeTo: originalProps.routeTo, name: originalProps.name, glyphIcon: originalProps.glyphIcon, isAuthenticated: state.userName != '' } } export default connect<LoggedInUserState, {}, LinkProps> (mapStateToProps)(AuthenticatedLink) as typeof AuthenticatedLink; TypeScript shows the following type error on the final line (mapStateToProps) of my tsx file: Argument of type '(state: LoggedInUserState, originalProps: LinkProps) => ExpandedAuthProps' is not assignable to parameter of type 'MapStateToPropsParam'. Type '(state: LoggedInUserState, originalProps: LinkProps) => ExpandedAuthProps' is not assignable to type 'MapStateToPropsFactory'. Types of parameters 'originalProps' and 'ownProps' are incompatible. Type 'LinkProps | undefined' is not assignable to type 'LinkProps'. Type 'undefined' is not assignable to type 'LinkProps'. What is wrong with the declarations? A: I can't reproduce the error you got; I get a different one. This compiles for me: export default connect(mapStateToProps)(AuthenticatedLink); If I understand react-redux correctly, you shouldn't be asserting the result back to typeof AuthenticatedLink. The whole point of the connect is that it changes the props type of the component from ExpandedAuthProps to LinkProps because the LoginStateProps part is supplied by your mapStateToProps function.
{ "pile_set_name": "StackExchange" }
Q: Android: Launch app from app installer will cause several instances? 1.install an apk from app installer 2.then just click "OPEN" to launch it at once 3.after the app launched and then press HOME key 4.find the app from app list and click its icon to launch again 5.then the app will be launched with a new instance. And if you repeat 3~5 several times, it will repeat create a new instance. if you press "BACK" key now, you will see the app is still there for the same times you launched. But if you just click "DONE" at step 2 and then launch the app from app list, everything will be OK then. Why? A: The app installer (as well as many Android IDEs) use different intent flags than the regular app launcher does, which means that the launcher's intent doesn't properly match with the Activity's existing intent and it ends up creating a new activity on top of the stack. I think this question is similar to what you're asking about: Activity stack ordering problem when launching application from Android app installer and from Home screen
{ "pile_set_name": "StackExchange" }
Q: Can you solve $\frac{dy}{dx}=(1-x)y^2+(2x-1)y-x$? $$\frac{dy}{dx}=(1-x)y^2+(2x-1)y-x$$ This is a form of riccati differential equation, which can be reduced to Bernoulli's equation if one particular solution is given. Here $y=1$ is a given solution. Hence the general solution must be in the form $y=1+z$ for some $z(x)$, but substituting this in main equation gives $$\frac{dz}{dx}+z^2x=z^2+z$$ Which is not in the form of Bernoulli equation. Please help ! Also $$2x^2\frac{dy}{dx}=(x-1)(y^2-x^2)+2xy$$ This is asked in the problem section of bernoulli's differential equation but i have no idea how to solve this. A: Bernoulli's equation has form, $$ \frac{dy}{dx}+p(x)y=q(x)y^n $$ Now, consider this, $$ \frac{dz}{dx}+z^2x=z^2+z $$ This easily simplifies to, $$ \frac{dz}{dx}-z=(1-x^2)z^2 $$ where $p(x)=-1$ and $q(x)=1-x^2$ . And similarly other one simplifies to, $$ 2x^2\frac{dy}{dx}=(x-1)(y^2-x^2)+2xy $$ $$ 2x^2\frac{dy}{dx}=xy^2-x^3-y^2+x^2+2xy $$ $$ \frac{dy}{dx}=\frac{xy^2}{2x^2}-\frac{x}{2}-\frac{y^2}{2x^2}+\frac{1}{2}+\frac{y}{x} $$ put $z=\frac{y}{x}$ and $\frac{dz}{dx}=\frac{-y}{x^2}+\frac{1}{x}\frac{dy}{dx}$ which is same as $\frac{dz}{dx}=\frac{-z}{x}+\frac{1}{x}\frac{dy}{dx}$ implies $\frac{dy}{dx}=x\frac{dz}{dx}+z$. Hence, the equation will be, $$ x\frac{dz}{dx}+z=\frac{xz^2}{2}-\frac{x}{2}-\frac{z^2}{2}+\frac{1}{2}+z $$ $$ 2x\frac{dz}{dx}=xz^2-x-z^2+1 $$ $$ 2x\frac{dz}{dx}=z^2(x-1)-(x-1) $$ $$ 2x\frac{dz}{dx}=(z^2-1)(x-1) $$ Finally, $$ \frac{2}{z^2-1}\frac{dz}{dx}=\frac{x-1}{x} $$ or $$ \frac{2}{z^2-1}dz=\frac{x-1}{x}dx $$ which can be solved by taking integration on both sides...
{ "pile_set_name": "StackExchange" }
Q: What happens when two threads trying to put the same key value in concurrent hashmap Imagine there are two threads A, B that are going to put two different values in the map, v1 and v2 respectively, having the same key. The key is initially not present in the map Thread A calls containsKey and finds out that the key is not present, but is immediately suspended Thread B calls containsKey and finds out that the key is not present, and has the time to insert its value v2 When thread A is back,what happens?. I assume that,It calls put method which in turn calls putIfAbsent But the key is already there inserted by thread B.so thread A will not override the value But from this link i found that Thread A resumes and inserts v1, "peacefully" overwriting (since put is threadsafe) the value inserted by thread B Is ConcurrentHashMap totally safe? A: Here's what ConcurrentHashMap will do for you: (1) Key/value pairs won't mysteriously appear in the map. If you try to get a value for some key, You are guaranteed to get a value that some thread in your program stored with that key, or you will get a null reference if no thread has ever stored a value for that key. (2) key/value pairs won't mysteriously disappear from the map. If you call get(K) for some K that previously had a value, and a null reference comes back, it's because some thread in your program stored the null. (3) It won't deadlock or hang or crash your program. Here's what ConcurrentHashMap will not do for you: It won't make your program "thread safe". The most important thing to remember about thread safety is this: Building a module or a program entirely from "thread-safe" components will not make the the program or module "thread-safe". Your question is a perfect example of why not. ConcurrentHashMap is a thread-safe object. No matter how many threads access it at the same time, it will keep the promises (1), (2), and (3) that I listed above. But if two of your program's threads each try put a different value into the map for the same key at the same time, that's a data race. When some other thread later looks up that key, the value that it gets will depend on which thread won the race. If the correctness of your program depends on which thread wins a data race, then your program is not "thread-safe" even though the objects from which it was built are called "thread safe".
{ "pile_set_name": "StackExchange" }
Q: Use of unassigned local variable 'totalroadtax' I'm trying to create a method for my web-service however i receive this error listed in the title Use of unassigned local variable 'totalroadtax' This is how the user have to input 2 different variable to trigger the method in the webmethod [WebMethod] public double RoadTax(int engineCapacity, int vehicleAge) { double totalroadtax; if (engineCapacity.Equals("600") && vehicleAge.Equals("12")) { totalroadtax = ((200.00 * 0.782) * (1.10)); } return totalroadtax; //return (engineCapacity - vehicleAge); } I declared my totalroadtax in my method, input some caluclation method and return the value. I checked the have the necessary information for this method to work but I still receive the error. Did i leave anything out here? A: The if may be skipped (if the condition is false) and you're returning totalroadtax. The variable is not initialized at that point because you declared it without an initial value. You should declare the variable with some initial value like: double totalroadtax = 0; Edit: Your code needlessly compares int values to string literals. It's cleaner and more efficient to perform the condition this way: [WebMethod] public double RoadTax(int engineCapacity, int vehicleAge) { double totalroadtax = 0; if (engineCapacity == 600 && vehicleAge ==12) { totalroadtax = ((200.00 * 0.782) * (1.10)); } return totalroadtax; } There's no need to call Equals() - the == operator reads better and it performs a type-safe check. I'd also recommend that you don't perform direct equality checks against floating-point values. Instead of using ==, you should really check for something like: if ( (engineCapacity >599.9999 && engineCapacity < 600.00001) && ... This is because floating-point values are not exact representations of fractional numbers. Read this question for more details. A: totalroadtax is unassigned when if condition is not met. Change your declaration to: double totalroadtax = 0d; A: It's good practice to always initialize variables. In this particular case if the if evaluates to false, the variable totalroadtax will be returned uninitialized. To fix the issue you need to initialize totalroadtax: double totalroadtax = 0d; Here is an alternative nicer solution imo, avoiding the variable all together: [WebMethod] public double RoadTax(int engineCapacity, int vehicleAge) { if (engineCapacity.Equals("600") && vehicleAge.Equals("12")) { return ((200.00 * 0.782) * (1.10)); } return 0d; }
{ "pile_set_name": "StackExchange" }
Q: Which integer sequence starts with small elements, and stays there for a (really) long time, but eventually escapes the initial area? Graphically, I am searching for something like this: The only additional requirement would be that the elements are defined by a closed formula or "simple" recursion, i.e. no definition by cases (Fallunterscheidung) and such. A: How about $a_n=2^{n\cdot\lfloor{n/1000000}\rfloor}$? A: This is not exactly the same thing, but consider the "Tower of Hanoi" sequence: 1 2 1 3 1 2 1 4 1 2 1 3 1 ... $a_n = k$ when $n$ is an odd number times $2^{k-1}$ We need more than 1000 terms before we see any term greater than 10 (in the Tower of Hanoi puzzle that means if you have 11 layers you need over 1000 moves to expose the bottom disk). Yet the sequence is ultimately unbounded.
{ "pile_set_name": "StackExchange" }
Q: Python/MySQL get data from table based on values in a dictionary I have a list of dictionaries of friends with the following structure friendships = [{'name1': 'Joe Bloggs', 'name2': 'Jane Bloggs'}, {'name1': 'Joe Bloggs', 'name2': 'Jan Doe'}, {'name1': 'Another Name', 'name2': 'Someone Else'}] I have a MySQL table with each person in called People. The structure of this table is id, name e.g. 1 Joe Bloggs 2 Jane Bloggs 3 Jan Doe 4 Another Name 5 Someone Else I want to write an SQL query which will get me the ids of the friends from the table in a similar structure to what I have at the start e.g. friendship_ids = [{'id1': '1', 'id2': '2'}, {'id1': '1', 'id2': '3'}, {'id1': '4', 'id2': '5'}] I currently do this by looping through each row in friendships and getting the ids that way but the list is quite large so wanted to do it with 1 query. friendship_ids = [] for f in friendships cur.execute("SELECT (SELECT id FROM Person WHERE name = '%s') AS id1, (SELECT id FROM Person WHERE name = '%s') AS id2" % (f.name1, f.name2)) d = cur.fetchone() friendship_ids.append(d) A: I guess if you really don't want a second table to store the friendships, you could use something like this: import itertools # collect all the names involved names = itertools.chain.from_iterables(f.values() for f in friendships) query = 'SELECT name, id FROM People WHERE name in (%s)' \ % ','.join(mysql_escape(n) for n in names) Replace mysql_escape with some quoting facility of your MySQL driver. Then execute the queryand use the returned rows like this: # will contain a map from names to IDs name_to_id = dict((row["name"], row["id"]) for row in rows) You can then build your friendship_ids like this: friendship_ids = [{'id1': name_to_id[f['name1']], 'id2': name_to_id[f['name2']]} for f in friendships]
{ "pile_set_name": "StackExchange" }
Q: user_id and group_id always starts from a unique value When i used useradd command in linux, the user_id and group_id for the account is automatically chosen as 500. Now if i delete the account and create it again, then also the user_id and group_id is 500. From where is this default value chosen ? I used this command : $ useradd ping password: and then looked into the following file $ cat /etc/group /etc/passwd root::0:root tty::5: disk:x:100: floppy:x:101: uucp:x:102: utmp:x:103: lp:x:104: kmem:x:105: vcsa:x:106: sshd:x:74: ping:x:500: root:x:0:0:root:/root:/bin/bash nobody:x:99:99:Nobody:/:/sbin/nologin vcsa:x:106:106:vcsa privsep:/var/empty:/sbin/false sshd:x:74:74:sshd privsep:/var/empty:/sbin/false ping:x:500:500::/home/ping:/bin/bash A: The defaults are dependent upon the linux distribution you're running. My debian box has UID_MIN 1000 set in the /etc/login.defs file. If your goal is to use a different UID, then you need to use the -u | --uid option for useradd.
{ "pile_set_name": "StackExchange" }
Q: mean of the entire dataframe I have a dataframe set.seed(123) df <- data.frame(loc.id = rep(1:5, each = 4*2), year = rep(rep(1980:1983,each = 2),times = 5), type = rep(2:3, times = 4*5), x = runif(5*4*2), y = runif(5*4*2), z = runif(5*4*2)) If I have to take the mean of col x or col y, I could use colMeans What I want to do is for each loc.id and year: test <- df[df$loc.id == 1 & df$year == 1980,] loc.id year type x y z 1 1980 2 0.6478935 0.5022996 0.2387260 1 1980 3 0.3198206 0.3539046 0.9623589 I want to take the mean, sd and cv of x,y,z which in the above case will be: mean.eg <- mean(c(test$x,test$y,test$z)) sd.eg <- sd(c(test$x,test$y,test$z)) cv.eg <- sd.eg/mean.eg * 100 So that my data looks like loc.id year mean.eg sd.eg cv.eg 1 1980 1 1981 1 1983 2 1980 2 1981 2 1983 This gives me an error df %>% group_by(loc.id,year) %>% summarise(mean = c(x,y,z)) A: How about this? > mean(apply(df,1,function(x) mean(x[4:6]))) [1] 0.510727
{ "pile_set_name": "StackExchange" }
Q: find number of connected edges to a node and node with max connected edges In a graph, how do I find the number of connected (directly bound) edges to a node? And then, it would be trivial, but if there is any direct method to find the unique(s) node(s) with the maximum edges connected to them it would be nice. I'm using Python 2.7 and Networkx. Until now, I'm doing like this: sG = list(nx.connected_component_subgraphs(G)) # sG is a sub_graph of main graph G nb_sG = len(sub_graphs) max_con_node = list() for m in xrange(nb_sG): sG_nodes = [(node, len(sG[m].edges(node)), sG[m].edges(node)) for node in sG[m].nodes()] connexions = [i[1] for i in sG_nodes] idx = [i for i,x in enumerate(connexions) if x==max(connexions)] max_con_node.append((max(connexions), [sG_nodes[i][0] for i in idx])) Thanks. A: edit -- I've updated for new version of networkx. In general, please look at the Migration Guide for how to update your code from networkx 1.11 to 2.x. I think you are asking for how to find how many edges a node has. This is known as the degree of a node. For networkx v2.x, G.degree(node ) gives you the dgree of the node and G.degree() is a 'DegreeView' object. It can be converted into a dict using dict(G.degree()). G = nx.Graph() G.add_edges_from([[1,2],[1,3],[2,4],[2,5]]) G.degree() > DegreeView({1: 2, 2: 3, 3: 1, 4: 1, 5: 1}) max(dict(G.degree()).items(), key = lambda x : x[1]) > (2,3) in networkx v1.11 and lower: G.degree(node) gives you the degree of the node and G.degree() is a dict whose keys are the nodes and whose values are the corresponding degrees. So max(G.degree().items(), key = lambda x: x[1]) is a simple one-liner that returns (node, degree) for the node with maximum degree. Here is an example: G = nx.Graph() G.add_edges_from([[1,2],[1,3],[2,4],[2,5]]) G.degree() > {1: 2, 2: 3, 3: 1, 4: 1, 5: 1} max(G.degree().items(), key = lambda x: x[1]) > (2,3)
{ "pile_set_name": "StackExchange" }
Q: Filter values based on row conditions I am dealing with a relative easy problem that I don't know how to solve. Let's imagine I have the following dataframe: Book Word Rel.Freq A art 0.56 A car 0.4 B car 0.58 B dog 0.32 C art 0.5 C car 0.48 C dog 0.35 So, I want to have a dataframe only with the values that are the same for the column word. I need some function that would compare A, B, and C values in words and extract only the ones that are shared, that is only the ones that are repeated in all "books". I would also need a way to sum the Rel. Freq. values and obtain a mean based on the number of variables in book. I want a dataframe that would look like this: word Mean.Rel.Freq car 0.48 A: After grouping by 'Word', we filter those 'Word' where the number of distinct elements of 'Book' is equal to the distinct elements of 'Book' in the whole dataset and summarise the 'Rel.Freq' by taking the mean of it library(tidyverse) df1 %>% group_by(Word) %>% filter(n_distinct(Book) == n_distinct(.$Book)) %>% summarise(Mean.Rel.Freq = mean(Rel.Freq)) # A tibble: 1 x 2 # Word Mean.Rel.Freq # <chr> <dbl> #1 car 0.487
{ "pile_set_name": "StackExchange" }
Q: Return data in ionic app I linked the webservice with the app successfully and the data is retrieved but I can't access the data to display it or use it in any process. constructor(public navCtrl: NavController, public navParams: NavParams, public apiProvider: ApiProvider, public alertCtrl: AlertController) { this.usercheck = this.apiProvider.UserCheck(); this.usercheck.subscribe(data => {console.log('my data: ', data); }); The result retrieved by the console.log is: and I am using this code to display the data in ionic element. <ion-list> <button ion-item *ngFor="let user of (usercheck|async)?.Array" (click)="openDetails(user)"> {{ user.CinemaName }} </button> </ion-list> but there is no result thanks in advance. A: You need to replace below code constructor(public navCtrl: NavController, public navParams: NavParams, public apiProvider: ApiProvider, public alertCtrl: AlertController) { this.usercheck = this.apiProvider.UserCheck(); this.usercheck.subscribe(data => {console.log('my data: ', data); }); to testData: any = []; constructor(public navCtrl: NavController, public navParams: NavParams, public apiProvider: ApiProvider, public alertCtrl: AlertController) { this.usercheck = this.apiProvider.UserCheck(); this.usercheck.subscribe(data => this.testData = data;); And replace below code <ion-list> <button ion-item *ngFor="let user of (usercheck|async)?.Array" (click)="openDetails(user)"> {{ user.CinemaName }} </button> </ion-list> to <ion-list> <button ion-item *ngFor="let user of testData" (click)="openDetails(user)"> {{ user.CinemaName }} </button> </ion-list>
{ "pile_set_name": "StackExchange" }
Q: making change to function in R package and installing on Ubuntu Short question: I want to edit the postgresqlWriteTable function in the RPostgreSQL package and install it on R running on an Ubuntu machine. Long explanation: The root of my problem is that I am trying to write to a postgres table with an auto-incrementing primary key column from R using dbWriteTable from RPostgreSQL package. I read this post: How do I write data from R to PostgreSQL tables with an autoincrementing primary key? which suggested a fix to my problem by changing the function postgresqlWriteTable in the RPostgreSQL package. It works when I interactively use fixInNamespace in OSX environment and edit the function. Unfortunately I have to run my script on an AWS instance running R on Ubuntu. I have RPostgreSQL installed at this location on my machine: /usr/local/lib/R/site-library/RPostgreSQL . I installed it by invoking R CMD install RPostgreSQL_0.4-1.tar.gz Now I am trying to find the function postgresqlWriteTable. It is supposed to be in the file PostgreSQLSupport.R . I have searched the whole library - there is no such file. I realized that on my local machine in the OSX Finder , when I unzip the tar.gz package folder, I can see the file PostgreSQLSupport.R where I am supposed to change the function. So I changed the function. Then I removed the installed RPostgreSQL from my Ubuntu machine and copied the new folder (from my local machine) into my Ubuntu machine and tried to use devtools to install the package as suggested in the post here: Loading an R Package from a Custom directory here's what happened: > library("devtools") > install("/usr/local/lib/R/site-library/RPostgreSQL") Error: Can't find '/usr/local/lib/R/site-library/RPostgreSQL'. > install("RPostgreSQL", "/usr/local/lib/R/site-library/RPostgreSQL") Installing RPostgreSQL '/usr/lib/R/bin/R' --no-site-file --no-environ --no-save --no-restore --quiet \ CMD INSTALL '/datasci/nikhil/RPostgreSQL' \ --library='/usr/local/lib/R/site-library' --install-tests * installing *source* package ‘RPostgreSQL’ ... file ‘R/PostgreSQLSupport.R’ has the wrong MD5 checksum ERROR: 'configure' exists but is not executable -- see the 'R Installation and Administration Manual' * removing ‘/usr/local/lib/R/site-library/RPostgreSQL’ Error: Command failed (1) I am at my wit's end ! A: Copy the pacakge .tar.gz file to the AWS machine. Unpack this file so you have a directory structure. Edit the function inside the file and save your changes. You may also have to increase the version number in the DESCRIPTION file. Use devtools::build to create a new .tar.gz file. Install this updated version of the package.
{ "pile_set_name": "StackExchange" }
Q: Choice in flow not accepting selection I have a very simple flow - it shows contacts filtered by one field. The dynamic choice is displayed using radio buttons (drop down shows the same behaviour). When I choose an option and click on next, a message appears "Please select a choice". If I filter by different fields, sometimes it works as expected, sometimes it doesn't. On different sandboxes filtering by that particular field works, not on others. This seems to be an issue with the particular field, but I cannot see any difference between fields or sandboxes. All fields used are definitely visible by me - filter field, id and label field. Is there anything on the field definition that might cause this issue? The flow in all its simplicity - I cannot see anything that I might change in order to correct this: Addendum: the filter above returns 10 results: A: After some digging and support from an SF employee, I have an answer now. The search works over a data set of 3.2 million contacts. When selecting the option, an exception is thrown: EXCEPTION_THROWN [EXTERNAL]|System.QueryException: Non-selective query against large object type (more than 200000 rows). Consider an indexed filter or contact salesforce.com about custom indexing. This exception can be seen if the log level is adjusted (I usually only have Apex logging on a high setting). It's currently unknown why that happens in that stage, but a solution is to have all fields that contribute to the filter to be indexed. The fields I used for testing when it worked were indexed, but in this case ssn__c was not. The issue is not related to the amount of data returned by the original filter, but to the amount of entries in the database.
{ "pile_set_name": "StackExchange" }
Q: C# - Faster way to check if a directory and sub-directories contain at least 1 file from a list of allowed file extensions? Part of my program involves validating 2 directories if both contain at least 1 file from a given list of allowed extensions. if (DoesDirectoryHaveValidFiles(directory1) && DoesDirectoryHaveValidFiles(directory2)) My current issue is that, given a directory tree that is deep enough, or having too much sub-directories, my current implementation takes too much time for what it does. Can anyone give me some help how I can speed up my checking? bool DoesDirectoryHaveValidFiles(string directory) { var allowedExtensions = new string[] {".aaa", ".bbb", ".ccc"}; var directoryInfo = new DirectoryInfo(directory); var fileInfos = directoryInfo.GetFiles("*.*", SearchOption.AllDirectories) .Where(file => allowedExtensions.Any(file.FullName.ToLower().EndsWith)); return fileInfos.Count() > 0; } A: UPDATE: After SBFrancies's help for the .Where to .Any, and Dour High Arch's help for the file.Extension, I have replaced it with the following code, and I think it is now fast enough for what I need it to do. But if you guys have other comments about my implementation, please dont hesitate to inform me, as Im still learning with regards to these parts. bool DoesDirectoryHaveValidFiles(string directory) { var allowedExtensions = new string[] {".aaa", ".bbb", ".ccc"}; var directoryInfo = new DirectoryInfo(directory); var hasValidFiles = directoryInfo.GetFiles("*.*", SearchOption.AllDirectories) .Any(file => allowedFileExtensions.Contains(file.Extension)); return hasValidFiles; }
{ "pile_set_name": "StackExchange" }
Q: Choose between 32 and 64 bit for an NSIS installer? I have found some similar questions but I'm not totally sure that they answer my question. I am needing to include Java within my installer, however, we will not know whether the client is using 32 or 64 bit and we do not want to make the assumption. We have considered just using the 32 bit JRE since it will also work on 64 bit systems and it will also not require packaging more than one JRE. We also will not know if the client has internet connectivity to have it connect and choose for the client. Is there an easy way to decide between these two in NSIS? Should I just use the 32 bit JRE and not worry about it? A: NSIS has a header file with some helper macros for 64-bit stuff: !include x64.nsh !include LogicLib.nsh Section !if "${NSIS_PTR_SIZE}" >= 8 DetailPrint "64-bit installer" !else ${If} ${RunningX64} DetailPrint "32-bit installer on a 64-bit OS" ${Else} DetailPrint "32-bit installer on a 32-bit OS" ${EndIf} !endif SectionEnd
{ "pile_set_name": "StackExchange" }
Q: it will bring up the deleted row when thead is clicked | Error I want to delete datatable row permanently if I delete all the rows, i want datatable will display the default "No data available" text. I already try some POST : But no luck DataTables remove row button with answer : $("#dataTables-example").on('click', '.btn-info', function () { $(this).parent().parent().remove(); }); I cannot remove row with jQuery with answer : $( 'tbody tr:last-child' ).remove(); But, when I delete all the rows, the text "No data available" does not appear. and when thead is clicked, it will bring up the deleted row. ======================== MY JSFiddle jQuery delete row : $(document).on('click', '.deleteRow', function() { $(this).closest('tr').remove(); }); in dataTable func : "columns": [ { "data": "id"}, { "data": "name" }, { "data": "subtype"}, { "data": "approximate_count" }, { "data": "time_created" }, {data: null , "sClass" : "center", "sDefaultContent" : '<button class="deleteRow">Delete</button> ' }, ], A: For displaying default text, you can try $('#example').DataTable({ "language": { "emptyTable": "My Custom Message On Empty Table" }, rowId: id }); For deleting row use, You need to remove data from backend as well using ajax. Than you can use below function. $(document).on('click', '.deleteRow', function(e) { var id = $(this).parents('tr').attr('id'); var rowid = document.getElementById(id); var Pos = table.fnGetPosition(rowid); table.fnDeleteRow(Pos); }); Please check jsfiddle. JSFIDDLE
{ "pile_set_name": "StackExchange" }
Q: How to detect leading double-quote in a string in Java? I'm writing a tokenizer that reads code from a file and am having difficulty with the - seemingly - trivial task of getting it to branch into the case that handles string constants (any token that starts and ends with a double quote). The conditional I wrote for the branch is if (token.charAt(0) == '"') { // Do some stuff } where token is the string that was read in. Alternatively, I've also tried if (token.startsWith("\"")) { // Do some stuff } I've checked the debugger and it still refuses to enter the branch even for valid cases such as the string "Paris" with value field [”, P, a, r, i, s, ”] Any suggestions would be appreciated. A: The left ” and right “ double quotes are different from the standard double quote character ". Try doing a replace() on the string to replace all left and right double quotes with the standard double quote before tokenizing.
{ "pile_set_name": "StackExchange" }
Q: ModSecurity default installation running on IIS 10.0 with CRS rule set generating a lot of errors I have just installed ModSecurity on IIS 10.0 running on Windows 10. However even a "clean" install generates a lot of errors only by visiting the default IIS site. By looking at eventvwr and making a single request I get a total of 14 new errors for a GET request to localhost. Every event has the following description: The description for Event ID 1 from source ModSecurity cannot be found. Either the component that raises this event is not installed on your local computer or the installation is corrupted. You can install or repair the component on the local computer. If the event originated on another computer, the display information had to be saved with the event. The following information was included with the event: Eventdata: [client ] ModSecurity: IPmatch: bad IPv4 specification "". [hostname "HOSTNAME"] [uri "/"] [unique_id "18158513704000290822"] [client ] ModSecurity: Rule processing failed. [hostname "HOSTNAME"] [uri "/"] [unique_id "18158513704000290822"] [client ] ModSecurity: Rule 15448555590 [id "981172"][file "C:\/Program Files/ModSecurity IIS/owasp_crs/base_rules/modsecurity_crs_41_sql_injection_attacks.conf"][line "157"] - Execution error - PCRE limits exceeded (-8): (null). [hostname "HOSTNAME"] [uri "/"] [unique_id "18158513704000290822"] [client ] ModSecurity: Rule 154485cd4a0 [id "981243"][file "C:\/Program Files/ModSecurity IIS/owasp_crs/base_rules/modsecurity_crs_41_sql_injection_attacks.conf"][line "245"] - Execution error - PCRE limits exceeded (-8): (null). [hostname "HOSTNAME"] [uri "/"] [unique_id "18158513704000290822"] [client ] ModSecurity: IPmatch: bad IPv4 specification "". [hostname "HOSTNAME"] [uri "/"] [unique_id "18158513704000290822"] [client ] ModSecurity: Rule processing failed. [hostname "HOSTNAME"] [uri "/"] [unique_id "18158513704000290822"] [client ] ModSecurity: Rule 15448555590 [id "981172"][file "C:\/Program Files/ModSecurity IIS/owasp_crs/base_rules/modsecurity_crs_41_sql_injection_attacks.conf"][line "157"] - Execution error - PCRE limits exceeded (-8): (null). [hostname "HOSTNAME"] [uri "/"] [unique_id "18158513704000290822"] [client ] ModSecurity: Rule 154485cd4a0 [id "981243"][file "C:\/Program Files/ModSecurity IIS/owasp_crs/base_rules/modsecurity_crs_41_sql_injection_attacks.conf"][line "245"] - Execution error - PCRE limits exceeded (-8): (null). [hostname "HOSTNAME"] [uri "/"] [unique_id "18158513704000290822"] [client ] ModSecurity: Rule 15448555590 [id "981172"][file "C:\/Program Files/ModSecurity IIS/owasp_crs/base_rules/modsecurity_crs_41_sql_injection_attacks.conf"][line "157"] - Execution error - PCRE limits exceeded (-8): (null). [hostname "HOSTNAME"] [uri "/iisstart.htm"] [unique_id "18158513704000290822"] [client ] ModSecurity: Rule 154485cd4a0 [id "981243"][file "C:\/Program Files/ModSecurity IIS/owasp_crs/base_rules/modsecurity_crs_41_sql_injection_attacks.conf"][line "245"] - Execution error - PCRE limits exceeded (-8): (null). [hostname "HOSTNAME"] [uri "/iisstart.htm"] [unique_id "18158513704000290822"] [client ] ModSecurity: collections_remove_stale: Failed to access DBM file "C:/inetpub/temp/ip": Access is denied. [hostname "HOSTNAME"] [uri "/iisstart.htm"] [unique_id "18158513704000290822"] [client ] ModSecurity: collections_remove_stale: Failed to access DBM file "C:/inetpub/temp/global": Access is denied. [hostname "HOSTNAME"] [uri "/iisstart.htm"] [unique_id "18158513704000290822"] [client ] ModSecurity: Rule 15448555590 [id "981172"][file "C:\/Program Files/ModSecurity IIS/owasp_crs/base_rules/modsecurity_crs_41_sql_injection_attacks.conf"][line "157"] - Execution error - PCRE limits exceeded (-8): (null). [hostname "HOSTNAME"] [uri "/iisstart.png"] [unique_id "18158513704000290823"] [client ] ModSecurity: Rule 154485cd4a0 [id "981243"][file "C:\/Program Files/ModSecurity IIS/owasp_crs/base_rules/modsecurity_crs_41_sql_injection_attacks.conf"][line "245"] - Execution error - PCRE limits exceeded (-8): (null). [hostname "HOSTNAME"] [uri "/iisstart.png"] [unique_id "18158513704000290823"] What I have done: Installed ModSecurity v2.9.1 for IIS MSI Installer - 64bits and Visual Studio 2013 Runtime (vcredist). Downloaded OWASP ModSecurity Core Rule Set (CRS) from https://github.com/SpiderLabs/owasp-modsecurity-crs and put the folder in C:\Program Files\ModSecurity IIS. Changed the name crs-setup.conf.example to crs-setup.conf. Under \rules I changed REQUEST-900-EXCLUSION-RULES-BEFORE-CRS.conf.example and RESPONSE-999-EXCLUSION-RULES-AFTER-CRS.conf.example to not contain .example. Modified modsecurity_iis.conf to the following: Include modsecurity.conf Include modsecurity_crs_10_setup.conf Include owasp_crs\base_rules\*.conf #OWASP-Rules include owasp-modsecurity-crs/crs-setup.conf include owasp-modsecurity-crs/rules/REQUEST-900-EXCLUSION-RULES-BEFORE-CRS.conf include owasp-modsecurity-crs/rules/REQUEST-901-INITIALIZATION.conf include owasp-modsecurity-crs/rules/REQUEST-905-COMMON-EXCEPTIONS.conf include owasp-modsecurity-crs/rules/REQUEST-910-IP-REPUTATION.conf include owasp-modsecurity-crs/rules/REQUEST-911-METHOD-ENFORCEMENT.conf include owasp-modsecurity-crs/rules/REQUEST-912-DOS-PROTECTION.conf include owasp-modsecurity-crs/rules/REQUEST-913-SCANNER-DETECTION.conf include owasp-modsecurity-crs/rules/REQUEST-920-PROTOCOL-ENFORCEMENT.conf include owasp-modsecurity-crs/rules/REQUEST-921-PROTOCOL-ATTACK.conf include owasp-modsecurity-crs/rules/REQUEST-930-APPLICATION-ATTACK-LFI.conf include owasp-modsecurity-crs/rules/REQUEST-931-APPLICATION-ATTACK-RFI.conf include owasp-modsecurity-crs/rules/REQUEST-932-APPLICATION-ATTACK-RCE.conf include owasp-modsecurity-crs/rules/REQUEST-933-APPLICATION-ATTACK-PHP.conf include owasp-modsecurity-crs/rules/REQUEST-941-APPLICATION-ATTACK-XSS.conf include owasp-modsecurity-crs/rules/REQUEST-942-APPLICATION-ATTACK-SQLI.conf include owasp-modsecurity-crs/rules/REQUEST-943-APPLICATION-ATTACK-SESSION-FIXATION.conf include owasp-modsecurity-crs/rules/REQUEST-949-BLOCKING-EVALUATION.conf include owasp-modsecurity-crs/rules/RESPONSE-950-DATA-LEAKAGES.conf include owasp-modsecurity-crs/rules/RESPONSE-951-DATA-LEAKAGES-SQL.conf include owasp-modsecurity-crs/rules/RESPONSE-952-DATA-LEAKAGES-JAVA.conf include owasp-modsecurity-crs/rules/RESPONSE-953-DATA-LEAKAGES-PHP.conf include owasp-modsecurity-crs/rules/RESPONSE-954-DATA-LEAKAGES-IIS.conf include owasp-modsecurity-crs/rules/RESPONSE-959-BLOCKING-EVALUATION.conf include owasp-modsecurity-crs/rules/RESPONSE-980-CORRELATION.conf include owasp-modsecurity-crs/rules/RESPONSE-999-EXCLUSION-RULES-AFTER-CRS.conf Restarted IIS and then checked Event Viewer. What have I missed or is this normal behavior? A: Regarding the description I found this: This is just an warning. That is actually the ModSecurity letting you know something about a given request. The "windows description" of the event can be ignored. Look at the content... https://github.com/SpiderLabs/ModSecurity/issues/877#issuecomment-267712103 1. Execution error - PCRE limits exceeded (-8): (null): Modified modsecurity.conf values to the following: SecPcreMatchLimit 500000 SecPcreMatchLimitRecursion 500000 Instead of reading data from EventLog I started using Audit log instead. Can be enabled via modsecurity.conf. Set format to JSON instead of Native to read the log file programatically. Remember to give the user IIS_IUSRS access to the logs folder and files. # -- Audit log configuration ------------------------------------------------- # Log the transactions that are marked by a rule, as well as those that # trigger a server error (determined by a 5xx or 4xx, excluding 404, # level response status codes). # SecAuditLogFormat JSON SecAuditEngine RelevantOnly SecAuditLogRelevantStatus "^(?:5|4(?!04))" # Log everything we know about a transaction. SecAuditLogParts ABIJDEFHZ # Use a single file for logging. This is much easier to look at, but # assumes that you will use the audit log only ocassionally. # SecAuditLogType Serial SecAuditLog c:\inetpub\logs\modsec_audit.log # Specify the path for concurrent audit logging. SecAuditLogStorageDir c:\inetpub\logs\
{ "pile_set_name": "StackExchange" }
Q: How do I resolve a missing project subtype error I recieve when creating a new zebble project? I have installed Visual Studio Update 3, and I'm trying to work with the Zebble framework. I installed Xamarin, UWP, and other prerequisites. Still, I cannot create a new Zebble for Xamarin - Cross platform solution project. I'm getting this error: Would you please help me out? A: That happens when you have an older version of UWP tools installed in your Visual Studio. You need to: Edit Visual Studio to uninstall UWP tools. Delete the old versions of UWP SDK from Programs and Features. Close and restart your computer. Edit Visual Studio to install UWP tools again.
{ "pile_set_name": "StackExchange" }
Q: Is there is any hook like "didInsertElement" in router? Using third party framework, I want set selected value. Is there is any hook after view inserted into DOM in ember.js new router? A: Agreed with Karl above. However, maybe you've just asked the question in a bad way. In the new router, you have the setupController, which is invoked when Ember moves into that route. So for example, if you move into /#/dashboard, then DashboardController, DashboardView, DashboardRoute will all be initialised. Aside from the fact that you could use the didInsertElement on the DashboardView at this point, you have the setupController method which you can overwrite in the DashboardRoute. In here you can set-up the controller, and perhaps do whatever it is you're trying to do: (The setupController will only be invoked when you enter the route, but the view won't have rendered by the time you're moving into it. For that you'll need didInsertElement and that's that. setupController is for setting up the controller, which can be thought of as an ever-persistent singleton.) var DashboardRoute = Ember.Route.extend({ setupController: function(controller) { // We're in the route, so let's do something now. controller.set('myText', 'Add this to the controller!'); } });
{ "pile_set_name": "StackExchange" }
Q: get object data stdCLass in PHP i want get data from stdclass object. i use foreach method to get key and value. with var_dump i can get all infromation about the post, buy i want extract all 'display'. foreach($data as $key=>$value){ var_dump($value); } var_dump result : i just want extract all display_ur property. can anyone exlain me ? A: Your original array is made out of stdClassObjects. Each of these class objects has a public property called node that is also a stdClassObject. That means that if you want to retrieve the display_url for each of these objects, you need: foreach ($array as $object) { $node = $object->node; var_dump($node->display_url); // this should return what you are looking for }
{ "pile_set_name": "StackExchange" }
Q: CSS: Why I can't use ID in this piece of code but with class it works? Hi I have a weird issue here with my menu. So I want to apply this transformation to just few links and for other just to not have it. Here is the CSS for the transformation without any changes: ul.menu > li > a:after, ul.drop-down > li > a:after { position: absolute; content: ''; top: 0; left: 0; width: 0; height: 100%; transition: all 0.15s linear; -moz-transition: all 0.15s linear; -webkit-transition: all 0.15s linear; -o-transition: all 0.15s linear; background: red; border-bottom: 1px solid rgba(0,0,0,0.1); } Now this is applied to every a tag in the ul with class "menu". OK that's fine but I want to apply this only to some links. so If I put ul.menu > li > a.foo:after it will work but if I use id there ul.menu > li > a#foo:after it won't work. Any reason why so? The problem is that if I stick with using the class foo instead of the ID than on the next pice of code trying to apply the class foo to the .active state doesn't work: ul.menu li a:hover:after, ul.menu li a.active:after { width: 100%; } So here if I apply ul.menu li a.foo:hover:after and ul.menu li a.foo.active:after is not going to work. Any ideas why so? Here is how my links look without putting th class foo to the <ul class="menu"> <li><a <?php if ($active_state == 'news'): ?> class="active" <?php endif; ?> href="bla"><span>News</span></a></li> <li><a <?php if ($active_state == 'lounge'): ?> class="active" <?php endif; ?> href="blaa"><span>Lounge</span></a></li> </ul> A: This article contains information about the difference between ID and class. I believe because you'd have multiple ul.menu > li > a#foo's this won't work with ID. ID applies to one element. http://css-tricks.com/the-difference-between-id-and-class/
{ "pile_set_name": "StackExchange" }
Q: Folding in argument list of std::initializer_list's constructor vs "normal" folding I learn C++17 from C++17 STL Cookbook by Jacek Galowicz and there is such an example about lambdas : template <typename... Ts> static auto multicall(Ts... functions) { return [=](auto x) { (void)std::initializer_list<int>{((void)functions(x), 0)...}; }; } template <typename F, typename... Ts> static auto for_each(F f, Ts... xs) { (void)std::initializer_list<int>{((void)f(xs), 0)...}; } static auto brace_print(char a, char b) { return [=](auto x) { std::cout << a << x << b << ", "; }; } int main() { auto f(brace_print('(', ')')); auto g(brace_print('[', ']')); auto h(brace_print('{', '}')); auto nl([](auto) { std::cout << '\n'; }); auto call_fgh(multicall(f, g, h, nl)); for_each(call_fgh, 1, 2, 3, 4, 5); } Why is the std::initializer_list used here and why is this void casting used (The author writes that there should be reinterpret_cast used instead of C-like casting, but the question is about why is this casting used)? When I change the multicall and for_each functions to such: template <typename... Ts> static auto multicall(Ts... functions) { return [=](auto x) { (functions(x), ...); }; } template <typename F, typename... Ts> static auto for_each(F f, Ts... xs) { (f(xs), ...); } Everything works as expected, I get the same results. A: It looks like for some reasons this part of the book operates C++14-way. Trick with std::initializer_list was needed before fold expressions were introduced in C++17 to call emulate variadic call. In C++17 fold with comma operator is absolutely legit
{ "pile_set_name": "StackExchange" }
Q: How do I find and remove emojis in a text file? I'm trying to remove all the emojis from a text file I'm parsing using mostly sed and some perl commands, and preferrably store them in a separate file but this isn't necessary. Can I do this easily with bash or perl? Or should I use another language? EDIT: Thank you to Cyrus and Barmar for pointing me in the right direction, towards this question. However, it doesn't tell me how to remove just the emojis from the text file. They use the bash line: grep -P "[\x{1f300}-\x{1f5ff}\x{1f900}-\x{1f9ff}\x{1f600}-\x{1f64f}\x{1f680}-\x{1f6ff}\x{2600}-\x{26ff}\x{2700}-\x{27bf}\x{1f1e6}-\x{1f1ff}\x{1f191}-\x{1f251}\x{1f004}\x{1f0cf}\x{1f170}-\x{1f171}\x{1f17e}-\x{1f17f}\x{1f18e}\x{3030}\x{2b50}\x{2b55}\x{2934}-\x{2935}\x{2b05}-\x{2b07}\x{2b1b}-\x{2b1c}\x{3297}\x{3299}\x{303d}\x{00a9}\x{00ae}\x{2122}\x{23f3}\x{24c2}\x{23e9}-\x{23ef}\x{25b6}\x{23f8}-\x{23fa}]" myflie.txt | more which gets me all the lines containing an emoji. grep -Pv will remove those lines from the input, grep -Po will return just the emojis, grep -Pov returns nothing. Does anyone know how to remove those specific characters from the text? Note: I am aware of this question, but my text file is not at all formatted. Emojis are mixed in with the rest of the text. A: In Perl, removing the emojis can be this easy. At its core, this is very close to what you'd do it sed. Update the pattern and other details for your task: #!perl use open qw(:std :utf8); my $pattern = "[\x{1f300}-\x{1f5ff}\x{1f900}-\x{1f9ff}\x{1f600}-\x{1f64f}\x{1f680}-\x{1f6ff}\x{2600}-\x{26ff}\x{2700}-\x{27bf}\x{1f1e6}-\x{1f1ff}\x{1f191}-\x{1f251}\x{1f004}\x{1f0cf}\x{1f170}-\x{1f171}\x{1f17e}-\x{1f17f}\x{1f18e}\x{3030}\x{2b50}\x{2b55}\x{2934}-\x{2935}\x{2b05}-\x{2b07}\x{2b1b}-\x{2b1c}\x{3297}\x{3299}\x{303d}\x{00a9}\x{00ae}\x{2122}\x{23f3}\x{24c2}\x{23e9}-\x{23ef}\x{25b6}\x{23f8}-\x{23fa}]"; while( <DATA> ) { # use <> to read from command line s/$pattern//g; print; } __DATA__ Emoji at end Emoji at beginning Emoji in middle UTS #51 mentions an Emoji property, but it's not listed in perluniprop. Were there such a thing, you would simplify that removing anything with that property: while( <DATA> ) { s/\p{Emoji}//g; print; } That would be fortunate for a one-liner: $ perl -pe 's/\p{Emoji}//g' file1 file2 There is the Emoticon property, but that doesn't cover your character class. I haven't looked to see if it would be the same as the Emoji property in UTS #51. Beyond that, you're stuck with the long character class in your one-liner.
{ "pile_set_name": "StackExchange" }
Q: Why does the MiG-15 have a cruciform tail? The horizontal stabilizers of the MiG-15 are halfway up the tail. This is called a cruciform tail. Why did they put them there? Why not a T-tail or the normal tail where the stabilizers are on the fuselage? A: The tail position is a compromise which is influenced by these factors: Interference with the wing's wake: The tail should be outside of the boundary layer flow coming off the wing root at all normal angles of attack. A high tail can cause a deep stall, something that was not known in 1947. Today all similar designs try to get the tail surface below the wing's wake. Lever arm: By mounting the tail higher up on the swept vertical tail, its lever arm (in horizontal direction) can be increased without lengthening the tailpipe. A longer tailpipe means more mass and more internal drag and is best avoided. Flutter: The higher the horizontal tail is along the vertical, the higher the danger of flutter. Here the longer lever arm (now in vertical direction) will lower the eigenfrequency of the bending mode of the vertical and the torsion mode of the rear fuselage. I suspect that for that reason the full T-tail was not chosen. Mounting the horizontal smack in the middle of the tailpipe would require a heavy spar there to carry the bending moment across the fuselage. Mounting it on the vertical tail allows for a much lighter construction. A: For a couple of reasons. First the shaping of the aft fuselage does not offer the space to accommodate the structure for the tailplane and flight controls without adding on an additional blisters to provide space. The routing of the jet pipe further uses up space as compared to an F-86. See images below. A low mounted tailplane would not have a clean airflow over it due to the MiG-15's middle mounted wing as opposed to the F-86's low wing design. A: It’s a good question. I remember that during lectures on aircraft structures, it was stated that the horizontal tail should be mounted either at the fuselage or at the top of the vertical tail. Not in between, since that involves having to implement the downsides of both methods. The case of the Bae 125 was mentioned: this was designed as a full T-tail, but during flight tests it turned out that additional vertical tail surface was required which was put on top of the existing structure. Wikipedia mentions that the design of the MIG 15 was based on that of the Focke-Wulf TA 183 Huckebein, which was only built as a wind tunnel model implementing a serious T-tail, not a cruciform. It seems probable that development of the MIG 15 vertical tail had a similar history to that of the Bae 125.
{ "pile_set_name": "StackExchange" }
Q: Does $ Ev(\cos(4\pi t)u(t)) $ signal has period? According to Oppenheim's signal and systems solution book and other solutions like this $$ Ev(\cos(4\pi t)u(t)) = 1/2 \times ( \cos(4\pi t)u(t) + \cos(4\pi t)u(-t)) = 1/2(\cos(4\pi t)) $$ $$ \textrm{for }-\infty < t < \infty $$ is periodic and its period $1/2$. But I think it is not equal $ 1/2(\cos 4\pi t) $ at $ t = 0 $ so it is not periodic because at $ t = 0 $ it is equal to $ 1 $ different from other multiples of period. I have also curious about the value of $ u(t)+u(-t) $. Is it $0$, $1$, or $2$ ? A: It is a matter of convention. The answer depends on the definition of the step function $u(t)$. In signal processing, it is common to define $u(0)=1/2$. Under this definition, we have that $Ev(\cos(4\pi t)u(t)) = 1/2(0.5+0.5)=1/2$, so the signal is indeed periodic. If $u(0)$ is defined as either 0 or 1, then you'd be correct and the signal wouldn't be periodic.
{ "pile_set_name": "StackExchange" }
Q: Encrypting HTML Forms I wrote a simple demo html (SSL enabled) forms to access some university services thru it. It requires the user to login with his university ID first . My question is , how to encrypt the logins data even from me the owner of this page ? Is it possible ? so that the user can confidently use this. A: You could use HTTP Digest Authentication which does challenge-response authentication and always sends password hashed. The problem with Digest is that UI for it is ugly and logging out is left up to the browser (you can't have a reliable logout link). Alternatively you could implement your own challenge-response mechanism in JavaScript, e.g. http://code.google.com/p/crypto-js/ but it's rather pointless, because the user doesn't have any guarantee that you're doing it, and that you won't replace the secure script with an insecure one in the future. As the site owner (or somebody that hacks your site) you could change the script and "steal" passwords at any time. SSL is good. That's the best real security you can do client-side. You can ensure that you're storing passwords securely on server-side — hash it with a slow hash such as bcrypt (not md5/sha1) and use unique salt for every password.
{ "pile_set_name": "StackExchange" }
Q: Why does IE give unexpected errors when setting innerHTML I tried to set innerHTML on an element in firefox and it worked fine, tried it in IE and got unexpected errors with no obvious reason why. For example if you try and set the innerHTML of a table to " hi from stu " it will fail, because the table must be followed by a sequence. A: You're seeing that behaviour because innerHTML is read-only for table elements in IE. From MSDN's innerHTML Property documentation: The property is read/write for all objects except the following, for which it is read-only: COL, COLGROUP, FRAMESET, HEAD, HTML, STYLE, TABLE, TBODY, TFOOT, THEAD, TITLE, TR. A: Don't know why you're being down-modded for the question Stu, as this is something I solved quite recently. The trick is to 'squirt' the HTML into a DOM element that is not currently attached to the document tree. Here's the code snippet that does it: // removing the scripts to avoid any 'Permission Denied' errors in IE var cleaned = html.replace(/<script(.|\s)*?\/script>/g, ""); // IE is stricter on malformed HTML injecting direct into DOM. By injecting into // an element that's not yet part of DOM it's more lenient and will clean it up. if (jQuery.browser.msie) { var tempElement = document.createElement("DIV"); tempElement.innerHTML = cleaned; cleaned = tempElement.innerHTML; tempElement = null; } // now 'cleaned' is ready to use... Note we're using only using jQuery in this snippet here to test for whether the browser is IE, there's no hard dependency on jQuery. A: "Apparently firefox isn't this picky" ==> Apparently FireFox is so buggy, that it doesn't register this obvious violation of basic html-nesting rules ... As someone pointed out in another forum, FireFox will accept, that you append an entire html-document as a child of a form-field or even an image ,-(
{ "pile_set_name": "StackExchange" }
Q: turn a string into plist - swift Looks like I might be the only one attempting this, or its so easy everyone but me already knows how! Website request returns a plist response, the response is received as a string. How do I then get that plist "string" into a dictionary? let url = NSURL(string: "http://...") let cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData var request = NSMutableURLRequest(URL: url!, cachePolicy: cachePolicy, timeoutInterval: 2.0) request.HTTPMethod = "POST" let boundaryConstant = "----------V2ymHFg03esomerasdfsalfkjlksjdfy" let contentType = "mulutipart/form-data; boundary=" + boundaryConstant NSURLProtocol.setProperty(contentType, forKey: "Content-Type", inRequest: request) var dataString = "" let requestBodyData = (dataString as NSString).dataUsingEncoding(NSUTF8StringEncoding) request.HTTPBody = requestBodyData var response: NSURLResponse? = nil var error: NSError? = nil let reply = NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: &error) let results = NSString(data: reply!, encoding: NSUTF8StringEncoding) results is a plist string with xml header and data following plist structure. the plist return works well if I use NSDictionary(contentsOfURL: NSURL(string: path)!)! however, I'm posting, not 'getting' so I can't use NSURL path as far as I know. thanks in advance! A: NSPropertyListSerialization is your friend here, so long as you're truly getting back plist data: if let plistData = results.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true) { var format = NSPropertyListFormat.XMLFormat_v1_0 let options = NSPropertyListMutabilityOptions.Immutable if let dict = NSPropertyListSerialization.propertyListWithData(plistData, options: NSPropertyListReadOptions(options.rawValue), format: &format, error: nil) as? NSDictionary { println(dict) } }
{ "pile_set_name": "StackExchange" }
Q: PageReference for Lookup Id I have two search criteria, one is for Account lookup it has to search in custom object based on the lookup selected value and other one is a text box which needs to enter the name. The user needs to search either using lookup value or text box value.I have one issue when i select the value form lookup and click the button it shows the values but the lookup field remains empty.I need to display the value after search in the lookup field.I had already asked this question for another issues. Public class sample_search { public List<sample_unit>Unt_sale{get;set;} public string partyNo{get;set;} public Boolean run{get;set;} public Id AccountId; public Account cont {get;set;} public sample_search() { Unt_sale=new List<sample_unit>(); run=false; } public PageReference runQuery() { run=true; try { cont=[select id, Name,ParentId from Account where id=:cont.ParentId limit 1]; } catch(QueryException qe){ // ApexPages.addMessage(ApexPages.Message(ApexPages.Severity.ERROR, qe.getMessage())); } string queryunit='select id,name,subject__c,detail__c,Account__r.Id from Units__c where name=:partyNo OR Account__r.ID =:AccountId'; process_unit(Database.query(queryunit)); } private void process_unit(List<Units__c> unitsale) { Unt_sale.clear(); for(Units__c cu:unitsale) { Unt_sale.add(new sample_unit(cu)); } } //wrapper class for sample_unit public with sharing class sample_unit { public Units__c unit{get;set;} public sample_unit(Units__c unt) { unit=unt; } } } <apex:page controller="sample_search" > <apex:pageBlock> <apex:inputField value="{!cont.ParentId}"> <apex:inputText value="{!partyNo}" id="accinfo1" /> <apex:commandButton value="Go" action="{!runQuery}"> </apex:pageBlock> <apex:pageBlock rendered="{!run}"> <apex:repeat value="{!Unt_sale}" var="us"> <apex:outputField value="{!us.unit.Name}"/> <apex:outputField value="{!us.unit.subject__c}"/> <apex:outputField value="{!us.unit.detail__c}"/> </apex:repeat> </apex:pageBlock> </apex:page> A: I do not see a reRender attribute in your apex:commandButton, which takes an Id as a parameter, and specifies which portion of the page to (aptly) rerender. Your command button also needs to be wrapped in a apex:form tag in order to function. I would try something like: <apex:page controller="sample_search" > <apex:form> <apex:pageBlock> <apex:inputField value="{!cont.ParentId}"> <apex:inputText value="{!partyNo}" id="accinfo1" /> <apex:commandButton value="Go" action="{!runQuery}" reRender="reRenderThisPls"> </apex:pageBlock> </apex:form> <apex:pageBlock id="reRenderThisPls" rendered="{!run}"> <apex:repeat value="{!Unt_sale}" var="us"> <apex:outputField value="{!us.unit.Name}"/> <apex:outputField value="{!us.unit.subject__c}"/> <apex:outputField value="{!us.unit.detail__c}"/> </apex:repeat> </apex:pageBlock> </apex:page>
{ "pile_set_name": "StackExchange" }
Q: Where can I find AndroidViewClient documentation? Is there any documentation on AndroidViewClient covering public classes, methods, and syntax? A: It is in the doc directory of the project. You have to clone or download the project to view it properly in your browser as github's web interface will show the source code instead. UPDATE jthurner found a way, I didn't know existed, of showing the docs over github pages. You can now view the documentation online at API Documentation.
{ "pile_set_name": "StackExchange" }
Q: How to implement server push in Flask framework? I am trying to build a small site with the server push functionality on Flask micro-web framework, but I did not know if there is a framework to work with directly. I used Juggernaut, but it seems to be not working with redis-py in current version, and Juggernaut has been deprecated recently. Does anyone has a suggestion with my case? A: Have a look at Server-Sent Events. Server-Sent Events is a browser API that lets you keep open a socket to your server, subscribing to a stream of updates. For more Information read Alex MacCaw (Author of Juggernaut) post on why he kills juggernaut and why the simpler Server-Sent Events are in manny cases the better tool for the job than Websockets. The protocol is really easy. Just add the mimetype text/event-stream to your response. The browser will keep the connection open and listen for updates. An Event sent from the server is a line of text starting with data: and a following newline. data: this is a simple message <blank line> If you want to exchange structured data, just dump your data as json and send the json over the wire. An advantage is that you can use SSE in Flask without the need for an extra Server. There is a simple chat application example on github which uses redis as a pub/sub backend. def event_stream(): pubsub = red.pubsub() pubsub.subscribe('chat') for message in pubsub.listen(): print message yield 'data: %s\n\n' % message['data'] @app.route('/post', methods=['POST']) def post(): message = flask.request.form['message'] user = flask.session.get('user', 'anonymous') now = datetime.datetime.now().replace(microsecond=0).time() red.publish('chat', u'[%s] %s: %s' % (now.isoformat(), user, message)) @app.route('/stream') def stream(): return flask.Response(event_stream(), mimetype="text/event-stream") You do not need to use gunicron to run the example app. Just make sure to use threading when running the app, because otherwise the SSE connection will block your development server: if __name__ == '__main__': app.debug = True app.run(threaded=True) On the client side you just need a Javascript handler function which will be called when a new message is pushed from the server. var source = new EventSource('/stream'); source.onmessage = function (event) { alert(event.data); }; Server-Sent Events are supported by recent Firefox, Chrome and Safari browsers. Internet Explorer does not yet support Server-Sent Events, but is expected to support them in Version 10. There are two recommended Polyfills to support older browsers EventSource.js jquery.eventsource A: Redis is overkill: use Server-Sent Events (SSE) Late to the party (as usual), but IMHO using Redis may be overkill. As long as you're working in Python+Flask, consider using generator functions as described in this excellent article by Panisuan Joe Chasinga. The gist of it is: In your client index.html var targetContainer = document.getElementById("target_div"); var eventSource = new EventSource("/stream") eventSource.onmessage = function(e) { targetContainer.innerHTML = e.data; }; ... <div id="target_div">Watch this space...</div> In your Flask server: def get_message(): '''this could be any function that blocks until data is ready''' time.sleep(1.0) s = time.ctime(time.time()) return s @app.route('/') def root(): return render_template('index.html') @app.route('/stream') def stream(): def eventStream(): while True: # wait for source data to be available, then push it yield 'data: {}\n\n'.format(get_message()) return Response(eventStream(), mimetype="text/event-stream") A: As a follow-up to @peter-hoffmann's answer, I've written a Flask extension specifically to handle server-sent events. It's called Flask-SSE, and it's available on PyPI. To install it, run: $ pip install flask-sse You can use it like this: from flask import Flask from flask_sse import sse app = Flask(__name__) app.config["REDIS_URL"] = "redis://localhost" app.register_blueprint(sse, url_prefix='/stream') @app.route('/send') def send_message(): sse.publish({"message": "Hello!"}, type='greeting') return "Message sent!" And to connect to the event stream from Javascript, it works like this: var source = new EventSource("{{ url_for('sse.stream') }}"); source.addEventListener('greeting', function(event) { var data = JSON.parse(event.data); // do what you want with this data }, false); Documentation is available on ReadTheDocs. Note that you'll need a running Redis server to handle pub/sub.
{ "pile_set_name": "StackExchange" }
Q: Why can't I bind a const lvalue reference to a function returning T&&? I was binding some return value of a function to a const lvalue reference, but the object was deleted, before the lifetime of the const lvalue reference ended. In the following example the Foo object is destroyed before the lifetime of foo ends: #include <iostream> #include <string> struct Foo { ~Foo() { std::cout << "Foo destroyed: " << name << std::endl; } std::string name; }; Foo&& pass_through(Foo&& foo) { return std::move(foo); } int main() { const Foo& foo = pass_through({"some string"}); std::cout << "before scope end" << std::endl; } The output is: Foo destroyed: some string before scope end live on coliru: 1 I thought you can bind const T& to anything. Is it bad practice to return T&& and should returning by value be preferred? I stumbled across this in the cpprestsdk here: inline utility::string_t&& to_string_t(std::string &&s) { return std::move(s); } https://github.com/Microsoft/cpprestsdk/blob/master/Release/include/cpprest/asyncrt_utils.h#L109 Very confusing, because the windows version of to_string_t (dispatched by preprocessor macros) returned by value: _ASYNCRTIMP utility::string_t __cdecl to_string_t(std::string &&s); Edit: Why does it work when passing the result of pass_through to a function taking const Foo&? The lifetime is extended in this case? A: From the standard: 15.2 Temporary objects 6.9 A temporary object bound to a reference parameter in a function call persists until the completion of the full-expression containing the call. Essentially what it's saying is that because you passed in a temporary object and then didn't extend its lifetime (say, by moving it into an lvalue) then its lifetime only lasts until the first ; after the call to pass_through in your code. After this point you are left with foo as a dangling reference. int main() { const Foo& foo = pass_through({"some string"}); // "some string" lifetime ends here std::cout << "before scope end" << std::endl; } As to whether it is good practice to to return an rvalue reference I believe these two answers already go into detail on the subject: Should I return an rvalue reference parameter by rvalue reference? Is returning by rvalue reference more efficient?
{ "pile_set_name": "StackExchange" }
Q: How to import an npm module with no available typings? I'm attempting to import this module, but there are no typings available. What is the mechanism in Typescript that will allow me to "ignore" this module? I've looked into setting noImplicitAny to false, but that doesn't feel like the correct approach. A: You can create a *.d.ts file and declare your module: // vorpal.d.ts declare module "vorpal";
{ "pile_set_name": "StackExchange" }
Q: PCIe TLP write packet address only 31:2 bits Let's take a sample write packet : Suppose that the CPU wrote the value 0x12345678 to the physical address 0xfdaff040 using 32-bit addressing This example is from this site (I didn't understand the explanations in the original post) Why does the address start at the second bit [31 : 2] Why isn't the address the same A: An address of an aligned, 32-bit chunk always has two zero bits at the end of the address. You can think of this as either writing the address of the chunk to the 32-bit slot or as writing the addresses divided by four to bits 2 through 31 of the address. The result is the same either way since dividing by four is equivalent to shifting two bit positions to the right.
{ "pile_set_name": "StackExchange" }
Q: APIC 2018.210 OVA: URL format error when associating Analytics with Gateway I am in the process of configuring the local Cloud. I have successfully registered: DataPower Gateway, Analytics and Portal services. When I tried to associate the Analytics and Gateway services, I got this error message: Associate Analytics has not been created! Error validating the request body against definition '#/components/schemas/GatewayService' analytics_service_url Does not match format 'uri' (context: (root).analytics_service_url, line: 1, col: 26) 400 I don't find this message to be at all helpful. The Gateway urls all use ip addresses; Analytics is hostname.domain.name (FQDN) and it is the endpoint defined for analytics-client. The yaml file defines 'analytics-ingestion' as different-hostname.domain.name. I'd be really grateful for any guidance. Regards, John A: This was caused by really poor basic GUI design. On the Associate Analytics Service page, there is only one row (Analytics Service | Availabilty Zone). On the far left is an extremely faint circular checkbox. I hadn't spotted it so it was not selected. It works when the checkbox selected. The Associate button should be disabled when the checkbox isn't selected. That's the poor design. It would also help if the checkbox were to be easier to spot. John
{ "pile_set_name": "StackExchange" }
Q: Seeing if values in a list are of equal value ~Python I was wondering if their is a way to see similar values in a list. So i could say if 2 numbers of the list are of equal value print that number. Thanks for the help EDIT: i was wondering if this would work a = [] v = 0 while v == 1: n = x - (func1sub/func1dsub) a.append(n) print (a) d = defaultdict(int) for v in a: d[v] += 1 print (v) A: What you want is called a histogram. After you have a histogram, printing what numbers satisfy your condition is easy. There are a few ways to create a histogram. Lets assume we have this list defined: list_ = [1,1,2,3,4,4,4,5,6] By Hand histogram = {} for i in list_: oldfreq = histogram.get(i, 0) # get the old number of times we've seen i, or 0 if we haven't seen it yet histogram[i] = oldfreq+1 # add one to the old count If you have Python >= 2.5, you can use defaultdict() to simplify those two lines in the loop defaultdict from collections import defaultdict histogram = defaultdict(int) # this means, "if we haven't seen a number before, set its default value to the result of int(), which is 0 for i in list_: histogram[i] += 1 If you have Python >= 2.7, you can use Counter, which is specially-made for histogram creation Counter from collections import Counter histogram = Counter(list_) Now that you have your histogram, you can filter it to get only those numbers that occur more than once. twoormore = [n for n,freq in histogram.iteritems() if freq > 1] print twoormore
{ "pile_set_name": "StackExchange" }
Q: Using `this` in Crockford's pseudoclassical inheritance pattern I've just read The Good Parts, and I'm slightly confused about something. Crockford's example of pseudoclassical inheritance goes like this: var Mammal = function (name) { this.name = name; }; Mammal.prototype.get_name = function () { return this.name; }; Part of the problem with this is that the constructor has "its guts hanging out" - the methods are outside of the constructor function. I don't see what's wrong with assigning get_name to this inside the constructor though. Is it because we'd end up with multiple copies of the get_name method? A: Yes, that's basically it. By assigning them to the prototype, they will be inherited by all instances of Mammal: there will only be one single copy of those functions in the entire system, no matter how many Mammals there are.
{ "pile_set_name": "StackExchange" }
Q: Vector operator [ ] return value I'm currently working with a 2d vector representation of a table, like so: vector< vector< myStruct > > table myStruct is a class I have made. Right now, I am making a variable of type myStruct, and setting it equal to a value from the table. I'm doing the following inside of a for loop. myStruct object = table[i][j]; I know that operator [] for a vector returns a reference, but since I'm declaring a new instance of myStruct, is something actually being copied into object? I'm wondering if doing something like the following would be different from what I have above: myStruct & object = table[i][j]; Would this prevent something from being copied, making object only a reference to something from the table, or are both of these doing essentially the same thing? A: Right on both counts. The first one copies into the object being created. The second one does not copy; it creates a reference to the array element.
{ "pile_set_name": "StackExchange" }
Q: Many-To-Many Sorting ASP.NET MVC4, C#. I have two models A and B. They have a many-to-many relationship with each other. Suppose A has a collection of B. I want to sort the collection of B on A and persist it in a database. The correct database design for this is to add an additional property to the bridge table A_B. However, entity framework does not allow this. What is the best solution to allow sorting in entity framework for many-to-many relationships? Thanks. A: You must model this with two one-to-many relationships instead of a single many-to-many. It means that you have to expose the bridge table as an entity in your model and this entity would have a SortOrder property: public class A_B { [Key, ForeignKey("A"), Column(Order = 1)] public int AId { get; set; } [Key, ForeignKey("B"), Column(Order = 2)] public int BId { get; set; } public A A { get; set; } public B B { get; set; } public int SortOrder { get; set; } } The entities A and B get collections not directly to each other but to this intermediate entity: public class A { public int AId { get; set; } public ICollection<A_B> A_Bs { get; set; } } public class B { public int BId { get; set; } public ICollection<A_B> A_Bs { get; set; } } To save the relationship "in sorted order" you could then write for example: var b1 = context.Bs.Find(1); var b2 = context.Bs.Find(2); var a = new A { A_Bs = new List<A_B> { new A_B { B = b1, SortOrder = 1 }, new A_B { B = b2, SortOrder = 2 } } }; context.As.Add(a); context.SaveChanges(); Now, when you load the A entity you can load the collection in that sort order: var a = context.As.Find(1); a.A_Bs = context.Entry(a).Collection(x => x.A_Bs).Query() .Include(y => y.B) .OrderBy(y => y.SortOrder) .ToList(); Here are more details how to work with such a model that has additional data in the bridge table.
{ "pile_set_name": "StackExchange" }
Q: Javascript .getAttribute() works but .attr() does not Try to understand why .getAttribute("id") can get the value but .attr("id") cannot. I wrote a Jquery plugin function and try to get the selector or id from the one that uses the plugin function. In my HTML, the plugin function call is - <script> $(document).ready(function() { var langObj = {"lang" : "en"}; var curMap = {"testMap" : "tttt"}; $("#test_id").testProduct({ 'error_msg' : 'ERROR NOT LOAD.' }).load(langObj, curMap); }); </script> In my JQuery plugin function - (function($){ var pluginName = "testProduct", defaults = {}; $.test.testProduct = function(element, options) { this.apiLoadType = { 'ERROR' : 'error' } this.options = $.extend({}, defaults, options); this.element = element; return this; }; $.test.testProduct.prototype = { _load: function(langObj, curMap) { console.log(this); //Chrome console log #1 console.log(this.element) //Chrome console log #2 this.element.getAttribute("id"); //show the id this.element.attr("id"); //not show the id }, //PUBLIC load: function(langObj, curMap) { var self = this; this._load(langObj, curMap); return this; } } $.fn[pluginName]= function(options) { var el = null; this.each(function () { el = new $.test[pluginName]( this, options ); }); return el; }; })(jQuery); Chrome console log #1 - $.testFn.testProduct {apiLoadType: Object, options: Object, element: div#test_id.test_id2, errorElement: null} apiLoadType: Object element: div#test_id.test_id2 accessKey: "" align: "" baseURI: null attributes: NamedNodeMap 0: id ... className:"test_id2" id:"test_id" outerHTML: "<div id="test_id" class="test_id2"></div>" outerText: "" ... options: Object __proto__: Object Chrome console log #2 - <div id="test_id" class="test_id2"></div> Why this.element.getAttribute("id"); can show the element id? Which Jquery method should I use to get the selector or element id from my element is this case? A: this.element is a native DOM element, accessed via JavaScript, not jQuery, so the .attr() jQuery funciton will not work on it. Try ... $(this.element).attr("id");
{ "pile_set_name": "StackExchange" }
Q: Spring boot transaction cannot work in timer I have a transaction like below, @Transactional public void changeJobStatus(Long jobId){ JobEntity jobEntity = jobRepository.findOneForUpdate(jobId); ... } And findOneForUpdate is to lookup database with pessimistic lock, public interface JobRepository extends CrudRepository<JobEntity, Long>{ @Lock(LockModeType.PESSIMISTIC_WRITE) @Query("select j from JobEntity j where j.id = :id") JobEntity findOneForUpdate(@Param("id") Long id); } This works well, if I call changeJobStatus normally. But when calling in a TimerTask like below, TimerTask task = new TimerTask() { @Override public void run() { changeJobStatus(jobId); } }; timer.schedule(task, waitTime); there would be an exception: javax.persistence.TransactionRequiredException: no transaction is in progress Why this happens? And if there is a way to call transaction in a TimerTask? A: The call to changeJobStatus() is effectively direct to your bean (self-invocation), and therefore not subject to the usual Spring proxying when calling between beans. For this reason no transaction is getting started. See: http://docs.spring.io/spring/docs/current/spring-framework-reference/html/transaction.html#transaction-declarative-annotations search for "self-invocation". There may be several potential ways to approach this: You could auto-wire a reference to your own bean, which would be fulfilled with a proxy, and call thru that; You could use mode="aspectj", which performs bytecode weaving (enhancement). You could control the transaction manually via PlatformTransactionManager; My approach would depend on whether this is isolated, or a common case. If common, I'd investigate "aspectj" mode; but I would probably hope that it were an outlier and I could stick to the standard Spring "proxy" mode.
{ "pile_set_name": "StackExchange" }
Q: Converting datetime to date I have indexes on tbl1.date and tbl2.datetime. When I do the following: EXPLAIN SELECT * FROM tbl1 LEFT JOIN tbl2 ON tbl2.datetime = tbl1.date tbl2.datetime index gets used (as expected) Obviously, I need to convert tbl2.datetime to a date in order for the SELECT statement to work in real life. However, doing so results in none of the indexes getting used: EXPLAIN SELECT * FROM tbl1 LEFT JOIN tbl2 ON DATE(tbl2.date) = tbl1.date What am I missing? UPDATE: I've tried something like this but keep getting syntax error "#1064.... check the manual that corresponds to your MySQL server version for the right syntax to use near 'SELECT * FROM tbl1 LEFT JOIN tbl2 ON DATE( SELECT * FROM (SELECT DISTINCT datetime FROM tbl2.datetime) as tem' at line 1" EXPLAIN SELECT * FROM tbl1 LEFT JOIN tbl2 ON DATE( SELECT * FROM (SELECT DISTINCT datetime FROM tbl2.datetime) as tempTable ) = quotes.GOOG.date A: What am I missing? Nothing - you can't alter the data or data type and expect to be able to use the index. While being altered for the comparison, there's no link between the value in the index and the value you want/need to use. The only option is to store the value in a way that doesn't require the alteration if you want to see an index get used.
{ "pile_set_name": "StackExchange" }
Q: How to write an update hook for git submodules? I would like to copy some files in the submodules in my "vendor/assets" directory to another directory -- "public/assets." I heard about update hooks but I am not sure if they work for submodules. I wrote a simple hook and ran update from commandline, but it didn't work. My update hook looks like this: #.git/gooks/update.rb #!/usr/bin/env ruby puts "Copying files..." So is this even possible? btw, I'm using Braid to manage my submodules. A: The update hook is only run when someone has pushed into the current repository, which doesn't sound like what you want. You could use the post-commit hook, if you want to copy these files into place every time you create a commit in your repository. (That should be sufficient, because you'd need to commit the new version of any submodule in the main project when you change the commit that the submodule is meant to be at. This would be a natural point to update the files in public/assets.) You say that your test hook isn't being run - that may be simply because you have the name wrong. The update hook must be an executable file called .git/hooks/update (n.b. without a .rb suffix). Similarly, a post-commit hook must be .git/hooks/post-commit. You shouldn't create hooks in any particular submodule for this task, since the action the hook will be taking is specific to the main project. Because of that, it doesn't really matter whether the change you're worried about it due to committing a new version of the submodules or just updating any random file. For writing hooks, you'll find the official githooks documentation useful, and possibly these additional tips.
{ "pile_set_name": "StackExchange" }
Q: MVC edit with an HttpPostedFileBase I have been mostly following this tutorial: http://cpratt.co/file-uploads-in-asp-net-mvc-with-view-models/ It created a good create view that allows the user to upload an image. How would I create a similar page that displays the current image file (such as what this shows when the user has selected one in the create view) and still allows the user to select a different image? @model ImageViewModel <form action="" method="post" enctype="multipart/form-data"> @Html.AntiForgeryToken() @Html.ValidationSummary(true) <div> Name: @Html.EditorFor(model => model.Name) </div> <div> Image Upload: @Html.TextBoxFor(model => model.ImageUpload, new { type = "file" }) </div> <button type="submit">Edit</button> </form> public class ImageViewModel { public string Name { get; set; } public HttpPostedFileBase ImageUpload { get; set; } } As it currently is, this just allows the Name to be changed and a new image to be uploaded. I want it to show the filename of the current image, but I don't know of a way to upload info to the HttpPostedFileBase attribute (database is currently holding the filename/path from create). Any thoughts would be appreciated. Thanks. A: Add an extra property to your ImageViewModel and bind the current filename to that property: public class ImageViewModel { public string Name { get; set; } public string FileName { get; set; } public HttpPostedFileBase ImageUpload { get; set; } } In your Edit View just display the FileName property: @model ImageViewModel <form action="" method="post" enctype="multipart/form-data"> @Html.AntiForgeryToken() @Html.ValidationSummary(true) <div> Name: @Html.EditorFor(model => model.Name) </div> <div> Current uploaded file: @Html.DisplayFor(model => model.FileName) </div> <div> Image Upload: @Html.TextBoxFor(m => m.ImageUpload, new { type = "file", value = "test" }) </div> <button type="submit">Save</button> </form>
{ "pile_set_name": "StackExchange" }
Q: Rails - Auto Populate Data in a Table on Deployment - Roles In my app I have a table for ROLES. Pretty simple: 1: Admin, DESC stuff 2: Guest, Desc stuff etc.. The issue I just got hit with was I went to deploy the app on heroku and everything broke, reason was that these default roles in the database were not populated on deployment... Something I hadn't thought about. With Rails 3, is there a way to say, hello Mr Rails, here are the table's default values? on migrate or database create? Thanks A: There is a concept called Seed Data in Rails which you can use to do this. There is a file called seeds.rb is created in the db directory. In which you can create such things. So for example Role.create(:name => "Administrator") will go into this file. You can call rake db:seed to seed this data into your application. There is a railscast about this as well - http://railscasts.com/episodes/179-seed-data.
{ "pile_set_name": "StackExchange" }
Q: React Native code hot load App store prohibits downloading remote code with the sole exception of WebKit + JS: 3.3.2 An Application may not download or install executable code. Interpreted code may only be used in an Application if all scripts, code and interpreters are packaged in the Application and not downloaded. The only exception to the foregoing is scripts and code downloaded and run by Apple's built-in WebKit framework, provided that such scripts and code do not change the primary purpose of the Application by providing features or functionality that are inconsistent with the intended and advertised purpose of the Application as submitted to the App Store. Does this adhere to React Native? Can I host my React Native script bundle on a CDN server and fix bugs by replacing my JS implementation? See: https://facebook.github.io/react-native/docs/embedded-app.html#add-rctrootview-to-container-view A: Yes, you are allowed to hot load JS into your iOS app. This is one of the big advantages of React Native.
{ "pile_set_name": "StackExchange" }
Q: Call method in MainActivty from Fragment I have MainActivty class with DrawerLayout, so I add Fragments dynamically. public void selectDrawerItem(MenuItem menuItem) { Fragment fragment = null; Class fragmentClass; switch(menuItem.getItemId()) { case R.id.nav_websites: fragmentClass = ScreenOne.class; break; case R.id.nav_commands: fragmentClass = ScreenTwo.class; break; case R.id.nav_help: fragmentClass = ScreenThree.class; break; default: fragmentClass = ScreenOne.class; } try { fragment = (Fragment) fragmentClass.newInstance(); } catch (Exception e) { e.printStackTrace(); } FragmentManager fragmentManager = getSupportFragmentManager(); fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit(); setTitle(menuItem.getTitle()); mDrawerLayout.closeDrawers(); } In first fragment public class ScreenOne extends Fragment implements Button.OnClickListener I have a function public void loadText() { SharedPreferences myPrefs; myPrefs = getActivity().getSharedPreferences("myPrefs", MODE_WORLD_READABLE); siteName1.setText(myPrefs.getString("siteName1_txt", "").toString()); siteURL1.setText(myPrefs.getString("siteURL1_txt", "").toString()); } In my mainActivity class, in onCreate method, I want to call loadText() method, I tried ScreenOne fragment = new ScreenOne(); fragment.loadText(); But that didn't work. I can't find fragment by ID or Tag, because they don't havy any. Please, any help or advice woild by much appreciated. A: There are several big problems with your code, these are the problems I see: You really need to get an understanding of How Fragments work You don't know which Fragment you have, but always try to access ScreenOne You want to use a fragment method in onCreate without caring about fragment lifecycle You try to create a Fragment instance, then use it even if it fails You create a fragment with a constructor when you should use newInstance and Arguments Your activity is coupled to your Fragment because you call concrete methods That being said, the easiest fix for this particular problem is to only call the loadText method when you are guaranteed that is the current screen (ie. do it when you change it OR keep a reference to the current item and use instanceOf) public void selectDrawerItem(MenuItem menuItem) { ... try { fragment = (Fragment) fragmentClass.newInstance(); FragmentManager fragmentManager = getSupportFragmentManager(); fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit(); ... if (ScreenOne.class.equals(fragmentClass)) { fragment.loadText(); } } catch (Exception e) { e.printStackTrace(); } } However I want to make clear, this is not the cleanest solution and I recommend you stick with single responsibility and have the fragment be responsible for loading its own text, while the activity is responsible for passing in the value from shared preferences as an argument (or via an interface callback pattern). This avoids any change of loadText being called before the fragment is ready.
{ "pile_set_name": "StackExchange" }
Q: Twitter Search Program I'm using this program, and all the tweets that I'm getting are like this"because it is in Arabic Language": "text": "\\u0637\\u0627\\u0644\\u0628\\u0629 \\u062c\\u0633\\u0645\\u0647\\u0627 \\u062c\\u0628\\u0627\\u0631 \\u062a\\u062a\\u062e\\u062f \\u0645\\u0646 \\u0627\\u0644\\u0634\\u0627\\u0631\\u0639 \\u0648 \\u062a\\u062a\\u0646\\u0627\\u0643..\\n\\n\\u0633\\u0643\\u0633_\\u0627\\u062c\\u0646\\u0628\\u064a\\n\\u0645 I had a question about it and got the answer here the question is : Where I can use ensure_ascii=False in the program so it can read the Arabic tweet correctly? I don't know in which place I need to copy it. A: You need to modify twitter_search.py Replace all json.dump(<something>,fd) For json.dump(<something>,fd,ensure_ascii=False) You'll also need to replace all <file_descriptor> for utf-8 ones import codecs ... ... fd = codecs.open("/tmp/lol", "w", "utf-8") If you're processing the results with python another approach would be to unescape the ascii string. s='\\u0637\\u0627\\u0644\\u0628\\u0629...' print s.encode("utf-8").decode('unicode_escape')
{ "pile_set_name": "StackExchange" }
Q: parse check doesn't work hi guys i am using this method to check if a string can be converted to a date or not but it seems that it's not working, this is the code i wrote, the user inputs a date in this format dd/MM/YYYY then this is what happens for checking it ... String date = JOptionPane.showInputDialog(frame,"Insert Date:"); if (date ==null) { return;} while (!(isValidDate(date))) { JOptionPane.showMessageDialog(frame, "Incorrect Date"); date = JOptionPane.showInputDialog(frame,"Insert Date:"); if (date ==null) { return;} } String[] parts = date.split("/"); int year = Integer.parseInt(parts[2]); int month = Integer.parseInt(parts[1]); int day = Integer.parseInt(parts[0]); ... and this is the method for check the date public boolean isValidDate(String dateString) { SimpleDateFormat df = new SimpleDateFormat("dd/MM/YYYY"); if (dateString.length() != "ddMMYYYY".length()) { return false; } try { df.parse(dateString); return true; } catch (ParseException e) { return false; } this seems not to work cause it always goes into the while block whatever i insert in the input, what is the problem with this code ? EDIT fixed the error on the condition if (dateString.length() != "ddMMYYYY".length()) now i got another problem it accepts values like 54/12/2030 which obvioiusly are not a date format A: Your if condition seems to be wrong... This is how it should be. if (dateString.length() != "dd/MM/YYYY".length()) return false; if input date is 22/07/1986 obviously it's length will be more than length of ddMMYYYY because of missing slashes. df.setLenient(false); Will ensure that it won't roll over for invalid dates. Just put thiss line after you created df object.
{ "pile_set_name": "StackExchange" }
Q: Bad input argument to theano function I am new to theano. I am trying to implement simple linear regression but my program throws following error: TypeError: ('Bad input argument to theano function with name "/home/akhan/Theano-Project/uog/theano_application/linear_regression.py:36" at index 0(0-based)', 'Expected an array-like object, but found a Variable: maybe you are trying to call a function on a (possibly shared) variable instead of a numeric array?') Here is my code: import theano from theano import tensor as T import numpy as np import matplotlib.pyplot as plt x_points=np.zeros((9,3),float) x_points[:,0] = 1 x_points[:,1] = np.arange(1,10,1) x_points[:,2] = np.arange(1,10,1) y_points = np.arange(3,30,3) + 1 X = T.vector('X') Y = T.scalar('Y') W = theano.shared( value=np.zeros( (3,1), dtype=theano.config.floatX ), name='W', borrow=True ) out = T.dot(X, W) predict = theano.function(inputs=[X], outputs=out) y = predict(X) # y = T.dot(X, W) work fine cost = T.mean(T.sqr(y-Y)) gradient=T.grad(cost=cost,wrt=W) updates = [[W,W-gradient*0.01]] train = theano.function(inputs=[X,Y], outputs=cost, updates=updates, allow_input_downcast=True) for i in np.arange(x_points.shape[0]): print "iteration" + str(i) train(x_points[i,:],y_points[i]) sample = np.arange(x_points.shape[0])+1 y_p = np.dot(x_points,W.get_value()) plt.plot(sample,y_p,'r-',sample,y_points,'ro') plt.show() What is the explanation behind this error? (didn't got from the error message). Thanks in Advance. A: There's an important distinction in Theano between defining a computation graph and a function which uses such a graph to compute a result. When you define out = T.dot(X, W) predict = theano.function(inputs=[X], outputs=out) you first set up a computation graph for out in terms of X and W. Note that X is a purely symbolic variable, it doesn't have any value, but the definition for out tells Theano, "given a value for X, this is how to compute out". On the other hand, predict is a theano.function which takes the computation graph for out and actual numeric values for X to produce a numeric output. What you pass into a theano.function when you call it always has to have an actual numeric value. So it simply makes no sense to do y = predict(X) because X is a symbolic variable and doesn't have an actual value. The reason you want to do this is so that you can use y to further build your computation graph. But there is no need to use predict for this: the computation graph for predict is already available in the variable out defined earlier. So you can simply remove the line defining y altogether and then define your cost as cost = T.mean(T.sqr(out - Y)) The rest of the code will then work unmodified.
{ "pile_set_name": "StackExchange" }
Q: Access Functions via Dictionary I have a function like this: def abc(a,b): return a+b And I want to assign it to a dictionary like this: functions = {'abc': abc(a,b)} The trouble is, when assigning it to the dictionary, since the arguments are not yet defined, I get the error: NameError: name 'a' is not defined I would do the obvious thing and define the arguments ahead of time but I need to define them in a loop (and then call the function based on locating it in a list) like this: functions_to_call = ['abc'] for f in functions_to_call: a=3 b=4 #This is supposed to locate and run the function from the dictionary if it is in the list of functions. if f in functions: functions[f] A: I need to define them in a loop (and then call the function based on locating it in a list) Then what's the issue with simply saving the function object in the dictionary: functions = {'abc':abc} and then applying a and b to the function while looping: functions_to_call = ['abc'] for f in functions_to_call: a, b = 3, 4 if f in functions: functions[f](a, b) A: You assign a reference to the function without any arguments, and then supply them when calling it: functions = {'abc':abc} # Assignment: no arguments! functions_to_call = ['abc'] for f in functions_to_call: a=3 b=4 if f in functions: functions[f](a, b) # calling with arguments
{ "pile_set_name": "StackExchange" }
Q: XPTable values added to combobox column not showing I am using an XPTable (http://www.codeproject.com/Articles/11596/XPTable-NET-ListView-meets-Java-s-JTable) and try to add a comboBox column. The comboBox column shows in the table but has no dropdown items to select. Here is my code: tblOrdModel.Rows.Clear(); var combo = new XPTable.Editors.ComboBoxCellEditor(); List<Supplier> sups = new DataRepository().GetSuppliers(); foreach (var s in sups) { combo.Items.Add(s); } combo.SelectedIndex = 0; combo.DropDownStyle = XPTable.Editors.DropDownStyle.DropDownList; colOrdModel.Columns[4].Editor = combo; XPTable.Models.Row r = new Row(); r.Tag = tli.ItemRawMaterial; r.Cells.Add(new Cell(tli.ItemRawMaterial.RM_StockCode)); r.Cells.Add(new Cell(tli.ItemRawMaterial.StockDescription)); r.Cells.Add(new Cell(tli.ItemQty)); r.Cells.Add(new Cell(tli.ItemDueDate.ToShortDateString())); r.Cells.Add(new Cell(combo.Items[0])); tblOrdModel.Rows.Add(r); Why is this not working? A: Ok, found the problem. I had the column not set to editable...set in designer or with: colOrdModel.Columns[4].Editable=true; Hope it helps someone else!
{ "pile_set_name": "StackExchange" }