text
stringlengths
64
89.7k
meta
dict
Q: Setting Up Drupal 8 REST Post Request I am having issues sending a POST request to create a node with Drupal 8 Core REST. Here are the steps I have went through several times. Note that these steps are in effort to produce a working example, I am not worried about the security implications as of yet. Install latest version of drupal 8 Enable all core web services modules (HAL, HTTP Basic Authentication, RESTful Web Services, Serialization) Go to permissions page. Find RESTful Web Services permissions and allow delete, get, patch, and post for all users. Find Node Article permissions, allow create, delete and edit for all users. Launch Dev HTTP Client in Chrome. Input the following request: After hitting Send, I receive the following message which I believe should be a 201 and not a 200 if a node were to successfully be created. I think the REST part is working, its just I cant seem to figure out how to get POST to create a node. I am having trouble finding any documentation on making post requests to Drupal 8 REST. Insight into how to construct these requests so that Drupal can parse them successfully would be very helpful. A: As I still ran into a lot of 403 Forbidden errors I'll summarize my overall solution here (Drupal 8.0.1): 1.) Setup & Configuration Enable all core web services modules (HAL, HTTP Basic Authentication, RESTful Web Services, Serialization Enable relevant permissions of RESTful Web Services and for creating the relevant Nodes. 2.) Get a CSRF Token: GET http://your-drupal8/rest/session/token 3.) POST to create a new node POST http://your-drupal8/entity/node?_format=hal+json Note that the URL for POST seems to be /entity/node rather than /node Headers: Authorization: Basic QWRt... X-CSRF-Token: zCf... Data { "title": [ { "value": "atest2" } ], "type": [ { "target_id": "article" } ], "_links": { "type": { "href": "http://your-drupal8/rest/type/node/article" } } } A: I posted the solution on the (identical) issue on drupal.org: https://www.drupal.org/node/2472451#comment-9903259 Also see the Dev HTTP Client screenshot attached in that comment. Basically there are a couple of things wrong in your example: endpoint is /entity/node add Accept header "application/json" add CSRF token (which can be requested via /rest/session/token)
{ "pile_set_name": "StackExchange" }
Q: Search accurev depot for unused workspaces Is there anyway using accurev CLI that I can search for old unused workspaces? Some way that I can get a list of workspaces that havent been accessed in x amount of days for example? A: The best you can do is to create a script. The logic will be to run the command 'accurev show -fx wspaces'. From this output, you will see a "Trans" value. Example output below. Trans="196431" This value is the workspace transaction level based upon the last time the workspace was successfully updated. You can run the command 'accurev hist -fx -p depotname -t TransNumber' From ths output, you will see a "time" value. Example output below. time="1361564066" This is the time value per workspace transaction level. You will convert this into a readable format using the command: perl -e "print scalar localtime(1361564066);" Example output. Fri Feb 22 15:14:26 2013 That all being said, you can compare this time against the current time to determine any old workspaces that have not been in use.
{ "pile_set_name": "StackExchange" }
Q: VC++ 2010 error in C struct malloc code Please consider the following C code in VC++2010 for creating BST in C language. By creating win32 console application in VC++ project. #include <stdio.h> #include <conio.h> #include <stdlib.h> #include <string.h> typedef struct BSTNode { char *data; struct BSTNode *left,*right; }Node; Node *createNode(char *str) { int strLength=strlen(str); char *data=(char *)malloc(strLength+1); strcpy(data,str); data[strLength+1]='\0'; Node *temp=(Node *)malloc(sizeof(Node)); temp->left=0; temp->right=0; temp->data=data; return temp; } int main() { Node *root=createNode("Ravinder"); printf("%s\n",root->data); return 0; } It give errors in VC++2010: warning C4996: 'strcpy': This function or variable may be unsafe. Consider using strcpy_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details. c:\users\radha krishna\documents\visual studio 2010\projects\binarysearchtree\binarysearchtree\main.c 17 warning C4047: 'return' : 'Node *' differs in levels of indirection from 'int' c:\users\radha krishna\documents\visual studio 2010\projects\binarysearchtree\binarysearchtree\main.c 25 error C2275: 'Node' : illegal use of this type as an expression c:\users\radha krishna\documents\visual studio 2010\projects\binarysearchtree\binarysearchtree\main.c 20 error C2223: left of '->right' must point to struct/union c:\users\radha krishna\documents\visual studio 2010\projects\binarysearchtree\binarysearchtree\main.c 22 error C2223: left of '->left' must point to struct/union c:\users\radha krishna\documents\visual studio 2010\projects\binarysearchtree\binarysearchtree\main.c 21 error C2223: left of '->data' must point to struct/union c:\users\radha krishna\documents\visual studio 2010\projects\binarysearchtree\binarysearchtree\main.c 23 error C2065: 'temp' : undeclared identifier c:\users\radha krishna\documents\visual studio 2010\projects\binarysearchtree\binarysearchtree\main.c 20 error C2065: 'temp' : undeclared identifier c:\users\radha krishna\documents\visual studio 2010\projects\binarysearchtree\binarysearchtree\main.c 21 error C2065: 'temp' : undeclared identifier c:\users\radha krishna\documents\visual studio 2010\projects\binarysearchtree\binarysearchtree\main.c 22 But if i replace above function createnode by this it work fine: Node *createNode(char *str) { Node *temp=(Node *)malloc(sizeof(Node)); temp->left=0; temp->right=0; temp->data=str; return temp; } A: MSVC 2010 does not support the modern dialects of C such as C99 - it is still only C89, so you need to move all variable declarations to the start of your function, e.g. a cleaned up version of your function might look like this: Node *createNode(const char *str) { int strLength = strlen(str); char *data = malloc(strLength + 1); Node *temp = malloc(sizeof(*temp)); strcpy(data, str); temp->left = NULL; temp->right = NULL; temp->data = data; return temp; } Note there was a serious bug here: data[strLength+1]='\0'; which would have caused an invalid write to unallocated memory. This should have been: data[strLength]='\0'; However this operation is redundant anyway, as strcpy will already have written '\0' at the end of the string, so you might as well just delete this line. Note also that you are casting the result of malloc in many places - this is redundant and potentially dangerous - you should remove these casts.
{ "pile_set_name": "StackExchange" }
Q: Cash On Delivery Payment method storewise I want to set Cash On Delivery Payment method storewise so how can it be done? Is it okay to change in system.xml <show_in_default> to make visible in Default Config Mode. <show_in_website> to make visible in Website Mode. <show_in_store> to make visible in Store View Mode. A: I've done in following way by overriding payment system.xml <?xml version="1.0"?> <config> <sections> <payment> <groups> <cashondelivery translate="label"> <label>Cash On Delivery Payment</label> <frontend_type>text</frontend_type> <sort_order>30</sort_order> <show_in_default>1</show_in_default> <show_in_website>1</show_in_website> <show_in_store>1</show_in_store> <fields> <active translate="label"> <label>Enabled</label> <frontend_type>select</frontend_type> <source_model>adminhtml/system_config_source_yesno</source_model> <sort_order>1</sort_order> <show_in_default>1</show_in_default> <show_in_website>1</show_in_website> <show_in_store>1</show_in_store> </active> <title translate="label"> <label>Title</label> <frontend_type>text</frontend_type> <sort_order>10</sort_order> <show_in_default>1</show_in_default> <show_in_website>1</show_in_website> <show_in_store>1</show_in_store> </title> <order_status translate="label"> <label>New Order Status</label> <frontend_type>select</frontend_type> <source_model>adminhtml/system_config_source_order_status_new</source_model> <sort_order>20</sort_order> <show_in_default>1</show_in_default> <show_in_website>1</show_in_website> <show_in_store>1</show_in_store> </order_status> <allowspecific translate="label"> <label>Payment from Applicable Countries</label> <frontend_type>allowspecific</frontend_type> <sort_order>50</sort_order> <source_model>adminhtml/system_config_source_payment_allspecificcountries</source_model> <show_in_default>1</show_in_default> <show_in_website>1</show_in_website> <show_in_store>1</show_in_store> </allowspecific> <specificcountry translate="label"> <label>Payment from Specific Countries</label> <frontend_type>multiselect</frontend_type> <sort_order>51</sort_order> <source_model>adminhtml/system_config_source_country</source_model> <show_in_default>1</show_in_default> <show_in_website>1</show_in_website> <show_in_store>1</show_in_store> <can_be_empty>1</can_be_empty> </specificcountry> <instructions translate="label"> <label>Instructions</label> <frontend_type>textarea</frontend_type> <sort_order>62</sort_order> <show_in_default>1</show_in_default> <show_in_website>1</show_in_website> <show_in_store>1</show_in_store> </instructions> <min_order_total translate="label"> <label>Minimum Order Total</label> <frontend_type>text</frontend_type> <sort_order>98</sort_order> <show_in_default>1</show_in_default> <show_in_website>1</show_in_website> <show_in_store>1</show_in_store> </min_order_total> <max_order_total translate="label"> <label>Maximum Order Total</label> <frontend_type>text</frontend_type> <sort_order>99</sort_order> <show_in_default>1</show_in_default> <show_in_website>1</show_in_website> <show_in_store>1</show_in_store> </max_order_total> <sort_order translate="label"> <label>Sort Order</label> <frontend_type>text</frontend_type> <sort_order>100</sort_order> <show_in_default>1</show_in_default> <show_in_website>1</show_in_website> <show_in_store>1</show_in_store> </sort_order> </fields> </cashondelivery> </groups> </payment> </sections> </config> And in module app/etc/modules/mymodule.xml <?xml version="1.0"?> <config> <modules> <my_module> <active>true</active> <codePool>local</codePool> <depends> <Mage_Payment /> </depends> </my_module> </modules> </config> Since in all stores currency is same so I think it won't be a problem.
{ "pile_set_name": "StackExchange" }
Q: Can't create on premise service fabric cluster using the powershell scripts When I attempt to create a cluster using the CreateServiceFabricCluster.ps1 script I get the following error: "JSON config is invalid. Check syntax/model.: System.IO.FileNotFoundException: Could not load file or assembly 'Newtonsoft.Json, Version=6.0.0.0...". I have tried this three different systems (2012 R2, and two 2016 servers) with the same results. I'm using runtime version 5.3.3.11 and SDK version 2.3.311. A: I found the problem. You can't have the Service Fabric Runtime or SDK installed on the same machine you are building the cluster on. Once I removed both of those I was able to create the cluster.
{ "pile_set_name": "StackExchange" }
Q: Rewriting $a+b + |a- b|$ Quoting: Write the following expression in equivalent forms not involving absolute values: $$a+b + |a- b|$$ long time I did not look at this. Here are all the cases I see existing: Case 1: when $a \geq 0$, $b\geq0$, and $a> b$ Case 2: when $a \geq 0$, $b\geq0$, and $b> a$ Case 3: when $a \geq 0$, $b\leq0$ Case 4: when $a \leq 0$, $b\geq0$ Case 5: when $a \leq 0$, $b\leq0$, and $a> b$ Case 6: when $a \leq 0$, $b\leq0$, and $b> a$ am i going in the right direction? or is there another way more efficient? any input is much appreciated A: The form of the formula varies depending on the sign of the expression $(a-b)$ under the module, therefore: $$a+b + |a - b| = \begin{cases} 2b,\text{ if } a < b\\ 2a,\text{ if } a\ge b. \end{cases}$$
{ "pile_set_name": "StackExchange" }
Q: Why didn't Dumbledore make a sound when he appeared at Privet Drive? In Harry Potter and the Sorcerer's Stone, Dumbledore appears at Privet Drive: A man appeared on the corner the cat had been watching, appeared so suddenly and silently you'd have thought he'd just popped out of the ground. The cat's tail twitched and its eyes narrowed. As far as I know, the only ways to travel almost instantaneously in the wizarding world are apparition, portkeys, and floo powder. I think we can ignore floor powder in this case. In most instances of apparition in the books, there is a reference to a loud "crack" sound: With two loud cracks, Fred and George, Ron’s elder twin brothers, had materialised out of thin air in the middle of the room. Pigwidgeon twittered more wildly than ever and zoomed off to join Hedwig on top of the wardrobe. ... And with another loud crack, the twins Disapparated ... The door slammed shut and at the same moment a loud crack echoed inside the cellar... revealing Dobby the house-elf, who has just Apparated into their midst. ... But then, with a very faint pop, a slim, hooded figure appeared out of thin air on the edge of the river... With a second and louder pop, another hooded firugre materialized. ... With a crack like a whip, Dobby vanished. ... There was a loud crack, and a house-elf appeared. According to the Harry Potter Wiki: Apparition can cause an audible noise ranging from a small faint pop to a loud crack that may sound to Muggles like a car backfiring. House-elves may also Apparate but without some of the restrictions that wizards have. For example, they can Apparate inside of Hogwarts and even the Crystal Cave, where powerful enchantments prevent witches and wizards from doing the same. Also, when they Apparate, the sound is mostly a loud crack. Finally, according to this answer: Fortunately JKR provided (most probably unintentionally) a nice explanation about how is this avoided - every time someone apparates/disapparates a loud bang is heard. This bang is most probably caused by the air filling in the vacuum when someone disapparates and the air being pushed out when someone apparates. I can think of 3 explanations for Dumbledore's silent appearance on Privet Drive: He is sufficiently skilled in apparition so that he does not make any sound. This would invalidate part of the answer to the question linked above. He was already on Privet Drive and simply deactivated his disguise, which would most likely have been a Disillusionment Charm. He did not apparate, but used some other form of instantaneous transportation that is not mentioned in the canon. So, the main question: Why did Dumbledore not make a sound when he appeared on Privet Drive? A: I was under the impression that those who were more skilled at apparation could do so quieter and even silently. Now some instances Rowling may have left out mention of pops/cracks as they did not contribute to the story, or they may have been left out simply because there were none/not audible. Inexperienced / Low Skilled Wizards We see those that are inexperienced or weaker apparating loudly: Fred and George: 'Mum,' said George and without further ado there was a loud crack and Harry felt the weight vanish from the end of his bed. (Order of the Phoenix, Chapter 6) Mundungus: A loud, echoing crack broke the sleepy silence like a gunshot; (Order of the Phoenix, Chapter 1) Gasping and spluttering, Mundungus seized his fallen case, then--CRACK-- he Disapparated. (Half-Blood Prince, Chapter 12) Experienced / Skilled Wizards While those that are typically more skilled being quieter (or no mention at all of popping/cracking): Assorted Death Eaters: The air was suddenly full of the swishing of cloaks. Between graves, behind the yew tree, in every shadowy space, wizards were Apparating. (Goblet of Fire, Chapter 33) Twycross: Twycross stepped forwards, turned gracefully on the spot with his arms outstretched and vanished in a swirl of robes, reappearing at the back of the Hall. (Half-Blood Prince, Chapter 18) Narcissa and Bellatrix: But then, with a very faint pop, a slim, hooded figure appeared out of thin air on the edge of the river. ... With a second and louder pop, another hooded figure materialized. (Half-Blood Prince, Chapter 2) Does the above hint that Narcissa, while more reserved, is more powerful than Bellatrix? Dumbledore and Voldemort In the Battle of the Ministry of Magic, we see instances of both Voldemort and Dumbledore apparating. 'Don't waste your breath!' yelled Harry, his eyes screwed up against the pain in his scar, now more terrible than ever. 'He can't hear you from here!' 'Can't I, Potter?' said a high, cold voice. Harry opened his eyes. Tall, thin and black-hooded, his terrible snakelike face white and gaunt, his scarlet, slit-pupilled eyes staring ... Lord Voldemort had appeared in the middle of the hall, his wand pointing at Harry who stood frozen, quite unable to move. (Order of the Phoenix, Chapter 36) In the passage above Voldemort appears completely silently. There is no mention of a crack or pop, and Harry only realizes Voldemort is present when he speaks. Later in the same chapter we have, Voldemort raised his wand and another jet of green light streaked at Dumbledore, who turned and was gone in a whirling of his cloak. Next second, he had reappeared behind Voldemort and waved his wand towards the remnants of the fountain. ... Voldemort, who vanished and reappeared beside the pool. ... Voldemort vanished; ... Then he was gone and the water fell with a crash back into its pool, slopping wildly over the sides, drenching the polished floor. Again, no mention of any sound being made or any of the characteristic CRACK we see with other practitioners. A: It's not much, but here's something Dumbledore says a bit later: "All day? When you could have been celebrating? I must have passed a dozen feasts and parties on my way here." If he had a "way here", and he "passed" things, then he didn't just Apparate straight from Hogwarts. It could've been a Disillusionment Charm that made him "appear." Or he could have used James's Invisibility Cloak, which I believe he had at the time. He definitely didn't Apparate there, since, obviously, there would be a loud crack if he did. It's not just that he's super good at Apparating. A: Maybe he didn't Apparate. This quote doesn't state that he Apparated or appeared while spinning, only that he appeared: A man appeared on the corner the cat had been watching, appeared so suddenly and silently you'd have thought he'd just popped out of the ground. The cat's tail twitched and its eyes narrowed. Later in Sorcerer's Stone he tells Harry: "I don't need a cloak to become invisible," said Dumbledore gently. Perhaps he simply removed the Disillusionment charm which would have been completely silent. Or as has been stated by Valorum in the comments, his Apparating could be so advanced that he no longer makes noise. Without a direct quote from JKR we may never know.
{ "pile_set_name": "StackExchange" }
Q: OpenCV 2.3 with VS 2008 - Mouse Events Obligatory - I'm a newbie. Have a job that involves programming and I'm teaching myself as I go. Needless to say as a teacher I get things wrong frequently and thoroughly. Where I'm at right now: I've created the class "Graph", it (surprisingly enough) makes graphs. But now I want to make it so that on a mouse click I modify the graph. But I can't seem to get a mouse handler to be a member function of the class. cv::setMouseCallback(windowName, onMouse, 0); // Set mouse handler to be onMouse Doesn't work with cv::setMouseCallback(windowName, Graph::onMouse, 0); It gives me lack of parameter errors. According to this I can't make it a member function. After following the answer given, it compiles but my this pointer is nulled. Ugh. OnMouse looks like this: void onMouse(int event, int x, int y,int, void*) { if (event == CV_EVENT_LBUTTONDOWN) { cvMoveWindow("Window", 500, 500); //Just to see if stuff happened } return; } I don't care about moving the window, I want to modify the graph itself - which is stored as a cv::Mat variable in a Graph object. And I can't figure out how to do it. Any help would be appreciated, and I really hope this wasn't just gibberish. A: Yes callback functions in C++ are a joy, aren't they? You actually have to give OpenCV a function (not a class method) as you've already found out. However, you can hack around this awfulness using the following technique: class MyClass { public: void realOnMouse(int event, int x, int y, int flags) { // Do your real processing here, "this" works fine. } }; // This is a function, not a class method void wrappedOnMouse(int event, int x, int y, int flags, void* ptr) { MyClass* mcPtr = (MyClass*)ptr; if(mcPtr != NULL) mcPtr->realOnMouse(event, x, y, flags); } int main(int argv, char** argc) { // OpenCV setup stuff... MyClass processor; cv::setMouseCallback(windowName, wrappedOnMouse, (void*)&processor); // Main program logic return 0; } That last parameter on setMouseCallback is quite useful for overcoming some of the problems you usually encounter like this.
{ "pile_set_name": "StackExchange" }
Q: Django Admin ManyToMany error I'm using the the built in django admin site to save instances of a model that has a ManyToMany field. If I save, not update, a model in the admin site without setting a value for the ManyToMany field it saves fine. I can also come back and set the ManyToMany field after saving the model and that works. However, if I try to save a new instance of my model, Exercise, that has the ManyToMany field, Exercise.muscles, set I get the following error: (1452, 'Cannot add or update a child row: a foreign key constraint fails (vitality.projectvitality_exercise_muscles, CONSTRAINT exercise_id_refs_exercise_id_a5d4ddd6 FOREIGN KEY (exercise_id) REFERENCES projectvitality_exercise (exercise_id))') My mysql tables are set to INNODB. My models are as follows: class Muscle(models.Model): def format(self): return "name:{0}:".format(self.name) def __unicode__(self): return unicode(self.name) muscle_id = UUIDField(primary_key = True) name = models.CharField(max_length=30, blank=False, default="") medical = models.CharField(max_length=150, blank=True, default="") description = models.TextField(blank=True, default="") class Exercise(models.Model): def format(self): return "name:{0}".format(self.name) def __unicode__(self): return unicode(self.name) ISOLATION_TYPE = "isolation" COMPOUND_TYPE = "compound" FULL_BODY_TYPE = "full" EXERCISE_TYPES = ( (ISOLATION_TYPE, "Isolation"), (COMPOUND_TYPE, "Compound"), (FULL_BODY_TYPE, "Full Body") ) UPPER_BODY_GROUP = "upper" LOWER_BODY_GROUP = "lower" GROUP_CHOICES = ( (UPPER_BODY_GROUP, "Upper Body"), (LOWER_BODY_GROUP, "Lower Body") ) exercise_id = UUIDField(primary_key=True) name = models.CharField(max_length=30, default="", blank=False) description = models.TextField(blank=True, default="") group = models.CharField(max_length=255, choices=GROUP_CHOICES, blank=False, default=UPPER_BODY_GROUP) exercise_type = models.CharField(max_length=255, choices=EXERCISE_TYPES, blank=False, default=ISOLATION_TYPE) muscles = models.ManyToManyField('Muscle', blank=True, null=True) class Meta: verbose_name = "Exercise" verbose_name_plural = "Exercises" A: After several days of debugging I found the issue. In my code I use UUIDField, from django-extensions library, as a primary key. When saving a new instance of Exercise model it is able to generate, set and save the primary key. However, when saving a new instance of Exercise that has the ManyToMany field set, UUIDField isn't generated in time. This leads to the Django admin attempting to insert a null/empty primary key, the UUIDField in Exercise model, into the join table which triggers the Foreign Key constraint failure.
{ "pile_set_name": "StackExchange" }
Q: How do i add pause button for automatic slideshow? I got the jquery from w3schools, i have looked and tried to add a working pause button but it doesnt work. <div class="realisatie" id="slideshow"> <img class="Realisaties" src="fotos/Slide/Foto1.png" alt="Begin van een werk"> <img class="Realisaties" src="fotos/Slide/Foto2.png" alt="Verdere progressie"> <img class="Realisaties" src="fotos/Slide/Foto3.png" alt="Nog niet gevoegd eindwerk"> <img class="Realisaties" src="fotos/Slide/Foto4.png" alt="Eindwerk + gevoegd"> <img class="Realisaties" src="fotos/Slide/Foto5.png" alt="Begin van een tweede werk"> <img class="Realisaties" src="fotos/Slide/Foto6.png" alt="Progressie van tweede werl"> <img class="Realisaties" src="fotos/Slide/Foto7.png" alt="Nog niet gevoegd eindwerk 2"> <img class="Realisaties" src="fotos/Slide/Foto8.png" alt="Eindwerk van een tweede werk"> <img class="Realisaties" src="fotos/Slide/Foto9.jpg" alt="Begin van een derde werk"> <img class="Realisaties" src="fotos/Slide/Foto10.jpg" alt="Progressie van eend erde werk"> <img class="Realisaties" src="fotos/Slide/Foto11.jpg" alt="Derde eindwerk nog niet gevoegd"> <img class="Realisaties" src="fotos/Slide/Foto12.jpg" alt="Derde eindwerk + gevoegd"> <img class="Realisaties" src="fotos/Slide/Foto13.jpg" alt="Houten vloer gelegd"> <img class="Realisaties" src="fotos/Slide/Foto14.png" alt="Andere houten vloer gelegd"> </div> <button class="controls" id="pause">Pause</button> This is my scrip from w3 schools: <script> var myIndex = 0; carousel(); function carousel() { var i; var x = document.getElementsByClassName("Realisaties"); for (i = 0; i < x.length; i++) { x[i].style.display = "none"; } myIndex++; if (myIndex > x.length) { myIndex = 1 } x[myIndex - 1].style.display = "block"; setTimeout(carousel, 2000); // Change image every 2 seconds } </script> This is the code i tried from https://codepen.io/SitePoint/pen/zqVGQK/ var playing = true; var pauseButton = document.getElementById('pause'); function pauseSlideshow(){ pauseButton.innerHTML = 'Play'; playing = false; clearInterval(slideInterval); } function playSlideshow(){ pauseButton.innerHTML = 'Pause'; playing = true; slideInterval = setInterval(nextSlide,2000); } pauseButton.onclick = function(){ if(playing){ pauseSlideshow(); } else{ playSlideshow(); } }; A: You have few issues in your code that @Brad has mentioned them in his comment. So I will fix those and change one or two lines for you: remove the carousel(); at the top of your script. We will call playSlideshow() instead at the end of the code. Remove setTimeout(carousel, 2000); at the end of the carousel() function. We will set the interval in the playSlideshow() function later. in the playSlideshow() function at this line slideInterval = setInterval(nextSlide,2000); you have to change nextSlide to carousel, So carousel() function will be called every 2 seconds. and at last we will call carousel(); one time(to avoid first 2 seconds delay) and then playSlideshow(); That's all. Your html part looks fine. So I did not change it. To sum thing up, your code will look like this: html <div class="realisatie" id="slideshow"> <img class="Realisaties" src="fotos/Slide/Foto1.png" alt="Begin van een werk"> <img class="Realisaties" src="fotos/Slide/Foto2.png" alt="Verdere progressie"> <img class="Realisaties" src="fotos/Slide/Foto3.png" alt="Nog niet gevoegd eindwerk"> <img class="Realisaties" src="fotos/Slide/Foto4.png" alt="Eindwerk + gevoegd"> <img class="Realisaties" src="fotos/Slide/Foto5.png" alt="Begin van een tweede werk"> <img class="Realisaties" src="fotos/Slide/Foto6.png" alt="Progressie van tweede werl"> <img class="Realisaties" src="fotos/Slide/Foto7.png" alt="Nog niet gevoegd eindwerk 2"> <img class="Realisaties" src="fotos/Slide/Foto8.png" alt="Eindwerk van een tweede werk"> <img class="Realisaties" src="fotos/Slide/Foto9.jpg" alt="Begin van een derde werk"> <img class="Realisaties" src="fotos/Slide/Foto10.jpg" alt="Progressie van eend erde werk"> <img class="Realisaties" src="fotos/Slide/Foto11.jpg" alt="Derde eindwerk nog niet gevoegd"> <img class="Realisaties" src="fotos/Slide/Foto12.jpg" alt="Derde eindwerk + gevoegd"> <img class="Realisaties" src="fotos/Slide/Foto13.jpg" alt="Houten vloer gelegd"> <img class="Realisaties" src="fotos/Slide/Foto14.png" alt="Andere houten vloer gelegd"> </div> <button class="controls" id="pause">Pause</button> JavaScript <script> var playing = true; var pauseButton = document.getElementById('pause'); var myIndex = 0; function carousel() { var i; var x = document.getElementsByClassName("Realisaties"); for (i = 0; i < x.length; i++) { x[i].style.display = "none"; } myIndex++; if (myIndex > x.length) { myIndex = 1 } x[myIndex - 1].style.display = "block"; } function pauseSlideshow(){ pauseButton.innerHTML = 'Play'; playing = false; clearInterval(slideInterval); } function playSlideshow(){ pauseButton.innerHTML = 'Pause'; playing = true; slideInterval = setInterval(carousel, 2000); } pauseButton.onclick = function(){ if(playing){ pauseSlideshow(); } else{ playSlideshow(); } }; carousel(); playSlideshow(); </script>
{ "pile_set_name": "StackExchange" }
Q: Remover a linha de um CSV pela posição - PHP Olá.Tenho um formulário que gera um Arquivo CSV com os dados inseridos pelo usuário. Os dados salvos nesse csv são printados na tela onde é atribuido um número para cada linha (1,2,3...). Eu precisava que o usuário pudesse excluir alguma linha que ele quisesse por meio dessa numeração, eu estou tentando fazer por meio de um input, onde ele digita o número da linha e clica no botão "excluir". O que eu não consigo é fazer que a partir do clique do botão seja excluida apenas uma linha (a que tem o mesmo valor digitado pelo usuário), o código está apagando todas. Segue o código que tenho até o momento. //Formulario e criação do CSV <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <?php if ($_POST){ $nome = $_POST["nome"]; $telephone = $_POST["telefone"]; $cargo = $_POST["cargo"]; $setor = $_POST["setor"]; $quantidadeLinhas = count($nome); $dados = ""; $fileName = "dados.csv"; for ($i=0; $i<$quantidadeLinhas; $i++) { $dados .= "$nome[$i],"; $dados .= "$telephone[$i],"; $dados .= "$cargo[$i],"; $dados .= "$setor[$i]"; $dados .= "\n"; } $fileHandle = fopen($fileName,"a+"); fwrite($fileHandle,"$dados"); fclose($fileHandle); } ?> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Formulário</title> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://rawgit.com/RobinHerbots/jquery.inputmask/3.x/dist/jquery.inputmask.bundle.js"></script> <script type="text/javascript" src="adiciona.js"></script> <script type="text/javascript" src="excluiLinha.js"></script> <style type="text/css" media="all"> body{ font-family:Arial, Helvetica, sans-serif } #tudo{ border:#CCCCCC 1px solid;width:570px;margin:0 auto } .bd_titulo{ text-align:center; background-color:#CCCCCC; font-weight:bold } </style> </head> <body> <form method="post" name="frm_campo_dinamico" action=""> <div id="tudo"> <table border="0" cellpadding="2" cellspacing="4" width="100%"> <tr><td colspan="4" class="bd_titulo">Formulário</td></tr> <tr><td colspan="4" align="center"></td></tr> <tr> <td class="bd_titulo" align="center">Nome</td><td class="bd_titulo" align="center">Telefone</td><td class="bd_titulo" align="center">Cargo</td><td class="bd_titulo" align="center">Setor</td> </tr> <tr class="linhas"> <td> <input style="text-align:center" align="center" type="text" name="nome[]"/> </td> <td> <input type="text" id = "telefone" align="center" name="telefone[]" class = "telMask"/> </td> <td> <select name="cargo[]"> <option>Selecione</option> <option value="Auxiliar">Auxiliar</option> <option value="Secretária">Secretária</option> <option value="Gerente">Gerente</option> </select> </td> <td> <select name="setor[]"> <option>Selecione</option> <option value="Comercial">Comercial</option> <option value="Administrativo">Administrativo</option> </select> </td> </td> </tr> <tr> <td colspan="4"> <a href="#" class="adicionarCampo" title="Adicionar item"><img src="add.svg" border="0" /></a> </td> </tr> <tr> <td align="center" colspan="0"> <td align="right" colspan="4"> <input type="submit" id="Salvar" value="Salvar" class = "gwt-Button" /> </td> </tr> </tr> </table> </form> </div> <hr width="1" size="1" color = "white"> <div id="tudo"> <table border="0" cellpadding="2" cellspacing="4" width="100%"> <tr><td colspan="4" class="bd_titulo">Dados Salvos</td></tr> <tr><td colspan="4" align="center"></td></tr> <tr> <td class="bd_titulo" align="center">Linha</td><td class="bd_titulo" align="center">Nome</td>td class="bd_titulo" align="center">Telefone</td><td class="bd_titulo" align="center">Cargo</td><td class="bd_titulo" align="center">Setor</td> </tr> <tr> <td align="center"><font color="black"><?php $file = fopen('dados.csv','r'); $contando = 1; while (($line = fgetcsv($file)) !== false){echo $contando++."<br />";} ?></font></td> <td align="center"><font color="black"><?php $file = fopen('dados.csv','r'); while (($line = fgetcsv($file)) !== false){echo $line[0]."<br />";}?></font></td> <td align="center"><font color="black"><?php $file = fopen('dados.csv','r'); while (($line = fgetcsv($file)) !== false){echo $line[1]."<br />";}?></font></td> <td align="center"><font color="black"><?php $file = fopen('dados.csv','r'); while (($line = fgetcsv($file)) !== false){echo $line[2]."<br />";}?></font></td> <td align="center"><font color="black"><?php $file = fopen('dados.csv','r'); while (($line = fgetcsv($file)) !== false){echo $line[3]."<br />";}?></font></td> </tr> </table> </form> </div> <hr width="1" size="1" color = "white"> <form method="post" name="salvos" action=""> <div id="tudo"> <table border="0" cellpadding="2" cellspacing="4" width="100%"> <tr><td colspan="4" class="bd_titulo">Excluir Linha</td></tr> <tr><td colspan="4" align="center"></td></tr> <tr> <td align="center" colspan="4"> <font color="black">Linha:</font> <input style="text-align:center" type="number" min = "1" name="deletar"/> <input type="submit" id="btnExcluir" value="Excluir" class = "gwt-Button"/> </tr> </table> </form> </div> </body> </html> //para a tabela dinamica $(function () { $(".adicionarCampo").click(function () { novoCampo = $("tr.linhas:first").clone(); novoCampo.find("input").val(""); novoCampo.insertAfter("tr.linhas:last"); }); }); //Ajax quando clica no botão de excluir $(document).ready(function() { $('#btnExcluir').click(function(){ //Pega o valor a ser excluido var deletar = $("deletar").val(); $.ajax({ type: "POST", url: "deletarLinhas.php", data: deletar, success: function () { alert("Teste se tá enviando"); } }); }); }); //PHP que vai excluir a linha (Parte que não funciona) <?php $removerLinha = $_POST["deletar"]; $meuArray = Array(); $file = fopen("dados.csv", "r"); while (($line = fgetcsv($file)) !== false){ $meuArray[] = $line; } fclose($file); $remover = $removerLinha - 1; $linhas = count(file("dados.csv")); $limite = $linhas -1; //verifica se o valor dado pelo usuário é menor ou igual ao numero de linhas do arquivo if ($remover<=$limite){ //remove unset($meuArray[$remover]); $meuArray = array_values($meuArray); //realinha var_dump($meuArray); //reescreve o arquivo sem a linha excluida $fileHandle = fopen("dados.csv","w"); fwrite($fileHandle,$meuArray); fclose($fileHandle); } ?> A: No seu arquivo php não conte as linhas do arquivo, já trate no for a linha que deseja remover. Exemplo <?php $removerLinha = $_POST["deletar"] - 1; $meuArray = Array(); $file = fopen("dados.csv", "r"); $index = 0; while (($line = fgetcsv($file)) !== false){ if($index != $removerLinha) { $meuArray[] = implode(",", $line); } $index++; } fclose($file); // apagando arquivo antigo unlink("dados.csv"); // recriando arquivo sem a linha $fileHandle = fopen("dados.csv", "a+"); fwrite($fileHandle, implode("\n", $meuArray)); fclose($fileHandle); E no seu ajax que envia a linha, lembre-se de especificar a propriedade deletar. Exemplo: $(document).ready(function() { $('#btnExcluir').click(function(){ //Pega o valor a ser excluido var deletar = $("[name=\"deletar\"]").val(); $.ajax({ type: "POST", url: "deletarLinhas.php", data: {deletar: deletar}, success: function () { alert("Teste se tá enviando"); } }); }); }); E pronto, com isso já vai funciona ;)
{ "pile_set_name": "StackExchange" }
Q: python/mongodb pymongo : nested find()/filter I would like to do something like this contents = contents.find() # get all from collection if user filled search box 1: contents = contents.find({'field1':seached_var}) if user filled search box 2: contents = contents.find({'field2':seached_var2}) contents would contain the final filtered result. Is it doable in python with mongodb? A: How about doing it this way: conditions = {} if user filled search box 1: conditions['field1'] = seached_var if user filled search box 2: conditions['field2'] = seached_var2 contents = contents.find(conditions) Hope that helps.
{ "pile_set_name": "StackExchange" }
Q: Multiple conditions in Pandas This is the Table I am working with I need to access the data points with 'Duration'>70 and 'End Terminal'==10 Hence I tried kj[kj['Duration']>70] kj[kj['End Terminal'] == 10] above commands are working fine separately but when I club them as: kj[kj['End Terminal'] == 10] & kj[kj['Duration']>70] there is an error, hence how to use both conditions in one statement in Pandas-Python A: This should do the trick: kj[(kj['End Terminal'] == 10) & (kj['Duration']>70)]
{ "pile_set_name": "StackExchange" }
Q: "R cannot be resolved to a variable " in android Activity i was doing small android application , i added blank xml file but it was showing some error although i did not add any code and still it was showing error so i cleaned project but now after cleaning for my activity when i write setContentView(R.layout.reminder_edit); its giving errors like this R cannot be resolved to a variable , for another activity named ReminderListaActivity i tried this setContentView(R.layout.reminder_edit) error was for xml file not for "R " error was :reminder_edit cannot be resolved or is not a field . xml file is in layout and its showing like never used file so how do i solve this issue , can someone help me with it pleae EDIT code added reminder_edit.xml <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent"> <LinearLayout android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:text="@string/title" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <EditText android:id="@+id/title" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/body" /> <EditText android:id="@+id/body" android:layout_width="fill_parent" android:layout_height="wrap_content" android:minLines="5" android:scrollbars="vertical" android:gravity="top" /> <TextView android:text="@string/date" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <Button android:id="@+id/reminder_time" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/Reminder_Time" /> <TextView android:text="@string/time" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <Button android:id="@+id/remindertime" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/remindertime" /> <Button android:id="@+id/confirm" android:text="@string/confirm" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout> </ScrollView> java File public class ReminderEditActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.reminder_edit); } } A: Fix the errors in XML so the resource compiler can generate R.java for you. A: Remove Import android.R; from imports in your activity class
{ "pile_set_name": "StackExchange" }
Q: Read a CSV file into a Data Grid View (Win Forms) Is there an easy way to read the contents of a CSV file/XML Sitemap (will just be a bunch of URLS) into a Datagrid view in a win form? Thankyou A: There is quite a good article for doing this located here: http://www.codeproject.com/Articles/16951/Populating-data-from-a-CSV-file-to-a-DataGridView the code is in VB.NET but it should be easy to convert either using your own knowledge or using an online conversion tool such as www.developerfusion.com/tools/convert/vb-to-csharp/
{ "pile_set_name": "StackExchange" }
Q: Delivery for the cult From time to times Trevor Phillips will meet random people who'll ask him to drive them somewhere. Trevor can of course do it, or he can deliver them to the Altruist Cult instead. I understand that the cult will reward Trevor with some money, and there's an achievement for doing so too. However, aside from the achievement and moral implications, what are the differences for "doing what's right" and "doing what's wrong"? Will I get more money when making a delivery for the cult? Will I get a different reward than money, when I don't? A: After experimenting for a while (God bless the poor victims' souls) and with the help of the Brady guide I have compiled a handy list related to the cult. For every victim delivered to the cult, Trevor receives $1'000. After he delivered his fourth victim, he will be "invited" by the cult, resulting in a bloodbath shootout. Because of that, you'll have to decide which victims to deliver if you plan on exterminating the cult. Keep in mind that only Trevor can make deliveries to the cult. Here's a list of potential victims, and the rewards they give, when you don't sell them out to the cult. Burial: There's a woman lying on the ground, surrounded by digging men. She's about to be buried alive. The creeps carry quite a bit of cash around. Saving her doesn't instantly give you a reward; her father - a gangster - will be very happy if you do save her and wire $60'000 to your bank account after a while. Domestic: There's a man who's just been thrown out of his home by his wife, who suspects him to be cheating on her. He asks you to drive him to the golf club. Do that, and he'll give you $80, his contact info, and will become available as a "Hard" opponent to play golf against. Drunk Driver 1: Two men are arguing. One of them asks you to drive the drunk other home. Back home, the drunkard will give you $80 and pass out. Drunk Driver 2: A young couple ask you to drive them to their motel. At some point they'll nonchalantly have sex in your car. They reward you with $80. Since they are two people, delivering them to the cult awards $2000. Escape Paparazzi: An actress wants to avoid Paparazzi, because she's not wearing enough make-up. She'll pay $750 for your troubles. Getaway Driver: Two robbers threatening a merchant at gunpoint ask you to help them get away. Do it, and they'll give you a $1000 cut. One of them turns out to be none other than Packie McReary from GTA IV, a fairly skilled Gunman for use in future heists. Hitch Lift 2: [Hitch Lift 1 is not a potential cult victim; this is not a typo] A woman with red backpack asks you to drive her back home. The reward for doing so is her contact info. Hitch Lift 3: A woman is waiting for a car to stop and pick her up. She wants you to take her to a broadcasting station close by the Vinewood sign in order to surprise her boyfriend. The only reward you'll ever get, is her boyfriend threatening to punch your teeth out, if you don't knock him out first. Oh, you could gun him down too, but where's the fun in that? Hitch Lift 4: A bride wants to escape from her groom. Why she ever agreed to marry him is a mystery, even to her. There is no reward for helping her. Snatched: A woman is being abducted by the Lost. You'll have to kill them, then save her. She'll ask you to drop her off someplace, where a friend will pick her up. She won't give you any reward, despite having to deal with a hail of bullets, talk about ungrateful...
{ "pile_set_name": "StackExchange" }
Q: Query in SQL using between Timestamp pulling wrong data I am using this query: SELECT ts as "TimeStamp", stat as "Status" FROM myTable WHERE stat = 'O' AND source = 'Source1' AND ts BETWEEN TO_TIMESTAMP('2013-10-05','yyyy-mm-dd') AND TO_TIMESTAMP('2013-10-06','yyyy-mm-dd') And also tried: SELECT ts as "TimeStamp", stat as "Status" FROM myTable WHERE stat = 'O' AND source = 'Source1' AND ts >= TO_TIMESTAMP('2013-10-05','yyyy-mm-dd') AND ts < TO_TIMESTAMP('2013-10-06','yyyy-mm-dd') It returns 0 records, but if I do SELECT ts as "TimeStamp", stat as "Status" FROM myTable WHERE stat = 'O' I can clearly identify 5 records. Apparently the TO_TIMESTAMP is not working properly I am hoping someone might be able to help identify the proper fix Edit: To clarify, I only want the timeframe for 10/5 not including 10/6 Sorry pasted wrong results Also the field is of type TIMESTAMP(6) A: Because the TO time stamp has time even though you're not specifying. So it is selecting only up to the very beginning of the lat day. Either specify time 23:59:59 and subseconds as required, or do less than the next day. ... AND ts >= TO_TIMESTAMP('2013-10-05','yyyy-mm-dd') AND ts < TO_TIMESTAMP('2013-10-07','yyyy-mm-dd')
{ "pile_set_name": "StackExchange" }
Q: Spring transaction boundary and DB connection holding I am using spring boot and hibernate over jpa with tomcat connection pooling. Can you please help me understanding how spring uses DB connections during transactions. For example consider following scenario: We have DB connection pool of 2 connections. Spring starts a transaction i.e. call method decorated with @Transactional annotation. This method do a DB update The calls an external service As response is received from the external service, it updates DB and return. Spring commits the transaction Assuming the external service(step 4) takes 1 minute to complete, how many DB connections will be available in the DB pool?. Assuming, spring keeps hold of DB connection until the transaction completes, there will be only 1 DB connection available for any request received during this time and if we received more than 1 requests, they will have to wait for DB connection. Please confirm my understanding and if it is correct, suggest how I can handle this situation in a high transaction volume system. Thanks A: First your understanding is correct. See the spring documentation about declarative transaction management. I guess you do the external service call within the transaction, because you want the database changes to be rollbacked in case of an exception. Or in other words you want the db updates to reflect the state of the external service call. If so you can't move it out the transaction boundary. In this case you should either increase your connection pool size or maybe you can delegate long running transactions to a dedicated server node that handles them. This would keep e.g. a "main" server node that handles user requests away from long running transactions. And you should think about the data consistency. Is it really necessary that the db update must be synchronized with the external service call? Can the external service call be moved out of the transaction boundary? A: You can specify initial size and maximum size of connection pool as per your requirement(depends on the performance of your application). For example, <bean id="springDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" > <property name="url" value="jdbc:oracle:thin:@localhost:1521:SPRING_TEST" /> <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" /> <property name="username" value="root" /> <property name="password" value="root" /> <property name="removeAbandoned" value="true"/> <property name="initialSize" value="20" /> <property name="maxActive" value="30" /> </bean> this will create 20 database connection as initialSize is 20 and goes up to 30 Database connection if required as maxActive is 30. you can customize your database connection pool by using different properties provided by Apache DBCP library. Above example is creating connection pool with Oracle 11g database and i am using oracle.jdbc.driver.OracleDriver comes along with ojdbc6.jar or ojdbc6_g.jar
{ "pile_set_name": "StackExchange" }
Q: Adding Shared Library Project Android I'm struggling with adding a library to my project. I've been following a few other SOs as well as the tictactoemain/lib sample Android provides, but I'm still getting a "unable to find explicit activity class" error. The library package I included showing up under Android Dependencies is com.example.surveymetest. I suspect the issue is how I'm calling/defining the activity in the manifest but I can't seem to get it right. Any ideas where I'm going wrong? Here's my manifest: <uses-permission android:name="android.permission.INTERNET" /> <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="18" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.example.surveymedemo.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name="com.example.surveymetest.SurveyActivity" android:label="@string/app_name" > </activity> <activity android:name="com.example.surveymetest.TakeSurveyActivity" > </activity> <provider android:name="com.example.surveymetest.SurveyMeContentProvider" android:authorities="io.surveyme.ContentProviders.SurveyMeContentProvider" android:exported="true" > </provider> </application> </manifest> Calling the Activity: package com.example.surveymedemo; import com.example.surveymetest.StartSurveyActivity; import com.example.surveymetest.SurveyMe; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.view.Menu; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Intent i = new Intent(this, StartSurveyActivity.class); startActivity(i); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } } A: Add: <activity android:name="com.example.surveymetest.StartSurveyActivity" android:label="@string/app_name" > </activity> to your manifest and you should be good. (you only defined com.example.surveymetest.SurveyActivity)
{ "pile_set_name": "StackExchange" }
Q: How to remove from a list 'setequally' duplicated elements in R? Suppose I have some list li in R whose elements are vectors. For instance, li=list(a=c(2,3,5),b=c(77,119,81),c=c(9,11,13),d=c(5,2,3),e=c(80,45,16),f=c(16,17,19),g=c(13,9,11),h=c(22,13,58)) It can be seen that all objects in li are different as vectors. Therefore, duplicated(li) [1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE Also, the command unique(li) will return the same list li. But note that the elements a and d as well as c and g are equal as sets. Namely, setequal(li$a,li$d) [1] TRUE and setequal(li$c,li$g) [1] TRUE Consequently, the element a is duplicated as set by the element d and the element c is duplicated as set by the element g. My question is: How to remove from a list such 'setequally' duplicated elements in R ? A: What about: li[apply(sapply(li, function(x) sapply(li, setequal, x)), 2, sum)==1] $b [1] 77 119 81 $e [1] 80 45 16 $f [1] 16 17 19 $h [1] 22 13 58 ?
{ "pile_set_name": "StackExchange" }
Q: Display Images in imageview I am making this post in utter anguish and scorn. Coming to question, I have 2 apps of a hotel, one a customer and other an admin one. Customer can view categories of food, various items in food and henceforth order them. Admin can add categories, add items in it, etc. This is a part of flow. The problem , however is like this: The images of categories and items in it seems to be somwehere else,seen in the logcat (path starts from 54.163), and the other PHP files are on different server. One tedious & consuming solution suggested was: Bring it down to localhost. Throw everything onto localhost from the server. Given, I don't have access to server wherein all php files are stored, which does all the API work. Suggestion #2: Keep Images in android asset folder and load them as per URL. I don't get the above one. So, how can I display the images? Please, do suggest solutions, as I am in dire need. Any help would be greatly appreciated. Somebody please help.. A: Found my answer. Did the tedious way. Brought it down to localhost. DB into phpmyadmin and all files under xampp->htdocs!!
{ "pile_set_name": "StackExchange" }
Q: Updating table after deleting an item: MGSwipeTableCell I am working on project in Xcode 7 with Swift 7 and using MGSwipeTableCell. When a user swipes left/right on a table cell I would like that cell to be deleted from the view but not from my backend database, and animate out left/right based on the direction of the swipe. When I run the app and test the function it sends back this error: 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of sections. The number of sections contained in the table view after the update (1) must be equal to the number of sections contained in the table view before the update (1), plus or minus the number of sections inserted or deleted (0 inserted, 1 deleted).' Here is my code for the function: cell.rightButtons = [MGSwipeButton(title: "Skip!", backgroundColor: UIColor(red: 245/255, green: 245/255, blue: 245/255, alpha: 1.0), callback: { (sender: MGSwipeTableCell!) -> Bool in print("Convenience callback for Skip button!") let indexPath = self.tableView.indexPathForCell(sender) self.tableView.deleteSections(NSIndexSet(index: indexPath!.section), withRowAnimation: UITableViewRowAnimation.Left) return true })] cell.rightExpansion.buttonIndex = 0 cell.leftButtons = [MGSwipeButton(title: "Apply!", icon: UIImage(named:"check.png"), backgroundColor: UIColor(red: 245/255, green: 245/255, blue: 245/255, alpha: 1.0), callback: { (sender: MGSwipeTableCell!) -> Bool in print("Convenience callback for Apply button!") let indexPath = self.tableView.indexPathForCell(sender) self.tableView.deleteSections(NSIndexSet(index: indexPath!.section), withRowAnimation: UITableViewRowAnimation.Right) return true })] cell.leftExpansion.buttonIndex = 0 return cell And here is my numberOfRowsInSection piece that I believe is causing the issue: func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return posts.count } Am I correct in thinking that the section above needs to be edited in order for this to work? I have tried a few different ways to fix this problem but haven't had much luck. Can anyone help me figure this out? Thank you in advance! Thanks to comments below I was able to figure it out self.posts.removeAtIndex(indexPath!.row) self.tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: UITableViewRowAnimation.Right) A: Replace deleteSections… with tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic). Directly before that line, remove the post from posts.
{ "pile_set_name": "StackExchange" }
Q: Appending an object to a list with python is throwing object memory address instead of the data inside the object I am getting an wierd output when I try to append an object created in the loop animals.txt ralph, dog, 3 buster, cat, 8 sammy, bird, 5 mac, dog, 1 coco, cat, 6 pet.py class Pet: # The __init__ method initializes the data attributes of the Profile class def __init__(self, name ='', animal_type = '', age = ''): self.__name = name self.__animal_type = animal_type self.age = 0 def __str__(self): string = self.__name + ' ' + self.__animal_type + ' ' + str(self.age) return string def set_name(self, name): self.__name = name def get_name(self): return self.__name def set_animal_type(self, breed): self.__animal_type = breed def get_animal_type(self): return self.__animal_type def set_age(self, old): self.age = old def get_age(self): return self.age animals.py import pet myPet = pet.Pet() animals = [] infile = open("animals.txt", "r") lines = infile.readlines() for line in lines: data = line.split(",") myPet.set_name(data[0]) myPet.set_animal_type(data[1]) myPet.set_age(data[2]) # print (data[0], data[1], data[2]) print(myPet) animals.append(myPet) print(animals) infile.close() when I print the object created with each iteration with print(myPet) I get this; ralph dog 3 buster cat 8 sammy bird 5 mac dog 1 coco cat 6 I then append the object myPet and this is the output repeated 5 times in the list when i print(animals) pet.Pet object at 0x00000185DCAE1128 I am not sure what is going on I have tried myPet.set_name(data[0]) animals.append(myPet.get_name) and myPet.set_name(data[0]) name = myPet.get_name animals.append(name) giving the same error bound method Pet.get_name of pet.Pet object at 0x000002C0F0BF6C88 A: When you print a single instance of MyPet, Python calls MyPet's __str__ method to get a string representation. When you print a list of objects, Python displays the result of calling repr on each element of the list. By default this will produce a string enclosed in angle brackets that contains the name of the type of the object together with additional information often including the name and address of the object You can override this behaviour by adding a __repr__ method to MyPet; this code makes __str__ and __repr__ the same: class MyPet: def __repr__(self): string = self.__name + ' ' + self.__animal_type + ' ' + str(self.age) return string __str__ == __repr__ Conventionally, the output of __repr__ is a string that would yield an object with the same value when passed to eval() which you could do with this code: class MyPet: def __repr__(self): return "MyPet(name='{}', animal_type='{}', age={})".format(self.__name, self.__animal_type, self.age) def __str__(self): string = self.__name + ' ' + self.__animal_type + ' ' + str(self.age) return string
{ "pile_set_name": "StackExchange" }
Q: Criar página de perfil de acordo com o usuário Quero fazer com que cada usuário cadastrado no meu site tenha sua própria página de perfil, em que todos usuários poderão acessá-la e ver as informações, como nome, e-mail, data de nascimento, etc.. Porém, não sei 2 coisas: 1ª: Como consigo fazer com que eu consiga mostrar as informações presentes na tabela do banco de dados MySQL? Já consegui apenas o e-mail, mas como sou iniciante não sei exatamente como mostrar com o resto das informações 2º: Essa é a minha maior dúvida. Como crio uma página para cada usuário? Já vi que ela não precisa ser exatamente "física" e sim virtual. Mas não sei como faço. connect.inc (faz o link para o banco de dados) <?php $dbservername = 'localhost'; $dbusername = 'root'; $dbpassword= ''; $dbdatabase = 'usuarios'; $connect = mysqli_connect ($dbservername, $dbusername, $dbpassword, $dbdatabase); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } ?> login.php <?php include "connect.inc"; session_start (); if (isset ($_POST['login'])) { $email = mysqli_real_escape_string ($connect, $_POST['email']); $senha = mysqli_real_escape_string ($connect, $_POST ['senha']); $sel_user = "select id from cadastro where email = '$email' AND senha = '$senha'"; $run_user = mysqli_query ($connect, $sel_user); $row = mysqli_fetch_array($run_user,MYSQLI_ASSOC); $active = $row ['active']; $check_user = mysqli_num_rows($run_user); if ($check_user == 1 ) { $_SESSION ['login_user'] = $email; header ("location: capa.php"); } else { echo "Email or password is not correct, try again’"; } } ?> session.php <?php include ("connect.inc"); session_start (); $user_check = $_SESSION ['login_user']; $ses_sql = mysqli_query($connect,"select email from cadastro where email = '$user_check' "); $row = mysqli_fetch_array($ses_sql,MYSQLI_ASSOC); $login_session = $row['email']; if(!isset($_SESSION['login_user'])){ header("location:login.html"); } ?> A: Fiz um exemplo básico sem usar banco de dados para que qualquer membro possa tirar algo de bom: <?php $usuarios = [ 1 => ['nome' => 'Josue Ramos', 'idade' => 54, 'ocupacao' => 'ambulante' ], 3 => ['nome' => 'Leonardo V.', 'idade' => 20, 'ocupacao' => 'desenvolvedor' ], 4 => ['nome' => 'Patricia S.', 'idade' => 20, 'ocupacao' => 'quimica' ], 5 => ['nome' => 'Figaldo M.' , 'idade' => 34, 'ocupacao' => 'medico' ], 7 => ['nome' => 'Ana Maria' , 'idade' => 45, 'ocupacao' => 'cozinheira' ], ]; if( isset($_GET['usuario']) ) { $usuario_id = (int)$_GET['usuario']; // faria aqui o: SELECT * FROM usuarios WHERE id = $usuario_id if( array_key_exists($usuario_id, $usuarios) ) // no meu caso esse seria meu SELECT $usuario = $usuarios[$usuario_id]; else die('Usuario nao encontrado'); } else die('Usuario nao encontrado'); ?> <h2>Perfil de '<?php echo $usuario['nome'] ?>'</h2> <p>Tem <?php echo $usuario['idade'] ?> anos de idade.</p> <p>Ocupa o cargo de <?php echo $usuario['ocupacao'] ?>.</p> Explicação Nesse exemplo tenho um array de usuários que simula uma tabela do banco de dados, ao acessar a página será necessário a informação de um identificador único para o usuário, como por exemplo temos aqui: http://pt.stackoverflow.com/users/23036/lvcs Onde 23036 é meu identificador de usuário. Ao acessar a página, precisamos pegar esse identificador que nos foi passado e exibir informações do usuário pertencente ao mesmo, nessa parte eu pego o $_GET['usuario'] e faço uma consulta no meu array, que no meu caso simula o banco de dados, caso exista esse usuário, gravo ele em uma variável par realizar a exibição, caso não exista, mato a página com uma mensagem qualquer de erro. Adaptar para banco de dados Para pegar o usuário a partir de um banco de dados e não de uma lista segue esses passos: Apagar lista $usuarios. Fazer conexão com banco de dados. Realizar consulta na tabela de usuários onde o identificador seja igual ao da URL. Verificar se houve um resultado verdadeiro. Armazenar na variável $usuario. Deixando o código mais ou menos assim (usando mysqli_*): if( isset($_GET['usuario']) ) { $usuario_id = (int)$_GET['usuario']; $usaurio = null; // faria aqui o: SELECT * FROM usuarios WHERE id = $usuario_id $connect = mysqli_connect ('localhost', 'root', 'root', 'lrv_001'); $sel_user = "select * from users where id = '$usuario_id'"; $run_user = mysqli_query ($connect, $sel_user); $usuario = mysqli_fetch_array($run_user, MYSQLI_ASSOC); if($row == $usuario) die('Usuario nao encontrado'); } else die('Usuario nao encontrado'); Pesquise por bind, para torna o sistema mais seguro. Não usei aqui porque estou sem tempo. Observações Para 'coloca parâmetro na URL', como você perguntou nos comentários, vai depender muito do contexto do seu sistema, normalmente é junto com a listagem de usuários, você coloca o link da página do perfil + o identificador do usuário.
{ "pile_set_name": "StackExchange" }
Q: How does this program stop taking input? I am working on a C source code and to get input it does while(!feof(stdin)){ fscanf(stdin, "%d ... What I can't understand is how do you get it to stop taking input and process the input? Ctr+Z just kills the whole process and I tried pressing enter a bunch without input and it doesn't work. A: EOF (usually a define with value -1) indicator on Linux will match CTRL+D (ASCII code 4) for text files. It's generic enough to be used with both binary and text files and on different environments too (for example it'll match CTRL+Z for text files on DOS/Windows). In your case loop will exit when user will type CTRL+D as input because input stream will reach its end (then feof() will return non zero). To see drawbacks (not so obvious behavior) for this method just try yourself to input some text then printf it out (using various inputs, terminating at the beginning or in the middle of a line). See also this post for more details about that. Better (least astonishment) implementation may avoid fscanf and rely on fgets return value (for example). Compare its behavior with this: char buffer[80]; while (fgets(buffer, sizeof(buffer), stdin) != NULL) { // ... }
{ "pile_set_name": "StackExchange" }
Q: Nonlinear ODE of second order. I have problems finding out whether this initial value problem has an explicit form solution or if it is possible to grind out a term-by-term representation of this solution using power series expansions. \begin{equation} f^{\prime\prime}(x)-\frac{f(x)-a}{b}f^{\prime}(x)=0,\qquad f(1/2)=a,\, f^{\prime}(1/2)=\sqrt{2\pi b}, \qquad x\in(0,1). \end{equation} where $a\in\mathbb{R}$ and $b\in(0,\infty)$ are constants. I have tried the considering the following: Rewrite the $f^{\prime}$ term in order to obtain an equation of first order. But I get stuck in the substitutions as I do not know what to make of the $f$ term. Any help or hint is greatly appreciated. A: First, $g(x):=f(x)-a$ gives us a simplification $$g''=g'g/b,\quad g(1/2) =0,\quad g'(1/2)=\sqrt {2\pi b}.$$ Next, change of variables $y=2x-1$, so the interval becomes $(-1,1)$, initial data is taken at zero. $$h(y):=g((y+1)/2),\quad 4h''(y) = g'' ((y+1)/2),\quad \quad 2h'(y) = g' ((y+1)/2).$$ The equation becomes $$h''(y)= \frac{h(y)h'(y)}{2b},\quad h(0) =0,\quad h'(0)=\frac{\sqrt {2\pi b}}{2}. $$ We can integrate this equation: $$h'(y) = \frac{h^2}{4b}+C,\quad h(0) =0,\quad h'(0)=\frac{\sqrt {2\pi b}}{2}.$$ We find $C$ from initial conditions: $C= h'(0)=\frac{\sqrt {2\pi b}}{2}>0$. At last, we obtain something of the first order. Once we recall that $\tan x'= \tan^2 x+1$, the further direction of reasoning is clear. We make another scaling of variables; if $$h(y) = A\tan(By),$$then$$ h' (y) = AB(\tan^2(By)+1)= \frac BA h^2(y) +AB= \frac{h^2}{4b}+ \frac{\sqrt {2\pi b}}{2}.$$ All we have to do now is to solve $$\frac BA =\frac{1}{4b},$$ $$ AB= \frac{\sqrt {2\pi b}}{2},$$ plug $A$, $B$ back to $h$ and revert all our changes of variables and translations back to $f$.
{ "pile_set_name": "StackExchange" }
Q: Change WizardSmallBitmapImage in Inno Setup Uninstaller In installer, you can easily change the small bitmap in wizard's top right corner using this code: [Setup] WizardSmallImageFile=gfx\bitmap.bmp Hovewer, how to change that same bitmap in uninstaller's wizard's top right corner? There doesn't seem to be any parameter for this. I think one of the solution is to let the installer extract the required bitmap into the {app} and then use this code: procedure InitializeUninstallProgressForm; var bitmap : string; begin bitmap := ExpandConstant('{app}\uninst.bmp'); uninstallProgressForm.WizardSmallBitmapImage.Bitmap.LoadFromFile(bitmap); end; However, I don't want to have that satelite bitmap hanging in my {app}, I want it to be compiled into the uninstaller. Is it possible to somehow compile that bitmap into the uninstaller? Or is there some other way how to change that bitmap in the uninstaller's wizard? A: No, there is no way to compile additional files into the uninstaller.
{ "pile_set_name": "StackExchange" }
Q: javascript slideshow malfunctioning after a while I have wrote this simple code to make a basic slideshow for my website. This code works fine for a while but after that it starts malfunctioning, I mean the image don't load appropriately, the same image suddenly pops ups and fades and then slowly appears back again. I though something could be wrong withe the SetTimeOut timing, but I've played with it a alot and it didn't solve my problem: var x = 1; function F() { $('#Left').html("<img src='Images/" + x + ".jpg' />").fadeOut(0).fadeIn(1000).delay(5000).fadeOut(1000); if (x < 3) { x++;} else { x = 1; } setTimeout("F()", 7000); } My question is what could be wrong with the simple code and how could I fix it or improve it. A: I think you may have a problem with the fade operations not taking exactly 7 seconds, but your timeout being scheduled for 7 seconds so over time, the two aren't lining up properly. You can make them line up perfectly with no accumulating error by starting the next animation when the last fade is done with the completion function. var x = 1; function F() { $('#Left').html("<img src='Images/" + x + ".jpg' />") .fadeOut(0) .fadeIn(1000) .delay(5000) .fadeOut(1000, F); if (x < 3) { x++;} else { x = 1; } }
{ "pile_set_name": "StackExchange" }
Q: HTML numeric input using Reactive forms is showing required validator error instead of Invalid pattern I am working on an Angular 8 application and following reacting forms approach. Facing an issue with numeric text box and copying a sample code below. Typescript: this.sampleForm = this.formBuilder.group({ age: ['', [Validators.required, Validators.pattern('/^-?(0|[1-9]\d*)?$/')]] }); HTML: <div class="form-group"> <label>Age</label> <input type="number" formControlName="age" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.age.errors }" /> <div *ngIf="submitted && f.age.errors" class="invalid-feedback"> <div *ngIf="f.age.errors.required">Age is required</div> <div *ngIf="f.age.errors.pattern">invalid age value</div> </div> </div> Sample Input value: '-035040958094385-3443-4355' Expected Validation error: 'invalid age value' Actual validation error: 'Age is required' A: Your regexp should look like this: It will accept age between 1 and 200. Taken from this answer. age: ["", [Validators.required, Validators.pattern("(0?[1-9]|[1-9][0-9]|[1][1-9][1-9]|200)")]] Check this working stackblitz.
{ "pile_set_name": "StackExchange" }
Q: Surface over plain plot Is there a way to generate a figure where the surface is over the plain plot? Like in the figure below. Notice that not only the contour and countourf would be used, but something more to add the 3D surface. I'm full able to make the plot with countour and contourf, but I'd like to make something like the image. Surface over plain plot A: Now, matplotlib has a module to perform Topographic hillshading --> https://matplotlib.org/3.2.1/gallery/specialty_plots/topographic_hillshading.html
{ "pile_set_name": "StackExchange" }
Q: How do I print a grid from a list of lists with numbered rows and columns I'm trying to create a grid that's n_rows by n_columns, which will be changeable. This is my code; it takes a list of lists and the two dimension integers: def _print_board(game_state: list, n_rows: int, n_columns: int)-> None: for i in range(n_rows): if i+1 < 10: print(i+1, '', end=' ') else: print(i+1, end=' ') for j in range(n_columns): if game_state[j][i] == NONE: print('.', end=' ') elif game_state[j][i] == WHITE: print(WHITE, end=' ') elif game_state[j][i] == BLACK: print(BLACK, end=' ') else: print('\n',end='') The output I get is: 1 . . . . . . . . . . . . . . . . 2 . . . . . . . . . . . . . . . . 3 . . . . . . . . . . . . . . . . 4 . . . . . . . . . . . . . . . . 5 . . . . . . . . . . . . . . . . 6 . . . . . . . . . . . . . . . . 7 . . . . . . . . . . . . . . . . 8 . . . . . . . B W . . . . . . . 9 . . . . . . . W B . . . . . . . 10 . . . . . . . . . . . . . . . . 11 . . . . . . . . . . . . . . . . 12 . . . . . . . . . . . . . . . . 13 . . . . . . . . . . . . . . . . 14 . . . . . . . . . . . . . . . . 15 . . . . . . . . . . . . . . . . 16 . . . . . . . . . . . . . . . . So I get numbered rows but I can't figure out how to format numbered columns properly, meaning that each dot aligns up with the row and column number. I would like to get something like this, but with each dot also aligned with the column number: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 1 . . . . . . . . . . . . . . . . 2 . . . . . . . . . . . . . . . . 3 . . . . . . . . . . . . . . . . 4 . . . . . . . . . . . . . . . . 5 . . . . . . . . . . . . . . . . 6 . . . . . . . . . . . . . . . . 7 . . . . . . . . . . . . . . . . 8 . . . . . . . B W . . . . . . . 9 . . . . . . . W B . . . . . . . 10 . . . . . . . . . . . . . . . . 11 . . . . . . . . . . . . . . . . 12 . . . . . . . . . . . . . . . . 13 . . . . . . . . . . . . . . . . 14 . . . . . . . . . . . . . . . . 15 . . . . . . . . . . . . . . . . 16 . . . . . . . . . . . . . . . . The column numbers can be on top or bottom, but I prefer them on top. How do I make it so that the dots align with the column numbers and there won't be those two numbers hanging off the edge? 16 is the max dimension for the grid, so this is the largest grid I would print. A: The easiest way to solve this is to format all numbers to two characters: def _print_board(game_state): print(" ".join("{0:2d}".format(i) if i else " " # or 0:02d to pad with zero for i in range(len(game_state[0]) + 1))) for i, row in enumerate(game_state, 1): print("{0:2d}".format(i), end=" ") print("".join(" {0} ".format(col if col != NONE else ".") for col in row)) Note that you don't need to pass the sizes if you can get them from game_state. For a 12x4 grid, this gives me: 1 2 3 4 5 6 7 8 9 10 11 12 1 . . . . . . . . . . . . 2 . . . . . . . . . . . . 3 . . . . . . . . . . . . 4 . . . . . . . . . . . . Expanding the above function a bit: def _print_board(game_state): # headers for i in range(len(game_state[0]) + 1): if i == 0: # column for row numbers print(" ", end="") else: # column headers print("{0:2d} ".format(i), end="") print() for i, row in enumerate(game_state, 1): # row number print("{0:2d} ".format(i), end="") for col in row: # row data if col == NONE: print(" {0} ".format("."), end="") else: print(" {0} ".format(col), end="") print()
{ "pile_set_name": "StackExchange" }
Q: STL unordered_map crashes with __m128 values I tracked a bug to the use of a __m128 (SSE vector) as a value in a std::unordered_map. This causes a runtime segmentation fault with mingw32 g++4.7.2. Please see the example below. Is there any reason why this should fail? Or, might there be a workaround? (I tried wrapping the value in a class but it did not help.) Thanks. #include <unordered_map> #include <xmmintrin.h> // __m128 #include <iostream> int main() { std::unordered_map<int,__m128> m; std::cerr << "still ok\n"; m[0] = __m128(); std::cerr << "crash in previous statement\n"; return 0; } Compilation settings: g++ -march=native -std=c++11 A: There are 2 issues regarding alignment: Does the ABI ensure that __m128 variables are always aligned on the stack? Does the global new operator return memory suitably aligned for the __m128 type? i.e., returns memory with a 16-byte alignment. A: C++ currently doesn't handle dynamic allocation of over-aligned types. With usual x86 ABIs, standard alignment is 8 and __m128 has an alignment of 16 bytes, so it is overaligned. With usual x86_64 ABIs, the standard alignment is 16 which makes __m128 safe (but __m256 is unsafe again with its 32-byte alignment). See this paper for a possible change in the next standard that would make things "just work": http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3396.htm In the meantime, you can specify your own allocator, for instance based on aligned_alloc (C11), posix_memalign (unix), _aligned_malloc (Microsoft), etc.
{ "pile_set_name": "StackExchange" }
Q: Sorting array of Ints I'm attempting to sort an array of Ints using the following function func sortArray(array [100]int) [100]int { var sortedArray = array sort.Sort(sort.Ints(sortedArray)) return sortedArray } and getting the following error: .\helloworld.go:22: cannot use sortedArray (type [100]int) as type []int in argument to sort.Ints .\helloworld.go:22: sort.Ints(sortedArray) used as value I'm trying to figure out Go and I'm getting stuck on this one. A: You can sort an array by taking a slice of the entire array sort.Ints(array[:]) You probably don't want an array in the first place however, and should be using a slice of []int. Also, your sortedArray is the same value as array, so there is no reason to create the second variable.
{ "pile_set_name": "StackExchange" }
Q: The CREATE UNIQUE INDEX statement terminated because a duplicate key was found This is unfinished database for selling train tickets. I want to create primary key for RouteId in Route table, but i got an exception: The CREATE UNIQUE INDEX statement terminated because a duplicate key was found for the object name 'dbo.Route' and the index name 'PK_Route'. The duplicate key value is (1). But there are no another key. I think the problem may be that initially I had 2 tables Route and RouteStation, than I delete table Route and rename RouteStation to Route. Another themes on this site does not help me. I also tried to see key for this table, but output was empty: SELECT Col.Column_Name from INFORMATION_SCHEMA.TABLE_CONSTRAINTS Tab, INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE Col WHERE Col.Constraint_Name = Tab.Constraint_Name AND Col.Table_Name = Tab.Table_Name AND Constraint_Type = 'PRIMARY KEY' AND Col.Table_Name = 'Route' A: The problem is with the content of the route table. The message tells you that you have duplicate values in columns that are reference by constraint PK_Route - probably RouteId. You can exhibit them with: select RouteId from Route group by RouteId having count(*) > 1
{ "pile_set_name": "StackExchange" }
Q: Boto3 SES email - showing HTML code in email client I am trying my hand at AWS SES and I have below code to send email from boto3 import client conn = client('ses',region_name='us-east-1') conn.send_email( Source=from_addr, Destination={'ToAddresses': '[email protected]'}, Message={ 'Subject': {'Data': self.subject,'Charset': 'UTF-8'}, 'Body': { 'Text': {'Data': 'Hello','Charset': 'UTF-8'}, 'Text': {'Data': '<html>Hello</html>','Charset': 'UTF-8'} } } ) The email is sent out but in the email client I am seeing HTML code rather than HTML email. I am wondering where to add content-type as the documentation doesn't have that info. Thanks A: You've used the Text field twice - the second one should be Html: conn = client('ses',region_name='us-east-1') conn.send_email( Source=from_addr, Destination={'ToAddresses': '[email protected]'}, Message={ 'Subject': {'Data': self.subject,'Charset': 'UTF-8'}, 'Body': { 'Text': {'Data': 'Hello','Charset': 'UTF-8'}, 'Html': {'Data': '<html>Hello</html>','Charset': 'UTF-8'} } } ) See the documentation here
{ "pile_set_name": "StackExchange" }
Q: TSQL duplicate on after join [strange syntax] In one of our ancient TSQL procedures, I've found this construct which lead to an business rule error: SELECT TOP 100 * FROM dbo.Table1 AS t1 LEFT JOIN dbo.Table2 AS t2 JOIN dbo.Table3 AS t3 ON t3.c1 = t2.c1 ON t2.c2 = t1.c2 The normal syntax I'd use for this would be SELECT TOP 100 * FROM dbo.Table1 AS t1 LEFT JOIN dbo.Table2 AS t2 ON t2.c2 = t1.c2 JOIN dbo.Table3 AS t3 ON t3.c1 = t2.c1 What exactly is this JOIN... ON... ON syntax? Is this a cross join becuase the on statement follows too late? Why am I getting a different result between the two queries? Thanks in advance A: It's easier to read with parenthesis: SELECT TOP 100 * FROM dbo.Table1 AS t1 LEFT JOIN ( dbo.Table2 AS t2 JOIN dbo.Table3 AS t3 ON t3.c1 = t2.c1 ) ON t2.c2 = t1.c2 No, this is not a cross join. You are getting different results because your second query does a left join and then inner join, but the first query does the inner join first.
{ "pile_set_name": "StackExchange" }
Q: How to use a cutom marker in Matplotlib with text inside a shape? Background In Matplotlib, we can render the string using mathtext as a marker using $ ..... $ (Reference 1) Question Is there any way to enclose this text in a circular or rectangular box, or any different different shape? Similar to the registered symbol as shown here I want to use this marker on a plot as shown below: Text '$T$' is used in this plot, I want the text to be enclosed in a circle or rectangle. Solution As suggested in the comments of the answer, I have plotted a square marker of a bit larger size before the text marker. This resolved the issue. The final figure is shown below: A: Edit: Easiest way is to simply place patches to be the desired "frames" in the same location as the markers. Just make sure they have a lower zorder so that they don't cover the data points. More sophisticated ways below: You can make patches. Here is an example I used to make a custom question mark: import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np import matplotlib.markers as m fig, ax = plt.subplots() lim = -5.8, 5.7 ax.set(xlim = lim, ylim = lim) marker_obj = m.MarkerStyle('$?$') #Here you place your letter path = marker_obj.get_path().transformed(marker_obj.get_transform()) path._vertices = np.array(path._vertices)*8 #To make it larger patch = mpl.patches.PathPatch(path, facecolor="cornflowerblue", lw=2) ax.add_patch(patch) def translate_verts(patch, i=0, j=0, z=None): patch._path._vertices = patch._path._vertices + [i, j] def rescale_verts(patch, factor = 1): patch._path._vertices = patch._path._vertices * factor #translate_verts(patch, i=-0.7, j=-0.1) circ = mpl.patches.Arc([0,0], 11, 11, angle=0.0, theta1=0.0, theta2=360.0, lw=10, facecolor = "cornflowerblue", edgecolor = "black") ax.add_patch(circ)#One of the rings around the questionmark circ = mpl.patches.Arc([0,0], 10.5, 10.5, angle=0.0, theta1=0.0, theta2=360.0, lw=10, edgecolor = "cornflowerblue") ax.add_patch(circ)#Another one of the rings around the question mark circ = mpl.patches.Arc([0,0], 10, 10, angle=0.0, theta1=0.0, theta2=360.0, lw=10, edgecolor = "black") ax.add_patch(circ) if __name__ == "__main__": ax.axis("off") ax.set_position([0, 0, 1, 1]) fig.canvas.draw() #plt.savefig("question.png", dpi=40) plt.show() Edit, second answer: creating a custom patch made of other patches: import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np import mpl_toolkits.mplot3d.art3d as art3d class PlanetPatch(mpl.patches.Circle): """ This class combines many patches to make a custom patch The best way to reproduce such a thing is to read the source code for all patches you plan on combining. Also make use of ratios as often as possible to maintain proportionality between patches of different sizes""" cz = 0 def __init__(self, xy, radius, color = None, linewidth = 20, edgecolor = "black", ringcolor = "white", *args, **kwargs): ratio = radius/6 mpl.patches.Circle.__init__(self, xy, radius, linewidth = linewidth*ratio, color = color, zorder = PlanetPatch.cz, *args, **kwargs) self.set_edgecolor(edgecolor) xy_ringcontour = np.array(xy)+[0, radius*-0.2/6] self.xy_ringcontour = xy_ringcontour - np.array(xy) self.ring_contour = mpl.patches.Arc(xy_ringcontour, 15*radius/6, 4*radius/6, angle =10, theta1 = 165, theta2 = 14.5, fill = False, linewidth = 65*linewidth*ratio/20, zorder = 1+PlanetPatch.cz) self.ring_inner = mpl.patches.Arc(xy_ringcontour, 15*radius/6, 4*radius/6, angle = 10, theta1 = 165 , theta2 = 14.5,fill = False, linewidth = 36*linewidth*ratio/20, zorder = 2+PlanetPatch.cz) self.top = mpl.patches.Wedge([0,0], radius, theta1 = 8, theta2 = 192, zorder=3+PlanetPatch.cz) self.xy_init = xy self.top._path._vertices=self.top._path._vertices+xy self.ring_contour._edgecolor = self._edgecolor self.ring_inner.set_edgecolor(ringcolor) self.top._facecolor = self._facecolor def add_to_ax(self, ax): ax.add_patch(self) ax.add_patch(self.ring_contour) ax.add_patch(self.ring_inner) ax.add_patch(self.top) def translate(self, dx, dy): self._center = self.center + [dx,dy] self.ring_inner._center = self.ring_inner._center +[dx, dy] self.ring_contour._center = self.ring_contour._center + [dx,dy] self.top._path._vertices = self.top._path._vertices + [dx,dy] def set_xy(self, new_xy): """As you can see all patches have different ways to have their positions updated""" new_xy = np.array(new_xy) self._center = new_xy self.ring_inner._center = self.xy_ringcontour + new_xy self.ring_contour._center = self.xy_ringcontour + new_xy self.top._path._vertices += new_xy - self.xy_init fig = plt.figure(figsize=(6, 6)) ax = fig.add_subplot() lim = -8.5, 8.6 ax.set(xlim = lim, ylim = lim, facecolor = "black") planets = [] colors = mpl.colors.cnames colors = [c for c in colors] for x in range(100): xy = np.random.randint(-7, 7, 2) r = np.random.randint(1, 15)/30 color = np.random.choice(colors) planet = PlanetPatch(xy, r, linewidth = 20, color = color, ringcolor = np.random.choice(colors), edgecolor = np.random.choice(colors)) planet.add_to_ax(ax) planets.append(planet) fig.canvas.draw() #plt.savefig("planet.png", dpi=10) plt.show()
{ "pile_set_name": "StackExchange" }
Q: The length of an interval covered by an infinite family of open intervals Prove that if $I$ is an interval of $\mathbb R$, covered by an infinite family $\{I_n, n\in \mathbb N\}$ of open intervals, then (where $\ell(I)$ denotes the length of $I$): $$\ell(I) \le \sum_{n=1}^{\infty} \ell(I_n)$$ It is very intuitive but hard to prove (in a formal manner). The exercise gives the hint: prove that $\ell(I) = \sup\{\ell(K), \text{$K$ is a compact subset of $I$}\}$. I proved this, but I can't see how this hint makes the problem any easier to prove. I thought about doing the following: If $I$ is unbounded, then we are done, so let's assume that it's bounded. Due to the connectedness of $I$, we can WLOG suppose that the $I_n$'s are such that $I_n \cap I_{n+1} \neq \varnothing$ for each $n$ (this would be the ideal situation, I guess). By the axiom of countable choice, we can find a sequence $(a_n)$ where $[a_n, a_{n+1}] \subset I_n$ for each $n$. Then: $$\sum_{n=1}^{\infty} \ell(I_n) = \sum_{n=1}^{\infty} \sup \{ \ell([a_n,a_{n+1}]) = a_{n+1} - a_n\}$$ Does this make any sense? How to proceed? Thank you. A: Following the hint let $K\subseteq I$ be compact. As the $I_n$ form an open cover of $K$, there exists a finite subcover. Assume two of these finitely many intervals intersect, say $I_i=(a_i,b_i)$ intersects $I_j=(a_j,b_j)$. Then $I_i\cup I_j$ is itself an open interval $(\min\{a_i,a_j\},\max\{b_i,b_j\})$ of length $$ \max\{b_i,b_j\}-\min\{a_i,a_j\}< b_i+b_j-a_i-a_j=\ell(I_i)+\ell(I_j)$$ Thus if we replace $I_i,I_j$ with this one larger interval, we decrease the number of intervals needed to cover $K$ while at the same time decreasing the sum of their lengths. We repeat this process until we cannot continue, i.e., until ther are no overlapping open intervals. As $K$ is connected, this means that we are left with a single open interval $I^*$. Then $$\ell (K)<\ell(I^*)\le \sum_{i=1}^N \ell(I_i)\le \sum_{i=1}^\infty \ell(I_i).$$ As we can make $\ell(I)-\ell(K)$ arbitrarily small, we conclude that $$\ell (I)\le \sum_{i=1}^\infty \ell(I_i).$$
{ "pile_set_name": "StackExchange" }
Q: Generating minimal/irreducible Sudokus A Sudoku puzzle is minimal (also called irreducible) if it has a unique solution, but removing any digit would yield a puzzle with multiple solutions. In other words, every digit is necessary to determine the solution. I have a basic algorithm to generate minimal Sudokus: Generate a completed puzzle. Visit each cell in a random order. For each visited cell: Tentatively remove its digit Solve the puzzle twice using a recursive backtracking algorithm. One solver tries the digits 1-9 in forward order, the other in reverse order. In a sense, the solvers are traversing a search tree containing all possible configurations, but from opposite ends. This means that the two solutions will match iff the puzzle has a unique solution. If the puzzle has a unique solution, remove the digit permanently; otherwise, put it back in. This method is guaranteed to produce a minimal puzzle, but it's quite slow (100 ms on my computer, several seconds on a smartphone). I would like to reduce the number of solves, but all the obvious ways I can think of are incorrect. For example: Adding digits instead of removing them. The advantage of this is that since minimal puzzles require at least 17 filled digits, the first 17 digits are guaranteed to not have a unique solution, reducing the amount of solving. Unfortunately, because the cells are visited in a random order, many unnecessary digits will be added before the one important digit that "locks down" a unique solution. For instance, if the first 9 cells added are all in the same column, there's a great deal of redundant information there. If no other digit can replace the current one, keep it in and do not solve the puzzle. Because checking if a placement is legal is thousands of times faster than solving the puzzle twice, this could be a huge time-saver. However, just because there's no other legal digit now doesn't mean there won't be later, once we remove other digits. Since we generated the original solution, solve only once for each cell and see if it matches the original. This doesn't work because the original solution could be anywhere within the search tree of possible solutions. For example, if the original solution is near the "left" side of the tree, and we start searching from the left, we will miss solutions on the right side of the tree. I would also like to optimize the solving algorithm itself. The hard part is determining if a solution is unique. I can make micro-optimizations like creating a bitmask of legal placements for each cell, as described in this wonderful post. However, more advanced algorithms like Dancing Links or simulated annealing are not designed to determine uniqueness, but just to find any solution. How can I optimize my minimal Sudoku generator? A: Here are the main optimizations I implemented with (highly approximate) percentage increases in speed: Using bitmasks to keep track of which constraints (row, column, box) are satisfied in each cell. This makes it much faster to look up whether a placement is legal, but slower to make a placement. A complicating factor in generating puzzles with bitmasks, rather than just solving them, is that digits may have to be removed, which means you need to keep track of the three types of constraints as distinct bits. A small further optimization is to save the masks for each digit and each constraint in arrays. 40% Timing out the generation and restarting if it takes too long. See here. The optimal strategy is to increase the timeout period after each failed generation, to reduce the chance that it goes on indefinitely. 30%, mainly from reducing the worst-case runtimes. mbeckish and user295691's suggestions (see the comments to the original post). 25%
{ "pile_set_name": "StackExchange" }
Q: Teradata conversion of seconds to hours I have a little problem with the conversion of seconds to hours in Teradata.. CAST((TRUNC(seconds/3600) (FORMAT '99')) AS VARCHAR(10)) ||':'|| CAST((TRUNC((seconds MOD 3600)/60) (FORMAT '99')) AS VARCHAR(10)) ||':'|| CAST((TRUNC(seconds MOD 60) (FORMAT '99')) AS VARCHAR(10)) AS SecToHours I need to convert seconds to minutes and hours in the format 00:00:00 but now if I have more than 100 hours instead of 100 hours getting the result ** I don't want a format of '999'. Awaited results: hours:minutes:seconds 00:00:59 00:59:59 09:59:59 99:59:59 100:59:59 Is it a possibility ?? A: Simply change the FORMAT using optional digits. This is a simplified version, if seconds is not a DECIMAL you might remove the TRUNC, too: (TRUNC( seconds/3600) (FORMAT 'ZZ99')) || (TRUNC((seconds MOD 3600)/60) (FORMAT ':99' )) || (TRUNC( seconds MOD 60) (FORMAT ':99' )) AS SecToHours Or use an INTERVAL (if less than 10000 hours): seconds * INTERVAL '0000:00:01' HOUR TO SECOND
{ "pile_set_name": "StackExchange" }
Q: Could black holes be a better source of energy than stars? In my story, set in the far(ish) future, humanity discovers a way to extract energy from black holes (perhaps via the Penrose process?), which sparks conflict as various factions attempt to take control over previously useless and dangerous but now suddenly valuable black holes. This energy is extremely valuable because warp drives for faster-than-light travel require massive amounts of power, which made them impractical before the proliferation of Penrose process power plants. In order for this to make sense, black holes would have to be a better source of energy than whatever humanity was using before, which I assume would be Dyson spheres/rings/swarms/etc. gathering energy radiated from stars. To see if this is plausible, I attempted to compare the energy output of a Penrose power plant vs a Dyson sphere around the sun. According to the Wikipedia article about the Penrose process, up to 29% of a black hole's mass energy can be contained in its angular momentum. So, assuming a black hole with the mass of the sun (which I know is too small to become a black hole, but I wanted to compare apples to apples), the total amount of energy that can be harvested from it is $(0.29\cdot1.989\times10^{30})c^2 = 5.18\times10^{46}$ joules. For comparison, the sun emits a total of $3.9\times10^{26}$ watts.2 Over the 5 billion remaining years of the sun's life, assuming its energy output remains constant, it will emit a total of $(5,000,000,000\cdot60\cdot60\cdot24\cdot365)(3.9\times10^{26}) = 6.15\times10^{43}$ joules. So the black hole has over 800 times as much energy to harvest! But the real question is, how quickly can that energy be harvested? According to Wikipedia, an object's energy can be increased by up to 20.7% using the Penrose process. That means the equation for how much energy we can get from a given mass is $0.207mc^2$. So, the amount of mass we need to toss into the black hole per second to match the sun is $\frac{3.9\times10^{26}}{0.207c^2} = 2.1\times10^{10}$ kilograms per second. But only half of that mass actually falls into the black hole, the rest can be re-used. So only $1.05\times10^{10}$ kilograms are consumed each second. How much mass is that? That's about 1.75 Great Pyramids of Giza every second. At that rate, the mass of the moon would be used in $\frac{7.3\times10^{22}}{1.05\times10^{10}} = 6.95\times10^{12}$ seconds, or about 220,000 years. For the sun, it would be $\frac{1.989\times10^{30}}{1.05\times10^{10}} = 1.89\times10^{20}$ seconds, or a little under 6 trillion years. Based on the math, it seems plausible. (Assuming you can toss stuff in fast enough.) So my questions are: If a civilization is not advanced enough to harvest energy from black holes, are stars the best source of energy? If a civilization is advanced enough to harvest energy from black holes, are black holes the best source of energy? Is the Penrose process the best way to harvest energy from a black hole? By "best" I mean produces usable energy the quickest. I know matter-antimatter annihilation would release energy extremely quickly, but you have to create the antimatter first, which uses a bunch of energy. (In my universe, humanity never figures out how to create antimatter efficiently enough to get a net gain of energy by annihilating it.) A: If a civilization is not advanced enough to harvest energy from black holes, are stars the best source of energy? Certainly not. There are quasars and pulsars and nova and heaven only knows what other sources of energy are out there. Quasars and blazars1 may be a bit too rare to be practical. It's like always having to drive a 40 mile round trip to get gas in your tank. Pulsars produce a ton of energy and are more frequent. In the long run, suns may have the lowest collectible energy density, but they're so honking common that practicality wins out over efficiency. In reality, your people would use a variety of sources. A passing quasar for a quick top-off would never be missed — but a star if you must 'cause it's right over there. If a civilization is advanced enough to harvest energy from black holes, are black holes the best source of energy? Ignoring the issue of practicality (which will always require multiple energy sources 'cause those folks on the rim are a long way out and that makes refueling very impractical), then quasars and blazars are still your best energy sources, but they're more rare than black holes. OK, You really can't ignore practicality. If you're half-a-galaxy away from the nearest black hole it simply doesn't matter if you can harvest or not. You're not going to spend the time and energy just to obtain the better energy density. If it takes less time to sit by a star than to travel to a black hole, you'll park that beast in orbit and get a tan. Is the Penrose process the best way to harvest energy from a black hole? This is, frankly, an impossible question to answer. (And don't believe anyone who tells you otherwise. No one can prove that one theory is better than another.) The Penrose process is theoretical. Hawking radiation, first theorized in 1974 only saw the first light of proof in 2010. Who knows when the Penrose Process will be proven, if ever? What's the value of claiming one theoretical method is better than another? What happens if you write your story this year only to have the Penrose Process disproven next year? You see, the problem is, you're treating hypotheses and theories as if they're right. Maybe they are. Maybe they aren't. I have a couple of favorite stories that are getting harder to read because the author depended on being too realistic, too "hard science," and the science changed. Some people are funny, they think what we "know" today (even when it's only just theorized) represents the end-all of knowledge. Knowledge changes, science changes, theories come and go. If you stick to today's proven facts, you're safe. But the more theoretical and unproven your story's critical science, the more likely the story won't stand the test of time. That's the value of fiction. It's nearly impossible to disprove fiction (e.g., Star Trek transporters) and once the fiction becomes popular people start working toward making it work (e.g., Star Trek transporters). But take an actual theory that becomes disproven. Now your "history" is wrong and people will stop liking the story. Yuck. Which is a fancy way of saying, have fun discovering whether or not your fictional society can harvest black holes, but when it comes to the actual science behind doing it, you might want to stick with "Lieutenant, open the collectors and start filling our reserves." 1 Please forgive me for forgetting the quasars and blazars are believed to be special cases of black holes. Mentioning them at this point in the text is improper as the OP was asking about "what if we can't harvest black holes?" If you can't harvest black holes, you can't harvest quasars and blazars, either. However, I didn't bother to rewrite the paragraph because I suspect y'all'll understand my point (and, having found a good reason to write "y'all'll," I couldn't pass it up). Cheers.
{ "pile_set_name": "StackExchange" }
Q: How long are Tiles cached in Android Google Maps v2 Using the standard UrlTileProvider https://developer.android.com/reference/com/google/android/gms/maps/model/UrlTileProvider.html to display PNG tiles on a map Are the tiles downloaded from the server cached ? If they are, how long ? Are the HTTP headers honored ? Is it possible to programmatically flush the cache ? A: Have you tried TileOverlay#clearTileCache() ?
{ "pile_set_name": "StackExchange" }
Q: can a css line contain multiple colons? I am writing a Python module that will be doing some css manipulations and modifications. As of my knowledge, the css template is: selector{ property:value; } my question is, is there any instance where value contains a colon? The reason for this is that I want to split the lines inside selectors by a colon and essentially grab the property and the value, but if the value has a colon in it, then the entire function will manipulate the css incorrectly. A: Yes. If you specify a filter (IE) it contains a second colon. Example: filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fad59f', endColorstr='#fa9907') Any CSS property that takes a url could easily contain http: Example: background-image: url("http://example.com/image.jpg"); A: Yes, for instance: selector:before{ content:":"; }
{ "pile_set_name": "StackExchange" }
Q: Use doctrine to connect to Hana We've been building a symfony/Postgre app for a client. The app is almost done and our client wishes to switch the database from Postgre to Hana. My question is simple, is that possible ? I've seen that Hana supports odbc but doctrine doesn't not seem to like it. I also have found that doctrine has a sqlAnywhere driver. Is it hana compatible ? Thank you. A: No. This is not possible with Doctrine. Also it is a bad practise to share a database accross contexts (apps) Better: Keep your postgres DB and introduce specific events or batch jobs to transfer the data back to HANA using pure SQL/ODBC. Rule of thumb: Only use ORM/Doctrine if you have full control / ownership of the schema.
{ "pile_set_name": "StackExchange" }
Q: Major difference between SAS Studio and SAS Enterprise I have been doing practices and exercising in SAS Studio for sometime. In addition to the fact that SAS Studio is free and better-looking, is there any other difference makes SAS Studio a better choice than SAS Enterprise? Aside from HTML, running in the cloud, is there any functional difference? Or is there any specific task can be done with more efficiency with either platform? A: There are several different implementations of SAS Studio, the On Demand version for Academics, the SAS University Edition as well as a version that companies can use to access their server. Each has different limitations. EG is more powerful in my opinion. However, if they're both installed such that you're accessing a remote server they'll be more equivalent. SAS UE is limited as well to the packages licensed, for example it does not support SAS Graph. Additionally, it runs on a VM which has limitations on what you can do. And most importantly - the licensing. SAS UE is designed primarily for learning. If you want to consult or implement in your workplace you'll need the full license and then can choose between EG and Studio. The brand new FAQ also lists a few comparisons: http://support.sas.com/software/products/sasstudio/faq/SASStudio_vsEG.htm
{ "pile_set_name": "StackExchange" }
Q: whats the difference between export.create and router.post? I've seen 2 ways of creating a restful API. 1: "export.create" and once you add code on postman you have to add it in json format. 2: "router.post" which I understand that's using express and when you add code on postman you add it using 'x-www-form-urlencoded' What's the difference? router.post("/", (req, res) => { if(!req.body.certifications, !req.body.memberships, !req.body.hobbies, !req.body.interests) { res.status(400) res.json({ error: "Bad Data" }) } else { Basic.create(req.body) .then(() => { res.send("Basic Added") }) .catch(err => { res.send("Error: " + err) }) } }) ------------------------------------------ exports.create = (req, res) => { var customer; Customer.create({ firstname: req.body.firstname, lastname: req.body.lastname, age: req.body.age }).then(createdCustomer => { // Send Created Customer to client customer = createdCustomer; return Address.create({ street: req.body.street, phone: req.body.phone }) }).then(address => { customer.setAddress(address) res.send('OK'); }) }; A: exports.create just exports the method as part of a commonjs module, that can then be used with router.post in another file. Something like this: const { create } = require('./the_file_name.js'); router.post('/', create);
{ "pile_set_name": "StackExchange" }
Q: Can't get a head block in Observer I don't know why but i get this error: Call to a member function setData() on boolean in observer line 22, and this line is: $head->setData('title', $metaTitle); Observer.php class Namespace_Category_Model_Observer { public function setMetaTitle(Varien_Event_Observer $observer) { $head = $observer->getLayout()->getBlock('head'); $metaTitle = Mage::registry('current_category')->getMeta_title(); Mage::log($metaTitle); //I get the right value if (Mage::registry('current_category')) { $head->setData('title', $metaTitle); //line 22 } } } The event that i used is: <controller_action_layout_load_before> EDIT: I just realized that i can't return a head block, $head return nothing ! I tryed also Mage::app()->getLayout()->getBlock('head') but it doesn't work A: Your getBlock('head') returns false, so setData() cant work. Please try controller_action_layout_render_before_catalog_category_view event and an observer like ... public function setMetaTitle(Varien_Event_Observer $observer) { $category = Mage::registry('current_category'); $head = Mage::app()->getLayout()->getBlock('head'); if ($head) { $head->setData('title', 'new meta title'); $category->setData('name', 'new category title'); } }
{ "pile_set_name": "StackExchange" }
Q: Server 2008 unresponsive after SP2 install I have a dev server that has an exact image of a production web server. The prod server only has SP1 installed on it. When I first fired up the dev box, the first thing I did was install SP2, and let it be. Almost every morning when I came in, the server was unusable. It would respond to ping, but RDP and the web site running on it were down. On the screen the screen saver was bouncing around, so it wasn't hard locked. But it was unresponsive to keyboard and mouse. So now I have to hard shut it down, but when it comes back up, the only thing in the event viewer is the unexpected shutdown, nothing else. I've since taken a fresh image of my prod box and put it on the dev server, and not installed SP2, and the dev box is humming along perfectly. I should also note that this is Server2k8 Web, 64bit Has anyone else seen anything like this? A: I should note that this was resolved. The dev box had a failing hard drive, and apparently SP2 was causing BSOD after being installed. The drive finally started clicking and died. After a fresh imaging with a copy of the production server, SP2 was installed, and has been good since.
{ "pile_set_name": "StackExchange" }
Q: Exit loop when the collection is changed? I have a For Loop which lists items from a collection (like 5 items per page). The user can go to other pages by clicking other page buttons, but this causes the following error if the current page is still being listed. Collection was modified. Enumeration operation may not execute. How would I abort the listing of the current page when the user clicks the other page buttons before the list is finished? I tried making two boolean variables called "isListing" and "isSkipping", then I tried putting the For Loop in a While statement like this: Public Sub list() lines.Items.Clear() lines = New List(Of String)() Dim reader As StringReader = New StringReader(listLines) 'listLines obtained from a file Do Until reader.Peek = -1 lines.Add(reader.ReadLine) Loop isListing = True While Not isSkipping AndAlso isListing For Each line As String In lines 'List Page Next isListing = False End While End Sub And the page button like: Private Sub btnPage_Click(...) ... If isListing Then isSkipping = True Else isSkipping = False list() End Sub But this causes the same error. Any help appreciated~! A: To abort the listing in progress you would need to put a command to abort the listing inside the foreach loop. You can also change the foreach loop to a for loop, which would remove that exception but could have other consequences like a null reference exception. It also makes sense to move the wait inside the button click event where you can easily see what's going to happen when the button is clicked. There is probably a more robust way to handle this, but it's hard to say without seeing more code. Private Sub btnPage_Click(...) ... While(isListing) isSkipping = true Thread.Sleep(100) End While isSkipping = false list() End Sub Public Sub list() isListing = true For Each line As String In lines 'List Page If isSkipping then isListing = false return End If Next isListing = false End Sub
{ "pile_set_name": "StackExchange" }
Q: Reading in a text file from a jar in Jython I have a Jython code base and several text files in a jar archive. I am using a script to pack them all into one jar file for easy distribution. I would like to be able to read the text files from within the jar file. I have tried the import statement the command: fin = java.lang.ClassLoader.getResourceAsStream('path to the text file inside the jar') and it says 2 arguments are expected instead of 1 for the getResourceAsStream method. I have searched quite a bit but have not found a clear way to do this using Jython. Thanks. A: Jars are simply zip files so you can use zipfile module. There is my example of reading version info from manifest file: def get_ver(jar_file): zf = zipfile.ZipFile(jar_file, 'r') try: lst = zf.infolist() for zi in lst: fn = zi.filename if fn.lower().endswith('manifest.mf'): try: manifest_txt = str(zf.read(zi.filename), encoding='utf8') except TypeError: manifest_txt = zf.read(zi.filename) lines = manifest_txt.split('\n') for line in lines: if 'Implementation-Version:' in line: return line[23:].strip() finally: zf.close() A: You are invoking getResourceAsStream() on the class, not an instance. That's why there is an error message. If you first create a classloader object and then use getResourceAsStream() on that object, it should work. Something like this: from java.lang import ClassLoader from java.io import InputStreamReader, BufferedReader loader = ClassLoader.getSystemClassLoader() stream = loader.getResourceAsStream("org/python/version.properties") reader = BufferedReader(InputStreamReader(stream)) line = reader.readLine() while line is not None: print line line = reader.readLine() Output: # Jython version information jython.version=2.5.3 jython.major_version=2 jython.minor_version=5 jython.micro_version=3 jython.release_level=15 jython.release_serial=0 jython.build.date=Aug 13 2012 jython.build.time=14:48:36 jython.build.hg_branch=2.5 jython.build.hg_tag= jython.build.hg_version=c56500f08d34+ The output shows the contents of the org/python/version.properties file inside jython.jar (which is on the classpath when the program runs).
{ "pile_set_name": "StackExchange" }
Q: Set spinner in Action-bar in android I want to set spinner in action bar so can any one provide me an example for it. How can I do this? When entering the page I want the spinner in the action bar to expand programmatically after it's populated with items so the user needs to pick an item. As of now the first item in the adapter is selected automatically. A: Adding an spinner to the action bar is pretty straightforward as mentioned in the guide here: https://developer.android.com/guide/topics/ui/actionbar.html#Dropdown They also have sample code there. Whenever you need to open the spinner programmatically, you can just send it a click event: mySpinner.performClick();
{ "pile_set_name": "StackExchange" }
Q: How to set the socket option SO_REUSEPORT in Rust? I've read the documentation for std::net and mio, and I've found some methods like set_nodelay and set_keepalive, but I haven't found a way to set other socket options like SO_REUSEPORT and SO_REUSEADDR on a given socket. How can I do this? A: Because SO_REUSEPORT isn't cross-platform, you will need to dip into platform-specific code. In this case, you can get the raw file descriptor from the socket and then use functions, types, and values from the libc crate to set the options you want: extern crate libc; // 0.2.43 use std::{io, mem, net::TcpListener, os::unix::io::AsRawFd}; fn main() -> Result<(), io::Error> { let listener = TcpListener::bind("0.0.0.0:8888")?; unsafe { let optval: libc::c_int = 1; let ret = libc::setsockopt( listener.as_raw_fd(), libc::SOL_SOCKET, libc::SO_REUSEPORT, &optval as *const _ as *const libc::c_void, mem::size_of_val(&optval) as libc::socklen_t, ); if ret != 0 { return Err(io::Error::last_os_error()); } } Ok(()) } I make no guarantee that this is the right place to set this option, or that I haven't screwed up something in the unsafe block, but it does compile and run on macOS 10.12. A better solution may be to check out the nix crate, which provides nicer wrappers for most *nix-specific code: extern crate nix; // 0.11.0 use nix::sys::socket::{self, sockopt::ReusePort}; use std::{error::Error, net::TcpListener, os::unix::io::AsRawFd}; fn main() -> Result<(), Box<Error>> { let listener = TcpListener::bind("0.0.0.0:8888")?; socket::setsockopt(listener.as_raw_fd(), ReusePort, &true)?; Ok(()) } An even better solution may be to check out the net2 crate, which provides higher-level methods aimed specifically at networking-related code: extern crate net2; // 0.2.33 use net2::{unix::UnixTcpBuilderExt, TcpBuilder}; fn main() -> Result<(), std::io::Error> { let listener = TcpBuilder::new_v4()? .reuse_address(true)? .reuse_port(true)? .bind("0.0.0.0:8888")? .listen(42)?; Ok(()) }
{ "pile_set_name": "StackExchange" }
Q: Interactive Graphing while logging data I'm looking to graph and interactively explore live/continuously measured data. There are quite a few options out there, with plot.ly being the most user-friendly. Plot.ly has a fantastic and easy to use UI (easily scalable, pannable, easily zoomable/fit to screen), but cannot handle the large sets of data I'm collecting. Does anyone know of any alternatives? I have MATLAB, but don't have enough licenses to simultaneously run this and do development at the same time. I know that LabVIEW would be a great option, but it is currently cost-prohibitive. Thanks in advance! A: For this answer, I have assumed that you prefer open source solutions to big data visualization. This assumption is based on budgetary details from your question. However, there is one exclusion to this - below I will add a reference to one commercial product, which I believe might be beneficial in your case (provided that you could afford that). I also assume that browser-based solutions are acceptable (I would even prefer them, unless you have specific contradictory requirements). Naturally, the first candidate as a solution to your problem I would consider D3.js JavaScript library: http://d3js.org. However, despite flexibility and other benefits, I think that this solution is too low-level. Therefore, I would recommend you to take a look at the following open source projects for big data visualization, which are powerful and flexible enough, but operate at a higher level of abstraction (some of them are based on D3.js foundation and sometimes are referred to as D3.js visualization stack). Bokeh - Python-based interactive visualization library, which supports big data and streaming data: http://bokeh.pydata.org Flot - JavaScript-based interactive visualization library, focused on jQuery: http://www.flotcharts.org NodeBox - unique rapid data visualization system (not browser-based, but multi-language and multi-platform), based on generative design and visual functional programming: https://www.nodebox.net Processing - complete software development system with its own programming language, libraries, plug-ins, etc., oriented to visual content: https://www.processing.org (allows executing Processing programs in a browser via http://processingjs.org) Crossfilter - JavaScript-based interactive visualization library for big data by Square (very fast visualization of large multivariate data sets): http://square.github.io/crossfilter bigvis - an R package for big data exploratory analysis (not a visualization library per se, but could be useful to process large data sets /aggregating, smoothing/ prior to visualization, using various R graphics options): https://github.com/hadley/bigvis prefuse - Java-based interactive visualization library: http://prefuse.org Lumify - big data integration, analysis and visualization platform (interesting feature: supports Semantic Web): http://lumify.io Separately, I'd like to mention two open source big data analysis and visualization projects, focused on graph/network data (with some support for streaming data of that type): Cytoscape and Gephi. If you are interested in some other, more specific (maps support, etc.) or commercial (basic free tiers), projects and products, please see this awesome compilation, which I thoroughly curated to come up with the main list above and analyzed: http://blog.profitbricks.com/39-data-visualization-tools-for-big-data. Finally, as I promised in the beginning, Zoomdata - a commercial product, which I thought you might want to take a look at: http://www.zoomdata.com. The reason I made an exclusion for it from my open source software compilation is due to its built-in support for big data platforms. In particular, Zoomdata provides data connectors for Cloudera Impala, Amazon Redshift, MongoDB, Spark and Hadoop, plus search engines, major database engines and streaming data. Disclaimer: I have no affiliation with Zoomdata whatsoever - I was just impressed by their range of connectivity options (which might cost you dearly, but that's another aspect of this topic's analysis).
{ "pile_set_name": "StackExchange" }
Q: how to grant update or select on some specified row in postgresql table? I want to create some roles in my Postgresql DB and grant some access. I have student role and i want to grant this user type : can edit only record a bout him/her in student table and can not edit other rows how can i do it? thanks A: Create a view on the table with an appropriate where clause, then grant access to that: create view students_view as select col1, col2, col3 -- limit column access here from mytable where <whatever>; -- limit row access here -- limit what he can do here grant update, select to student_role; BTW It is a commonly held misconception that you can't update a view, but that is only true if the view is a join or similarly complicated query. A: PostgreSQL doesn't have row-level declarative security (yet, there's ongoing work into it) so if you can't just create a view - say, if you have many different people who need this access - you will probably need a SECURITY DEFINER helper function or trigger. You've got a couple of options: Write a SECURITY DEFINER function that lets them make only the permitted changes and limit their access to the table to SELECT, revoking UPDATE, DELETE, TRUNCATE and INSERT rights; or write a trigger that tries to restrict them from making changes you don't want them to make and GRANT them write access to the table. Of the two, the function and restricted rights approach is by far the safest option so long as you follow the SECURITY DEFINER secure coding guidelines set above - setting search_path for the function, avoiding dynamic SQL (EXECUTE) with string substitutions, etc. The view approach given above can work quite nicely if it's a view that filters by current_user. You may also want to look at the new SECURITY BARRIER views; see this post for a useful discussion of them.
{ "pile_set_name": "StackExchange" }
Q: SQL select subquery runs forever when passing MONTH to sub query The purpose of this query: contracts in the database have a start date, contract date and closing date. When a contract goes pending, the contract date is set and the closing date is set to a around 40 days in the future. I need to run a query that gets the contracts that have a contract date in the past and closing date that has not been reached to find the number of pending contracts for that month. This query generate a report of pending contracts from the last full month and going back 12 months. My thought is to get the last day of each month and count the number of contracts that have closing date > the last day of month and contract date <= last day of month The following query executes in 51ms. the query returns rows for July SELECT DATE_FORMAT(LAST_DAY(NOW() - INTERVAL 2 MONTH), '%Y-%m-%d 23:59:59') as lastDay, count(*) as total FROM contracts WHERE L_ClosingDate >= DATE_FORMAT(LAST_DAY(NOW() - INTERVAL 2 MONTH), '%Y-%m-%d 23:59:59') AND L_ContractDate <= DATE_FORMAT(LAST_DAY(NOW() - INTERVAL 2 MONTH), '%Y-%m-%d 23:59:59') Now I need to run the query to get rows grouped by month, so I altered the query to the following: select MONTH(L_ClosingDate) as m, YEAR(L_ClosingDate) as y, (SELECT count(*) FROM contracts WHERE L_ClosingDate >= DATE_FORMAT(LAST_DAY(CONCAT(y,'-',m,'-',LPAD(1,2,'00'))), '%Y-%m-%d 23:59:59') AND L_ContractDate <= DATE_FORMAT(LAST_DAY(CONCAT(y,'-',m,'-',LPAD(1,2,'00'))), '%Y-%m-%d 23:59:59') ) as total FROM contracts WHERE L_ClosingDate > DATE_ADD(NOW(), INTERVAL -2 MONTH) AND L_CLosingDate < DATE_ADD(NOW(), INTERVAL -1 MONTH) GROUP BY YEAR(L_ClosingDate), MONTH(L_ClosingDate) ORDER BY L_ClosingDate DESC It executes forever... I've tweaked it and found that the MONTH and YEAR 'm' and 'y' in the subquery is causing the problem. If I hardcode a date it executes as expected. Expected output: Month | Year | total 8 | 2015 | 74 7 | 2015 | 87 6 | 2015 | 45 I'm working on getting some sample data Is there another way to perform the group by query? A: How about this? (Assumes closing date is a datetime) SELECT MONTH(L_ClosingDate) as m, YEAR(L_ClosingDate) as y , count(*) as total FROM contracts WHERE L_ClosingDate >= LAST_DAY(CURDATE() - INTERVAL 3 MONTH) + 1 DAY AND L_CLosingDate < LAST_DAY(CURDATE() - INTERVAL 1 MONTH) + INTERVAL 1 DAY GROUP BY m, y ORDER BY y DESC, m DESC ;
{ "pile_set_name": "StackExchange" }
Q: Android app not running from market but pushing apk works I have created an app the past could of days which has been great so far. I published app to play store and all worked fine. Last night I uploaded an upgrade version with a few minor changes, when I try to install the app from the market it doesnt work I get ClassNotFoundException as soon as the main activity starts. If I run the app directly from eclipse or I push the compiled APK to the device over adb it works fine. Has anyone seen this before, its a new one on me. As per advice on IRC ProGuard is commented out in the properties file. A: Without more information from logcat (with the android market version), the best guess to try is: uninstall any versions of your app on your device and redownload it again export into signed APK and directly push that onto your device with the "adb install MY_APP.apk" and see if that app works. (then make SURE you upload this particular one APK, and not some other one by accident)
{ "pile_set_name": "StackExchange" }
Q: Firebase IllegalAccessException in release apk I have added SHA1 for both debug and release keystore in firebase project console. I have also updated by google-services.json file in app. Debug apk is working fine and accessing all realtime database of firebase but when I build release apk I get the following exception while accessing Firebase database. 07-29 08:48:04.527 20997-20997/? E/AndroidRuntime: FATAL EXCEPTION: main Process: com.entrance.nepal, PID: 20997 java.lang.RuntimeException: java.lang.IllegalAccessException: java.lang.Class<com.tenhaff.uniingress.fragments.UserListFragment$UserViewHolder> is not accessible from java.lang.Class<com.firebase.ui.database.FirebaseRecyclerAdapter> at com.firebase.ui.database.FirebaseRecyclerAdapter.onCreateViewHolder(FirebaseRecyclerAdapter.java:171) at android.support.v7.widget.RecyclerView$Adapter.createViewHolder(RecyclerView.java:5779) at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5003) at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:4913) at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2029) at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1414) at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1377) at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:578) at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3260) at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:3069) at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:3518) A: ViewHolder Classes should be public rather than private or protected. It was because of proguard.
{ "pile_set_name": "StackExchange" }
Q: In SQL Server, finding in a string record with 7 but not 17, but could have both The title may not seem to make sense, but I've been trying to get something to work here, but I must be missing a trick. To explain... For example, take these records containing the strings: (1) 7 bla bla bla 17 bla bla 9 bla (2) Bla 12 bla bla 7 bla bla bla 54 bla bla (3) Bla bla bla 6 bla bla 17 bla bla bla 2 bla So, I need to find records, using the example above, which have the value of 7 anywhere in the string. If I use a ...LIKE '%7%'... it finds records 1, 2 and 3, but I only want it to find records with 7 (and not just 17), so it should only find records 1 and 2. Obviously, if I add ...NOT LIKE '%17%'... then I only get record 2 so that doesn't help. A: You should probably be storing these values in a junction table, rather than in delimited lists. However, you can do what you want using like: where ' ' + col + ' ' like '% 7 %' That is, add delimiters to the beginning and end of the string and then use them in the pattern to match.
{ "pile_set_name": "StackExchange" }
Q: Evaluation on the right side of an assignment This int c = (a==b) is exactly what I'd like to say in my C program, compiling with GCC. I can do it, obviously (it works just fine), but I don't know whether it may cause undefined behavior. My program will not be compiled with some other compiler or in other architectures. Is this legal ANSI C? Thanks. A: It's completely legal. if a is equal to b, then c will be 1. else, it will be 0.
{ "pile_set_name": "StackExchange" }
Q: Razor view engine - exception when calling Any Function I am trying to convert an existing ASPX page to cshtml format. The original ASPX looks something like this: <% if (!Model.ObjectList.Any()) { %> <tr> <td>No data found</td> </tr> <% } The equivalent Razor version looks like this: @if (!Model.ObjectList.Any()) { <tr> <td>No data found</td> </tr> } While the original syntax works just fine, the equivalent fails with the following message 'System.Collections.Generic.List' does not contain a definition for 'Any' I was wondering a) why this is happening and b) how to resolve this issue. I've added a reference to the System.LINQ namespace in my CSHTML file but to no avail. Any help is much appreciated, JP A: Thanks to everyone for their answers. This turned out to be an ID 10 T.... Essentially I neglected to strongly type my view. I was using @inherits System.Web.Mvc.WebViewPage<dynamic> instead of using @inherits System.Web.Mvc.WebViewPage<MyViewModel> Using the correct type fixed the issue. Thanks again, JP
{ "pile_set_name": "StackExchange" }
Q: Many-to-Many, Unidirectional, Self-referencing association in Doctrine2 I would like to 'link' some objects. Imagine you have Person table with these records: Barack Obama Obama Barack Barack Hussein Obama As you can see it is one the same person. I would like to have association that stores alternative persons. For example for Person with ID=1 and NAME=Barack Obama linkedPersons would look like this: linkedPersons: Obama Barack Barack Hussein Obama (optionally with Barack Obama itself) IMHO it should be Many-to-Many, Unidirectional, Self-referencing association but I have no idea how to implement such an association. A: I think you could do simple ManyToMany unidirectional mapping. On relation just relate both users. This would make additional records in database (A -> B and B -> A), but I think it should work as you want. <?php /** @Entity */ class User { /** * @ManyToMany(targetEntity="User") * @JoinTable(name="alternateUsers", * joinColumns={@JoinColumn(name="user_id", referencedColumnName="id")}, * inverseJoinColumns={@JoinColumn(name="alternate_user_id", referencedColumnName="id")} * ) */ private $alternateUsers; public function __construct() { $this->alternateUsers = new \Doctrine\Common\Collections\ArrayCollection(); } public function addAlternateUser(User $user) { $this->alternateUsers[] = $user; $user->alternateUsers[] = $this; } }
{ "pile_set_name": "StackExchange" }
Q: Need to create a custom blank page in drupal I've installed Drupal to have a basic user registration layer. Now I need to code some PHP code in a blank page, how I can achieve this in Drupal? I need to know where I must put my PHP code. Thanks a lot Edit. Basically I need Drupal only for user authorization. After a user logged into the system I want to show him a table with some data. This table was managed with JQuery. A: for what you want to do I think it's not necessary a custom module, but if so, it's not so hard to do, but you can allways use some existing drupal modules mixed together to do what you want. You will need: Display Suite and Login Redirect module Basically I need Drupal only for user authorization. After a user logged into the system I want to show him a table with some data. For this purpose you can use Login Redirect module to redirect user to any page you want. Now I need to code some PHP code in a blank page, how I can achieve this in Drupal? I need to know where I must put my PHP code. For this you can use Display Suite. Display suite or simply DS comes with a new a new Text Format: "Display Suite code". This text format allow you to add some custom code to your pages (javascript,php,etc)
{ "pile_set_name": "StackExchange" }
Q: What would be the most efficient method for storing/updating Interval based data in SQL? I have a database table with about 700 millions rows plus (growing exponentially) of time based data. Fields: PK.ID, PK.TimeStamp, Value I also have 3 other tables grouping this data into Days, Months, Years which contains the sum of the value for each ID in that time period. These tables are updated nightly by a SQL job, the situation has arisen where by the tables will need to updated on the fly when the data in the base table is updated, this can be however up to 2.5 million rows at a time (not very often, typically around 200-500k up to every 5 minutes), is this possible without causing massive performance hits or what would be the best method for achieving this? N.B The daily, monthly, year tables can be changed if needed, they are used to speed up queries such as 'Get the monthly totals for these 5 ids for the last 5 years', in raw data this is about 13 million rows of data, from the monthly table its 300 rows. I do have SSIS available to me. I cant afford to lock any tables during the process. A: 700M recors in 5 months mean 8.4B in 5 years (assuming data inflow doesn't grow). Welcome to the world of big data. It's exciting here and we welcome more and more new residents every day :) I'll describe three incremental steps that you can take. The first two are just temporary - at some point you'll have too much data and will have to move on. However, each one takes more work and/or more money so it makes sense to take it a step at a time. Step 1: Better Hardware - Scale up Faster disks, RAID, and much more RAM will take you some of the way. Scaling up, as this is called, breaks down eventually, but if you data is growing linearly and not exponentially, then it'll keep you floating for a while. You can also use SQL Server replication to create a copy of your database on another server. Replication works by reading transaction logs and sending them to your replica. Then you can run the scripts that create your aggregate (daily, monthly, annual) tables on a secondary server that won't kill the performance of your primary one. Step 2: OLAP Since you have SSIS at your disposal, start discussing multidimensional data. With good design, OLAP Cubes will take you a long way. They may even be enough to manage billions of records and you'll be able to stop there for several years (been there done that, and it carried us for two years or so). Step 3: Scale Out Handle more data by distributing the data and its processing over multiple machines. When done right this allows you to scale almost linearly - have more data then add more machines to keep processing time constant. If you have the $$$, use solutions from Vertica or Greenplum (there may be other options, these are the ones that I'm familiar with). If you prefer open source / byo, use Hadoop, log event data to files, use MapReduce to process them, store results to HBase or Hypertable. There are many different configurations and solutions here - the whole field is still in its infancy.
{ "pile_set_name": "StackExchange" }
Q: Javascript execution in Adobe PDF I'm using iTextSharp in C# to read the pdf and fill values for text fields in it and based on one text field value, I'm trying to run javascript action to fill two other fields before saving the document. I can see the script store in the pdf but it is not executing. Is there a better way to run the scripts in iTextSharp or in adobe? A: As far as I know, iText does not have an Acrobat JavaScript engine. In order to run (Acrobat) JavaScript in your form, you will have to open it in Acrobat/Reader, and provide a trigger to execute the scripts. Depending on which event the scripts are attached, you would either just have to run them (for example in the pageOpen event of the page on which the document opens), or using this.calculateNow() (again) in the pageOpen event of the page on which the document opens. If you have a multi-page document, you may also add a mechanism which runs those scripts only once (how to do that has been explained many times in many places (here on stackoverflow, but also in the Adobe forums, the AcrobatUsers forums (rest in peace), PlanetPDF etc.).
{ "pile_set_name": "StackExchange" }
Q: Braces around scalar initializer error in C++ I am trying to make a simple "font" for numbers to use on my 8x8 display through Arduino. This is just a simple test. #include <iostream> using namespace std; class Font{ public: void Number(int num){ switch(num){ case 0: bool Font[][5] = {{{{ 0, 1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 1, 0 }}}}; break; for(int y = 0; y < 5; y++){ for(int x = 0; x < 3; x++){ cout << Font[y][x]; } cout << endl; } } } }; int main() { Font myFont; myFont.Number(0); return 0; } However, when I run this, I get an error saying "13:34: error: braces around scalar initializer for type 'bool' 0, 1, 0 }}}};" A: That's not how you initialize a multidimensional array. You can either use bool Font[][5] = {{ 0, 1, 0 }, { 1, 0, 1 }, { 1, 0, 1 }, { 1, 0, 1 }, { 0, 1, 0 }}; or bool Font[][5] = {0, 1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 1, 0};
{ "pile_set_name": "StackExchange" }
Q: How to mount /tmp in /mnt on EC2? I was wondering what is the best way to mount the /tmp endpoint in the ephemeral storage /mnt on an EC2 instance and give the ubuntu user default write permissions. Some suggest editing /etc/rc.local this way: mkdir -p /mnt/tmp && mount --bind -o nobootwait /mnt/tmp /tmp However that doesn't work for me (files differs). I tried editing the default fstab entry: /dev/xvdb /mnt auto defaults,nobootwait,comment=cloudconfig 0 2 replacing /mnt with /tmp and and giving it a umask=0777, however it doesn't work because of cloudconfig. I'm using Ubuntu 12.04. Thanks. A: There are a couple problems with the initial suggestion you list, though it seems like it's headed in a good direction: For security purposes, the mkdir command should create the directory with the sticky bit set in the mode: mkdir -m 1777 /mnt/tmp The -o nobootwait doesn't seem necessary as this is not being saved in /mnt/fstab. So, I'd recommend trying this in /etc/rc.local: test -d /mnt/tmp || mkdir -m 1777 /mnt/tmp mount --bind /mnt/tmp /tmp Any attempt to put the bind mount in /etc/fstab is going to run into problems when you stop/start the instance or when you create an AMI and run a new instance as /mnt is ephemeral storage and all contents (including the /mnt/tmp directory) are going to disappear. A: A more robust approach, since you're running Ubuntu, would be to put Eric Hammond's suggestion inside an Upstart script, and have the bind done immediately after mounting /mnt: # File /etc/init/mounted-mnt.conf # mounted-mnt - Binds /tmp to /mnt/tmp description "Binds /tmp to /mnt/tmp" start on mounted MOUNTPOINT=/mnt task script test -d /mnt/tmp || mkdir -m 1777 /mnt/tmp mount --bind /mnt/tmp /tmp end script Some servers, like Apache/Passenger, might create important temporary files on /tmp. Once rc.local – the last in the boot sequence – ran they would get hidden and confuse the servers.
{ "pile_set_name": "StackExchange" }
Q: Devise: I can't display only current user workouts I created little sport app and now I have problem with show only current user workouts on index page. The problem : NoMethodError in WorkoutsController#index. undefined method `workouts' for nil:NilClass. def index @workouts = current_user.workouts.all end I leave all details below: Associations In my User model I have has_many :workouts In my Workout model I wrote belongs_to :user In my views/workouts/index.html.erb <% @workouts.each do |workout| %> <h4><%= link_to workout.date, workout %></h4> <h3><%= workout.workout %></h3> <% end %> A: try this: def index @workouts = current_user.present? ? current_user.workouts : [] end i think there is error when you are not loged, and current_user return nil
{ "pile_set_name": "StackExchange" }
Q: Extracting files at the start up setup instead of the end I am using the latest version of inno that does the following during setup: Perform dependency check to see what is installed Installs dependencies that are not already installed (.net, sql server, directx etc) Install the application and the files from the [Files] section (wpReady) Checks SQL Server for previously installed database and creates / updates the tables etc Step [4] creates the database and tables etc and only works if SQL Server has already been installed which is why it is done in Step [2]. The output directory contains the created setup.exe and I manually place the additional dependencies folder containing the files required for steps [1,2 and 4] mentioned above. This works great but I would like to create a single exe only that includes all the dependencies and extracts the dependencies BEFORE wpReady and before Step [1] above. The dependencies are in the [Files] section but these files are not extracted until the setup executes wpReady message after the setup has gone through all the forms and attempts to install the files. I use the following that adds what I need to the setup.exe [Files] Source: Output\Dependencies\*; DestDir: {tmp}; Flags: deleteafterinstall What is the best way to extract the files to the temp directory before wpReady or should I perform the actions of wpReady first then go about installing the Dependencies (not ideal though). A: You can use the ExtractTemporaryFile() function in the PrepareToInstall event function to extract any file from the [Files] section to {tmp} earlier, and it will be deleted when the setup finishes. Together with scripting and the various hooks Inno Setup gives you nearly everything can be achieved. Have a look at the "Pascal Scripting" section of the Inno Setup help, specifically the "Support Functions Reference". There you will find documentation for ExtractTemporaryFile() and more.
{ "pile_set_name": "StackExchange" }
Q: Python : compare lists of a list by length and create new lists of equal sizes i have a big list that consists of multiple lists of arbitrary lengths. I want to compare each list length and create new lists of equal sizes. For example, biglist = [['x','y','z'],['a','b'],['d','f','g'],...,['r','e','w','q','t','u','i']] expected_list= [['a','b'],[['x','y','z'],['d','f','g']],....,['r','e','w','q','t','u','i']] I am new to python. can anyone suggest me a less expensive method to do the above process. Thanks in advance. A: May I suggest using itertools groupby function? import itertools biglist = [['x','y','z'],['a','b'],['d','f','g'],['r','e','w','q','t','u','i']] print(list(list(i[1]) for i in itertools.groupby(sorted(biglist, key=len), len))) Which outputs [[['a', 'b']], [['x', 'y', 'z'], ['d', 'f', 'g']], [['r', 'e', 'w', 'q', 't', 'u', 'i']]]
{ "pile_set_name": "StackExchange" }
Q: Finite Group Proving finite order of elements and Subgroup Question The question is as follows Let G be a finite group. (i) Prove that every element of G has finite order. For this want to use the idea that if G is finite then for a in G, $a^{n}$ = $e$ for some n in $Z^{+}$ and treat a is a generator of a cyclic group that is a subset of G the the order of each $<a_{i}>$ must be less than or equal to G. since G is of finite order each $<a_{i}>$ is also of finite order. but i am really not sure i can treat this group in such a way? (Secondly) Suppose that H is a subset of G which is non-empty and, for any a, b in H, ab is also in H. Prove that H is a subgroup of G. For this i want to try and use that since ab is in H $(ab)^{n}$ should be in H and for some n in $Z^{+}$ $(ab)^{n}$ = e but im not sure my assumption in part 1 is correct... could someone point me in the right direction please? EDIT I think i understand since H is finite ( cause G is finite) I understand why for any h in H $<h>$ must be a subset of H but how do we prove that $(h)^{2}$ is in H oh! Perhaps we use for any a,b in H ab is H and just pick h twice so hh must be in H thus $(h)^{n}$ must be in H and $(h)^n$ = e for some n in $Z^{+}$ by G and this must be true for all h in H ? EDIT (ii) Ok let a and b be in H and left $a^{l} = e$ and $b^{k}= e$ for some l and k in $Z^{+}$ then $b^{k}$$a^{l}$ is in H and $b^{k}$$a^{l}$ = e so $b^{-k}$$b^{k}$$a^{l}$ = $b^{-k}$ so $a^{l}$ = $b^{-k}$ Can we assume from this that every h in H has an inverse because every $h^{n}$ has one? Im still curious about above but i think that anon actually had answered my question of where the i could find the Inverse element from at the end of his post. ( i just need to digest the information a bit) Thanks so much to all of you, its very helpful to be able ask a question and get such a wonderful number of different ways of looking at the problem. A: For (i) you are right. Take the cyclic group $\langle g\rangle\subseteq G$ generated by an arbitrary $g\in G$; since it is a subset of a finite set ($G$ is finite) it must be finite, so the order of $g$ is finite (note that an equivalent way of defining the order of $g$ is as $\#\langle g\rangle$, if you're not already using this definition). For (ii), since $a,b\in G\implies ab\in G$, there are two other group properties you need to check: first, that $H$ contains the identity $e\in G$, and second, that for all $a\in H$, the inverse $a^{-1}\in H$ is too. For this part, finiteness of $G$ is critical (it is not generally true that a subset closed under the group operation need be a subgroup of an infinite group; take the nonnegative naturals under addition as a subset of the group of integers under addition). To do this, prove that for any $h\in H$, we have $\langle h\rangle\subseteq H$. Then show both $e$ and $h^{-1}$ are in $\langle h\rangle$, and hence in $H$ as well. This would establish all three properties of $H$'s being a subgroup.
{ "pile_set_name": "StackExchange" }
Q: Meaning of Total errors on result of Clamav scan I scanned my Ubuntu computer using Clamav the following are the results Known viruses: 2288150 Engine version: 0.97.8 Scanned directories: 55215 Scanned files: 283662 Infected files: 0 Total errors: 18736 Data scanned: 16464.40 MB Data read: 30027.11 MB (ratio 0.55:1) Time: 4558.179 sec (75 m 58 s) My Question is what are total errors and I should I do some thing to remove them? A: Read this Clamav faq question #21. No need to sweat. These "errors" are not actually errors but are usually files you don't have read access to. They may belong to another user or to the System. Either way they probably aren't anything to be concerned about.
{ "pile_set_name": "StackExchange" }
Q: Linked list insert a node in sorted linked list emphasized text i need to pass header of the LINKED LIST and data to be inserted in that linked list.assuming the list is in sorted order i need to check data from each node and insert new node to give newly sorted list. im getting null pointer exception ,, i need to know what im doing wrong /* Insert Node at the end of a linked list head pointer input could be NULL as well for empty list Node is defined as class Node { int data; Node next; Node prev; } */ Node SortedInsert(Node head,int data) { Node root= head; if(head==null){ root.data=data; root.next=null; root.prev=null; }else if(head.data>data){ Node newnode = new Node(); newnode.data=data; newnode.next=head; newnode.prev=null; head.prev=newnode; root=newnode; } int k=0; while(head!=null && k==0){ if(head.data<data && head.next.data>data && head.next!=null){ Node temp=head.next; Node newnode = new Node(); newnode.data=data; newnode.next=temp; newnode.prev=head; head.next=newnode; temp.prev=newnode;k++; break; } else if(head.data<data && head.next==null){ //Node temp=head.next; Node newnode = new Node(); newnode.data=data; newnode.next=null; newnode.prev=head; head.next=newnode;k++;break; //temp.prev=newnode; }else {head=head.next;} } return root; } im getting null pointer exception at second if statement inside while loop. A: I found some errors in your code which might be giving NullPointerException So change it accordingly. First mistake is here: Node root= head; if(head==null){ root.data=data; root.next=null; root.prev=null; } So here you need to first create an object of Node class and assign it to root so code will look like : Node root= head; if(head==null){ root=new Node(); root.data=data; root.next=null; root.prev=null; } Another Mistake I encountered is in condition of if(head.data<data && head.next.data>data && head.next!=null). Here you are should validate head.next before accessing it in head.next.data. Suppose if head.next is null then the evaluation of condition of loop goes like this. 1) head.data<data so suppose this return true so we will check next condition. 2) head.next.data>data now if head.next is null then here condition would be null.data which will throw an NullPointerException. So here you should also check that head.next is not null. You are doing this is next condition but it is getting executed before validation it. So here you just need to change order of the condition of if statement like: if(head.data<data && head.next!=null && head.next.data>data). This will solve your problem.
{ "pile_set_name": "StackExchange" }
Q: Resizing SVG in html? So, I have an SVG file in HTML, and one of the things I've heard about the format is that it doesn't get all pixelated when you zoom in on it. I know with a jpeg or whatever I could have it stored as a 50 by 50 icon, then actually display it as a (rather pixelated) 100 by 100 thumbnail (or 10 by 10), by manually setting the height and width in the image_src tag. However, SVG files seem to be used with object/embed tags, and changing the height or width of THOSE just results in more space being allocated for the picture. IS there any way to specify that you want an SVG image displayed smaller or larger than it actually is stored in the file system? A: Open your .svg file with a text editor (it's just XML), and look for something like this at the top: <svg ... width="50px" height="50px"... Erase width and height attributes; the defaults are 100%, so it should stretch to whatever the container allows it. A: Try these: Set the missing viewbox and fill in the height and width values of the set height and height attributes in the svg tag Then scale the picture simply by setting the height and width to the desired percent values. Good luck. Set a fixed aspect ratio with preserveAspectRatio="X200Y200 meet (e.g. 200px), but it's not necessary e.g. <svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" width="10%" height="10%" preserveAspectRatio="x200Y200 meet" viewBox="0 0 350 350" id="svg2" version="1.1" inkscape:version="0.48.0 r9654" sodipodi:docname="namesvg.svg"> A: you can resize it by displaying svg in image tag and size image tag i.e. <img width="200px" src="lion.svg"></img>
{ "pile_set_name": "StackExchange" }
Q: When I use await in an async method why does it not skip that so it can work in the background and go to the following lines? I have the following code: protected override async void OnStart() { await Helper.PopulateMetrics(); await Helper.LogStart(); if (Settings.Rev == REV.No && (new[] { 15, 30, 50 }).Contains(Settings.Trk2)) I guess I am confused as when I set a breakpoint in await Helper.LogStart() I see that breakpoint his before the line starting with "if (Settings ... " as there is an await should the code after those not be hit first? Here's what the LogStart() method looks like: public static async Task LogStart() { // code await App.CDB.InsertLogItem(logStart); } Ideally I would like these two methods to just run in the background one after the other while the code immediately skips them. A: The await keyword causes the execution to wait until the Helper.LogStart() function has completed. If you want to continue executing, you can store the returned Task object into another variable and await on it later: var task = Helper.LogStart(); /* something else */ await task;
{ "pile_set_name": "StackExchange" }
Q: An inequality involving integrals and square root Could someone help me with this inequality? $$\left( \int_a^b \sqrt{\sum_{j=1}^n f_j^2(x)} dx \right)^2 \geq \sum_{j=1}^n \left(\int_a^b f_j(x) dx \right)^2$$ I tried to used the concavity of square root and then Cauchy Schwarz, but the latter is in the wrong direction. I appreciate any help! A: Let $(a_1,a_2,\cdots,a_n)$ be a unit vector in $\mathbb R^{n}$. Then $\sum_j a_j \int_a^{b} f_j (x) dx=\int_a^{b}\sum_j a_j f_j (x) dx \leq \int_a^{b} \sqrt {\sum f_j^{2}}$ by C-S inequlaity. By taking sup over all u nit vectors $(a_1,a_2,\cdots,a_n)$ we get the desire dinequality.
{ "pile_set_name": "StackExchange" }
Q: Saving NSMutableArray and loading it in a UITableView I want to save multiple NSMutableArray and load it because this array gets it content from a server and i don't want to reload that data every time the app is opened. First I declared the paths: NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *firstPath = [documentsDirectory stringByAppendingPathComponent:@"first"]; NSString *secondPath = [documentsDirectory stringByAppendingPathComponent:@"second"]; NSString *thirdPath = [documentsDirectory stringByAppendingPathComponent:@"third"]; NSString *fourthPath = [documentsDirectory stringByAppendingPathComponent:@"fourth"]; then save the NSMutableArrays: [firstArray writeToFile:firstPath atomically:YES]; [secondArray writeToFile:secondPath atomically:YES]; [thirdArray writeToFile:thirdPath atomically:YES]; [fourthArray writeToFile: fourthPath atomically:YES]; then open these files in other NSMutableArrays: firstArrayget = [NSMutableArray arrayWithContentsOfFile:firstPath]; secondArrayget = [NSMutableArray arrayWithContentsOfFile:secondPath]; thirdArrayget = [NSMutableArray arrayWithContentsOfFile:thirdPath]; fourthArrayget = [NSMutableArray arrayWithContentsOfFile:fourthPath]; then I try to load these Arrays (...Arrayget i.e. firstArrayget) into a TableView. The data gets loaded into the TableView, but when I scroll down the App crashes with the Error: *** -[CFArray objectAtIndex:]: message sent to deallocated instance 0x930fc80 and in the file: Thread 1:EXC_BREAKPOINT(code=EXC_1386_BPT,subcode=0x0) but if I say the TableView to load the data from the (...Array i.e. firstArray),so the data downloaded from the server unsaved. A: Assuming you're using MRC and not ARC: Looks like you're setting an ivar to an autoreleased NSMutableArray. Try calling retainon the NSMutableArrays, otherwise your NSMutableArrays will just get released and thus deallocated when the autoreleasepool drains. Another solution is to use a property for each of your NSMutableArrays like this: // Create a property in your header file @property (retain) NSMutableArray *firstArrayget; // And set the property in your method [self setFirstArrayGet:[NSMutableArray arrayWithContentsOfFile:firstPath]]; You can find more about Objective-C memory management at https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/MemoryMgmt/Articles/MemoryMgmt.html
{ "pile_set_name": "StackExchange" }
Q: Change Text Node via For Loop but resulted in Unexpected Identifier So I have this problem that I think Javascript can solve and since I'm still learning the language that's another problem, so here I am asking for help. I want to wrap the text node I would like to opt in to receive future communication from. in <span class="something"></span>. My plan is to Loop it so that it will add span to all node text contents under an element So I coded it and the console shows error Uncaught SyntaxError: Unexpected identifier Orginal HTML <tbody> <tr> <td> <label class="gotowebinar-required" for="577271555173">I would like to opt in to receive future communication from</label> </td> </tr> </tbody> So I arrived at this I think terrible looking code that is seemingly not working and a variable freak. JS function changeEl(){ var r = document.getElementsByClassName('gotowebinar-required').length; for (var i = 0; i <= r; i++){ console.log(r); var m = '['; var n = ']'; var b = m+i+n; var x = document.getElementsByClassName('gotowebinar-required')b; var w = document.getElementsByClassName('gotowebinar-required')b.innerHTML; var y = x.innerHTML; var p = '<span style="font-weight: bold;"class="label_1">'; var q = '</span>'; x.innerHTML = p+w+q; }; }; changeEl(); In the end, what im looking for is <tbody> <tr> <td> <label class="gotowebinar-required" for="577271555173"> <span style="font-weight: bold;"class="label_1">I would like to opt in to receive future communication from.</span> </label> </td> </tr> </tbody> to all the elements that has a class of gotowebinar-required. A: You cant't use '[' and ']' to reference a item inside array like you did. If you use straight [i] like code below you are good to go. function changeEl(){ var r = document.getElementsByClassName('gotowebinar-required').length; for (var i = 0; i < r; i++){ console.log(r); var x = document.getElementsByClassName('gotowebinar-required')[i]; var w = document.getElementsByClassName('gotowebinar-required')[i].innerHTML; var y = x.innerHTML; var p = '<span style="font-weight: bold;"class="label_1">'; var q = '</span>'; x.innerHTML = p+w+q; }; }; changeEl();
{ "pile_set_name": "StackExchange" }
Q: When taking passengers, what should I do to prepare them? What kinds of stuff should I think about in terms of taking other passengers flying in a small airplane? Many potential passengers have never been in a small airplane. A: I go through the SAFETY checklist with all my passengers. The FAA recommends this as well. Seat Belts - This is where they are and how to use them. Air Vents - Here are the air vents and how to use them Fire - In case of a fire here is the location of the fire extinguisher and this is how you use it. PASS method. Exits, Emergencies and Equipment - Here are the exits on the airplane and here is how to open the door. Know that you are in good hands and that I have been well trained to land safely under most situations. If for some reason an emergency occurs in flight follow my directions. If we need to land off the airport, I will ask you to pop open the door just before landing to ensure we can exit the airplane safely. Here is any safety equipment that you may want to use on this flight. i.e. supplemental oxygen. Traffic and talking - Please point out an traffic that you see and I will do the same. Please no talking while I am on the radio. Once we start taxiing to the runway please remain quiet til we are far enough away from the airport. I will let you know when it is safe to talk again. When we come in to land, I will ask that you remain quiet, unless an emergency situation occurs, till after the landing is complete and we are taxiing back to parking. Your questions - Do you have any questions? Alright, lets go have some fun! A: The essentials Seat belts—Operation of seat belts is the only FAA-required briefing item. Airplane seat belts can be complicated, even for other pilots. Make sure everyone knows how to fasten and unfasten, and when the lap and shoulder portions should be worn. Doors—Car makers have generally figured out how to standardize door handles. Not so with airplanes. Demonstrate how to open and close the door, the location of all the exits, and how to kick out the windows if the doors won’t open after an accident. Also, be sure to mention if one of your doors has a habit of opening in flight. Fire suppression—Point out the fire extinguisher and explain how to use it. Your rental airplane doesn’t have one? Buy one and keep it in your flight bag. The good-to-know Dress—Airplanes are a foreign environment. Give guidance on how to dress, both for the flight itself and in the event of an off-airport landing (boots, coats, hats, gloves, sunscreen, et cetera). Signaling devices—A tutorial on how to tune and transmit on 121.5 MHz is helpful, as is a discussion of how to use a personal locator beacon, the emergency locator transmitter, and any survival devices. Creature comforts—Maybe not today, maybe not tomorrow, but someday one of your passengers will get sick. Carry bags and point out where they are and how to use them. Also explain the location of the vents, heat, and sunshades. Talk time—A strict sterile cockpit may not be necessary at all times below 5,000 feet, but mentioning when it’s OK to talk and when it’s not is a good practice. So is pointing out what a passenger can touch and what he or she absolutely should not (we’re looking at you, ejection handle). —AOPA I'd add to that list to not hold back when something needs pointing out, like another plane's lights. And as Ron Beyer pointed out, to explain to the front seated passenger to keep their feet off the rudder pedals. A: We were required to give what amounted to an "airline" briefing before each flight. We were also required to have those stupid little briefing cards for each passenger (of which at least one was stolen on each flight). Our Cessna 210, oddly enough, seemed to have the most popular cards! We couldn't make enough of them. Maybe people just think it's silly that a "little Cessna Piper Cub" has a briefing card just like a "real" plane. I quit flying professionally in 2013 but continue to use 135.117 as my standard briefing. •these are the seatbelts, this is how they work. •these are the exits, this is how they work. •these are oxygen masks, this is how they work. •your seats recline but please leave your seatbacks in the upright position for takeoff and landing. •the fire extinguisher is here, this is how it works. •please don't smoke. •there is a survival kit in the back of the plane...or in my flight bag...or both •(front seat passenger) these are the controls, please keep from touching them. •if you see another plane, let me know if the wings are on the top or the bottom and the number of engines you see (prevents passengers from reporting every single glint that may possibly be an airplane) •if you have any questions, PLEASE ASK! If I things are busy and can't answer you immediately, I'll ignore you but circle back later.
{ "pile_set_name": "StackExchange" }
Q: dg-projective complex and module category. If R is a ring.then the complex $D^.$ of R-modules is called dg-projective complex if Hom complex $Hom^.(D^.,A^.)$ is acyclic for arbitrary acyclic complex $A^.$ of R modules.this is equivalent to $Hom_{K(R-Mod)}(D^.,A^.)=0$for arbitrary acyclic complex $A^.$ of R modules. My Question:if $Hom_{K(R-Mod)}(D^.,A^.)=0$ for arbitrary acyclic complex $A^.$ of finite generated R modules.Is $D^.$ dg-projective complex? when I think about this question,I also find a question. if $A$ is abelian category with direct limit,is homotopy category $K(A)$ has direct limit? thanks a lot! A: Take $R=\mathbb{Z}$ and $D^.=\mathbb{Q}$, considered as a complex concentrated in degree zero. $\text{Hom}_\mathbb{Z}(\mathbb{Q},X)=0$ for any finitely generated $\mathbb{Z}$-module $X$, and so $\text{Hom}_{K(\mathbb{Z}-\text{Mod}))}(\mathbb{Q},A^.)=0$ is zero (and so acyclic) for all complexes $A^.$ (and in particular acyclic ones) of finitely generated $\mathbb{Z}$-modules.
{ "pile_set_name": "StackExchange" }
Q: rescheduling a meeting in lotus notes programatically using java i have written a webservice for rescheduling a non recurring meeting in lotus notes using domino designer 8.5.3.when i reschedule a meeting for the first time in the Invitee's calendar the entry will be removed from the previous date and will be placed in the rescheduled date.But when i reschedule the same meeting for the second time the it will create a meeting in the rescheduled date but the previous entry will not be removed from the calendar. Hers is what i am doing to reschedule the meeting.i rescheduled a meeting from lotus notes and to reschedule from code i am creating a child document from make response method and i am putting all the properties by checking the properties in the meeeting rescheduled from lotus notes. So can anyone please tell which property of the document is responsible for removing the calendarDate time property.so that the previous calendar entry will be removed from the calendar. A: The issues was with the SQUENCENUM property of the document.As i was creating a child document using make response method i was incrementing the SQUENCENUM of the child document only but not of the parent document.And because of that reason the value of SQUENCENUM of the child document will always be 2 and hence it was not removing the previous entry from the Invitees calendar.The problem got solved by incrementing the SQUENCENUM of the parent document after each reschedule.
{ "pile_set_name": "StackExchange" }
Q: Cross table query for showing comments and thread name while both values in different table I have 2 tables, one for comments and one for the thread. They are both connected with the thread_id which checks what comments belong to what thread. Now I got a profile page and I want to show the comments posted by the user (which already works) and to what thread(column title) each comment belongs to. I am a beginner with cross table queries and I was wondering how I could accomplish this. Here is my code for showing the comments posted by the user: $sql_result4 = $mysqli2->query("SELECT * FROM comments WHERE username = '".$profileusername."'"); while($postcomments = mysqli_fetch_assoc($sql_result4)){ echo"<a href='thread.php?thread_id={$postcomments['comment_id']}'>{$postcomments['comment']}</a></br>"; } I was thinking about something like this: $sql_result4 = $mysqli2->query("SELECT * FROM comments WHERE username = '".$profileusername."'"); $sql_result5 = $mysqli2->query("") while($postthread = mysqli_fetch_assoc($sql_result5){ while($postcomments = mysqli_fetch_assoc($sql_result4)){ echo"<a href='thread.php?thread_id={$postcomments['comment_id']}'>{$postcomments['comment']}</a></br>"; } } but I have no idea what to use for $sql_result5 What should I put as $sql_result5 A: You can use just 1 query and use left join. SELECT c.*, t.* FROM comments c LEFT JOIN threads t ON t.id = c.thread_id WHERE c.username = 'username' Now you have all data in 1 result.
{ "pile_set_name": "StackExchange" }
Q: What is the best jquery tooltip plugin? What is the best jquery tooltip plugin? A: check out qtip. its my go to tool tip plugin, very flexible and easy http://craigsworks.com/projects/qtip/ This is the updated version of the library: qtip2
{ "pile_set_name": "StackExchange" }
Q: Transform of ELMAH string when publishing to production server name not working I am running Visual Studio 2010, using an ASP.Net forms application.I am trying to transform XMl on build but it is not working. In my config section I have the following: <elmah> <security allowRemoteAccess="yes" /> <errorLog type="Elmah.SqlErrorLog, Elmah" connectionString="Data Source=TestServer;Initial Catalog=OnlineApplication;Trusted_Connection=True" /> <errorMail from="[email protected]" to="[email protected]" subject=" Exception" async="true" smtpserver="smtpgate.server.edu" /> I am trying to get it the ELMAH server name to transform when I publish to production via web.config.production xml transformation. All of my other settings for the app settings and connection strings work fine. I have the following in my web.production.config: <add type="Elmah.SqlErrorLog, Elmah" connectionString="Server=ProductionServer;Initial Catalog=OnlineApplication;Integrated Security=True" xdt:Transform="SetAttributes" xdt:Locator="Match(type)"/> </elmah> It doesn't complain but it also does't transform the text. What do I need to change to make the file transform on build/publish. A: Since is only one errorLog tag, you can use Replace instead of SetAttributes with a locator. Also note that you have to use the actual tag name, not <add>. <errorLog type="Elmah.SqlErrorLog, Elmah" connectionString="Server=ProductionServer;Initial Catalog=OnlineApplication;Integrated Security=True" xdt:Transform="Replace"/>
{ "pile_set_name": "StackExchange" }
Q: search lines in bash for specific character and display line I am trying to write search a string in bash and echo the line of that string that contains the + character with some text is a special case. The code does run but I get both lines in the input file displayed. Thank you :) bash #!/bin/bash printf "Please enter the variant the following are examples" echo " c.274G>T or c.274-10G>A" printf "variant(s), use a comma between multiple: "; IFS="," read -a variant for ((i=0; i<${#variant[@]}; i++)) do printf "NM_000163.4:%s\n" ${variant[$i]} >> c:/Users/cmccabe/Desktop/Python27/input.txt done awk '{for(i=1;i<=NF;++i)if($i~/+/)print $i}' input.txt echo "$i" "is a special case" input.txt NM_000163.4:c.138C>A NM_000163.4:c.266+83G>T desired output ( this line contains a + in it) NM_000163.4:c.266+83G>T is a special case edit: looks like I need to escape the + and that is part of my problem A: you can change your awk script as below and get rid of echo. $ awk '/+/{print $0,"is a special case"}' file NM_000163.4:c.266+83G>T is a special case
{ "pile_set_name": "StackExchange" }
Q: Regular expression to select all characters except letters or digits I have this regular expression: ^[a-zA-Z0-9] I am trying to select any characters except digits or letters, but when I test this, only the first character is matched. When I use [a-zA-Z0-9] the matches are correctly digits and letters. I need to negate it, but the ^ does not work. A: Below is a quick summary of regexps and how you can group together a query set using the commands below. In your case place the ^ inside the [a-zA-Z0-9] to achieve the desired result. . Single character match except newline "." Anything in quotations marks literally A* Zero or more occurrences of A A+ One or more occurrences of A A? Zero or one occurrence of A A/B Match A only if followed by B () series of regexps grouped together [] Match any character in brackets [^] Do not match any character in brackets [-] Define range of characters to match ^ Match beginning of new line $ Match end of a line {} Cardinality of pattern match set \ Escapes meta-characters | Disjunctive matches, or operation match A: Putting the ^ at start of your expression means "search from the beginning of the string". You need to put it inside the square brackets to make it a negation. [^a-zA-Z0-9]
{ "pile_set_name": "StackExchange" }
Q: Setting up a WLAN usb stick I'm trying to make the WLAN USB stick connect to a wireless network. There was an official Linux driver available for download (v4.0.2_9000.20130911, which supports my Linux kernel version) and I used wifi-radar Both had no success in making it work. Probably the driver is not compatible with my Oracle Linux (based on Red Hat Enterprise Linux 6) # lsusb | grep WLAN Bus 002 Device 017: ID 0bda:8178 Realtek Semiconductor Corp. RTL8192CU 802.11n WLAN Adapter The problem is that the device still can't be detected even after the driver installation runs to the end. I don't know how to check if it was actually installed, or where it is mounted. # cd RTL8188C_8192C_USB_linux_v4.0.2_9000.20130911/driver/rtl8188C_8192C_usb_linux_v4.0.2_9000.20130911 # make (no errors) # make install (no errors) # /sbin/modprobe 8192cu # ifconfig wlan0 up wlan0: unknown interface: No such device # /sbin/iwconfig virbr0-nic no wireless extensions. eth0 no wireless extensions. eth1 no wireless extensions. virbr0 no wireless extensions. lo no wireless extensions. Is it possible to somehow specify it manally in wifi-radar or what steps should I take? A: After plugging the USB in and out and running the updated script again I made it work. I also ran the install.sh script provided with the driver, but it seems that was not needed. Here is my setup: # cd RTL8188C_8192C_USB_linux_v4.0.2_9000.20130911/driver/rtl8188C_8192C_usb_linux_v4.0.2_9000.20130911 # make (no errors) # make install (no errors) # /sbin/modprobe 8192cu # /sbin/iwconfig eth0 no wireless extensions. wlan0 IEEE 802.11bgn ESSID:"KDG-44A11" Nickname:"<WIFI@REALTEK>" Mode:Managed Frequency:2.412 GHz Access Point: DC:53:7C:A4:4A:16 Bit Rate:300 Mb/s Sensitivity:0/0 Retry:off RTS thr:off Fragment thr:off Encryption key:****-****-****-****-****-****-****-**** Security mode:open Power Management:off Link Quality=100/100 Signal level=73/100 Noise level=0/100 Rx invalid nwid:0 Rx invalid crypt:0 Rx invalid frag:0 Tx excessive retries:0 Invalid misc:0 Missed beacon:0 eth1 no wireless extensions. virbr0 no wireless extensions. lo no wireless extensions.
{ "pile_set_name": "StackExchange" }
Q: Get user-inputed file name from JFileChooser Save dialog box This answer to this question may seem obvious, but I'm actually struggling with it quite a bit. I've searched through JFileChooser methods in the API, and I've looked at some of the questions already asked and answered here on stackoverflow. My question is this. In my program, I am to allow the user to type in a file name which I will then use to create a brand new file that I will write on. How do you get the text the user has entered in the textfield next to the label "Save As:" on the Save dialog box provided by JFileChooser? Is there a JFileChooser method that would allow me to get that user-inputed text? Or would I have to go through another class, or do something else to get that text? Thank you so much, to anyone who answers. It's very late for me now, and this program is due in a few hours (meaning I'll be having another sleepless night). Desperate may be too strong a word, but I'm something close enough. A: JFileChooser chooser=new JFileChooser(); chooser.setFileSelectionMode(JFileChooser.DIRECTORY_ONLY); chooser.showSaveDialog(null); String path=chooser.getSelectedFile().getAbsolutePath(); String filename=chooser.getSelectedFile().getName(); ......in filename variable you will get the file name entered by the user A: After you've opened the save file dialog and determined that the user wants to save the file, grab the file name with this: String filename = mySaveDialog.getSelectedFile().getName(); A: JFileChooser has a method, getSelectedFile(). Which is a File. If you open the dialog with showSaveDialog() you should be able to get the File from that (file.getName()). And you can parse that to get the user's entered text. (e.g. drop the extension... I don't know what you want :) ) Good luck with your assignment.
{ "pile_set_name": "StackExchange" }
Q: Database doesn't exist, the other file it works this is really weird and I don't know why it is like this. I have my other files work fine (login, registration, and memberadd) however, on memberaddprocess file, when it try to connect to the database, it says that my database doesn't exist. The other works fine, only the memberadd process. If anyone knows why, please kindly explain. This is my memberadd.php code <?php session_start(); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/chtml-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en" > <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <meta name="description" content="Web Programming :: Assignment 2" /> <meta name="Keywords" content="Web, programming" /> <title>Member Login</title> </head> <body> <h1>My Member System</h1> </body> </html> <?php require_once('sqlconnect.inc.php'); if(isset($_SESSION['membername'] )) { echo "".$_SESSION['membername']."<p>Add Member Page</p>"; $conn = @mysqli_connect($host, $user, $pswd, $dbnm); if (!$conn) { echo "<p>Database connection failure</p>"; } else { @mysqli_select_db($conn, $dbnm) or die ("Database not available"); } $memberHid = $_SESSION['membername']; $query = "SELECT member_name FROM team"; $result = mysqli_query($conn, $query); if(!$result) { echo "<p>Query failed to execute, Error with: ", $query, "</p>"; } $queryFetch = mysqli_fetch_row($result); //echo "<p> $queryResult1</p>"; $m=0; while($queryFetch) { $mQueryFetch[$m] = $queryFetch[0]; $queryFetch = mysqli_fetch_row($result); $m++; } $i=0; $query2 = "SELECT member_id FROM team WHERE member_name='$memberHid'"; $result2 = @mysqli_query($conn, $query2); $queryFetchResult = mysqli_fetch_row($result); $memId = $queryFetchResult[0]; $query3 = "SELECT COUNT(*) FROM myteam WHERE member_id1 = '$memId'"; //query for counting the no of friends $resultSelect = @mysqli_query($conn,$query3) or die ("<p>Query failed to execute.</p>". "<p>Error with:" . mysqli_errno($conn) .":" . mysqli_error($conn))."</p>"; $arCount = mysqli_fetch_row($resultSelect); echo "<p>Number of Current team member is"." ". $arCount[0]." "."</p>"; $querySelect = "SELECT member_id2 FROM myteam WHERE member_id1 = '$memId'"; $resultSelect2 = @mysqli_query($conn, $querySelect); $memArr = mysqli_fetch_row($resultSelect2); if($memArr) { while($memArr) { foreach($memArr as $value) { $querySelect3 = "SELECT member_name FROM team WHERE member_id = '$value'"; $queryResult = @mysqli_query($conn,$querySelect3); $fetchArr = mysqli_fetch_row($queryResult); foreach($fetchArr as $value) { $newDat[$a] = $value; $a++; } } $memArr = mysqli_fetch_row($resultSelect2); } $curLog = array_diff($mQueryFetch, $newDat); //for displaying profile names without the currently logged in user and his old friends profile names $querySelect2 = "SELECT member_name FROM team;"; $querySelectResult = @mysqli_query($conn,$querySelect2) or die ("<p>Query Failed to Execute.</p>". "<p>Error with" . mysqli_errno($conn) .":" . mysqli_error($conn))."</p>"; echo "<table width='20%' border='1'>"; echo "<tr><th>Member Name</th>"; echo "<th>Status</th></tr>"; $fetchArray = mysqli_fetch_row($querySelectResult); foreach($diff as $value) { if($value!=$_SESSION['membername']) { echo "<tr><td>{$value}</td>"; $memberHid1 = $value; $memberHid = $_SESSION['membername']; echo "<td>"?> <form action ="memberaddprocess.php" method = "post" > <?php echo'<input type="hidden" name="memberHid1" value="'.htmlspecialchars($memberHid1).'" />';?> <?php echo'<input type="hidden" name="memberHid" value="'.htmlspecialchars($memberHid).'" />';?> <p><input type="submit" name="Addmember" value="AddMember" /></p> </form> <?php "</td></tr>"; } $fetchArray = mysqli_fetch_row($querySelectResult); } echo"</table>"; } else { $n=0; $querySelect2 = "SELECT member_name FROM team ; "; $querySelectResult = @mysqli_query($conn, $querySelect2) or die ("<p>Query Failed to Execute.</p>". "<p>Error with" . mysqli_errno($conn) .":" . mysqli_error($conn))."</p>"; $fetchArray = mysqli_fetch_row($querySelectResult); while($fetchArray) { if($fetchArray[0] != $_SESSION['membername']) { $name[$n] = $fetchArray[0]; $n++; } $fetchArray = mysqli_fetch_row($querySelectResult); } sort($name); echo "<table width='20%' border='1'>"; echo "<tr><th>Member Name</th>"; echo "<th>Status</th></tr>"; for($n = 0; $n<sizeof($name); $n++) { $memberHid1 = $name[$n]; $memberHid = $_SESSION['membername']; echo "<tr><td>{$memberHid1}</td>"; echo "<td>"?> <form action ="memberaddprocess.php" method = "post" > <?php echo'<input type="hidden" name="memberHid1" value="'.htmlspecialchars($memberHid1).'" />';?> <?php echo'<input type="hidden" name="memberHid" value="'.htmlspecialchars($memberHid).'" />';?> <p><input type="submit" name="Addmember"value="AddMember" /></p> </form> <?php "</td></tr>"; } echo "</table>"; } echo"<p><a href='memberlist.php'>List members</a></p>"; echo"<p><a href='logout.php'>Log out</a></p>"; } else { echo "<p> Unauthorized access.Pls login</p>"; echo"<p><a href='login.php'>Log in</a></p></div>"; } ?> This is my memberaddprocess.php code <?php ////////////////////////////////////// session_start(); require_once('sqlconnect.inc.php'); ///////////////////////////////////// $memberHid1 = $_POST['memberHid1']; $new_session = $_POST['memberHid']; $conn = @mysqli_connect($host, $user, $pswd, $dbnm); if (!$conn) { echo "<p>Database connection failure</p>"; } else { @mysqli_select_db($conn, $dbnm) or die ("Database not available"); } $query = "SELECT member_id FROM team WHERE member_name = '$memberHid1'"; $queryResult = @mysqli_query($conn, $query) or die ("<p>Unable to execute query.</p>". "<p>Error code:" . mysqli_errno($conn) .":" . mysqli_error($conn)); $fetchArr = mysqli_fetch_row($queryResult); $memberHid3 = $fetchArr[0]; $memberHid = $_SESSION['membername'] = $new_session; $query2 = "SELECT member_id FROM member WHERE member_name = '$memberHid'"; $queryResult2 = @mysqli_query($conn,$query2) or die ("<p>Unable to execute query.</p>". "<p>Error code" . mysqli_errno($conn) .":" . mysqli_error($conn)); $fetchArr2 = mysqli_fetch_row($queryResult2); $memberHid4 = $fetchArr2[0]; $query3 = "INSERT INTO myteam VALUES($memberHid4, $memberHid3)"; $queryResult3 = @mysqli_query($conn,$query3) or die ("<p>Unable to execute query.</p>". "<p>Error code" . mysqli_errno($conn) .":" . mysqli_error($conn))."</p>"; echo "<p>$memberHid1"." "." Successfully added</p>"; $queryCount = "SELECT COUNT(*) FROM team"; $countResult = @mysqli_query($conn,$queryCount); $fetchCountArr = mysqli_fetch_row($countResult); for($n=0;$n<$fetchCountArr[0];$n++) { $pst = $n+1; $query4 = "SELECT member_id2 FROM myteam WHERE friend_id1 = '$pst'"; $countResult2 = @mysqli_query($conn,$query4); $countArr = mysqli_fetch_row($countResult2); $a=0; while($countArr) { $a++; $countArr = mysqli_fetch_row($countResult2); //echo "<p>$a</p>"; } $query4 = "UPDATE team SET num_of_members= '$a' WHERE member_id = '$pst' "; $countResult2 = @mysqli_query($conn,$query4); } $querySelect = "SELECT member_id2 FROM myteam WHERE member_id1 = '$memberHid4'"; $querySelectResult = @mysqli_query($conn, $querySelect); $fetchArr = mysqli_fetch_row($querySelectResult); while($fetchArr) { foreach($fetchArr as $value) { //echo $value; $querySelect2 = "SELECT member_name FROM friends where friend_id='$value'"; $querySelectResult2 = @mysqli_query($conn, $querySelectResult2); $fetchArr2 = mysqli_fetch_row($querySelectResult2); foreach($fetchArr2 as $value) { //echo $value; } } $fetchArr = mysqli_fetch_row($querySelectResult); } header("Location:memberadd.php"); echo('<a href="memberlist.php">Updated memberlist</a></p></div>'); //header('Location: friendadd.php'); ?> A: It's no easy to determine the problem, but i found a topic on mysql forum (MySQL says a table doesn't exist, when it does) that could be related with your problem. It's important to make sure that there is no other mysql instance on the computer. This could result in your problem too.
{ "pile_set_name": "StackExchange" }
Q: Player object glitching around when there is a low framerate Unity C# I just started to make this game, it runs fine on my computer. 60fps, but when I tested it on another computer, with lower fps, the player just started to jitter and glitch around a lot. The game is basically unplayable like that, and I want to make sure that everyone who plays my game will be able to enjoy the full experience. I have pasted the specific part of the code for the movement below. void Update () { rb.AddForce (Vector3.forward * ForwardSpeed); if (Input.GetKeyDown (KeyCode.A) && side > maxSideLeft) { rb.AddForce (-Vector3.right * Speed); side -= 1; } else if (Input.GetKeyDown (KeyCode.D) && side < maxSideRight) { rb.AddForce (Vector3.right * Speed); side += 1; } if (Input.GetKeyDown (KeyCode.W) && level < maxLevelHeight) { rb.AddForce (Vector3.up * Speed); level += 1; } else if (Input.GetKeyDown (KeyCode.S) && level > minLevelHeight) { rb.AddForce (-Vector3.up * Speed); level -= 1; } if (Input.GetKeyDown (KeyCode.R) || Input.GetKeyDown(KeyCode.Space)) { SceneManager.LoadScene ("Scene1"); Time.timeScale = 1; } } A: You appear to be moving the player in the Update() method, applying direction and speed. For smooth movement, you also need to accommodate for the time in between updates. Consider this: your telling your player to move by a set distance every time you perform an Update(). We will say your hardware is fast enough to perform Update() 60 times per second. If you play your game using hardware that is only fast enough to perform Update() 30 times per second, you will only get to tell the player to move half as many times as before. Using only speed, your player would only be able to move half the distance in the same amount of time. The solution is quite simple. You use the time since the last Update() as a multiplier, to ensure smooth movement, regardless of hardware. Unity provides this value as Time.deltaTime. Simply replacing Speed with Speed * Time.deltaTime should ensure smooth movement.
{ "pile_set_name": "StackExchange" }
Q: How can I "kill" a computer network services on my lan? I'm in a strange situation... A customer has a huge network based on static IPs. All machine names are not useful to identify a computer location and network switches are not managed. One of the computers on the network started broadcasting like crazy hogging their astaro security gateway CPU (probably virus). I've been able to cut the problem down setting a rule on the astaro to drop all the request from the problematic IP. Now I need to find out where that PC is. I thought that if I'm able to shut down its network services the user will call me for assistance and then I'll be able to find the PC and discover what happened. How can I obtain that? Sounds like a DDoS attack in "my" network, right? I have no access to that PC because everyone's admin of his own PC with his own password so no Dameware working, no remote desktop, no mmc snap in, no regedit. A: You've got the MAC address so assuming these are brand name machines rather than generics you should be able to track down the manufacturer ( http://www.coffer.com/mac_find/ ), that may narrow you search slightly (assuming you don't have all Dell or similar). You can use the IP address and a port scanner like nmap to finger print the host and find the likely OS it's running, perhaps narrowing it down further. If the host is running Windows it will display an error if it detects an IP conflict on the network - I'd suggest intentionally causing an IP conflict and using that method to flag up an alert on the screen of likely candidates.
{ "pile_set_name": "StackExchange" }
Q: Subfields of the splitting field of $x^4 - 2$ over $\mathbf Q$ I understand why the Galois group is isomorphic to $D_8$ let's say with \begin{align*} r: 2^{\frac{1}{4}} &\mapsto 2^{\frac{1}{4}}i &&& s: 2^{\frac{1}{4}} &\mapsto 2^{\frac{1}{4}} \\ i &\mapsto i &&& i &\mapsto -i\\ \end{align*} as generators. I don't understand how to find the fixed fields given a subgroup of the the Galois group. For example, I believe the fixed field of $\langle r^3s\rangle$ is $\mathbf Q((1 + i)2^{\frac{1}{4}}$) and the fixed field of $\langle rs \rangle$ is $\mathbf Q((1 - i)2^{\frac{1}{4}}$). However, is there an easy way I could see this without just plugging in many random elements to see if they are fixed? A: let be $x\in K; K=\mathbb Q(\alpha,i); \alpha^4=2, i^2=-1$ $K$ splitting and separable field then $|Gal(K,\mathbb Q)|=[K,\mathbb Q]$ Galois group is $\{ id,\sigma,\sigma^2,\sigma^3,\tau, \sigma\tau,\sigma^2\tau,\sigma^3\tau\} ; \sigma: \sqrt[4] {2}\to i \sqrt[4]{2}; \tau: i\to -i $ let be $H=\{id,\sigma\tau \}$ $id(x)=a_1+a_2\alpha+a_3\alpha^2+a_4\alpha^3+a_5i+a_6i\alpha+a_7i\alpha^2+a_8i\alpha^3$ $\sigma \tau(x)=a_1+a_6\alpha-a_3\alpha^2-a_8\alpha^3-a_5i+a_2i\alpha+a_7i\alpha^2-a_4i\alpha^3$ then $id(x)=\sigma\tau(x) \Leftrightarrow a_2=a_6, a_3=-a_3, a_4=-a_8, a_5=-a_5$ then $x\in K_H \Leftrightarrow x=a_1+a_2(1+i)+a_4(1-i)\alpha^3+a_7i\alpha^2$ then $K_H=\mathbb Q((1+i)\alpha)$
{ "pile_set_name": "StackExchange" }
Q: How can i set a timeout for my text to appear after 3 seconds? I am currently trying to get my text to appear on the video after 3 seconds but unfortunately, I'm not able to do it and i am not sure where I am going wrong. Im trying to get the text on the video to appear after 3 seconds so e.g. have a delay of text but i did read about it and it is to do with the set timeout which i tried but it does not seem to work. <html> <head> <link rel="stylesheet" type="text/css" href="style.css" title="Default Styles"/> <script> var r_text = new Array(); r_text[0] = "How can we become more self-organised in the next sprint?"; r_text[1] = "How can we improve our productivity, increase our velocity?"; r_text[2] = "How can we get better in Transparency and Visibility of issues and challenges?"; r_text[3] = "How can our PO help us, to focus more on the sprint goal?"; r_text[4] = "How can our SM help us improve our delivery?"; r_text[5] = "How can we be more T-shaped in the next sprint?"; r_text[6] = "How should we celebrate our successes more?"; r_text[7] = "How can we reduce our cycle times?"; r_text[8] = "How can we make our daily scrum more effective?"; r_text[9] = "How can we improve our delivery flow by applying WIP Limit?"; r_text[10] = "How can we improve our collaboration?"; r_text[11] = "How can I help someone else in the next sprint?"; r_text[12] = "How can we improve our Sprint planning event?"; r_text[13] = "How can we demonstrate Scrum Value Courage more?"; r_text[14] = "How can we demonstrate Scrum Value Respect more?"; r_text[15] = "How can we demonstrate Scrum Value Focus more?"; r_text[16] = "How can we demonstrate Scrum Value Commitment more?"; r_text[17] = "How can we demonstrate Scrum Value Openness more?"; r_text[18] = "How can we make Sprint Review more effective?"; r_text[19] = "How can I help PO breakdown user stories better?"; r_text[20] = "How can we improve user story refinement?"; r_text[21] = "How did you overcome a dfficult situation/chalenge?"; r_text[22] = "How can we be more confident about our delivery?"; r_text[23] = "How well do you communicate with others?"; r_text[24] = "How well the team communicates with each other?"; var talk = new Array(); talk[0] = "Talk about issues in our Processes"; talk[1] = "Talk about issues in the Team behaviour"; talk[2] = "Talk about what you want your team to do more"; talk[3] = "Talk about what you want the team to stop doing"; talk[4] = "Talk about what you want the team to start doing"; talk[5] = "Tell us about something that helped you during the sprint to achieve work"; talk[6] = "Talk about something you learnt during the previous sprint"; talk[7] = "Talk about your sprint experience through a sport's game?"; talk[8] = "Talk about your worst time during the sprint?"; talk[9] = "Talk about the biggest success during the sprint?"; talk[10] = "Talk about he major issue you faced during the sprint?"; talk[11] = "Talk about a most recent problem and how did you overcome it?"; talk[12] = "Talk about something that you feared during sprint planning however it was not mentioned at that time?"; talk[13] = "Talk about someone in the team you inspire from and why? Don’t mention the name"; var what = new Array(); what[0] = "What can Scrum Master to improve our Scrum Events?"; what[1] = "What made you feel happy?"; what[2] = "What made you feel unhappy?"; what[3] = "What was your key observations?"; what[4] = "What minor issues that slowed you down"; what[5] = "What can we change to make the biggest leap ahead?"; what[6] = "What did you see happening by someone you think everyone should try?"; what[7] = "What advise would you give to your team members? And why?"; what[8] = "What has been the biggest challenge so far?"; what[9] = "Which problems came up most frequently?"; what[10] = "What has been the most difficult situation in the sprint?"; what[11] = "What obstacles do you anticipate and how you think that can be addressed?"; what[12] = "What can we do to improve our Sprint planning event?"; what[13] = "What would you do differently in the next Sprint?"; what[14] = "What would you like to avoid in the next Sprint?"; what[15] = "What can we do to make our Scrum events more fun?"; what[16] = "What can we do to get full trust of our key stakeholders?"; what[17] = "What support do we need from our PO?"; what[18] = "What support do we need from our SM?"; what[19] = "What support do we need from our Stakeholders? Sponsrs/External…"; what[20] = "Describe the most difficult challenge team faced? What could have been done to avoid/fix it?"; what[21] = "What do you wish you could change in the way of working?"; what[22] = "What support do you need to achieve your sprint goal?"; what[23] = "What areas of your team WOW would you like to improve/change?"; what[24] = "What routinely gets in your way?"; what[25] = "What would you like your PO to do more and why?"; what[26] = "What would you like your SM to do less and why?"; var morefun = new Array(); morefun[0] = "Describe your feeling by naming a Movie. Explain"; morefun[1] = "Describe your feeling by singing a Song. Explain"; morefun[2] = "Describe your feeling by hands/body gestures."; morefun[3] = "Describe your sprint experience by telling a story?"; morefun[4] = "Who's someone you admire in the team?"; morefun[5] = "What is your favorite quotes?"; morefun[6] = "Who had the most influence on you growing up?"; morefun[7] = "What advise can you give us?"; morefun[8] = "If you could go back in time, what would you like to change? Work or Life"; morefun[9] = "Show your best dance moves?"; morefun[10] = "Draw an emoji to show how you feel about the sprint"; morefun[11] = "How would you have handled Brexit?"; morefun[12] = "If you would become the Prime Minister what would be your top agenda items?"; morefun[13] = "Do an animal impression (please don’t tell)"; morefun[14] = "Do an impression of a Cartoon character (please don’t tell)"; morefun[15] = "If you had a 30 hours a day, how would you use the extra time?"; morefun[16] = "If you could swap your role with another team member, who would it be?"; morefun[17] = "Do a Bhangra dance?"; morefun[18] = "Ask anyone in the team to perform an act? Movie character, cartoon character etc…"; morefun[19] = "Stand on one leg and jump 5 times, or ask your PO to do this act?"; morefun[20] = "Ask your SM or PO to perform a celebration move, or could decide to do it yourself."; var showshare = new Array(); showshare[0] = "Share your most recent learning experience?"; showshare[1] = "Share any productivity improvement tip with the team?"; showshare[2] = "Share your best moment during the Sprint and why?"; showshare[3] = "if you could change one thing about yourself what would you choose?"; showshare[4] = "If you could eliminate one thing from your daily routine what whould it be?"; showshare[5] = "If you could become an expert in any area instantly, what would it be?"; showshare[6] = "Share a tip to help others improve their ways of working?"; var goingtodo = new Array(); goingtodo[0] = "Do I/we understand the Product Vision? Team and I"; goingtodo[1] = "Do I/we understand the Sprint Goal? Why, Value, Benefits. Team and I"; goingtodo[2] = "Do I/we communicate well within the team? Team and I"; goingtodo[3] = "Do I/we communicate well outside the team? Team and I"; goingtodo[4] = "Do I/we collaborate with team and outside team? Team and I"; goingtodo[5] = "Do I/we openly raise issues and challenges? Team and I"; goingtodo[6] = "Do I/we openly talk about impediments?"; goingtodo[7] = "Do we ask each other for help and support?"; var videos = [{ id: 1, url: "http://ebeessolutions.com/wp-content/uploads/2019/10/Dice-3d-1.mp4?autoplay=1", text: function(){ return r_text[Math.floor(r_text.length*Math.random())]; } }, { id: 2, url: "http://ebeessolutions.com/wp-content/uploads/2019/10/Dice-3d-2.mp4?autoplay=1", text: function(){ return what[Math.floor(what.length*Math.random())]; } }, { id: 3, url: "http://ebeessolutions.com/wp-content/uploads/2019/10/Dice-3d-3.mp4?autoplay=1", text: function(){ return talk[Math.floor(talk.length*Math.random())]; } }, { id: 4, url: "http://ebeessolutions.com/wp-content/uploads/2019/10/Dice-3d-4.mp4?autoplay=1", text: function(){ return morefun[Math.floor(morefun.length*Math.random())]; } }, { id: 5, url: "http://ebeessolutions.com/wp-content/uploads/2019/10/Dice-3d-5.mp4?autoplay=1", text: function(){ return showshare[Math.floor(showshare.length*Math.random())]; } }, { id: 6, url: "http://ebeessolutions.com/wp-content/uploads/2019/10/Red-dice.mp4?autoplay=1", text: function(){ return goingtodo[Math.floor(goingtodo.length*Math.random())]; } } ]; window.onload = function() { function rollVideo(numberRand) { let playerDiv = document.getElementById("random_player"); if (document.querySelector("iframe") !== null) { document.querySelector("iframe").remove(); } let player = document.createElement("IFRAME"); let randomVideoUrl = videos[numberRand].url; player.setAttribute("width", "640"); player.setAttribute("height", "390"); player.setAttribute("src", randomVideoUrl); playerDiv.appendChild(player); document.getElementById("text").innerHTML = ""; document.getElementById("text").innerHTML = videos[numberRand].text(); setTimeout(() => { text.innerHTML = videos[current].text; }, 3000) } document.getElementById("btn-roll").addEventListener("click", startRoll); function startRoll() { let currentNumber = Math.floor(Math.random() * videos.length); rollVideo(currentNumber); } }; </script> </head> <div id="random_player"> <div id="text"></div> </div> <button id="btn-roll">Roll</button> </html> A: The code you added is wrong, current is not set and text() is a function call. Better: document.getElementById("text").innerHTML = videos[numberRand].text(); setTimeout(() => { document.getElementById("text").innerHTML = videos[numberRand].text(); }, 3000); You should also store the timeout so you can stop it: //outside on top level var currentTimeout = null; ... //inside rollVideo clearTimeout(currentTimeout); ... document.getElementById("text").innerHTML = videos[numberRand].text(); currentTimeout = setTimeout(() => { document.getElementById("text").innerHTML = videos[numberRand].text(); }, 3000);
{ "pile_set_name": "StackExchange" }
Q: Program not working? The question is to find the number of days between two dates.example-input-26/3/2000 and 12/8/2014.the output will be the no of days in between these two dates. There is an error saying "identifier expected" and i=1 is highlighted.Also I am not sure whether the program is completely correct. import java.util.*; class yearst { int a[]={0,31,28,31,30,31,30,31,30,31,30,31,30}; int i,s,s1,s2,s3,k,diy,m,m1,m2,d1,d2,y1,y2,y; i=1;s1=0;s2=0;s3=0;diy=365; void leap(int y) { if(y%4==0 && y%100!=0 || y%400==0) //for leap year { a[2]=29; diy=366; } else { a[2]=28; diy=365; } } public static void main(String args[]) { Scanner ob=new Scanner(System.in); System.out.println("Enter the months,dates and years"); m1=ob.nextInt(); m2=ob.nextInt(); d1=ob.nextInt(); d2=ob.nextInt(); y1=ob.nextInt(); y2=ob.nextInt(); for(i=y1;i<y2;i++) { ob.leap(i+1) m=1*diy; s1=s1+m; } for(i=1;i<m1;i++)//no of days left in y1 { ob.leap(y1); s2+=a[i]; } s2+=d1; k=diy-s2; for(i=1;i<m2;i++)//no of days passed { ob.leap(y2); s3+=a[i]; } s3+=d2; s=s1+s2+s3; System.out.println("No of days in between"+s) } } Please help. A: Your program is a bunch of errors. First, you are calling class variables in main method without declaring them static or initializing them in constructor. Second, you are calling leap() which is method of a class from object of Scanner. It is not possible. The program will never compile nor run this way. I have modified your code to make it compilable and runnable. But one thing is for sure. Its logic is incorrect. It is giving wrong output as you want to calculate number of days between two dates. That is your job. I removed its errors. Now it is running. Here you are :- import java.util.*; class yearst { static int a[]={0,31,28,31,30,31,30,31,30,31,30,31,30}; static int i=1,s,s1=0,s2=0,s3=0,k,diy=365,m,m1,m2,d1,d2,y1,y2,y; static void leap(int y) { if(y%4==0 && y%100!=0 || y%400==0) //for leap year { a[2]=29; diy=366; } else { a[2]=28; diy=365; } } public static void main(String args[]) { //i=1;s1=0;s2=0;s3=0;diy=365; Scanner ob=new Scanner(System.in); System.out.println("Enter the months,dates and years"); m1=ob.nextInt(); m2=ob.nextInt(); d1=ob.nextInt(); d2=ob.nextInt(); y1=ob.nextInt(); y2=ob.nextInt(); for(i=y1;i<y2;i++) { leap(i+1); m=1*diy; s1=s1+m; } for(i=1;i<m1;i++)//no of days left in y1 { leap(y1); s2+=a[i]; } s2+=d1; k=diy-s2; for(i=1;i<m2;i++)//no of days passed { leap(y2); s3+=a[i]; } s3+=d2; s=s1+s2+s3; System.out.println("No of days in between"+s); } } All the Best :)
{ "pile_set_name": "StackExchange" }
Q: Android Service is Called before Activity I am making a service periodically sending location to the server. But when my application started service started while I am not calling service in my Main Activity. The service is automatically called. Thanks in advance... my java code setContentView(R.layout.sliding); startService(new Intent(getBaseContext(), response.class)); Calendar cal = Calendar.getInstance(); cal.add(Calendar.SECOND, 40); Intent intent = new Intent(this, response.class); // Add extras to the bundle intent.putExtra("foo", "bar"); // Start the service // startService(intent); PendingIntent pintent = PendingIntent.getService(this, 0, intent, 0); AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE); int i; i=15; alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), i* 1000, pintent); startService(intent); My Manifest File ` <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name="com.siliconicpro.sayminicab.Register" android:windowSoftInputMode="adjustPan" android:configChanges="keyboardHidden|orientation|screenSize"/> <activity android:name="com.siliconicpro.sayminicab.Login" android:windowSoftInputMode="adjustPan" android:configChanges="keyboardHidden|orientation|screenSize"/> <activity android:name="com.siliconicpro.sayminicab.sliding" android:hardwareAccelerated="true" android:windowSoftInputMode="adjustPan" android:configChanges="keyboardHidden|orientation|screenSize" /> <service android:name="services.response" ></service> <service android:name="services.CallService" ></service> and my service code is following public class response extends Service { private static String KEY_SUCCESS = "success"; private static String KEY_ERROR = "error"; private String email1; @Override public IBinder onBind(Intent intent) { // TODO: Return the communication channel to the service. throw new UnsupportedOperationException("Not yet implemented"); } @Override public void onCreate() { // TODO Auto-generated method stub Toast.makeText(getApplicationContext(), "Service Created", 1).show(); super.onCreate(); } @Override public void onDestroy() { // TODO Auto-generated method stub Toast.makeText(getApplicationContext(), "Service Destroy", 1).show(); super.onDestroy(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { // TODO Auto-generated method stub // Toast.makeText(getApplicationContext(), "service running", 1).show(); } return super.onStartCommand(intent, flags, startId); } A: startService(new Intent(getBaseContext(), response.class)); this is the culprit, remove it and then try.
{ "pile_set_name": "StackExchange" }
Q: Consulta retornando erro em consulta entre período de datas Consulta: SELECT ROW_NUMBER() OVER(ORDER BY V.DATA ASC) AS ID, V.CHAPA AS CHAPA, F.NOME AS NOME, V.DATA AS DATA, CASE WHEN V.BATIDA IS NULL THEN 0 ELSE V.BATIDA END AS FOLGA FROM ARELBATIDATRANSITOVIEW AS V LEFT JOIN V_DADOSFUNC AS F ON V.CHAPA = F.CHAPA WHERE V.CHAPA = 123 AND V.DATA BETWEEN '2016-04-01 00:00:00.000' AND '2016-09-30 00:00:00.000' GROUP BY V.CHAPA,V.DATA,F.NOME,V.BATIDA ORDER BY DATA ASC Esta me retornando a seguinte mensagem: Mensagem 242, Nível 16, Estado 3, Linha 27 The conversion of a varchar data type to a datetime data type resulted in an out-of-range value. SQL SERVER 2008 A: Se o campo V.DATA for do tipo DATETIME você pode utilizar o CONVERT e especificar o tipo de modelo que sua string estará. Ficaria mais ou menos desse jeito. SELECT * FROM #TMP_B WHERE DATA BETWEEN CONVERT(DATETIME,'2016-10-19',120) AND CONVERT(DATETIME,'2016-10-21',120) Se quiser ver os modelos de conversão, você pode olhar aqui: http://www.w3schools.com/sql/func_convert.asp ou aqui: https://msdn.microsoft.com/pt-br/library/ms187928.aspx
{ "pile_set_name": "StackExchange" }
Q: Collation for Pivot UnPivot Sql queries I have a huge problem on my application my sql settings is 'Latin1_General_100_CI_AS' but our customer collation is 'Georgian_Modern_Sort_CI_AS' so when we executing some queries it returns to much problem but we sole that problem with when we use in queries for nvarchar values 'collate Latin1_General_100_CI_AS' keyword so problem solved BUT We have some Pivot & UNPIVOT queries and that queries still return problem. Do you know any solutions for it? Example ALTER Procedure [dbo].[Mg_Web_PurchasePerMonths] ( @Gsm nvarchar(15), @Year int ) AS BEGIN declare @tbPivot4 table(MshStok varchar(22), [Jan] money, [Feb] money, [Mar] money, [Apr] money, [May] money, [Jun] money, [Jul] money, [Aug] money, [Sep] money,[Oct] money, [Nov] money, [Dec] money ) insert into @tbPivot4 Select MshStok collate Latin1_General_100_CI_AS,isnull([Jan],0) as [Jan],isnull([Feb],0) as [Feb],isnull([Mar],0) as [Mar],isnull([Apr],0) as [Apr],isnull([May],0) as [May], isnull([Jun],0) as [Jun],isnull([Jul],0) as [Jul],isnull([Aug],0) as [Aug],isnull([Sep],0) as [Sep],isnull([Oct],0) as [Oct],isnull([Nov],0) as [Nov],isnull([Dec],0) as [Dec] From ( select (select substring(StokNam,0,21) collate Latin1_General_100_CI_AS from Stoklar where StokKod = MshStok) collate Latin1_General_100_CI_AS as MshStok,(SELECT CONVERT(CHAR(3), DATENAME(MONTH, MshTarih))collate Latin1_General_100_CI_AS) as ay,sum(MshTutar) as toplam from Mg_MusHars inner join Mg_MusCards on MshLoylId = McrIdent where (McrGsm = @Gsm or @Gsm is null) AND (YEAR(MshTarih) = @Year or @Year is null) group by MshStok,MshTarih ) as gTablo PIVOT ( Sum(toplam) For ay IN ([Jan],[Feb],[Mar],[Apr],[May],[Jun],[Jul],[Aug],[Sep],[Oct], [Nov],[Dec]) ) as p SELECT * FROM @tbPivot4 UNPIVOT ( TotalPurchase FOR Months IN ([Jan],[Feb],[Mar],[Apr],[May],[Jun],[Jul], [Aug],[Sep],[Oct],[Nov],[Dec]) ) AS UNPVTTable END A: When I declare table i forgot to put collation there when i put my problem solved. declare @tbPivot4 table(MshStok collate Latin1_General_100_CI_AS varchar(22), [Jan] money, [Feb] money, [Mar] money, [Apr] money, [May] money, [Jun] money, [Jul] money, [Aug] money, [Sep] money,[Oct] money, [Nov] money, [Dec] money ) Thanks for help!
{ "pile_set_name": "StackExchange" }
Q: git - Is it safe to delete a branch which has a tag based on a merge commit? Let's say that I peform a non-fast-forward merge from branch a to branch b. This means that b is now 1 commit ahead of a i.e. the merge commit. I then tag this merge commit. Then I delete branch b. Why is it that my tag is still available? Will it disappear at some point in the future via garbage collection? A: "Why is it that my tag is still available?" Tags don't need to be referenced by a branch to be kept around. "Will it disappear at some point in the future via garbage collection?" No, the tag is a permanent reference and any commit reachable through the tag will also be kept from garbage collection. This is one of the main features of a tag.
{ "pile_set_name": "StackExchange" }
Q: VS error when creating new WebAPI project When I create a new WebAPI project (MVC4) I get the following error. EntityFramework.5.0.0: Failed to initialize the Powershell host. If your powershell execution policy setting is set to AllSigned, open the package manager console to initialize the host first. jQuery.1.7.1.1: Failed to initialize the Powershell host. If your powershell execution policy setting is set to AllSigned, open the package manager console to initialize the host first. After Googling I have found a few answers but nothing that works yet. Error creating new MVC project - EF and JQuery This answer seems like it should work for me as my last project was a 7z Command Line app and I might have done something daft with 7zip. But I copy pasted the 7-Zip directory from Program Files to Program Files (86) with no luck. http://social.msdn.microsoft.com/Forums/en-US/vssetup/thread/c934fed4-e44e-4a06-9e3b-eccb9c8aa8d6 There is an answer here that might work (I haven't tried it) but even if it does work I wouldnt want to do this every time I create a new project. Is anyone able to help me with this one? A: I got around a similar error by running PowerShell as administrator with the command Set-ExecutionPolicy Unrestricted, restarting Visual Studio, and opening the Package Manager Console before what I wanted to do. Make sure you understand the security implications of doing this first. http://technet.microsoft.com/en-us/library/ee176961.aspx Restricted - No scripts can be run. Windows PowerShell can be used only in interactive mode. AllSigned - Only scripts signed by a trusted publisher can be run. RemoteSigned - Downloaded scripts must be signed by a trusted publisher before they can be run. Unrestricted - No restrictions; all Windows PowerShell scripts can be run.
{ "pile_set_name": "StackExchange" }
Q: Notepad++ Search and Replace: delete 3 to 4 numbers after N in each row I have a text file where almost all the lines start with the letter N followed by 3 or 4 numbers as below N970 G2 X-1.0591 Y-1.7454 I0. J-.04 N980 G1 Y-1.7554 N990 X-1.0594 Y-1.7666 N1000 Z-.2187 N1010 Y-1.7566 How can I remove the N followed by the 3 or 4 numbers in Notepad++ to look like this? if i need to search twice (once for N### and then again for N####) that is fine also. G2 X-1.0591 Y-1.7454 I0. J-.04 G1 Y-1.7554 X-1.0594 Y-1.7666 Z-.2187 Y-1.7566 the numbers go from 100-9990 in increments of 10 if that helps A: You can use the following regex that should work for your case: ^N[0-9]+\s*(.*) It will match every line that starts with a capital letter N immediately followed by one or more digits. Matched results will include a single group which will contain the text you are looking for. Note that whitespaces between the N tags and the actual text will not be matched. Try it out in this DEMO Breakdown ^ # Assert position at the start of the line N # Matches capital letter 'N' literally [0-9]+ # Matches any digit between 1 and unlimited times \s* # Matches whitespace between 0 and unlimited times (.*) # The rest of the text you are looking for Find/Replace The regex will match each individual line so you can either select Find Next and then Replace and process your file one line at a time or you can choose Replace All to process the whole file at once. Substitution line (Replace with:) line should just include the first group ($1) which represents the rest of your text with N-prefix tags trimmed. Make sure that the Search Mode is set to Regular expression.
{ "pile_set_name": "StackExchange" }
Q: Getting next ID as PK for table insert I'm working on some old java code, and as part of an insert, the code makes a db call to get the last ID used in a table, then increments the ID, and uses the incremented ID as the next ID to use for the insert, as the PK. It's a web application, and it seems to me that the same ID could be retrieved on a subsequent get ID call before the first/prior insert is done. How would I prevent this, to ensure that the same ID is not reused? A: Use a transaction in your sql code.
{ "pile_set_name": "StackExchange" }