text
stringlengths
64
89.7k
meta
dict
Q: AngularJS kendo treeview selected child node programmatically Based on the following code I am able to select nodes in the tree view if the id I provide belongs to a parent node, example: 1. But when I provide the id of a child node, example: 2.1, it is not able to select the node from code level. The following is the code I am currently using: <div id="example" ng-app="KendoDemos"> <div class="demo-section k-content" ng-controller="MyCtrl"> <div class="box-col"> <h4>TreeView</h4> <div kendo-tree-view="tree" k-data-source="treeData" k-on-change="selectedItem = dataItem"> <span k-template> {{dataItem.text}} </span> </div> </div> </div> </div> angular.module("KendoDemos", [ "kendo.directives" ]) .controller("MyCtrl", ["$scope", "$timeout", function($scope, $timeout) { $scope.treeData = new kendo.data.HierarchicalDataSource({ data: [ { text: "Item 1", id: 1 }, { text: "Item 2", id: 2, items: [ { text: "SubItem 2.1", id: 2.1 }, { text: "SubItem 2.2", id: 2.2 } ] }, { text: "Item 3", id: 3 } ]}); $scope.click = function(dataItem) { alert(dataItem.text); }; $scope.selectNode = function(id) { $scope.branchId = id; var item = $scope.treeData._data.find(findKendoBranchById); var node = $scope.tree.findByUid(item.uid); $scope.tree.select(node); } function findKendoBranchById(item, index, kendo) { var isThisBranch = false; if (item.id == null) { isThisBranch = item.text == $scope.branchId; } else { isThisBranch = item.id == $scope.branchId; } return isThisBranch; } $timeout(function() { $scope.selectNode(2); //when this runs, will show the error below $scope.selectNode(2.1); }, 2000); }]); VM1703 angular.min.js:107 TypeError: Cannot read property 'uid' of undefined at n.$scope.selectNode (<anonymous>:20:50) at <anonymous>:38:18 at VM1703 angular.min.js:146 at e (VM1703 angular.min.js:43) at VM1703 angular.min.js:45 A: In the end i chose to re-init the treeview when the selected node is changed. $scope.rawData = [ { text: "Item 1", id: 1 }, { text: "Item 2", id: 2, items: [ { text: "SubItem 2.1", id: 2.1 }, { text: "SubItem 2.2", id: 2.2 } ] }]; $scope.selectNode = function(id){ $scope.treeData = new kendo.data.ObservableArray(processSelectedNode($scope.rawData, id)); }; function processSelectedNode(array, id){ var navigationData = []; for (var i = 0; i < array.length; i++) { var obj = array[i]; obj.expanded = true; obj.selected = obj.id == id; if (array[i].items) { obj.items = prepareNavigationTreeDataSource(array[i].items, id); } navigationData.push(obj); } } This works for me as the Kendo Treeview will select the node with selected = true
{ "pile_set_name": "StackExchange" }
Q: Using natural keys as part of equals and hashCode I know that this topic has been discussed umpteen number of times, but still need some clarifications on the issue we are facing. Hibernate best practices talk about using natural keys for the equals / hashCode methods. We do have a composite key which consists of 2 parameters (say String name, Organization org) to which a particular object belongs. Unfortunately I can't use org since it is lazily loaded and leads to other issues and I don't want to create a surrogate key either (maybe auto generated from the database or a UUID created via an API call prior to object creation). What kind of options do I really have since in the above Object (name, org) fields are unique and I can't just write my logic just based on the name field itself. Is surrogate key the only option, does this mean I have to store this value as part of each row in the table? A: If you desire something like public class MyEntity { private String name; private Organization organization; // getter's and setter's public boolean equals(Object o) { if(!(o instanceof MyEntity)) return false; MyEntity other = (MyEntity) o; return new EqualsBuilder().append(getName(), other.getName()) .append(getOrganization(), other.getOrganization()) .isEquals(); } } But if you want to avoid it because you do now want to load a lazy loaded entity, you can rely on Hibernate.isInitialized method and supply your custom routine public boolean equals(Object o) { if(!(o instanceof MyEntity)) return false; MyEntity other = (MyEntity) o; boolean equals = new EqualsBuilder().append(getName(), other.getName()) .isEquals(); if(Hibernate.isInitialized(getOrganization())) { // loaded Organization } else { // supply custom routine } return equals; } I have a not-updated web page where Hibernate supply the following matrix no eq/hC at all eq/hC with the id property eq/hC with buisness key use in a composite-id No Yes Yes multiple new instances in set Yes No Yes equal to same object from other session No Yes Yes collections intact after saving Yes No Yes Where the various problems are as follows: use in a composite-id: To use an object as a composite-id, it has to implement equals/hashCode in some way, == identity will not be enough in this case. multiple new instances in set: Will the following work or not: HashSet someSet = new HashSet(); someSet.add(new PersistentClass()); someSet.add(new PersistentClass()); assert(someSet.size() == 2); equal to same object from another session: Will the following work or not: PersistentClass p1 = sessionOne.load(PersistentClass.class, new Integer(1)); PersistentClass p2 = sessionTwo.load(PersistentClass.class, new Integer(1)); assert(p1.equals(p2)); collections intact after saving: Will the following work or not: HashSet set = new HashSet(); User u = new User(); set.add(u); session.save(u); assert(set.contains(u)); It also highlight this Thread where equals/hashCode implementation is heavily discussed A: Hibernate best practices talk about using natural keys for the equals / hashCode methods. Yes so I won't elaborate on this. We do have a composite key which consists of 2 parameters (say String name, Organization org) to which a particular object belongs. Unfortunately I can't use org since it is lazily loaded and leads to other issues. Could you elaborate a bit and maybe illustrate with some code? I'd like to understand how you got this working exactly and what the problem is. What kind of options do I really have since in the above Object (name, org) fields are unique and I can't just write my logic just based on the name field itself. As I said, providing more details might help. But just in case, note that calling org.getId() on a proxy should not trigger the loading of the entity, as long as you're using property access type, so you should be able to use this in your equals implementation.
{ "pile_set_name": "StackExchange" }
Q: Java Crazyness - Contains fails when equals passes This is the most crazy thing I have seen in java (1.6): Set<ActionPlan> actionPlans = assessment.getActionPlans(); //getActionPlans() returns a java.util.HashSet<ActionPlan> ActionPlan actionPlan = actionPlans.iterator().next(); assertTrue(actionPlan1.equals(actionPlan)); assertEquals(actionPlan1.hashCode(), actionPlan.hashCode()); assertTrue(actionPlans.contains(actionPlan1)); The first two asserts pass but the last one fails. I'm not giving you details on the ActionPlan and Assessment classes because it shouldn't matter. The contains method fails where the equals and hash don't. I'm not saying that java is broken or anything, there is probably something funny going on in my code. Note that I'm an experienced java programmer and I'm aware of the dos and don't for implementing equals and hashCode. So if something is missing in my code it's not something obvious. Has anyone ever seen something that puzzling? EDIT I did some research in my code and I now think the problem is in hibernate. I have logged the hashCode of the ActionPlan object, after creation, and at different parts of the code until the failing assert is getting called. It does not change. Also I have checked the class returned by assessment.getActionPlans() and it is: org.hibernate.collection.internal.PersistentSet I'm tempted to believe that this implementation of Set does not use equals or hashcode properly. Does anyone have insight on that? A: There is possible explainations You have a sorted set which doesn't use equals or hashCode. You have "overriden" equals(MyClass) instead of equals(Object) The fields used by the hashCode are changed. This leave the Set in a state which is not usable. The simplest way to test the last possibility is to try assertTrue(new HashSet(actionPlans).contains(actionPlan1)); I suspect this will pass in your case. ;) Date has a flaw that it is mutable and hashCode uses that mutable fields so you can corrupt any hash collection it is in by mutating it. A similar problem occurs when you alter a field which is used in compareTo. Set<Date> dates = new HashSet<Date>(); SortedSet<Date> dates2 = new TreeSet<Date>(); Date d1 = new Date(1), d2 = new Date(2), d3 = new Date(3); dates.add(d1); dates.add(d2); dates.add(d3); dates2.add(d1); dates2.add(d2); dates2.add(d3); d1.setTime(6); d2.setTime(5); d3.setTime(4); System.out.print("The dates contains ["); for (Date date : dates) { System.out.print("date " + date.getTime() + " "); } System.out.println("]"); System.out.print("The sorted dates2 contains ["); for (Date date : dates2) { System.out.print("date " + date.getTime() + " "); } System.out.println("]"); for (int i = 1; i <= 6; i++) System.out.println("date " + i + " found is " + dates.contains(new Date(i)) + " and " + dates2.contains(new Date(i))); prints The dates contains [date 6 date 5 date 4 ] The sorted dates2 contains [date 6 date 5 date 4 ] date 1 found is false and false date 2 found is false and false date 3 found is false and false date 4 found is false and false date 5 found is false and true date 6 found is false and false Note: the sorted collection is now in the wrong order. A: This will happen if you overload equals but don't override equals(Object). For example, you may have: public boolean equals(ActionPlan plan) { ... } That will be called by: assertTrue(actionPlan1.equals(actionPlan)); ... but will not be called by contains. You need: @Override public boolean equals(Object object) { ... } Of course, it's possible that that's not what's happening. There's no way we can tell for sure without seeing your code. I'm not giving you details on the ActionPlan and Assessment classes because it shouldn't matter. This answer contradicts that assumption... as does Peter's answer, which contains alternative failure modes. This is why giving a short but complete example is always important.
{ "pile_set_name": "StackExchange" }
Q: How can I remove the argslist files from the buffer list? When using the args list, Vim adds those arglist files to the buffer list. Once I'm finished with the argslist, I then have many unwanted argslist files in the bufferlist. They don't have a contiguous number sequence, so I cant just say, :11,24 bd. Is it possible to remove these files from the bufferlist?, possibly using the same pattern I used to create the arglist? e.g. :bd tests/unit/**/*.js A: Use :argdo: :argdo bd :argdo {cmd} will run command, {cmd}, on every item in the argslist. In this case you use :bdelete as the command to unload the buffer and delete it from the buffer list. For more help see: :h :argdo
{ "pile_set_name": "StackExchange" }
Q: How can I check which page has sent the form? I want to be sure that the data I receive came from a specific page (it's for a navigator game). I would prefer a solution using RoR but if we can do it with JS it's ok =) A: In your controller, you have access to the request variable (type of ActionDispatch::Request) which represents the actual request received by your server: def index puts request.inspect # see in your server's console the output # ... end With this variable, you can access to the referer, which returns the path (as String) of the last page seen, or nil if you came from another domain (or blank page). To check which page sent your form, you could use: def my_controller_action if request.referer.present? && request.referer.include?('/string/to/check/') # yay! else # well, the request is not coming from there end end You could also set it as a before_filter in your controller in order to check "quietly" the requests and not in each controller's action.
{ "pile_set_name": "StackExchange" }
Q: Why does running an update query on an embedded HSQLDB consume a lot of memory? I am using HSQLDB 2.4.1 (embedded with cached tables). I have a large database (with ~21 million rows. DB Size is 5GB) I'm trying to run the following query: UPDATE TABLE_NAME SET COLUMN1=0 I tried changing and playing around with theses properties but eventually this update statement is consuming huge amount of ram, as if it is copying the entire database into memory. properties.setProperty("hsqldb.large_data" , "true"); properties.setProperty("hsqldb.log_data" , "false"); properties.setProperty("hsqldb.default_table_type" , "cached"); properties.setProperty("hsqldb.result_max_memory_rows" , "50000"); properties.setProperty("hsqldb.tx" , "mvcc"); properties.setProperty("sql.enforce_tdc_update" , "false"); properties.setProperty("shutdown" , "true"); properties.setProperty("runtime.gc_interval" , "100000"); When I execute this query in DBeaver, I notice that the memory consumption increases significantly and keeps increasing until it reaches the maxmem of 4GB at which point the application crashes with an out of memory error. PS: Running this exact query on an identical embedded Derby database takes around 5 minutes, but eventually returns and memory usage in DBeaver remains constant at around ~400mb. A: All the updated rows are loaded into memory until commit. You can update in chunks based on primary key and a LIMIT clause. For example: UPDATE TABLE_NAME SET COLUMN1= 0 WHERE COLUMN1 != 0 AND (PK_ID > 1000000 AND PK_ID < 2000000) LIMIT 1000000 The above statement shows two different techniques to limit the rows. First, by using an indexed column to limit; Second by using LIMIT to stop updating after a number of rows have been updated. http://hsqldb.org/doc/2.0/guide/dataaccess-chapt.html#dac_update_statement
{ "pile_set_name": "StackExchange" }
Q: Best martial art for someone with bad elbow? I have the onset of rheumatoid arthritis in one of my elbows. My other arm is fine and everything else is fine. What martial arts could I practise without excessive strain on the elbows? EDIT: The specialist has told me to do whatever I want. But if (be it any type of activity) causes me pain of inflammation, stop immediately) The one that interests me most is Ju-Jitsu but I know there are quite a few twists. I was also considering Judo. I wonder what people's thoughts were on these two? My aims, is to build my self confidence mainly and have fun. I don't have ambitions to be a professional or compete in top competitions. The ones I'm ruling out immediately are Karate, kick boxing, because of the velocity of the punch that would be needed and also the training I believe involves a lot of push up s which I can't really do.= without strain. A: Don't choose an art, choose a school. I'm suffering from arthritis in my knees and medial epicondlyitis (a temporary condition in my elbow which gives me some understanding of your plight). I practice Tai chi and Aikido; the style of aikido I practice (Tomiki) borrows heavily from Judo. My sister was an Olympic level Kareteka until she injured her elbow; she switched schools because her senior teacher wouldn't permit her to adapt her training to the injury. Make sure the school respects injuries. My primary school is probably all over 30, and most of us are over 50. Injuries happen, and if we want to keep training with one another we have to learn to respect those injuries. We've dismissed students for failing to respect injuries. Look for a school with older students, and teachers who are used to teaching older students. Many schools will use tape (duct tape or red tape) to indicate an injury; training partners should ask about the tape if the joint is involved in the technique you're practicing. Adapt your training. Because my elbow is munged up, I've been practicing all the techniques on the reverse side - Some of the techniques get more complicated in reverse, but my training partners have been enthusiastic about using the complexity as a way to test our understanding. (all techniques should be practiced on both sides as a normal event, but we happen to be working on a kata which is asymmetrical for reasons that are not really relevant to your question). Tap out. Protect that joint. When the technique puts any pressure on my joint I tap out before there is a problem. At the moment I have a glass elbow. If there is any doubt as to whether the technique is effective, we switch sides and do it on my stronger elbow. My job as Uke is not to test my partner's effectiveness, it is to react correctly, and tapping out fast is reacting correctly. That is a general rule; there are exceptions, but they can be accomodated Don't do the dangerous stuff. There are techniques I can no longer do because the arthritis in my knees make me weaker in certain postures. When we do kneeling work, I either bow out, or do the technique standing up. My temporary injury to my elbow makes push hands dangerous, so I've had to take six weeks off. I still perform and practice Tai Chi, but push hands is the wrong thing for me right now. Might not be a problem for you under the conditions you describe. There are other techniques that I refuse to do because if my knee were to give out, there are situations where it might injure my partner. (my knee folded during shihonage once and nearly separated my partner's shoulder. I do shihonage differently now). Get a second medical opinion. I say this for two reasons: Most of the aikdoka I work with share an orthopod - because he used to be one of us, and he knows exactly what locks are dangerous. Different doctors have different levels of familiarity with martial arts. An adequate answer from a GP is adequate, but a second opinion from a doctor/martial artist might open whole new worlds of possibility Most chronic injuries can be partially compensated through some form of physical therapy. I can compensate for my elbow by strengthening the muscles and relying less on the damaged tendons. I can compensate for the knee by making sure that the muscles are strong enough to bear additional strain. Check with the doctor to see if you can design a program of stretches and exercises that will maximize your participation and minimize the chance that you'll exacerbate an injury. The most important tip I'll give you For Tomiki Aikido, the promotion to second degree black belt involves a set of kneeling techniques. I can't do kneeling techniques, and when I try, the effort is embarassing to all concerned. Sensei allowed me to test standing up. The standing techniques teach an entirely different set of lessons, and if I ever reach a teaching rank, I'm going to have to confront that gap in my trainng. But Sensei was willing to work with me to create a demonstration that allowed me to show my mastery of the portion of the art I can show. If the teacher you're working with won't adapt the technique to your limitations, leave. There is no excuse for that. Working through a chronic injury with the risk of doing further harm to your body is bad art, bad martial, bad personal development, bad budo, bad human relations. Failing to adapt to the student is contemptible. On the flip side, I need to accept that I'll never be the lineage master, and that if/when I teach, I need to address that so that I don't shortchange my students. Some people will challenge me because they believe that the art isn't pure if it is adapted. With all due respect, that's crap. My teacher's teacher believes that, and although he is a brilliant man, on this count he is wrong. The art is going to be different for a 5' 100lb girl than it is for a 6'1 300 pound man. Different for people with long arms than short arms. Shuhari. But that whole rant is the answer to a different question so I'll shut up now. ** Ask** the teacher how the two of you could work together to achieve your goals. You have realistic goals specified in your question, and any decent teacher should be able to accomodate your limitations. tl;dr You should be able to do what you want to do. I do joint locks, I do throws, I do the occasional high flying breakfall (flying breakfalls are actually easier on my knees than low soft breakfalls; but Sensei doesn't like me to do them because he wants me to come back.) Find a school where you can achieve your goals. A: There are a great many martial arts that would be good for someone with rheumatoid arthritis. I would recommend Tai Chi or some other internal martial art like BaGua specifically for rheumatoid arthritis. I am not sure it would make the arthritis any better (it might), but there is very little emphasis on concussive force in the internal arts, at least not of the high impact variety seen in hard striking arts like Karate and TKD. More specifically, strikes are not "thrown" in the internal arts so much as "placed", if that makes sense. A Tai Chi punch will not wrench your elbow like a Karate or Boxing style punch might. I take it that since you mention Judo and Juijitsu, you are interested in grappling and throwing. Tai Chi is mainly a grappling style, even if the way it approaches grappling is more subtle than you may prefer. Now, the question is if you can get behind the idea of using internal structure rather than external force. Some people like external styles better, and I can certainly see why. Don't necessarily rule out Karate, TKD, etc... While these are hard striking arts, some schools teach them in less concussive ways that would be amenable to your requirements. A: Any martial art should be fine as long as you (and whoever is training with you) are careful with your elbow. Any good teacher should (read: will) accommodate you and not put excessive pressure on your bad elbow. If you were planning to compete in either amateur or professional circles, I would ask for medical advice as you are likely to get your elbow strained. However, this should not bare you for any style that hold competitions with the above caveat. For example: Aikido has a lot of elbow techniques but those can be done safely or missed. Muay Thai has a lot of elbow strikes but those can be done safely or at very low power so not to acerbate your injury. Clearly, monitoring the state of your elbow will be critical whatever art you chose.
{ "pile_set_name": "StackExchange" }
Q: How does automatic weapon fire interact with the scatter property? I am confused how to determine hits from a combat shotgun in Dark Heresy. How does the scatter property interact with an auto-fire action when attacking? A: It's confusing but they answered it in the Errata: The Actions section starting on page 190 should include a special note concerning combining semi-auto and full-auto fire with the Scatter quality, which reads “When firing a semi- or full-auto burst at point blank range with a weapon that has the Scatter quality, the extra hits for rate of fire and scatter are worked out separately and both applied. For example, Horatius Kane fires his combat shotgun at Heretic X. Kane is at point-blank range and fires a semiautomatic burst. Kane rolls 01 with his modified Ballistic Skill of 70 (30 BS, +30 for point-blank range, +10 for firing semi-auto) and hits by an amazing six degrees of success. He gets one hit at 70, one hit for semi-automatic at 50, and a third hit for semi-auto at 30 (he does not get a fourth hit at 10, because the combat shotgun’s rate of fire is 3). He would get additional hits for scatter at 50, 30 and 10, for a total of 6 hits on Heretic X, most likely shredding the cultist to bits in the Emperor’s name.” http://www.fantasyflightgames.com/ffg_content/dark-heresy/pdf/darkheresy-errata-v3.0-printable.pdf
{ "pile_set_name": "StackExchange" }
Q: django filter for URL that consists of two variables In all code snippets I see basic pattern of how filter is applied to an URL. For example, <img src="{{obj.url|filter}}" /> I wonder how can I use filter with URL that consists of two parts? <img src="{{something}}{{obj.url}}" /> Note: filter should deal with the complete URL, not just the second part of it EDIT: Model: class Foo(models.Model): token = models.CharField(max_length=150) reference = models.ForeignKey(Reference) View: def index(request): foos = Foo.objects.filter(reference=value).all() return render(request, 'index.html', {'foos' : foos}) Template: {% for foo in foos %} <img id="foo_{{foo.pk}}" src="{{MEDIA_URL}}{{foo.token}}" /> {% endfor %} As a matter of fact, I want to just apply easythumbnail URL filter to image URL, which has two parts. A: If you're wanting to do things with context variables like this then you should make what you require available in the context rather than trying to manipulate things in the template. Either add variable from your view or create a context processor if you have variables that you require in lots of places, because through a context processor you can create variables that are always available. Check out this answer I wrote recently on this; https://stackoverflow.com/a/27797061/1199464 update following your comment There's nothing wrong with writing a method on your model to format a string or similar; class Foo(models.Model): token = models.CharField(max_length=150) reference = models.ForeignKey(Reference) def get_url(self): url = u'{media_url}{path}'.format( media_url=settings.MEDIA_URL, path=self.token ) return url Template: {% for foo in foos %} <img id="foo_{{ foo.pk }}" src="{{ foo.get_url }}" /> {% endfor %} And on a sidenote if you're not too familiar with Django yet, you should use MEDIA_URL for user uploaded content and STATIC_URL for content that is yours. You can read more on these here; How can I get the MEDIA_URL from within a Django template? Django docs; https://docs.djangoproject.com/en/1.7/ref/settings/#media-url
{ "pile_set_name": "StackExchange" }
Q: Are there police in the Wizarding World? In the Wizarding World of Harry Potter, courts exist (such as the one that Harry went to for his trial during Order of the Phoenix) and there are Aurors who are specifically tasked with tracking down dark wizards. However, I don't recall any mention of more general police in the world that might catch criminals for crimes of lesser importance, such as shoplifting in Diagon Alley or vandalism in Hogsmeade. Surely such law enforcement must exist for a functioning society, but is there any explicit evidence that such police exist? A: Yes. Arthur Weasley and Harry discussing the regurgitating public toilets: 'Will it be Aurors who catch them?' 'Oh no, this is too trivial for Aurors, it'll be the ordinary Magical Law Enforcement Patrol - ah, Harry, this is Perkins.' Harry Potter and the Order of the Phoenix - p.123 - Bloomsbury - Chapter 7, The Ministry of Magic Also in The Half-Blood Prince, Arthur heads up the Office for the Detection and Confiscation of Counterfeit Defensive Spells and Protective Objects, which seems to have an element of law enforcement behind it. Also, in his role in the Misuse of Muggle Artefacts Office he had the power to conduct raids. Plainly there is a Magical Law Enforcement Patrol, but, also, general law enforcement seems to be spread across departments at the Ministry of Magic, rather than being entirely under one crime-fighting arm. Thus, Arthur's Misuse of Muggle Artefacts Office is a small part of level two at the Ministry of Magic: 'Level Two, Department of Magical Law Enforcement, including the Improper Use of Magic Office, Auror Headquarters and Wizengamot Administration Services.' Harry Potter and the Order of the Phoenix - p.120 - Bloomsbury - Chapter 7, The Ministry of Magic I also find it interesting that Level Four is the Department for the Regulation and Control of Magical Creatures, which - again - seems to have some law enforcement powers, such as punishing people who breed experimentally and ordering and carrying out the execution of dangerous animals. One thing we can say, though, is that nobody in the wizarding world is called a policeman. Amos Diggory on the break-in to Mad-Eye Moody's house. '... Muggle neighbours heard bangs and shouting, so they went and called those what-d'you-call-'ems - please-men.' Harry Potter and the Goblet of Fire - p.141 - Bloomsbury - Chapter 11, Aboard the Hogwarts Express Interestingly, in this case, it seems to be "the Improper Use of Magic lot" who set off for Moody's house (GoF, p.142). A: In film canon, there's actually something called the Ministry (of Magic) Police - at least while Voldemort controls the Ministry. Look at the bottom right corner of this poster: Here's the signature zoomed up a bit: However, as AlbeyAmakiir says, this seems to contradict book canon, where wizards, even those working in the Ministry, are unaware of the 'Muggle' word policemen or even its proper pronunciation. See the quote at the end of Au101's answer.
{ "pile_set_name": "StackExchange" }
Q: A hitman falls in love with a victim girl I have seen this movie when I was very young (11 or 12). I am 19 now and I want to know the name of this movie. The movie is obviously produced before the 2000. Genre: Drama. Seen on television. What the movie is about": It is about a hit-man who invades a house for theft or murder (one of them). He kills everyone there. However, the girl (I do not remember if she was related to the victims) is found there sitting on stairs, sad, depressed and smoking. The hit-man feels compassion for her and starts developing a relationship with her. Whether it was romantic or not, the hit-man and the girl are pictured inside a house taking care of flowerpot or a pot. The movie ends with the hit-man killing himself with a bomb, in order to let the girl go to school again. Anyone to identify this movie for me? A: This sounds like Luc Besson's Leon: The Professional from 1994 with Natalie Portman about a hitman adopting a girl after her family is wiped out (he also finds her sitting and smoking on the stairs in his building). They also take care of a potted plant together. It ends in the manner you've described (he offs himself with grenades to take out the villain). The film gained a cult status and is now considered one of Besson's best (it's currently #27 on IMDb's Top 250 rated films of all time). Here's the trailer:
{ "pile_set_name": "StackExchange" }
Q: How to pasteurize lacto-fermented hot sauce? So, I've got a 2-3dl batch of lacto-fermented hot sauce in the works. Approximately half the vegetables in the ferment are large brown habaneros and the other half is sweet pepper, ginger and some slices of carrot to get the ferment going. So, I expect the sauce to last me quite some time. Therefore, I'm planning on pasteurizing the sauce to extend its shelf-life. My main goal in the pasteurization is to stop the fermentation already going on. For equipment, I have a thermometer from the brewing supplies aisle, various different sizes of pots and pans, some of which can be nested for a double boiler, and an electric stove. Is there a reasonable process to pasteurize a batch of fermented hot sauce with these? A: According to the US FDA, normal pastuerization for fruit juice would be 160F for 6 seconds. This should be easily accomplished in a hot water bath; just heat up the water to 160f, and dip the bottles. However, a fermented sauce made with chopped peppers has poor circulation compared to fruit juice, and you are heating bottles rather than passing the liquid through a narrow, heated pipe. So more time would be required for the heat to penetrate, possibly as much as 5 minutes. I can't find specific guidance for something like a chopped pepper sauce. This would pastuerize the hot sauce, but not make it shelf-stable. The criteria to bottle it, as mentioned in the comments, is how acidic the sauce is after fermentation, so you should add some form of Ph tester to your list of equipment. If the acidity is 4.6 or below, then a slightly hotter hot water bath (say, 180F) for a few minutes you could not only pastuerize it, but make it shelf-stable.
{ "pile_set_name": "StackExchange" }
Q: Servlet running under Grails How can I run a servlet (UploadAction from GWTUpload project) under grails? I've successfully added the servlet and use it from the web.xml file. However, I really want to wrap some logic around the doPost/doGet methods using the grails framework (gorm). Can I just subclass the servlet as a Controller, maybe just instantiate the servlet in the controller and call init()? I'm not sure how to do this properly. A: The simplest thing that comes to my mind is: write a grails controller, instantiate the servlet (once, in the contstructor or in @PostConstruct) and call init()` map the controller method (via UrlMappings.groovy) to the url that your servlet would be mapped call servlet.service(request, response). It's a bit of a hack though. Another way is to get ahold of a spring (grails) bean in a filter applied to the servlet, with WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext()) and invoke the custom logic there.
{ "pile_set_name": "StackExchange" }
Q: I need to know what kind of spokes to buy I have a Trek 7500FX with Bontrager race lite 700x32 tires. I have broken spokes, I no longer have the book what size spokes do I need? A: "The correct length" can be found by measuring an existing spoke. If your broken spokes have failed at the hub, simply measure from the thread end to the inside of elbow/turn and buy that measurement. Otherwise take off a known-good spoke, measure, and reinstall. I've occasionally had to shorten spokes by 1-3 mm because they poke through the nipple into the tube. 10 seconds with a dremel or a couple of minutes with a hand file are all it takes. Whereas you can't lengthen a spoke, so if in doubt go for a 1mm longer spoke. Depending on how many spokes have broken, you might find the adjacent surviving spokes are overtensioned now, so get a couple spares, and a decent spoke tool if you don't already have one. EDIT: Moz makes an excellent point if your wheel is a low spoke count (like in the picture) If you're not feeling confident, it may be safer to take the wheel to a shop for spoke replacement and true and tension check.
{ "pile_set_name": "StackExchange" }
Q: url not correctly shown in email template I've got the following set up, the $url is taken from <td> <?php echo $row['url']?> </td> And a ping is done via curl which works fine (loading time is long but its aprox. 160 sites that are being pinged) <?php $url = $row['url']; $ch = curl_init($url); curl_setopt($ch, CURLOPT_NOBODY, true); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); curl_exec($ch); $retcode = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); if (200==$retcode) { echo "<td><span class='badge badge-success'>LIVE</span></td>"; } else { echo "<td><span class='badge badge-danger'>DOWN</span></td>"; $path_to_file = './emailtemplate.html'; $file_contents = file_get_contents($path_to_file); $file_contents = str_replace("depplaceholder","$url",$file_contents); file_put_contents($path_to_file,$file_contents); $to = "--"; $subject = "$url down"; $headers = "From:Deployment Monitor <-->" . "\r\n"; $headers .= 'MIME-Version: 1.0' . "\r\n"; $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n"; $message = file_get_contents('./emailtemplate.html'); mail($to,$subject,$message,$headers); } ?> Depending on how the ping returns the system will show two badges LIVE or DOWN: if (200==$retcode) { echo "<td><span class='badge badge-success'>LIVE</span></td>"; } else { echo "<td><span class='badge badge-danger'>DOWN</span></td>"; When the ping comes back with DOWN an email is sent out automatically as shown in the code above, this works partially, as shown the word depplaceholder in emailtemplate.html needs to be replaced by $url which it does, for the first website is down. i.e. emails: email 1: Title: server 1 down Body: server 1 down email 2: Title: server 2 down Body: server 1 down email 3: Title: server 3 down Body: server 1 down for some reason the body doesn't change like the title does, is this because the title is pulled from the same page and not from the emailtemplate.html A: Ok, since comments are too limited I'm writing a full answer. Suppose, as you say in the comments, that your template file is as follows: <body> <h1> depplaceholder is down </h1> </body> So you open that file (called ./emailtemplate.html), read its content and put it inside the $file_contents variable. At this point you replace dapplaceholder inside that variable with the content of $url. $file_contents = str_replace("depplaceholder", $url, $file_contents); Then you overwrite emailtemplate.html with file_put_contents($path_to_file,$file_contents); At this point you send the email with the content of emailtemplate.html as its body. Then you ping another server and you load your template, which, at this point (since you overwrote it) contains <body> <h1> 1 is down </h1> </body> You try $file_contents = str_replace("depplaceholder", $url, $file_contents); But there's no dapplaceholder in your file anymore! So this line actually does nothing! And you end up with your mails containing <body> <h1> 1 is down </h1> </body> Forever and ever. I hope my point is clear now. EDIT: As for how to solve this. Unless you have a requirement to keep the email texts (in which case I suggest you save the information to a database instead) you have to realize that you don't actually need to save anything to the filesystem. So just lose this line file_put_contents($path_to_file, $file_contents); And change the part where you set the message to $message = $file_contents; Problem solved!
{ "pile_set_name": "StackExchange" }
Q: Paramconverter with FOSRestbundle I am trying to convert in a route the username to a user. Unfortunately the paramconverter searches always for the id. I have already tried it with several settings, my current settings look like this: /* * @ParamConverter("username", class="StregoUserBundle:User") * @Rest\View(serializerEnableMaxDepthChecks=true, serializerGroups={"Default","user"}) * @param User $user username */ public function getUserAction(User $username){ $return = array('user' => $user); return $return; } The route itself is automatically defined by the FOSRestBundle and looks like this: get_user GET ANY ANY /api/users/{username}.{_format} What can I do that the user is found via the user name? A: From Symfony documentation: http://symfony.com/doc/current/bundles/SensioFrameworkExtraBundle/annotations/converters.html#built-in-converters /* * @ParamConverter("username", class="StregoUserBundle:User", options={"id" = "username"}) * @Rest\View(serializerEnableMaxDepthChecks=true, serializerGroups={"Default","user"}) * @param User $user username */ public function getUserAction(User $username){ $return = array('user' => $user); return $return; } Set the id to whatever your parameter name is and you're all set.
{ "pile_set_name": "StackExchange" }
Q: Why would anyone use WCF basicHttp webservice over WCF RIA Services in Silverlight? So, I've been using WCF Ria services for a few months now and I am wondering why would anyone use WCF basicHttp webservice over using WCF RIA Services? Someone told me that RIA Services is not good for Enterprise Level Applications and I am wondering why? W/out RIA it seems you have to write validation logic in 2 areas, client and server. Also, RIA handles roles and membership fairly easily. How much extra work is involved if you want to use WCF basicHttp webservice? What is the benifit over using RIA? and.. Does anyone have any good examples of an enterprise level silverlight application using wcf basicHttp webservice? Thanks! A: The issues with WCF support in Silverlight relates to the limited subset of the .NET Framework embedded in the Silverlight plug-in as it's essentially a scaled down version of the .NET Framework. As a result of the scaled down .NET runtime in the Silverlight plug-in, it does not have the same full support for WCF that you get from standard .NET projects. This was done to make the initial download of SL quick from a client perspective and increase time-to-market of SL as a product. Keep in mind that the SL plug-in has no dependency on an existing .NET framework being installed which is why Linux, Windows Phone 7, and OS X versions are on the market. As time has progressed they continue to add in-demand features in. For example, Silverlight 5 will support WS-Trust (see here for a complete list of new features in 5). I recommend you read this resource to see what you may miss out on by trying to call WCF Services from the client: http://msdn.microsoft.com/en-us/library/cc896571(v=vs.95).aspx Keep in mind you could very easily proxy out calls to more complex WCF services through RIA Services endpoints which are in effect calling the service directly from server-side. As for using standard WCF instead of RIA ... there are advantages when your middle tier has multiple client types, though with RIA you could simply expose your endpoints out as SOAP 1.1 endpoints and require people to connect using that paradigm instead of WCF. You do not have to use RIA or nothing; you could mix and match to meet your requirements as you see fit. Personally I am big on just using RIA if at all possible.
{ "pile_set_name": "StackExchange" }
Q: Máscara em imagem Estou tentando aplicar uma "máscara" em minha imagem, para pegar apenas o centro da mesma e aplicar 50px por 52px, tentei utilizar o clip-path mas não funciona, estou utilizando o opera e o chrome para testes, segue meu código: CSS .img_tamanho_icon { width: 50px; height: 55px; clip-path: inset(52px 50px 52px 50px); -webkit-clip-path:inset(52px 50px 52px 50px); display: block; overflow: hidden; } HTML <img src="minhaImg.jpg" class="img_tamanho_icon"> Como eu poderia fazer isto? Sem perder a resolução da imagem, por exemplo "esticar" a mesma A: Uma solução é utilizar a imagem como plano de fundo de um elemento: .centro { width: 50px; height: 52px; background-repeat: no-repeat; background-size: cover; background-position: center center; background-image: url('http://placehold.it/200x100'); } <div class="centro"></div>
{ "pile_set_name": "StackExchange" }
Q: Странность с указателями в Си Я хочу узнать, почему вот эта программа работает без ошибки сегментации: #include <stdio.h> char *month_name(int); main() { char *month[15]; for(int i = 1, j = 0; month_name(i) != "No month"; i++, j++) { month[j] = month_name(i); while(*month[j]) { printf("%c", *month[j]++); if(!*month[j]) { printf("\n"); } } } } char *month_name(int num) { static char *name[] = { "No month", "January", "February", "Mart", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; return (num < 1 || num > 12) ? name[0] : name[num]; } А эта с ошибкой сегментации и выводом непонятных символов на экран: #include <stdio.h> char *month_name(int); main() { char *month[15]; int k = 0; for(int i = 1, j = 0; month_name(i) != "No month"; i++, j++) { month[j] = month_name(i); } !!!!! while(*month[k]) { printf("%c", *month[k]++); if(!*month[k]) { printf("\n"); k++; } } !!!!! } char *month_name(int num) { static char *name[] = { "No month", "January", "February", "Mart", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; return (num < 1 || num > 12) ? name[0] : name[num]; } A: Вот так month_name(i) != "No month" писать в общем случае нельзя. Если у вас отрабатывает верно - то только из-за оптимизации, которая одинаковые строки только для чтения объяединяет. Стоит скомпилировать в VC++ код с ключиком /GF-, как все тут же перестанет работать... Во втором случае вы просто идете по массиву указателей (из-за k++) и выскакиваете за декабрь к следующему указателю - а он содержит какой-то мусор, который указывает на другой мусор, каковой и пытается не то вывестись, не то привести к аварийному завершению. Вот если вы напишете char *month[15] = {"","","","","","","","","","","","","","",""}; то все сработает :)
{ "pile_set_name": "StackExchange" }
Q: Convert polymorphic case classes to json and back I am trying to use spray-json in scala to recognize the choice between Ec2Provider and OpenstackProvider when converting to Json and back. I would like to be able to give choices in "Provider", and if those choices don't fit the ones available then it should not validate. My attempt at this can be seen in the following code: import spray.json._ import DefaultJsonProtocol._ case class Credentials(username: String, password: String) abstract class Provider case class Ec2Provider(endpoint: String,credentials: Credentials) extends Provider case class OpenstackProvider(credentials: Credentials) extends Provider case class Infrastructure(name: String, provider: Provider, availableInstanceTypes: List[String]) case class InfrastructuresList(infrastructures: List[Infrastructure]) object Infrastructures extends App with DefaultJsonProtocol { implicit val credFormat = jsonFormat2(Credentials) implicit val ec2Provider = jsonFormat2(Ec2Provider) implicit val novaProvider = jsonFormat1(OpenstackProvider) implicit val infraFormat = jsonFormat3(Infrastructure) implicit val infrasFormat = jsonFormat1(InfrastructuresList) println( InfrastructuresList( List( Infrastructure("test", Ec2Provider("nova", Credentials("user","pass")), List("1", "2")) ) ).toJson ) } Unfortunately, it fails because it can not find a formatter for Provider abstract class. test.scala:19: could not find implicit value for evidence parameter of type Infrastructures.JF[Provider] Anyone have any solution for this? A: What you want to do is not available out of the box (i.e. via something like type hints that allow the deserializer to know what concrete class to instantiate), but it's certainly possible with a little leg work. First, the example, using a simplified version of the code you posted above: case class Credentials(user:String, password:String) abstract class Provider case class Ec2Provider(endpoint:String, creds:Credentials) extends Provider case class OpenstackProvider(creds:Credentials) extends Provider case class Infrastructure(name:String, provider:Provider) object MyJsonProtocol extends DefaultJsonProtocol{ implicit object ProviderJsonFormat extends RootJsonFormat[Provider]{ def write(p:Provider) = p match{ case ec2:Ec2Provider => ec2.toJson case os:OpenstackProvider => os.toJson } def read(value:JsValue) = value match{ case obj:JsObject if (obj.fields.size == 2) => value.convertTo[Ec2Provider] case obj:JsObject => value.convertTo[OpenstackProvider] } } implicit val credFmt = jsonFormat2(Credentials) implicit val ec2Fmt = jsonFormat2(Ec2Provider) implicit val openStackFmt = jsonFormat1(OpenstackProvider) implicit val infraFmt = jsonFormat2(Infrastructure) } object PolyTest { import MyJsonProtocol._ def main(args: Array[String]) { val infra = List( Infrastructure("ec2", Ec2Provider("foo", Credentials("me", "pass"))), Infrastructure("openstack", OpenstackProvider(Credentials("me2", "pass2"))) ) val json = infra.toJson.toString val infra2 = JsonParser(json).convertTo[List[Infrastructure]] println(infra == infra2) } } In order to be able to serialize/deserialize instances of the abstract class Provider, I've created a custom formatter where I am supplying operations for reading and writing Provider instances. All I'm doing in these functions though is checking a simple condition (binary here as there are only 2 impls of Provider) to see what type it is and then delegating to logic to handle that type. For writing, I just need to know which instance type it is which is easy. Reading is a little trickier though. For reading, I'm checking how many properties the object has and since the two impls have different numbers of props, I can differentiate which is which this way. The check I'm making here is very rudimentary, but it shows the point that if you can look at the Json AST and differentiate the types, you can then pick which one to deserialize to. Your actual check can be as simple or as complicated as you like, as long as it's is deterministic in differentiating the types.
{ "pile_set_name": "StackExchange" }
Q: Scrolling to make div visible I am trying to make it so that the fullcalendar scheduler scrolls to the area a person clicks on, and this code works somewhat, but depending on the screen size, the actual area it should zoom to is often scrolled past, and is not visible within the window. Is there a way to ensure that the table header cell's left border is aligned with the window's left border? In the view, there is a horizontal scrolling table inside a div $('.fc-time-area.fc-widget-header .fc-scroller'), and the cell I want visible can be found with something like this: $(".fc-time-area.fc-widget-header .fc-content th[data-date='2017-2-11T10:00:00']") var centerTime = function (day) { $('.fc-time-area.fc-widget-header .fc-scroller').animate({ scrollLeft: $(".fc-time-area.fc-widget-header .fc-content").find("th[data-date='" + day + "']").offset().left }, 750); }; A: I figured it out. Apparently there is a difference between using offset() and position(). By changing that simple thing, it works great now. var centerTime = function (day) { $('.fc-time-area.fc-widget-header .fc-scroller').animate({ scrollLeft: $(".fc-time-area.fc-widget-header .fc-content").find("th[data-date='" + day + "']").offset().left }, 750); };
{ "pile_set_name": "StackExchange" }
Q: Why does that fact that $a_n \equiv 3 \pmod 5$ and $b_n\equiv 1 \pmod 5$ imply $1/\pi(\arctan(1/3))$ is irrational So since I've started this multi-part question I've learned: $(3+i)^n = a_n+ib_n$ $a_{n+1} = 3a_n-b_n$ $b_{n+1} = b_n+a_n$ $a_n \equiv 3 \pmod 5$ $b_n \equiv 1 \pmod 5$ Now I am asked why the fact that, for $n\geq 1, a_n \equiv 3 \pmod 5$ and $b_n \equiv 1 \pmod 5$ implies that $\frac{1}{\pi} \arctan(\frac{1}{3})$ is irrational. I notice the similarities between $\frac{b}{a}$ and $\frac{1}{3}$, but I honestly have no clue how to go about this. A: Let $z=3+i$. Then $\arg z = \arctan ⅓ =: t$. Now, since $b_n \neq 0$, we have that $nt = m\pi$ is impossible for any integer $n,m$. (Note: $nt=\arg z^n$ comes from repeatedly taking powers of $z$. Suppose it can equal $m\pi$ for some integer $m$, then we must have $b_n=0$ for some $n$) Thus, $t/ \pi = m/n$ has no solutions over the integers, so this number is irrational.
{ "pile_set_name": "StackExchange" }
Q: perl use hash to read a file I am trying to write a function in Perl which takes a hash and a file name as input. Basically my hash is like this eg datahash is the name of the hash then datahash(Attr1) = 1 datahash(Attr2) = 5 datahash(Attr3) = 4 datahash(Attr4) = 6 My file is a csv with Attr1,Attr2.. as the column names in the csv and the valuess of the hash are the column numbers in the same file. My function needs to extract data from the file based on the hash keys and values. Any clues or ideas ? It needs to match the column name of the file to the hash, find out the column number and then extract the values of the column numbers. Several columns need to be extracted. Below is the code I have: (Don't bother about the multiple prints I can put a loop) my %dataHash = %{$_[0]}; my $fileName = $_[1]; my @keys = keys %dataHash; my @values = values %dataHash; open my $info, $file; while( my $line = <$info>) { my @arrdata = split(/,/, $line); print @arrdata[values[0]]; print @arrdata[values[1]]; print @arrdata[values[2]]; print @arrdata[values[3]]; print @arrdata[values[4]]; print @arrdata[values[5]]; } Sample file : attr1,abc,def,ghi,attr3,attr2,attr4,attr5,attr6 1,2,3,4,5,6,7,8,9 11,12,13,14,15,16,17,18,19 11,12,13,14,15,16,17,18,19 11,12,13,14,15,16,17,18,19 SO the hash has the column names and column numbers I need to extract and the file is like this. A: Using Text::CSV use strict; use warnings; use Text::CSV; my @rows; my $csv = Text::CSV->new ( { binary => 1 } ) or die "Cannot use CSV: ".Text::CSV->error_diag (); my $fh = \*DATA; # Open a fh instead my $header = $csv->getline( $fh ); while ( my $row = $csv->getline( $fh ) ) { my %hash; @hash{@$header} = @$row; push @rows, \%hash; } $csv->eof or $csv->error_diag(); close $fh; use Data::Dump; dd \@rows; __DATA__ attr1,abc,def,ghi,attr3,attr2,attr4,attr5,attr6 1,2,3,4,5,6,7,8,9 11,12,13,14,15,16,17,18,19 11,12,13,14,15,16,17,18,19 11,12,13,14,15,16,17,18,19 Outputs: [ { abc => 2, attr1 => 1, attr2 => 6, attr3 => 5, attr4 => 7, attr5 => 8, attr6 => 9, def => 3, ghi => 4, }, { abc => 12, attr1 => 11, attr2 => 16, attr3 => 15, attr4 => 17, attr5 => 18, attr6 => 19, def => 13, ghi => 14, }, { abc => 12, attr1 => 11, attr2 => 16, attr3 => 15, attr4 => 17, attr5 => 18, attr6 => 19, def => 13, ghi => 14, }, { abc => 12, attr1 => 11, attr2 => 16, attr3 => 15, attr4 => 17, attr5 => 18, attr6 => 19, def => 13, ghi => 14, }, ]
{ "pile_set_name": "StackExchange" }
Q: Removing stop words from String class MyClass { public static void remove_stopwords(String[] query, String[] stopwords) { A: for (int i = 0; i < query.length; i++) { B: for (int j = 0; j < stopwords.length; j++) { C: if (query[i].equals(stopwords[j])) { break B; } else { System.out.println(query[i]); break B; } } } } } For some reason this code only works correctly about halfway through the problem. It takes the first stopword out of the query, but it ignores the rest. Any help would be appreciated. A: class MyClass { public static void remove_stopwords(String[] query, String[] stopwords) { A: for (int i = 0; i < query.length; i++) { //iterate through all stopwords B: for (int j = 0; j < stopwords.length; j++) { //if stopwords found break C: if (query[i].equals(stopwords[j])) { break B; } else { // if this is the last stopword print it // it means query[i] does not equals with all stopwords if(j==stopwords.length-1) { System.out.println(query[i]); } } } } } }
{ "pile_set_name": "StackExchange" }
Q: Frobenius norm of a binary matrix In term of the mathematical distance measurement, What is the significance of a Frobenius norm for a binary matrix? A: The Frobenius norm of a binary matrix is the square root of the number of non-zero elements. Let the point (0.,...0) be the origin, and let's say the vec'd binary matrix elements are the coordinates of a point, with coordinates being zero or one. Then the Frobenius norm is the Euclidean distance from the origin to that point.
{ "pile_set_name": "StackExchange" }
Q: In Rails models, can I change belongs_to to has_one and has_one to belongs_to? If I have two models. Model1 belongs_to Model2, and Model2 has_one Model1. Thus I can access Model2 from Model1 as well as Model1 from Model2. Now my question is, can I change the relationship to Model2 belongs_to Model1 and Model1 has_one Model2? It also can let me traverse from Model1 to Model2 and from Model2 to Model1. I'm not sure of that, anyone can explain it please? Thanks. A: You can certainly change a relationship from one way round to the other. You'll obviously need to add a model_1_id column on the model_two table, migrate any existing associations across and remove the model_2_id column on the model_one table. I can't think of anything else you'd particularly need to do to get it to work. The associations behave pretty much identically when belongs_to is paired with has_one.
{ "pile_set_name": "StackExchange" }
Q: non-maximal prime ideal in the ring of continuous functions Let $A=C(0,1)$ be the ring of continuous real valued functions on the open interval $(0,1)$. It is not too difficult to show that if $\mathfrak{m}\subseteq A$ is a maximal ideal with residue field $A/\mathfrak{m}\simeq \mathbb{R}$ then $\mathfrak{m}=\mathfrak{m}_a:=ker(ev_a)$ where for $a\in(0,1)$, $ev_a:A\rightarrow\mathbb{R}$ is the evaluation map at $a$. It is easy to show that there are maximal ideals not of the for $\mathfrak{m}_a$. For instance one may look at the ideal $$ I=\{f\in A:\exists n\in\mathbf{Z}_{\geq 1}, f\equiv 0\;\;\mbox{on $(0,1/n]$}\} $$ Then $I$ is not contained in any $\mathfrak{m}_a$ but by Zorn's lemma it is contained in some maximal ideal $\mathfrak{M}$. So here are two natural questions on the ring $A$ for which I don't have an answer: Q1: Do we have a structure theorem for the possible residue fields of maximal ideals of $A$. Q2: How does one show the existence (or construct) of a prime ideal of $A$ which is not maximal? A: Take any free ultrafilter $U$ on $(0,1)$, and let $m_U$ be the set of functions which are $0$ "almost everywhere", i.e., on a set in the ultrafilter. It seems to me that is a prime ideal, which is in general not maximal. If all ultrafilter sets have, say, the number 1/2 as a limit point, then $m_U$ is properly contained in the ideal of functions vanishing at 1/2. Why is it an ideal? That looks easy. E.g., if you have two functions vanishing on $A_1$, $A_2$ respectively, then their sum vanishes on $A_1\cap A_2$, which is again in the ultrafilter. Why is it prime? Let $f_3:=f_1\cdot f_2$. Let $A_i:= \{x:f_i(x)=0\}$. Then $f_3\in m_U$ iff $A_3 \in U$ iff $A_1\cup A_2\in U$ iff $A_1\in U $ or $A_2\in U$ iff one of $f_1$, $f_2$ is in $m_U$.
{ "pile_set_name": "StackExchange" }
Q: comparing two uuid in sqlalchemy core I'm using sqlalchemy 1.2 In short what produces errors is this : uuidvar = uuid4() mytable.select().where(mytable.c.uuidColumn == uuidvar) #where mytable is of type sqlalchemy.Table Error : File "/Users/remi/PycharmProjects/my_venv/lib/python3.6/site-packages/sqlalchemy/dialects/postgresql/psycopg2.py", line 448, in process value = _python_UUID(value) File "/usr/local/Cellar/python3/3.6.3/Frameworks/Python.framework/Versions/3.6/lib/python3.6/uuid.py", line 137, in __init__ hex = hex.replace('urn:', '').replace('uuid:', '') sqlalchemy.exc.StatementError: (builtins.AttributeError) 'UUID' object has no attribute 'replace' [SQL: 'SELECT col1, col2, col3 FROM myTable \nWHERE uuidColumn = '%(uuidColumn_1)s'] With a table like this : CREATE TABLE myTable ( uuidColumn uuid primary key default uuid_generate_v4() col1 text, col2 text, col3 text ) and table generate in python : metadata = MetaData(engine=db) # db is created by "create_engine", nothing fancy myTable = Table('myTable', metadata, autoload=True) A: I had a similar issue. To solve this error, you need to define uuidColumn with as_uuid=True. Like so: from sqlalchemy.dialects import postgresql uuidColumn = db.Column(postgresql.UUID(as_uuid=True)) For more details see Michael Bayer's comments here: https://bitbucket.org/zzzeek/sqlalchemy/issues/3323/in-099-uuid-columns-are-broken-with
{ "pile_set_name": "StackExchange" }
Q: How to Move Parent Div Position using css on hover Anyone have solution for this i want to move div position via css on mouse hover move div down when i mouse over on div.... HTML <div class="movediv">I Want to Move this div on hover via css</div> <div class="testing"> <a class="Linktohover">Test</a> <div class="showDiv"> <ul> <li>test</li> <li>test</li> <li>test</li> <li>test</li> </ul> </div> </div> CSS .showDiv { position: absolute; left: -9999px; display: block !important; font-size: 14px !important; } .testing:hover .showDiv { left: 0px; display: block !important; } .testing { position: absolute; top: 0px; } .movediv { margin-top: 30px; } SEE DEMO A: Like this types DEMO .container { position:absolute; bottom:0; right:0; left:0; margin-right:auto; margin-left:auto; width:50%; height:10%; } .a {position:absolute; bottom:0; left:20px; width:30%;} .b { position:absolute; bottom:0; right:0; left:0; margin-right:auto; margin-left:auto; width:30%; } .c {position:absolute; bottom:0; right:20px; width:30%;} .b:hover ~ .a{ -moz-transform:translatex(-50px); -ms-transform:translatex(-50px); -o-transform:translatex(-50px); -webkit-transform:translatex(-50px); transform:translatex(-50px); } .b:hover ~ .c{ -moz-transform:translatex(50px); -ms-transform:translatex(50px); -o-transform:translatex(50px); -webkit-transform:translatex(50px); transform:translatex(50px); }
{ "pile_set_name": "StackExchange" }
Q: What's the most efficient way to fit a surface to three or more points? Say I have a function of the form $s=b-mp+at$, where $p$ and $t$ are the independent variables, and I have 3 or more points of the form $(p,t,s)$. I want to find the best values for $b$, $m$, and $a$ to give me the best fit. Is there an analogue of linear regression for this situation? A: Here are some matrix algebra equations you can try. I'm suggesting this approach because you mentioned that there may be future cases where you have more than three points to work with and in such cases the linear regression solution is what you want. Starting with your equation for $s$, define the following quantities: $$\underline s = \begin{bmatrix} s_1\\ s_2\\ s_3 \end{bmatrix}$$ $$X = \begin{bmatrix} 1 \ \ p_1 \ \ t_1\\ 1 \ \ p_2 \ \ t_2\\ 1 \ \ p_3 \ \ t_3\\ \end{bmatrix}$$ $$\underline\beta = \begin{bmatrix} b\\ m\\ a \end{bmatrix}$$ Then per your equation $\underline s = X \ \underline\beta$. In your case you have three data points and 3 unknowns. If $X$ is full column rank (its determinant is not zero, points are not colinear) and since $X$ is square, multiplication of both sides of the equation for $ \underline s$ by $X^{-1}$ gives $\underline\beta = X^{-1} \underline s$. If you have more than three data points (more than 3 rows of the $s$ vector and the X matrix) the following equation will do the trick: $$\underline\beta = (X'X)^{-1}X' \underline s$$ again as long as $X$ is full column rank, or equivalently, as long as $det(X'X) \neq 0$. In this case the equation gives the least squares estimate for $\underline \beta$. The second equation will work as well for the case of only 3 points, which means you can solve your initial problem with a standard regression package. In this case you have a saturated model which has no degrees of freedom left over to estimate an error term, but with three points and three parameters to estimate you'll have a perfect fit, as has been pointed out in the comments. I hope this helps.
{ "pile_set_name": "StackExchange" }
Q: FTP date variable to grab ftp file I am trying to write a script that will grab a file from an ftp site. The issue I am having is figuring out how to grab the files that have dates on them. For example on January 1st we run mar2019. February 1st would run apr2019. I am trying to figure out how to write something to automate this but cannot figure out how to grab the correct dated file. Any help with this would be greatly appreciated. u.ftp open ftp.site.com username password mget 'Name.Name.RENEWALS.MAR2019' disconnect quit run with ftp -i -s:u.ftp A: The concept to insert a variable into a template and write that to a file is the same in batch/powershell. As getting/formatting the date is easier in PowerShell a here string is used for the template: ## Q:\Test\2019\01\02\SO_54009396.ps1 $Month = (Get-Date).AddMonths(2).ToString('MMMyyyy') $ftpScript = '.\u.ftp' @" open ftp.site.com username password mget 'Name.Name.RENEWALS.$Month' disconnect quit "@ | Set-Content $ftpScript &ftp -i -s:$ftpscript
{ "pile_set_name": "StackExchange" }
Q: Insert the current date (format yyyy/mm/dd) into a list box - I need to insert the date at the end of the following line lstReport.Items.Add('***** END OF REPORT *****'); A: FormatDateTime would be appropriate: lstReport.Items.Add('***** END OF REPORT ' + FormatDateTime('yyyy/mm/dd', Date) + ' *****') ;
{ "pile_set_name": "StackExchange" }
Q: how do i change a database value to a normal String? I have stored a database value orgname in a result set. I get only one orgname and i stored it in a Result set. orgName = result.getString("orgname"); I tried to retrieve the value using this getString function of result set. But the output I am receiving orgname as com.mysql.jdbc.JDBC4ResultSet@333ce5bb. how can I get the actual name of the organization. A: Have a look at this: Getting Data From Resultset It isn't the same as your issue, but in general, the answers for that question cover how to do it properly. My guess (and guessing is all I can do without proper information) is that you have missed a call to position the result cursor... something like: result.first();
{ "pile_set_name": "StackExchange" }
Q: How do I make two observeEvent function for different options in selectinput The result page in my program aims to respond differently to the different options the user enters. I feel observeEvent seems relevant but when I wrote this way it only displays the latest observeEvent (which is the female one). Here is the simplified version of my code: library(shiny) ui <- fluidPage( mainPanel( tabsetPanel(type = "tabs", tabPanel("Personal Information", selectInput( "gender", "What is your biological gender?:", c("--" = "null","male" = "gender1","female" = "gender2") ) ), tabPanel("Result", verbatimTextOutput("result") ) ) ) ) server <- function(input, output) { #Events observeEvent( {input$gender == "gender1"}, output$result <- renderPrint ("You are a male.") ) observeEvent( {input$gender == "gender2"}, output$result <- renderPrint ("You are a female.") ) } shinyApp(ui, server) A: You should use one observeEvent that triggers whenever input$gender changes. Then have a conditional inside that which determines what value to return. You actually don't need the observeEvent at all, since any reactive expression (including a renderPrint) will update if any reactive values in it are invalidated. So the best way to do what you want is to replace bout observeEvent functions with the below: output$result <- renderPrint({ if (input$gender == 'gender1') { return("You are a male.") } else if (input$gender == 'gender2') { return("You are a female.") } }) The difference with using an event function vs a render* is that the code block is considered to be in an isolate block and only the change of the eventExpr will trigger the code to run. That's good if you want to make the code only run when an Update button is pressed, but if you want it to be reactive to changing values (like in your example) you shouldn't use an event function. Also, you are strongly encouraged not to nest reactive expressions as you do above. If you must have an event function drive a renderPrint function (as in your example), the reccomended way of doing that is with an eventReactive: gender_input <- eventReactive(input$update, { if (input$gender == 'gender1') { return("You are a male.") } else if (input$gender == 'gender2') { return("You are a female.") } }) output$result <- renderPrint({gender_input()})
{ "pile_set_name": "StackExchange" }
Q: ignoring jshint Unnecessary semicolon error I am using jshint which gives me the error "Unnecessary semicolon". I do not control the file in question and I would like to ignore this error. I am not able to find any such option on the jshint doc page A: Turns out you can ignore any error message by setting an option for specific error numbers: "-W032": true
{ "pile_set_name": "StackExchange" }
Q: What is proper use of Apache method apr_pool_create_ex in Delphi XE? What is proper use of Apache method apr_pool_create_ex in Delphi XE? I’ve created Apache modules before, but all were Handlers. Now I’m working on developing a Service provider. A skeleton module has been created and my child_init call back method is being called by Apache. In the child_init method I call ap_pool_create_ex* successfully (returns APR_SUCCESS), but after leaving the child_it call, I receive an access violation either during the (httpd.exe) spawning of the third or the fourth worker thread (third is showing in the event log). procedure provider_child_init(pchild: Papr_pool_t; s: Pserver_rec); cdecl; var rv : apr_status_t; mypool : Papr_pool_t; begin rv := -1; rv := apr_pool_create_ex(@mypool,pchild,nil,nil); end; The AV message is: “Project C:\Apache2.2\bin\http.exe raised too many consecutive exceptions: ‘access violation at 0x00000000: read of address 0x00000000’. Process Stopped. Use Step or Run to continues” Event Log: … Thread Start: Thread ID: 5652. Process httpd.exe (4212) Thread Start: Thread ID: 5132. Process httpd.exe (4212) Thread Start: Thread ID: 5988. Process httpd.exe (4212) NOTE: The AV occurs in Thread ID 5988 and 4212 is the Parent httpd.exe process. The windows “libapr-1.dll” does not include “apr_pool_create”, that is why I’m using the “_ex” version. Any idea why apr_pool_create is missing? I see apr_pool_create being used in other successful modules although they are written in ‘C’. OS: Windows 7 Enterprise 64-bit Apache: 2.2.17.0 IDE: Delphi XE A: Is your translation of the function correct? Delphi XE Version Insight (Subversion plugin) declares it as follows: type PAprPool = ^TAprPool; TAprPool = THandle; PAprAllocator = ^TAprAllocator; TAprAllocator = THandle; TAprAbortFunc = function(retcode: Integer): Integer; stdcall; var apr_pool_create_ex: function(out newpool: PAprPool; parent: PAprPool; abort_fn: TAprAbortFunc; allocator: PAprAllocator): TAprStatus; stdcall; Also check if your provider_child_init callback should really be declared as cdecl and not stdcall. Also, some ideas since you get a null pointer access violation. According to the apr source code comment: if (as in your case) you pass it a nil allocator the allocator of the parent pool will be used. I assume that in case the parent pool is nil the allocator must not be nil. abort_fn will be called back if the pool cannot allocate memory. You're passing it nil; perhaps the pool is trying to call it because it cannot allocate memory? I don't think you can access the same pool from different threads. You probably have to create a separate pool for each thread.
{ "pile_set_name": "StackExchange" }
Q: using xilinx cores in modelsim via .do file Tool versions: Modelsim PE 10.4a student edition Xilinx ISE 14.7 I am trying to use xilinx cores from xilinxcorelib_ver and unisims_ver for simulation but I am seeing this error: Error: (vsim-3033) ../rtl/verilog/RdidTopLevel.v(72): Instantiation of 'bufg' failed. The design unit was not found. Here is my .do file: vlib ./work vmap -modelsim_quiet xilinxcorelib_ver C:/Modeltech_pe_edu_10.4a/xilinxcorelib/xilinxcorelib_ver vmap -modelsim_quiet unisims_ver C:/Modeltech_pe_edu_10.4a/xilinxcorelib/unisims_ver set top_level spi_rdid_tb vsim -novopt $top_level vsim -lib unisims_ver I am instantiating the bufg like so: BUFG bufg(.I(clkNoBuf), .O(clk)); What exactly am I doing wrong? I want to be able to map my source directory that compxlib created and include this in my designs so that I can simulate from anywhere with a simple .do file. I've looked around for the past few hours and can't seem to find anything that works. EDIT: When I run this, the GUI in modelsim has these libraries mapped with all the compiled sources, but my designs still can't see them. A: I figured out my mistake, reference the template after the explanation. For anyone wondering how to get compxlib to work with an automated script from step 1: Ensure the path to your core bin directory where compxlib.exe lives (NOTE: this is for Xilinx, but Altera/Intel might be similar) C:\Xilinx\*Tool\*version\ISE_DS\ISE\bin Once your system has reference to your bin directory, run the following from a terminal/command line. This will compile the cores for your edition of ModelSim, all architectures, and languages to your desired directory: >>> compxlib -s mti_pe -arch all -l all -w -lib all -dir c:/Modeltech_pe_edu_10.4a /xilinxcorelib from the .do/.tcl script, perform the following: # 0) Create work directory for modelsim vlib ./work # 1) map core libs vmap -modelsim_quiet xilinxcorelib_ver C:/Modeltech_pe_edu_10.4a/xilinxcorelib/xilinxcorelib_ver vmap -modelsim_quiet unisims_ver C:/Modeltech_pe_edu_10.4a/xilinxcorelib/unisims_ver # 2) Compile files in use order # vcom -93 -work work dirToSrc/file.vhd # vlog ../rtl/verilog/*.v # 3) use specific top level set top_level spi_rdid_tb # vsim -novopt $top_level # use this line instead of next if no core lib vsim -novopt -L unisims_ver work.$top_level # 4) the rest of your tb stuff for automation
{ "pile_set_name": "StackExchange" }
Q: Not able to execute the stored procedure I have table in which my date column value is saved with time also like this 2016-06-10 14:56:11.000 Now while executing my SP, I pass one parameter as date like this exec UserReportData '06-10-2016' but it is not showing any records. As it has 4 records in the table. Why? UPDATE ALTER PROCEDURE [dbo].[UserReportData] @As_ONDATE Datetime AS BEGIN DECLARE @REPORTDATE datetime DECLARE @OPENING INT SELECT * INTO #temptable FROM (SELECT DISTINCT a.CUser_id, b.User_Id,a.U_datetime as REPORTDATE, b.first_name + ' ' + b.last_name AS USERNAME, 0 OPENING, 0 TOTAL_DOCUMENT, 0 INWARD, 0 FIRST_LEVEL_PROCESSING, 0 DATA_ENTRY FROM inward_doc_tracking_trl a, user_mst b WHERE a.CUser_id = b.mkey AND a.U_datetime = CONVERT(varchar(10), @As_ONDATE, 103)) AS x DECLARE Cur_1 CURSOR FOR SELECT CUser_id, User_Id FROM #temptable OPEN Cur_1 DECLARE @CUser_id INT DECLARE @User_Id INT FETCH NEXT FROM Cur_1 INTO @CUser_id, @User_Id WHILE (@@FETCH_STATUS = 0) BEGIN SELECT @REPORTDATE FROM inward_doc_tracking_trl WHERE U_datetime = CONVERT(varchar(10), @As_ONDATE, 103) UPDATE #temptable SET REPORTDATE = @REPORTDATE WHERE CUser_id = @CUser_id AND User_Id = @User_Id FETCH NEXT FROM Cur_1 INTO @CUser_id, @User_Id END CLOSE Cur_1 DEALLOCATE Cur_1 SELECT * FROM #temptable DROP TABLE #temptable END A: You are passing in a date as a string (with implicit time being 00:00) which you are casting to be a date, still with time being 00:00, and trying to match dates with times. There won't be any results as the time doesn't match. You have to either: Cast the datetime to a date to match an exact date (not good, requires recalculating every date in the column) Change the search to look between date + '00:00' to date + '23:59' (or if you are happy, you could just add a day) Update for your where clause to take the easy option 2: where a.CUser_id = b.mkey and a.U_datetime BETWEEN CONVERT(varchar(10), @As_ONDATE, 103) AND DATEADD(day, 1, CONVERT(varchar(10), @As_ONDATE, 103))
{ "pile_set_name": "StackExchange" }
Q: jQuery explanation needed regarding this code I recently read a jQuery tutorial about best practices. I usually run all my functions from one js file called global, but the article advised not to do this. Below is the code that should be used with inline javascript, called on the page that needs the function: <script type="text/javascript> mylib.article.init(); </script> What I don't understand is the code below. The tutorial didn't go into any detail; what it is doing? var mylib = { article_page : { init : function() { // Article page specific jQuery functions. } }, traffic_light : { init : function() { // Traffic light specific jQuery functions. } } } A: Basically, you are setting up a namespace 'mylib' in which all your custom code resides. The reason you wouldn't want all global variables, is that they may be overwritten or reassigned by other included libraries, and you wouldn't even know it happened. Rather than having a variable named 'count', you would have a variable essentially named 'mylib.count', which much less likely to exist somewhere else. In the code you provided, you would init the article page by calling 'mylib.article_page.init()'. You can also do something like this : with (mylib){ article_page.init() }
{ "pile_set_name": "StackExchange" }
Q: Highstock columnrange data grouping values not consistent The highstock column range with dataGrouping enabled seems not to be computing dataAggregation correctly. The aggregated values seem to change when changing the range. March 2014 will show different values if scrolling more towards the right. Code and jsfiddle: dataGrouping: { enabled: true, approximation: function() { const indices = _.range(this.dataGroupInfo.start, this.dataGroupInfo.start + this.dataGroupInfo.length); const low = _.min(indices.map(i => this.options.data[i][1])); const high = _.max(indices.map(i => this.options.data[i][2])); return [low, high]; }, groupPixelWidth: 50 } See jsfiddle A: The columns are changed only when the navigator does not start from the beggining - and that happens because the way you defined approximation callback. dataGroupInfo contains information according to the visible points (which fall into x axis range, cropped points) in the chart, not all the points - so to have proper indices for the initial data, you need to add this.cropStart - it is the index from which points are visible. approximation: function() { const start = this.cropStart + this.dataGroupInfo.start; const stop = start + this.dataGroupInfo.length; const indices = _.range(start, stop); const low = _.min(indices.map(i => this.options.data[i][1])); const high = _.max(indices.map(i => this.options.data[i][2])); return [ low, high ]; }, example: https://jsfiddle.net/12o4e84v/7/ The same functionality can be implemented easier approximation: function(low, high) { return [ _.min(low), _.max(high) ]; } example: https://jsfiddle.net/12o4e84v/8/ Or even simpler: approximation: 'range', However, by default approximation for columns is set to range, so you do not have to do it manually. example: https://jsfiddle.net/12o4e84v/9/
{ "pile_set_name": "StackExchange" }
Q: python date from datetime How do you get just the date part from a datetime value to show in an html template. This link shows what I want with a lambda, but I don't know how to use lambdas to assign values to a variable A: This is actually an example in the jinja2 documentation; you can create a custom formatter and then just pass the datetime to your template and use the formatter to display only the date: http://jinja.pocoo.org/docs/api/#custom-filters – Wooble 22 hours ago I am adding Wooble's comment as an answer.
{ "pile_set_name": "StackExchange" }
Q: wget - download all files but not preceding folders I'm using wget to download all files from within a folder using the -r and -np options. However this also downloads the preceding folders, which I don't want. For example: wget -r -np ftp://user:[email protected]/articles/artist/images/ this downloads all files from within "images" (which is good) but then also downloads the folders articles, artist and images (which is bad). What option fixes this? A: I think what you are looking for is the --cut-dirs option. Used in conjunction with the -nH (no hostname) option, you can specify exactly which level of directory you want to appear in your local output. As an example, I have a .pkg download that I want to write to my local directory, and I don't want all of the parent tree to be included, just the subdirectories. In this case, my starting point to just get the .pkg name as the parent directory is 5 levels down: wget -np -nH --cut-dirs 5 -r http://www.myhost.org/pub/downloads/My_Drivers/OS_10_5_x/Letter_Format/driver_C123_105.pkg What you will see, then, is the name driver_C123_105.pkg in your current directory. % ls -lt | head drwxr-xr-x 12 rob rob 408 Feb 22 12:54 driver_C123_105.pkg -rw-------@ 1 rob rob 0 Feb 16 15:59 1kPSXcUj.pdf.part -rw-------@ 1 rob rob 842 Feb 3 14:47 WcUuL69s.jnlp.part [...etc...] % find driver_C123_105.pkg driver_C123_105.pkg driver_C123_105.pkg/Contents driver_C123_105.pkg/Contents/Archive.bom driver_C123_105.pkg/Contents/Archive.pax.gz driver_C123_105.pkg/Contents/index.html driver_C123_105.pkg/Contents/index.html?C=D;O=A driver_C123_105.pkg/Contents/index.html?C=D;O=D driver_C123_105.pkg/Contents/index.html?C=M;O=A driver_C123_105.pkg/Contents/index.html?C=M;O=D driver_C123_105.pkg/Contents/index.html?C=N;O=A driver_C123_105.pkg/Contents/index.html?C=N;O=D driver_C123_105.pkg/Contents/index.html?C=S;O=A driver_C123_105.pkg/Contents/index.html?C=S;O=D driver_C123_105.pkg/Contents/Info.plist driver_C123_105.pkg/Contents/PkgInfo driver_C123_105.pkg/Contents/Resources driver_C123_105.pkg/Contents/Resources/background.jpg [.....etc....] You can direct this output to go elsewhere with the -P option. A: The --no-parent-Option is what you are looking for.
{ "pile_set_name": "StackExchange" }
Q: How to compile an element in a directive with an ngModel? I'm trying to build an editable table cell however there are some conditions that determine whether it is editable or not so I can't just include an input in the template. My goal is to have the cell create an input using the same model that the cell has but it doesn't seem to work. HTML: <td editable-grid-cell ng-model="batch.amount" name="amount"></td> Directive Code: .directive('editableGridCell', function($compile) { return { link: function(scope, ele, attrs) { scope.field = attrs.ngModel; ele.append($compile('<input type="text" class="form-control" ng-model="field"/>')(scope)); } } }) Doing this results in the input being populated with 'batch.amount'. I've gotten this to work by using an isolated scope: scope: { model: '=ngModel' } ... ele.append($compile('<input type="text" class="form-control" ng-model="model"/>')(scope)); However, I need access to the parent scope because I have all my table options set in the controller so I think isolated scope won't work here. Thanks for the help! A: you can pass all the table options to you editable grid cell directive through scope scope: { model: '=ngModel', tableOptions: '=' } or if you dont want to use isolate scope then, you can create your html using attrs .directive('editableGridCell', function($compile) { return { link: function(scope, ele, attrs) { var html = '<input type="text" class="form-control" ng-model="'; html += attrs.ngModel; html += '"/>'; ele.append($compile(html)(scope)); } } })
{ "pile_set_name": "StackExchange" }
Q: What parameters does Rails expect for editing nested models? Problem After some success creating nested models from a form in Rails 4 (with the help of the Cocoon gem), I am now trying to stretch a little further - to editing those nested models after they've been created. When I attempt to update for a parent with two children - no actual changes have been made in the form, it's just been loaded and then saved straight away again - the update is not successful, I have a validation error, and the children in the newly render edit form look incorrect. Markup <%= form_for @parent do |f| %> <%= f.fields_for :children do |builder| %> <%= builder.label :some_property %> <%= builder.text_field :some_property %> <%= builder.label :some_other_property %> <%= builder.text_field :some_other_property %> <% end %> <% end %> Controller action def update @parent = Parent.find(params[:id]) if (@parent.update(parent_params)) redirect_to somewhere else flash.now[:error] = "Oops, this didn't work." render 'edit' end end def parents_params params.require(:parent). permit(:id, child_attributes: [:id, :some_property, :some_other_property, :_destroy]) end Parameters being passed to the controller --- !ruby/hash:ActionController::Parameters utf8: ✓ _method: patch authenticity_token: // blah parent: !ruby/hash:ActionController::Parameters children_attributes: !ruby/hash:ActionController::Parameters '0': !ruby/hash:ActiveSupport::HashWithIndifferentAccess some_property: FOO some_other_property: 46 _destroy: 'false' id: '8' '1': !ruby/hash:ActiveSupport::HashWithIndifferentAccess some_property: BAR some_other_property: 25 _destroy: 'false' id: '9' commit: Save action: update controller: parents id: '3' Validation failure This validation fails, and the child is claimed to not be unique. # from child.rb validates :some_property, uniqueness: true Summary This form works fine when saving the first children - even multiple children - it's when revisiting the page and trying to save again that the problem arises. Note that when the form is rendered the second tme (after the failed save), it now contains details for the second child, twice over (i.e. BAR/25) as the only two children. (I've considered some workarounds - switching to a specific model to cover the nested model and then mapping it back, for example - but I'd like to get to the bottom of why this isn't behaving as I want to improve my knowledge of the rails internals.) Thanks for any help in advance! A: I found the solution (after adding some debugging code in desperation and seeing my test suddenly pass!). For some reason, in the controller, loading the parent did not also load the existing children fully, so the new children were being incorrectly recognised. Changing the controller code to this: def update # This is the key line - note the additional .includes @parent = Parent.includes(:children).find(params[:id]) if (@parent.update(parent_params)) ... end Solved the problem.
{ "pile_set_name": "StackExchange" }
Q: Update method isn't working [DjangoRestFramework] I am trying to abstract my endpoints by using the Viewsets and for some reasons the update() method to one of the endpoints isn't saving an updated field. How do I update the fields? NB: I am testing using Postman using PUT method serializers.py: class UpdateArticleSerializer(serializers.Serializer): title = serializers.CharField(max_length=250, required=True) body = serializers.CharField() image_url = serializers.URLField() keypoint = serializers.ListField() country = CountrySerializer(read_only=True) category = CategorySerializer(read_only=True) def create(self, validated_data): return Article(**validated_data) def update(self, instance, validated_data): instance.title = validated_data.get('title', instance.title) instance.body = validated_data.get('body', instance.body) instance.image_url = validated_data.get('image_url', instance.image_url) instance.keypoint = validated_data.get('keypoint', instance.keypoint) instance.country = validated_data.get('country', instance.country) instance.category = validated_data.get('category', instance.category) instance.save() return instance views.py [update method]: def update(self, request, pk=None): article = Article.objects.get(id=pk) serializer = UpdateArticleSerializer(data=request.data) if article.author == request.user: if article.is_published != True: if serializer.is_valid(): serializer.save(author=request.user) queryset = article serializer = ArticleSerializer(queryset) return Response(jsend.success({'post':serializer.data}), status=status.HTTP_200_OK) else: return Response((jsend.error('Published post cannot be edited')), status=status.HTTP_409_CONFLICT) else: return Response((jsend.error("You are not authorized to perform this action")), status=status.HTTP_403_FORBIDDEN) A: serializer = UpdateArticleSerializer(data=request.data) You don't provide an existing instance thus serializer.save() will be routed to serializer.create() it should instead be something like: serializer = UpdateArticleSerializer(instance=self.get_object(), data=request.data)
{ "pile_set_name": "StackExchange" }
Q: How to Clear The Previous Gridview Item and refill with new adapter in android? how to clear the gridview when i request for another adapter if i use the lazy adapter here i put my code for gridview activity and lazyadapter i m use the asynctask for gridview items here i put my code for gridview Gridview Activity.java public class VisitorActivity extends Activity implements OnClickListener{ { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); new visitormiddlelistasyntask.execute(""); } public class VisitorMiddleListAsyncTask extends AsyncTask<String,ArrayList<HashMap<String, String>>,ArrayList<HashMap<String, String>>> { String city; JsonParser jparser=new JsonParser(); String visitorurl="http://digitalhoteladnetwork.com/vixxa_beta/index.php/visitors/webvisitorlist"; //String visitorurl="http://digitalhoteladnetwork.com/vixxa_beta/index.php/visitors/websearch_visitor_guide"; @Override protected ArrayList<HashMap<String, String>> doInBackground(String... params) { //For Get city Geocoder geocoder = new Geocoder(VisitorActivity.this, Locale.getDefault()); try { List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1); Log.e("Addresses","-->"+addresses); city = addresses.get(0).getSubAdminArea(); // Log.e("Cityname","--->"+city); } catch (IOException e) { e.printStackTrace(); // Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show(); } WebServiceData wsd=new WebServiceData(); String visitorstring=wsd.VisitorGuide(city, visitorurl); //Log.e("webservice visitorstring","-->"+wsd.VisitorGuide(city, visitorurl)); Log.e("webservice visitorstring","-->"+visitorstring); try { JSONObject jobject=new JSONObject(visitorstring); JSONArray jvisitorlist=jobject.getJSONArray(TAG_VISITORGUIDELIST); for(int i=0;i<jvisitorlist.length();i++) { HashMap<String, String> map=new HashMap<String, String>(); String id=jvisitorlist.getJSONObject(i).getString(TAG_VISITORGUIDEID).toString(); //Log.e("Id","-->"+id); String title=jvisitorlist.getJSONObject(i).getString(TAG_VISITORGUIDETITLE).toString(); //Log.e("Title","-->"+title); String image=jvisitorlist.getJSONObject(i).getString(TAG_VISITORGUIDEIMAGE).toString(); //Log.e("Image","-->"+image); //String show=jvisitorlist.getJSONObject(i).getString(TAG_VISITORTITLESHOW).toString(); map.put(TAG_VISITORGUIDEID,id); map.put(TAG_VISITORGUIDETITLE,title); map.put(TAG_VISITORGUIDEIMAGE, image); //map.put(TAG_VISITORTITLESHOW,show ); visitormiddle.add(map); } //Log.e("Visitor Guide List","-->"+jvisitorlist); } catch (Exception e) { e.printStackTrace(); } return visitormiddle; } protected void onPostExecute(ArrayList<HashMap<String, String>> result) { gridview=(GridView)findViewById(R.id.gridview); adapter=new LazyAdapter(VisitorActivity.this, visitormiddle); gridview.setAdapter(adapter); } } } LazyAdapter.java public class LazyAdapter extends BaseAdapter { private static final String TAG_VISITORGUIDELIST="visitorlist"; private static final String TAG_VISITORGUIDEID="visitor_guide_id"; private static final String TAG_VISITORGUIDETITLE="visitor_guide_cat_title"; private static final String TAG_VISITORGUIDEIMAGE="visitor_guide_cat_image"; //private static final String TAG_VISITORTITLESHOW="visitor_guide_cat_titleshow"; private Activity activity; private ArrayList<HashMap<String, String>> result; private static LayoutInflater inflater=null; public GridImageLoader gridimageLoader; public LazyAdapter(Activity a, ArrayList<HashMap<String, String>> r) { activity = a; result=r; inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); gridimageLoader=new GridImageLoader(activity.getApplicationContext()); } public int getCount() { return result.size(); } public Object getItem(int position) { return position; } public long getItemId(int position) { return position; } public static class ViewHolder{ public TextView text; public ImageView image; } public View getView(int position, View convertView, ViewGroup parent) { View vi=convertView; ViewHolder holder; if(convertView==null){ vi = inflater.inflate(R.layout.griditem, null); //vi = inflater.inflate(R.layout.griditem,parent,false); holder=new ViewHolder(); holder.text=(TextView)vi.findViewById(R.id.textview);; holder.image=(ImageView)vi.findViewById(R.id.imageview); vi.setTag(holder); } else holder=(ViewHolder)vi.getTag(); holder.text.setText(result.get(position).get(TAG_VISITORGUIDETITLE)); holder.image.setTag(result.get(position).get(TAG_VISITORGUIDEIMAGE)); gridimageLoader.DisplayImage(result.get(position).get(TAG_VISITORGUIDEIMAGE), activity, holder.image); return vi; } } A: You can use ArrayAdapter and then call adapter.clear() to clear the grid view and then refill it with new data. You can use same VisitorMiddleListAsyncTask to fill the data again.
{ "pile_set_name": "StackExchange" }
Q: Need my App to take pic or Upload pic and show it in another activity at all time I am totally new to java development. I am working on an App that has a profile page where it contains username, First&lastname, phone# etc(these info are saved by SharedPreference). In the same page i have pic ImageButton when clicked, it takes it to another activity where user can upload pic from gallery or take a pic. Problem 1- (Camera Activity)I am able to take a pic using the camera which also is saved in Gallery since i am using the camera app but it doesn't stay there case R.id.takepic: Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); startActivityForResult(intent, cameraData); protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) { super.onActivityResult(requestCode, resultCode, imageReturnedIntent); case cameraData: if (resultCode == RESULT_OK) { Bundle extras =imageReturnedIntent.getExtras(); bmp = (Bitmap) extras.get("data"); imagepreview.setImageBitmap(bmp); Problem 2: I am not sure how to bring the uploaded pic to another Activity(MainActivity) I would really appreciate if anyone can tell me how can i have my pic brought back to my MainActivity or have it save so i could use it in any other Activity by calling it. I have done some searches but it is really confusing for me to understand how saving images and retrieving it works, therefore not able to get it to work. Please HELP. Thanks A: On Click event Just write this code case R.id.iv_attachment_pic: CharSequence[] names = { "From Galary", "From Camera" }; new AlertDialog.Builder(context) .setTitle("Select an option") .setItems(names, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int pos) { // TODO Auto-generated method stub if (pos == 0) { Intent i = new Intent( Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); startActivityForResult(i, GET_GAL_IMG); } else { Intent i = new Intent( android.provider.MediaStore.ACTION_IMAGE_CAPTURE); startActivityForResult(i, GET_CAM_IMG); } } }) .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { } }).create().show(); break; and to get that back to main activity just use onactivity result like this @Override public void onActivityResult(int requestCode, int resultCode, Intent intent) { super.onActivityResult(requestCode, resultCode, intent); switch (requestCode) { case 2: if (resultCode == -1) { encodedImageString = null; Uri selectedImage = intent.getData(); String[] filePathColumn = { MediaStore.Images.Media.DATA }; Cursor cursor = context.getContentResolver().query( selectedImage, filePathColumn, null, null, null); cursor.moveToFirst(); int columnIndex = cursor.getColumnIndex(filePathColumn[0]); String filePath = cursor.getString(columnIndex); cursor.close(); bmp_image = BitmapFactory.decodeFile(filePath); ByteArrayOutputStream baos = new ByteArrayOutputStream(); iv_attachment.setImageBitmap(bmp_image); if (bmp_image.compress(Bitmap.CompressFormat.JPEG, 50, baos)) { byte[] image = baos.toByteArray(); encodedImageString = Base64.encodeToString(image, Base64.DEFAULT); } else { System.out.println("Compreesion returned false"); Log.d("Compress", "Compreesion returned false"); } } break; case 3: if (resultCode == -1) { encodedImageString = null; bmp_image = null; Bundle extras = intent.getExtras(); bmp_image = (Bitmap) extras.get("data"); iv_attachment.setImageBitmap(bmp_image); ByteArrayOutputStream baos = new ByteArrayOutputStream(); if (bmp_image.compress(Bitmap.CompressFormat.JPEG, 50, baos)) { byte[] image = baos.toByteArray(); encodedImageString = Base64.encodeToString(image, Base64.DEFAULT); } else { System.out.println("Compreesion returned false"); Log.d("Compress", "Compreesion returned false"); } } break; } } Here GET_GAL_IMG and GET_CAM_IMG are two variables and iv_attachment is the imageview in your main activity
{ "pile_set_name": "StackExchange" }
Q: Autohotkey - convert clipboard formatted text to plain text How to convert clipboard formatted text to plain text with Autohotkey on just a few programs only? Let say on google chrome? OnClipboardChange: if (A_EventInfo = "1") { Clipboard=%Clipboard% } return This works perfect, but how to limit it to chrome only? If I wrap with #IfWinActive don't do any limitation, just works everywhere. #IfWinActive ahk_class Chrome_WidgetWin_1 code goes here #IfWinActive A: I tried to create small separate script, and this one works for me as you described (strips off the formatting when I copy something from the Chrome browser): #SingleInstance #Persistent SetTitleMatchMode, 2 OnClipboardChange: if (A_EventInfo = 1) and (WinActive("Chrome")) { Clipboard=%Clipboard% } return You may of course use WinActive("ahk_class Chrome_WidgetWin_1") instead of WinActive("Chrome") as you did in your example, that also works.
{ "pile_set_name": "StackExchange" }
Q: MATLAB containers.Map with tuple as key I'd like to make a containers.Map object that uses a tuple, such as [4,1], as the key. However, this is not a valid key type. How can I convert this into a valid key type? My ultimate goal is to have something like a sparse cell array that I can index like a matrix but store arbitrary objects. A: I received a lot of answers as comments, so for posterity (and my own sanity) I am writing these up as actual answers. Tuple to scalar via sub2ind If you are trying to emulate the behavior of a sparse matrix with a known size, then you can convert any valid tuple into a unique linear index using sub2ind. For example, if your hypothetical sparse cell array is to be 1000 x 200 in size, then you can do: sp_cell = containers.Map('KeyType','double', 'ValueType','any'); key_converter = @(i,j) sub2ind([1000,200], i,j); sp_cell(key_converter(4,1)) = 'foo'; Tuple to string via mat2str Alternatively (and more generally), you can use mat2str to convert your tuples into strings, but then you'll lose the checking of array index bounds that sub2ind provides: sp_cell = containers.Map('KeyType','char', 'ValueType','any'); key_converter = @(tup) mat2str(tup); sp_cell(key_converter([4 1])) = 'bar' Tuple as unicode string From this answer: if each index is less than or equal to 65535, then you can convert the tuple into a string directly. key_converter = @(tup) char(tup); Hashing From this answer: You can hash the tuple into a string. md = java.security.MessageDigest.getInstance('MD5'); key_converter = @(tup) char(md.digest(tup)); The downside here is that you can't convert the map key back into a tuple. Sparse lookup table From @SamRobert's comment: you can create a sparse array of indices into a 1-D cell array. Here is a quick-and-dirty mockup of a class: classdef SparseCellArray properties (Access=protected) lookup contents end methods function self = SparseCellArray(m,n) % Constructor; takes array dimensions as [#rows, #cols] self.lookup = sparse(m,n); self.contents = {}; end function B = subsref(self, S) % Overload matrix-style indexing assert(isscalar(S) && strcmp(S.type,'()')); idx = self.lookup(S.subs{1}, S.subs{2}); assert(idx ~= 0, 'Index not found'); B = self.contents{idx}; end function newobj = subsasgn(self, S, B) % Overload matrix-style indexing assert(isscalar(S) && strcmp(S.type,'()')); idx = self.lookup(S.subs{1}, S.subs{2}); newobj = self; if (idx == 0) idx = length(self.contents) + 1; newobj.lookup(S.subs{1}, S.subs{2}) = idx; end newobj.contents{idx} = B; end end end And the usage is as follows: sp_cell = SparseCellArray(2000,100); sp_cell(4,1) = 'foo'; Downside is that it only accepts 2-D arrays (since sparse only produces 2-D arrays). Note also that any of these solutions can be wrapped in a class like this.
{ "pile_set_name": "StackExchange" }
Q: UWP MasterDetail control UserControl dependancy property I'm working on a master detail page created by the Windows Template Studio. I'm trying to have a comboBox in the userControl that defines the DetailsTemplate, which loads its values from a list in the page. Here's the code: ArticlesPage.xaml <Page x:Class="Estimates.Views.ArticlesPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" Style="{StaticResource PageStyle}" xmlns:controls="using:Microsoft.Toolkit.Uwp.UI.Controls" xmlns:model="using:Estimates.Models" xmlns:views="using:Estimates.Views" xmlns:fcu ="http://schemas.microsoft.com/winfx/2006/xaml/presentation?IsApiContractPresent(Windows.Foundation.UniversalApiContract,5)" xmlns:cu ="http://schemas.microsoft.com/winfx/2006/xaml/presentation?IsApiContractNotPresent(Windows.Foundation.UniversalApiContract,5)" mc:Ignorable="d"> <Page.Transitions> <TransitionCollection> <NavigationThemeTransition /> </TransitionCollection> </Page.Transitions> <Page.Resources> <DataTemplate x:Key="ItemTemplate" x:DataType="model:Article"> <Grid Height="64" Padding="0,8"> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto"/> <ColumnDefinition Width="*"/> </Grid.ColumnDefinitions> <StackPanel Grid.Column="1" Margin="12,0,0,0" VerticalAlignment="Center"> <TextBlock Text="{x:Bind Description, Mode=TwoWay}" Style="{ThemeResource ListTitleStyle}"/> </StackPanel> </Grid> </DataTemplate> <DataTemplate x:Key="DetailsTemplate" x:DataType="views:ArticlesPage"> <views:ArticlesDetailControl MasterMenuItem="{Binding}" MeasureUnits="{x:Bind MeasureUnits}" /> </DataTemplate> <DataTemplate x:Key="NoSelectionContentTemplate"> <TextBlock x:Uid="Articles_NoSelection" Style="{StaticResource ListNoSelectionTextStyle}" /> </DataTemplate> </Page.Resources> <Grid> <Grid.RowDefinitions> <RowDefinition x:Name="TitleRow" Height="Auto"/> <RowDefinition Height="Auto"/> <RowDefinition Height="Auto"/> </Grid.RowDefinitions> <TextBlock x:Uid="Articles_Title" x:Name="TitlePage" Margin="12,0,12,7" Style="{StaticResource PageTitleStyle}" /> <controls:MasterDetailsView Grid.Row="1" x:Name="MasterDetailsViewControl" ItemsSource="{x:Bind Items}" SelectedItem="{x:Bind Selected, Mode=TwoWay}" ItemTemplate="{StaticResource ItemTemplate}" NoSelectionContentTemplate="{StaticResource NoSelectionContentTemplate}" BorderBrush="Transparent" DetailsTemplate="{StaticResource DetailsTemplate}" > </controls:MasterDetailsView> <Grid VerticalAlignment="Bottom" HorizontalAlignment="Right" Padding="0,15,0,0" Grid.Row="2"> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto" /> <ColumnDefinition Width="Auto" /> <ColumnDefinition Width="Auto" /> </Grid.ColumnDefinitions> <Button x:Uid="AddButton" Grid.Column="0" Margin="5" Click="AddButton"/> <Button x:Uid="SaveButton" Grid.Column="1" Margin="5" Click="SaveButton"/> <Button x:Uid="DeleteButton" Grid.Column="2" Margin="5" Click="DeleteButton"/> </Grid> <!-- Adaptive triggers --> <VisualStateManager.VisualStateGroups> <VisualStateGroup x:Name="WindowStates"> <VisualState x:Name="WideState"> <VisualState.StateTriggers> <AdaptiveTrigger MinWindowWidth="640"/> </VisualState.StateTriggers> </VisualState> <VisualState x:Name="NarrowState"> <VisualState.StateTriggers> <AdaptiveTrigger MinWindowWidth="0"/> </VisualState.StateTriggers> <VisualState.Setters> <Setter Target="TitlePage.Margin" cu:Value="60,0,12,7" fcu:Value="12,0,12,7"/> </VisualState.Setters> </VisualState> </VisualStateGroup> </VisualStateManager.VisualStateGroups> </Grid> ArticlesPage.xaml.cs public sealed partial class ArticlesPage : Page, INotifyPropertyChanged { private Article _selected; private ObservableCollection<MeasureUnit> _measureUnits; private IRepositoryService _repositoryService { get; set; } public Article Selected { get { return _selected; } set { Set(ref _selected, value); } } public ObservableCollection<MeasureUnit> MeasureUnits { get { return _measureUnits; } set { Set(ref _measureUnits, value);} } public ObservableCollection<Article> Items { get; private set; } = new ObservableCollection<Article>(); public ArticlesPage() { InitializeComponent(); Loaded += ArticlesPage_Loaded; _repositoryService = new RepositoryService(); } private void ArticlesPage_Loaded(object sender, RoutedEventArgs e) { Items.Clear(); ArticledDetailControl.xaml <UserControl x:Class="Estimates.Views.ArticlesDetailControl" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:model="using:Estimates.Models" Background="{ThemeResource ApplicationPageBackgroundThemeBrush}" mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="400"> <ScrollViewer Name="ForegroundElement" VerticalScrollMode="Enabled" HorizontalAlignment="Stretch" Padding="12,0"> <StackPanel HorizontalAlignment="Stretch"> <StackPanel Orientation="Horizontal" HorizontalAlignment="Stretch" Margin="0,8,0,0"> <TextBlock Margin="12,0,0,0" Text="{x:Bind MasterMenuItem.Description, Mode=TwoWay}" Style="{StaticResource SubheaderTextBlockStyle}" /> </StackPanel> <StackPanel Name="block" Padding="0,15,0,0"> <TextBox x:Uid="Description" Text="{x:Bind MasterMenuItem.Description, Mode=TwoWay}" /> <TextBox x:Uid="Notes" Text="{x:Bind MasterMenuItem.Notes, Mode=TwoWay}" Margin="0,6,0,0"/> <Grid Margin="0,6,0,0"> <Grid.ColumnDefinitions> <ColumnDefinition Width="0.33*" /> <ColumnDefinition Width="0.33*" /> <ColumnDefinition Width="0.33*" /> </Grid.ColumnDefinitions> <ComboBox x:Uid="MeasureUnits" x:Name="MeasureUnitsCB" ItemsSource="{x:Bind MeasureUnits}" Grid.Column="0"> <ComboBox.ItemTemplate> <DataTemplate x:DataType="model:MeasureUnit"> <TextBlock Text="{x:Bind Description}"/> </DataTemplate> </ComboBox.ItemTemplate> </ComboBox> <TextBox x:Uid="Price" Text="{x:Bind MasterMenuItem.Price, Mode=TwoWay}" Grid.Column="2" /> </Grid> </StackPanel> </StackPanel> </ScrollViewer> ArticlesDetailControl.xaml.cs public sealed partial class ArticlesDetailControl : UserControl { public Article MasterMenuItem { get { return GetValue(MasterMenuItemProperty) as Article; } set { SetValue(MasterMenuItemProperty, value); } } public IEnumerable<MeasureUnit> MeasureUnits { get { return GetValue(MeasureUnitsProperty) as IEnumerable<MeasureUnit>; } set { SetValue(MeasureUnitsProperty, value); } } public static readonly DependencyProperty MasterMenuItemProperty = DependencyProperty.Register("MasterMenuItem", typeof(Article), typeof(ArticlesDetailControl), new PropertyMetadata(null, OnMasterMenuItemPropertyChanged)); public static readonly DependencyProperty MeasureUnitsProperty = DependencyProperty.Register("MeasureUnits", typeof(IEnumerable<MeasureUnit>), typeof(ArticlesDetailControl), new PropertyMetadata(null, OnMeasureUnitsPropertyChanged)); public ArticlesDetailControl() { InitializeComponent(); } private static void OnMasterMenuItemPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var control = d as ArticlesDetailControl; control.ForegroundElement.ChangeView(0, 0, 1); } private static void OnMeasureUnitsPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { Debug.WriteLine("PD"); } } So, the question is: How MasterMenuItem is populated? And why my property MeasureUnits it's not populated in the UserControl? Edit: As suggested by TheZapper in the accepted answer, here's the implementation of OnMenuMasterItemPropertyChanged: private static void OnMasterMenuItemPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var control = d as ArticlesDetailControl; control.ForegroundElement.ChangeView(0, 0, 1); if (control.MasterMenuItem.MeasureUnit != null) { control.MeasureUnitsCB.SelectedItem = control.MeasureUnits.First(s => s.Id == control.MasterMenuItem.MeasureUnit.Id); } if (control.MasterMenuItem.VatCode != null) { control.VatCodesCB.SelectedItem = control.VatCodes.First(s => s.Id == control.MasterMenuItem.VatCode.Id); } } I load the lists in the constructor of the UserControl. A: I guess your problem results from binding to MasterMenuItemProperty in your UserControl Maybe you could add DependencyProperties as Notes, Description in your user control and define your Template like this <DataTemplate x:Key="DetailsTemplate" x:DataType="views:ArticlesPage"> <views:ArticlesDetailControl Notes="{x:Bind Notes}" MeasureUnits="{x:Bind MeasureUnits}" /> </DataTemplate> or you could try to update your bindings in the Changed-Event. private static void OnMasterMenuItemPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var control = d as ArticlesDetailControl; control.ForegroundElement.ChangeView(0, 0, 1); *** Update Binding *** }
{ "pile_set_name": "StackExchange" }
Q: Undefined index when passing variable from jquery to php I'm trying to pass a variable from an html file, using jquery and ajax to a php file, where I want to process it. I have two test files: ajax.html <html> <head> <title>ajax</title> <script type="text/javascript" src="jquery.js"></script> <link href="ajax.css" rel="stylesheet" type="text/css" /> <script type="text/javascript"> $(document).ready(function () { $("#call_back").click(function () { $.post( "ajax.php", { value: $("#input_text").val() }, function (data) { $("#response_text").val(data); } ); }); }); </script> </head> <body> <div id="wrapper"> <h3>Ajax</h3> <div class="entry-wrapper"> <h4>Data to send to the server</h4> <input type="text" size="50" id="input_text" /> <input type="button" value="Ajax Callback" id="call_back" /> </div> <div id="response_wrapper"> <textarea id="response_text"></textarea> </div> </div> </body> </html> and ajax.php <?php $value = $_POST['value']; echo "Returned from the server: $value"; ?> The html works fine. If I enter a value in the text field, it's passed to the php file, processed and sent back to be displayed in the textarea. I've looked in firebug and the post tag in the console shows the values that I enter. The problem is that I want to be able to use the variable in the php file, for arithmetic operations or running an sql query with it, but it shows up as undefined index when I open the php file. I've looked through multiple threads on passing variables from jquery to php but still found no answer. I have no idea what the problem is. Suggestions are much appreciated. Thanks. A: If I understand you question correctly, you need to define the variable in your url. Example: http://yoursite.com/ajax.php?value=yourdata This way when you open the file you are defining the value which is all you are doing with your ajax request. If this is not what you are trying to accomplish, try to rephrase your question. Revised after 1st comment: <?php if(isset($_POST['value'])){ //do whatever in here dowhatever(); } function dowhatever() { $value = $_POST['value']; echo "Returned from the server: $value"; if(value == 'data') { //run query }//end if } ?>
{ "pile_set_name": "StackExchange" }
Q: How to get the keyword from category name in C# TBB? I am trying to fetch the keyword present in the Category using C# TBB to use the output in following DWT TBB. For that I have a component with the Category field. I am trying to write the following C# TBB to get the keyword value. <%@Import NameSpace="Tridion.ContentManager.Templating.Expression" %> try { string className = package.GetValue("Component.Fields.title"); KeywordField keywordField = package.GetKeywordByTitle(className); package.PushItem("Class", package.CreateStringItem(ContentType.Text, keywordField.Value.Key)); } catch(TemplatingException ex) { log.Debug("Exception is " + ex.Message); } But I am getting following compilation error. Could not compile template because of: error CS0246: The type or namespace name 'KeywordField' could not be found (are you missing a using directive or an assembly reference?) error CS1061: 'Tridion.ContentManager.Templating.Package' does not contain a definition for 'GetKeywordByTitle' and no extension method 'GetKeywordByTitle' accepting a first argument of type 'Tridion.ContentManager.Templating.Package' could be found (are you missing a using directive or an assembly reference?) Please suggest me how can I achieve it? Thanks in advance A: Af Jeremy suggested you should study API, I am providing you example of getting keywords from categories. Hope it may help Include files using Tridion.ContentManager; using Tridion.ContentManager.CommunicationManagement; using Tridion.ContentManager.Templating.Assembly; using Tridion.ContentManager.ContentManagement; using Tridion.ContentManager.ContentManagement.Fields; using Tridion.ContentManager.Templating; Sample Code, You can use Key and Value from loop here as per your requirement. string catID = package.GetByName("CategoryID").GetAsString(); TcmUri catURI = new TcmUri(int.Parse(catID), ItemType.Category, PubId); var theCategory = m_Engine.GetObject(catURI) as Category; catKeywords = GetCatKeywords(theCategory); string strSelect = "<select>"; foreach (Keyword k in catKeywords) { k.Key // Keyowrd key k.Value // KEyword Value } //keyword list private IList<Keyword> GetCatKeywords(Category category) { IList<Keyword> keywords; if (!Utilities.IsNull(category)) { Filter filter = new Filter(); filter.BaseColumns = ListBaseColumns.IdAndTitle; keywords = category.GetKeywords(filter); if (!Utilities.IsNull(keywords)) { return keywords; } } return null; } A: The error message is absolutely clear what the problem is - there's no reference to the KeywordField class. You need to import the relevant namespace: <%@Import NameSpace="Tridion.ContentManager.ContentManagement.Fields" %> Also absolutely clear is the fact that the Package object doesn't have a method called GetKeywordByTitle. There is a GetByName method, but this is for retrieving a named item from the Package, not for getting an object from the respository. Tridion.ContentManager.ContentManagement.Category does have a GetKeywordByTitle method, but to use this you will have to get the category first, which will likely mean having to know the URI of the category. Perhaps you need to study the API docs some more?
{ "pile_set_name": "StackExchange" }
Q: Prefix Expression evaluating incorrectly - Java private class InputListener implements ActionListener { public void actionPerformed(ActionEvent e) { // Create an integer and character stack Stack<Integer> operandStack = new Stack<Integer>(); Stack<Character> operatorStack = new Stack<Character>(); // User input in input text field String input = inputTextField.getText(); // Create string tokenizer containing string input StringTokenizer strToken = new StringTokenizer(input); // Loop while there are tokens while (strToken.hasMoreTokens()) { String i = strToken.nextToken(); int operand; char operator; try { operand = Integer.parseInt(i); operandStack.push(operand); } catch (NumberFormatException nfe) { operator = i.charAt(0); operatorStack.push(operator); } } // Loop until there is only one item left in the // operandStack. This one item left is the result while(operandStack.size() > 1) { // Perform the operations on the stack // and push the result back onto the operandStack operandStack.push(operate(operandStack.pop(), operandStack.pop(), operatorStack.pop())); } // Display the result as a string in the result text field resultTextField.setText(Integer.toString(operandStack.peek())); } // Sum and product computed public int operate(Integer operand1, Integer operand2, char operator) { switch(operator) { case '*': return operand2 * operand1; case '/': return operand2 / operand1; case '%': return operand2 % operand1; case '+': return operand2 + operand1; case '-': return operand2 - operand1; default: throw new IllegalStateException("Unknown operator " + operator + " "); } } } The prefix expression code provided is incorrectly evaluating expressions with more than one operator. The expression: * + 16 4 + 3 1 should evaluate to 80 = ((16 + 4) * (3 + 1)), but instead it evaluates to 128, which I think is evaluating as: ((16 + 4) * (3 + 1) + (16 * 3)). How do I edit the code to correct this problem? Thank you for your help. A: In prefix evaluation,Important thing to remember is operand 1= pop(); operand 2= pop(); and say the operator is - The value that is pushed is operand 1 - operand 2 and not operand 2 - operand 1 But something else is causing * + 16 4 + 3 1 to evaluate to 128. I used the following algo for evaluating in java and it works fine 1.Take the prefix expression as a string in a variable with characters separated by single space. 2.Traverse the string from index length-1 to 0 3.If its a number, perform push ,and if its a multidigit number,first obtain the full number and then push it 4.If its an operator then simply do the thing which i mentioned in beginning of the answer. It is a simple code. import java.io.*; import java.util.*; class PREFIXEVAL { public static void main(String []args)throws IOException { String p,n="";StringBuffer b;int i,op1,op2;char c;Stack<Integer> s=new Stack<Integer>(); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("enter the prefix expression separated by spaces"); p=br.readLine(); i=p.length()-1; while(i>=0) { c=p.charAt(i); if(c>=48&&c<=57) n=n+c; else if(c==' '&&!n.equals("")) {/*handles both single and multidigit numbers*/ b=new StringBuffer(n);b.reverse();n=b.toString(); s.push(Integer.parseInt(n));n=""; } else { if(c=='+') { op1=s.pop(); op2=s.pop(); s.push(op1+op2); } else if(c=='-') { op1=s.pop(); op2=s.pop(); s.push(op1-op2); } else if(c=='*') { op1=s.pop(); op2=s.pop(); s.push(op1*op2); } else if(c=='%') { op1=s.pop(); op2=s.pop(); s.push(op1%op2); } else if(c=='/') { op1=s.pop(); op2=s.pop(); s.push(op1/op2); } } i--; } System.out.println("the prefix expression evaluates to "+s.peek()); } }
{ "pile_set_name": "StackExchange" }
Q: Facebook PHP SDK vs Third party Python SDK I need Facebook API for my web app. Official Facebook only provide API in Android, IOS, JavaScript, PHP etc but not in Python. There are third party SDK's available for Python. What should i use PHP SDK (which is official by Facebook ) or Third party Python SDK. I cannot compromise on scalability of app. Will third party python API be slower then PHP API in case of Facebook data fetching. A: I use Django-facebook in my django projects. I recommend its use because it's an active github project and you can also contribute to it whenever you want/need.
{ "pile_set_name": "StackExchange" }
Q: CSS Auto hide elements after 5 seconds Is it possible to hide element 5 seconds after the page load? I know there is a jQuery solution. I want to do exactly same thing, but hoping to get the same result with CSS transition. Any innovative idea? Or am I asking beyond the limit of css transition/animation? A: YES! But you can't do it in the way you may immediately think, because you cant animate or create a transition around the properties you'd otherwise rely on (e.g. display, or changing dimensions and setting to overflow:hidden) in order to correctly hide the element and prevent it from taking up visible space. Therefore, create an animation for the elements in question, and simply toggle visibility:hidden; after 5 seconds, whilst also setting height and width to zero to prevent the element from still occupying space in the DOM flow. FIDDLE CSS html, body { height:100%; width:100%; margin:0; padding:0; } #hideMe { -moz-animation: cssAnimation 0s ease-in 5s forwards; /* Firefox */ -webkit-animation: cssAnimation 0s ease-in 5s forwards; /* Safari and Chrome */ -o-animation: cssAnimation 0s ease-in 5s forwards; /* Opera */ animation: cssAnimation 0s ease-in 5s forwards; -webkit-animation-fill-mode: forwards; animation-fill-mode: forwards; } @keyframes cssAnimation { to { width:0; height:0; overflow:hidden; } } @-webkit-keyframes cssAnimation { to { width:0; height:0; visibility:hidden; } } HTML <div id='hideMe'>Wait for it...</div> A: based from the answer of @SW4, you could also add a little animation at the end. body > div{ border:1px solid grey; } html, body, #container { height:100%; width:100%; margin:0; padding:0; } #container { overflow:hidden; position:relative; } #hideMe { -webkit-animation: cssAnimation 5s forwards; animation: cssAnimation 5s forwards; } @keyframes cssAnimation { 0% {opacity: 1;} 90% {opacity: 1;} 100% {opacity: 0;} } @-webkit-keyframes cssAnimation { 0% {opacity: 1;} 90% {opacity: 1;} 100% {opacity: 0;} } <div> <div id='container'> <div id='hideMe'>Wait for it...</div> </div> </div> Making the remaining 0.5 seconds to animate the opacity attribute. Just make sure to do the math if you're changing the length, in this case, 90% of 5 seconds leaves us 0.5 seconds to animate the opacity. A: Of course you can, just use setTimeout to change a class or something to trigger the transition. HTML: <p id="aap">OHAI!</p> CSS: p { opacity:1; transition:opacity 500ms; } p.waa { opacity:0; } JS to run on load or DOMContentReady: setTimeout(function(){ document.getElementById('aap').className = 'waa'; }, 5000); Example fiddle here.
{ "pile_set_name": "StackExchange" }
Q: Static vs dynamic type In Swift we can determine type of variable by type(of:) and Mirror(reflecting:).subjectType. Documentation about Mirror.subjectType says: The static type of the subject being reflected. This type may differ from the subject’s dynamic type when self is the superclassMirror of another mirror. I did not find docs for type(of:) but the proposal says that it's replacement for .dynamicType property. So we have dynamic and static types. What the difference between them and in what circumstances does it show up? P.S. I'm asking because I'm having strange issue. This code: protocol A: class { } class B: A { } let b = B() class C<T> { func test(value: T) { print("\(type(of: value))") print("\(Mirror(reflecting: value).subjectType)") } } func test(a: A) { print("\(type(of: a))") print("\(Mirror(reflecting: a).subjectType)") } C<A>().test(value: b) test(a: b) when running on iPhone from Xcode using Debug configuration gives output: B B B B and running using Release configuration (switch to it under Product -> Scheme -> Edit -> Build Configuration -> Release) gives: A B B B which seams to be a bug in Swift compiler. UPDATE I opened JIRA ticket. A: The issue should be fixed in master now and in next (after 3.0.2) Swift version soon. Thanks to Joe Groff.
{ "pile_set_name": "StackExchange" }
Q: Returning keys from key-value pairs based on maximum value in apache spark I'm new to apache spark and I need some advice. I have an RDD with [String, Int] type. RDD values are like that: ("A,x",3) ("A,y",4) ("A,z",1) ("B,y",2) ("C,w",5) ("C,y",2) ("E,x",1) ("E,z",3) What I want to accomplish is to get an RDD like that (String,String): ("A","y") //among the key's that contains A, (A,y) has the max value ("B","y") //among the key's that contains B, (B,y) has the max value ("C","w") //among the key's that contains C, (C,w) has the max value ("E","z") //among the key's that contains E, (E,z) has the max value I tried a loop concept (by using a counter) in flatMap but it doesn't work. Is there an easy way to do this? A: Just reshape and reduceByKey: val pattern = "^(.*?),(.*?)$".r rdd // Split key into parts .flatMap{ case (pattern(x, y), z) => Some((x, (y, z))) } // Reduce by first part of the key .reduceByKey( (a, b) => if (a._2 > b._2) a else b ) // Go back to the original shape .map { case (x, (y, z)) => (s"$x,$y", z) }
{ "pile_set_name": "StackExchange" }
Q: How are passive houses made in very hot regions (like Saudi Arabia)? I think, here is the main problem the difference between the internal and the external temperature. For example, in Saudi Arabia, in 50 C, a passive house needed probably much sophisticated planning as in Paris. Compared to the traditional cooling systems, in the second case is enough only to get a cooling system with bigger power. I think, they are much more scalable. Is it anyways possible? A: A yahkchal is an example of a type of passively cooled building in Iran They utilise a combination of passive evaporative cooling and thick thermally insulating walls in order to keep the interior temperatures low enough. First, wind is directed into underground aquifers known as qanat. They are then cooled due to the low humidity desert air causing water to evaporate. The cooled air then flows through the interior of the yakhchal, cooling the interior. The thick insulating walls (filled with earth and various insulating materials such as straw and feathers) help to insulate the cool interior from the hot exterior, therefore maintaining a low temperature inside the yakhchal. A: Insulation, shade, the use of low thermal conductivity materials and utilising any cool breeze at any time of the day are going to be key to passively cooling buildings in a hot climate. Different solutions will be more applicable to houses than non residential buildings. The other thing to consider is whether the climate hot and dry or hot and humid. In hot dry regions of Australia passive cooling measures used until the mid 20th Century included thick exterior walls, high ceilings, verandas, double roofs and where double roofs weren't used roof ventilators. The verandas and double roofs off shade. In the hot humid parts of Australia houses were built on stilts, approximately 2m to 3m high. This continued until the late 1970s in Darwin. Such houses were also built to encourage airflow inside by have louvred internal walls and sometimes short height internal walls so the rooms looked like cubicles in modern day offices. http://melbourneblogger.blogspot.com.au/2010/01/traditional-queenslander-house.html https://en.wikipedia.org/wiki/Queenslander_%28architecture%29 http://www.territorystories.nt.gov.au/handle/10070/19572 One thing that is sometimes overlooked in the passive cooling of buildings is the used green foliage gardens to offer shade and to reduce the amount of radiated and reflected heat reaching buildings. A: Diurnal swings, i.e. temperature differences between day and night, are also an important consideration in hot climates. If the temperature at night drops to something acceptable, you can use night purge to cool a thermal mass (e.g. concrete slabs or walls, phase change materials if you'd like to get fancy). This works well together with a well insulated envelop. In essence what @MarchHo talked about. If on the other hand temperatures are high 24/7 (the tropics come to mind), you would avoid using thermal mass as it will stabilise the high temperatures and make it more difficult to cool down the building by other means. Your main source of passive cooling are breezes. Insulation to the roof and extensive shading will be important. If possible, the floor could be raised to allow breezes extracting heat from both sides. In addition to cooling loads, dehumidifications loads will be significant and are hard to deal with passively. All this is based on common rules of thumb; there might be some smart design solutions that achieve comfort in different ways. Alternatively you can go underground as for example in Coober Pedy. Find some images here.
{ "pile_set_name": "StackExchange" }
Q: Transparent Status Bar Android 4.3 In the 'new' Android Version 4.3 there is a new feature. The status Bar on the top of the screen is transparent in the launcher (I'm using Samsung TouchWiz on Galaxy S3) and in some other Apps too I think (looks a little bit like the iOS 7 style). Can you tell me how I can make the Status Bar transparent (or colored) in my own App (Eclipse, Java)? A: Theme.Holo.NoActionBar.TranslucentDecor Theme.Holo.Light.NoActionBar.TranslucentDecor Based on the best answer here: How to make the navigation bar transparent
{ "pile_set_name": "StackExchange" }
Q: With double-checked locking, does a put to a volatile ConcurrentHashMap have happens-before guarantee? So far, I have used double-checked locking as follows: class Example { static Object o; volatile static boolean setupDone; private Example() { /* private constructor */ } getInstance() { if(!setupDone) { synchronized(Example.class) { if(/*still*/ !setupDone) { o = new String("typically a more complicated operation"); setupDone = true; } } } return o; } }// end of class Now, because we have groups of threads that all share this class, we changed the boolean to a ConcurrentHashMap as follows: class Example { static ConcurrentHashMap<String, Object> o = new ConcurrentHashMap<String, Object>(); static volatile ConcurrentHashMap<String, Boolean> setupsDone = new ConcurrentHashMap<String, Boolean>(); private Example() { /* private constructor */ } getInstance(String groupId) { if (!setupsDone.containsKey(groupId)) { setupsDone.put(groupId, false); } if(!setupsDone.get(groupId)) { synchronized(Example.class) { if(/*still*/ !setupsDone.get(groupId)) { o.put(groupId, new String("typically a more complicated operation")); setupsDone.put(groupId, true); // will this still maintain happens-before? } } } return o.get(groupId); } }// end of class My question now is: If I declare a standard Object as volatile, I will only get a happens-before relationship established when I read or write its reference. Therefore writing an element within that Object (if it is e.g. a standard HashMap, performing a put() operation on it) will not establish such a relationship. Is that correct? (What about reading an element; wouldn't that require to read the reference as well and thus establish the relationship?) Now, with using a volatile ConcurrentHashMap, will writing an element to it establish the happens-before relationship, i.e. will the above still work? Update: The reason for this question and why double-checked locking is important: What we actually set up (instead of an Object) is a MultiThreadedHttpConnectionManager, to which we pass some settings, and which we then pass into an HttpClient, that we set up, too, and that we return. We have up to 10 groups of up to 100 threads each, and we use double-checked locking as we don't want to block each of them whenever they need to acquire their group's HttpClient, as the whole setup will be used to help with performance testing. Because of an awkward design and an odd platform we run this on we cannot just pass objects in from outside, so we hope to somehow make this setup work. (I realise the reason for the question is a bit specific, but I hope the question itself is interesting enough: Is there a way to get that ConcurrentHashMap to use "volatile behaviour", i.e. establish a happens-before relationship, as the volatile boolean did, when performing a put() on the ConcurrentHashMap? ;) A: Yes, it is correct. volatile protects only that object reference, but nothing else. No, putting an element to a volatile HashMap will not create a happens-before relationship, not even with a ConcurrentHashMap. Actually ConcurrentHashMap does not hold lock for read operations (e.g. containsKey()). See ConcurrentHashMap Javadoc. Update: Reflecting your updated question: you have to synchronize on the object you put into the CHM. I recommend to use a container object instead of directly storing the Object in the map: public class ObjectContainer { volatile boolean isSetupDone = false; Object o; } static ConcurrentHashMap<String, ObjectContainer> containers = new ConcurrentHashMap<String, ObjectContainer>(); public Object getInstance(String groupId) { ObjectContainer oc = containers.get(groupId); if (oc == null) { // it's enough to sync on the map, don't need the whole class synchronized(containers) { // double-check not to overwrite the created object if (!containers.containsKey(groupId)) oc = new ObjectContainer(); containers.put(groupId, oc); } else { // if another thread already created, then use that oc = containers.get(groupId); } } // leave the class-level sync block } // here we have a valid ObjectContainer, but may not have been initialized // same doublechecking for object initialization if(!oc.isSetupDone) { // now syncing on the ObjectContainer only synchronized(oc) { if(!oc.isSetupDone) { oc.o = new String("typically a more complicated operation")); oc.isSetupDone = true; } } } return oc.o; } Note, that at creation, at most one thread may create ObjectContainer. But at initialization each groups may be initialized in parallel (but at most 1 thread per group). It may also happen that Thread T1 will create the ObjectContainer, but Thread T2 will initialize it. Yes, it is worth to keep the ConcurrentHashMap, because the map reads and writes will happen at the same time. But volatile is not required, since the map object itself will not change. The sad thing is that the double-check does not always work, since the compiler may create a bytecode where it is reusing the result of containers.get(groupId) (that's not the case with the volatile isSetupDone). That's why I had to use containsKey for the double-checking.
{ "pile_set_name": "StackExchange" }
Q: Multiple If Statements VBA I'm very new to VBA and SQL, and I'm currently building a table to be uploaded to SQL onto Excel and using VBA. I want to essentially say if column I(Check Market) or J(Check m2) have a value that says #NA then go no further and don't carry out the upload or the rest of the code. I think one of the problems might be I already have an IF loop - which is successful and has no errors associated with it. This is my code so far 'Where Marked sht.Cells(Row,15) = "x" 'FIRST IF LOOP If sht.Cells(lRow, 15) = "X" Then 'If I or J columns say #N/A then DO NOT continue If IsError(sht.Cells(lRow, 9).Value) Then MsgBox "Error in Column 'Check Market'" If IsError(sht.Cells(lRow, 10).Value) Then MsgBox "Error in Column 'Check m2'" ''''At the moment it is the above part that isn't successfully running, it notifies the user of an error but doesn't stop the process. 'Change blank spaces to be Null ******* sSQL = *******Main part of code goes here****** 'execute queries ******** 'Put back all the 'null' values to blank ''''' End If 'END OF IF X LOOP A: I'm not clear if there's a possibility that both columns might have an error but I've provided for that just in case. 'If I or J say #N/A then dont proceed with upload. If iserror(sht.Cells(lRow, 9).value) and iserror(sht.Cells(lRow, 10).value) Then MsgBox "Errors in both Columns" ElseIf iserror(sht.Cells(lRow, 9).value) Then MsgBox "Error in Column 'Check Market'" ElseIf iserror(sht.Cells(lRow, 10).value) Then MsgBox "Error in Column 'Check KPI'" Else: 'Continue End if
{ "pile_set_name": "StackExchange" }
Q: Can I change my Podcast name without loosing my subscribers in iTunes? I have a Podcast. I herd that if I change the Title of it I might loose my subscribers. Is there a way to change my Podcast Title without loosing my subscribers in iTunes? A: Making a change to the title tag within your podcast's RSS feed will update the podcast title within iTunes, without losing subscribers. It may take a day or two for such a change take effect within iTunes. Note: The main concern is that making a title change to a podcast where the feed is created for you automatically could potentially change the url for the feed which will stop the podcast from updating [...and an 'easy fix' for that could be resubmitting your podcast, which would lose your subscribers!]. So http://example.com/oldTitle.rss might become http://example.com/newTitle.rss. If needed, it's possible to update the feed URL within iTunes, without resubmitting your podcast or losing subscribers, as described by Apple in the 'Changing Your RSS Podcast Feed URL' section of their podcast specs: You can move your podcast feed from one location to another. To avoid losing subscribers, you must announce the change directly to all users who are subscribed to your feed. To do so, you should: – Use the <itunes:new-feed-url> tag described in the iTunes RSS Tags section below. – Set your web server to return an HTTP 301 redirect response when receiving a request for the old feed. This will update the iTunes Store with the new feed URL and your subscribers will continue to receive new episodes automatically. Be sure to maintain the <itunes:new-feed-url> tag and the HTTP 301 redirect response for at least 4 weeks to ensure that most subscribers have attempted to download your most recent episode and have thereby received the new URL.
{ "pile_set_name": "StackExchange" }
Q: Cheapest way to index a large dataset on linux (preferably with sphinx) I have a database with 150 million products, I would like index these using sphinx but only have ~2 GB of RAM, is there any feasible way to index all of this data using sphinx but staying under 2 GBs? I only need to index Product name, Product description, and brand. Although I do have several attributes, but those wouldnt need to be searchable. A: Change ondisk_dict http://sphinxsearch.com/docs/current.html#conf-ondisk-dict That way only a small amount of data is loaded. Sphinx shouldnt need much memory at all. As you using attributes, docinfo, could be used to control them http://sphinxsearch.com/docs/current.html#conf-docinfo Also reducing max_matches via the setLimit function should also reduce runtime memory usage.
{ "pile_set_name": "StackExchange" }
Q: Rails 4 Devise, Pundit, Join Table ActionView::Template::Error (undefined method `task_definition_path' for #<#:0x6919b2b2>): Here is my use case: I have one user model with Devise for AuthN and I am using Pundit for AuthZ. I restrict access to the main application through a subdomain constraint. I have some pages that are for end users (will be a different LandF at some point) and I have administrative pages etc. Common story you know the drill. I am using a has_and_belongs_to_many utilizing a join table with :id's I have my controllers, view directories and migrations named as plurals, my models as singular. Example: TaskDefinition => Model, TaskDefinitions => Controller and Tables. The default routes are generated and i have provided the content. I am using partials in the view directories and this is very new issue since a port from Ruby to JRuby. Stack Trace: ActionView::Template::Error (undefined method `task_definition_path' for #<#<Class:0x37682f95>:0x6919b2b2>): 10: <div class="col-md-10"> 11: <div class="panel-body"> 12: <div class="form"> 13: <%= bootstrap_form_for @task do |f| %> 14: <div class="form-group"> 15: <%= render '/admin/task_definitions/errors' %> 16: </div> app/views/admin/task_definitions/edit.html.erb:13:in`_app_views_admin_task_definitions_edit_html_erb__1276994696_33458' Migrations: class CreateTaskDefinitions < ActiveRecord::Migration def change create_table :task_definitions do |t| # foreign key t.integer :organization_id # attributes .... t.timestamps end # index add_index :task_definitions, :name, unique: true end end class CreateOrganizations < ActiveRecord::Migration def change create_table :organizations do |t| # for the relationship between parent orgs and child nodes t.references :parent # Used to determine Parent or Child t.string :org_type # Subdomain used for scoping site t.string :subdomain # Common fields .... t.timestamps end # index add_index :organizations, [:name, :subdomain], unique: true end end class CreateOrganizationsTaskDefinitions < ActiveRecord::Migration def change create_table :organizations_task_definitions, id: false do |t| t.integer :organization_id t.integer :task_definition_id end add_index :organizations_task_definitions, [:organization_id, :task_definition_id], name: 'index_organizations_task_definitions' end end models: class Organization < ActiveRecord::Base #associations has_many :users, class_name: 'User', inverse_of: :organization has_and_belongs_to_many :task_definitions, class_name: 'TaskDefinition', inverse_of: :organizations has_one :address, class_name: 'Address' has_many :children, class_name: 'Organization', foreign_key: 'parent_id' belongs_to :parent, class_name: 'Organization' accepts_nested_attributes_for :address end class TaskDefinition < ActiveRecord::Base #associations has_many :steps, class_name: 'TaskStep', inverse_of: :task_definition has_and_belongs_to_many :organizations, class_name: 'Organization', inverse_of: :task_definitions has_and_belongs_to_many :task_events, class_name: 'TaskEvent', inverse_of: :task_definitions accepts_nested_attributes_for :steps end Controller: class Admin::TaskDefinitionsController < ApplicationController before_filter :authenticate_user! after_action :verify_authorized ..... def edit @tasks = current_organization.task_definitions if(@tasks.size > 0 ) @task = @tasks.find(params[:id]) authorize @task # add breadcrumb add_breadcrumb @task.name, admin_task_definition_path(@task) unless current_user.org_super_admin? or current_user.finch_admin? unless @user == current_user redirect_to :back, :alert => "Access denied." end end end end end Routes: Rails.application.routes.draw do ...... constraints(Finch::Constraints::SubdomainRequired) do # # dashboards # resource :dash_boards, only: [:index, :show, :edit, :update, :destroy] # # orgss # resource :organizations, only: [:index, :show, :edit, :update, :destroy] # # Only Admins are allowed to access # namespace :admin do # # Workflow Data # resources :task_definitions, only: [:index, :show, :edit, :update, :destroy] resources :task_steps, only: [:show, :edit, :update, :destroy] resource :task_actions, only: [:show, :edit, :update, :destroy] resource :task_action_attributes, only: [:show, :edit, :update, :destroy] resource :task_transitions, only: [:show, :edit, :update, :destroy] end end end view: <div class="form"> <%= bootstrap_form_for @task do |f| %> <div class="form-group"> <%= render '/admin/task_definitions/errors' %> </div> rake routes: edit_organizations GET /organizations/edit(.:format) organizations#edit organizations GET /organizations(.:format) organizations#show PATCH /organizations(.:format) organizations#update PUT /organizations(.:format) organizations#update DELETE /organizations(.:format) organizations#destroy admin_task_definitions GET /admin/task_definitions(.:format) admin/task_definitions#index edit_admin_task_definition GET /admin/task_definitions/:id/edit(.:format) admin/task_definitions#edit admin_task_definition GET /admin/task_definitions/:id(.:format) admin/task_definitions#show A: Undefined method errors ending in _path or _url usually indicate a bad route helper. Checking the spot of the error, it seems that a helper method (bootstrap_form_for) is calling the route helper task_definitions_path, which is incorrect. That route is namespaced under admin according to your routes file, so the proper route helper is: admin_task_definitions_path I don't know what is in the bootstrap_form_for helper method, so I don't have a specific fix for you. Assuming you use the Bootstrap forms gem, skip it and write the form manually. In the future, rake routes will show all registered route helpers. A handy list for debugging bad route helpers.
{ "pile_set_name": "StackExchange" }
Q: Mysql error in syntax at 'Ctrl-C' line 1 restoring MysqlDump I'm using linux and i've tried both mysql -u root -pabc123 < ~/Desktop/restore.sql and while logged in as root to mysql \. ~/Desktop/restore.sql I keep getting the error You have an error in your SQl syntax; check the manual that corresponds to your MYSQL server version for the right syntan to use near 'Ctrl-C' at line 1 this is driving me bananas, does anybody have any idea why? This is a mysqldump --all-databases file Thanks! here is the first few lines -- MySQL dump 10.13 Distrib 5.1.58, for debian-linux-gnu (x86_64) -- -- Host: localhost Database: -- ------------------------------------------------------ -- Server version 5.1.58-1ubuntu1 /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8 */; /*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; /*!40103 SET TIME_ZONE='+00:00' */; /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; -- -- Current Database: `mytmpDB` -- CREATE DATABASE /*!32312 IF NOT EXISTS*/ ` A: mysql -u root -pabc123 < sed -e 's/^C//g' ~/Desktop/restore.sql
{ "pile_set_name": "StackExchange" }
Q: drawImage from an array I'm trying to draw images from an array in such a loop: var frames = []; for(var i=0;i<assets.length;i++){ frames[i] = new Image(); frames[i].onload = function() { ctx.drawImage(frames[i],10,10); }; frames[i].src = assets[i]; and get the error: Value could not be converted to any of: HTMLImageElement, HTMLCanvasElement, HTMLVideoElement. I seems like the way "frames[i]" is passed to drawImage() is causing the problem. Why is that so and what is the proper way to do it? Is the variable "i" not valid in the context that the onload function is called? Thanks A: Your problem is that the onload callback is asynchronous, so when the callback function is called, the loop may have ended, and the i variable isn't defined anymore. Anyway, the this keyword point to the image inside the callback : var frames = []; for (var i=0; i<assets.length; i++) { frames[i] = new Image(); frames[i].onload = function() { ctx.drawImage(this, 10, 10); }; frames[i].src = assets[i]; } The next problem you'll may have is that you won't control in which order the images are drawn on the canvas. See this JsFiddle.
{ "pile_set_name": "StackExchange" }
Q: AttributeError: 'list' object has no attribute 'dtype' I have trouble with Bollinger Band algorithm. I want to apply this algorithm to my time series data. The code: length = 1440 dataframe = pd.DataFrame(speed) ave = pd.stats.moments.rolling_mean(speed,length) sd = pd.stats.moments.rolling_std(speed,length=1440) upband = ave + (sd*2) dnband = ave - (sd*2) print np.round(ave,3), np.round(upband,3), np.round(dnband,3) Input: speed=[96.5, 97.0, 93.75, 96.0, 94.5, 95.0, 94.75, 96.0, 96.5, 97.0, 94.75, 97.5, 94.5, 96.0, 92.75, 96.5, 91.5, 97.75, 93.0, 96.5, 92.25, 95.5, 92.5, 95.5, 94.0, 96.5, 94.25, 97.75, 93.0] Result of "ave" variable: [1440 rows x 1 columns] 0 0 NaN 1 NaN 2 NaN 3 NaN 4 NaN 5 NaN 6 NaN 7 NaN 8 NaN 9 NaN 10 NaN 11 NaN 12 NaN 13 NaN 14 NaN 15 NaN 16 NaN 17 NaN A: The first point is, as i allready mentioned in the comment rolling_mean needs a DataFrame you can achieve this by inserting the line speed = pd.DataFrame(data=speed) before the ave = ... line. Nonetheless you also missed to define the window attribute in rolling_std (See: http://pandas.pydata.org/pandas-docs/stable/generated/pandas.rolling_std.html)
{ "pile_set_name": "StackExchange" }
Q: Does java security flaw affects ubuntu also? There are rumors about an actual java security problem. The BSI advises people to deactivate java plugins version 7 and prior in all kind of OS, even in linux. Does this mean, I should deactivate iced-tea plugin in ubuntu now? Or is this specific version not concerned? Thank you very much for your answer. I looked for this information in the internet already but wasn't able to find what you found out since I don't know much about the interdependence. I have disabled icedtea plugin now. Better safe than sorry... How can we warn all the other ubuntu users out there? According to the BSI the exploit is already excessively used in the coutries Norway, Germany and the Netherlands. Since ubuntu is also affected as you concluded this seems to be really important. Also heise security writes now, the bug concerns every kind of os and browser which is supported by java. Btw, Oracle has finally managed to fix the bug in Ver 7 update 7 http://www.oracle.com/technetwork/topics/security/alert-cve-2012-4681-verbose-1835710.html How can I tell when the problem is fixed in the icedtea version ubuntu uses? Aditional information: http://www.kb.cert.org/vuls/id/636312 A: From here they said it was reported as CVE-2012-4681 for Oracle Java 7 Update 6, and possibly other versions , It seems that it has not been reported or accounted for Ubuntu yet but can be seen reported for Debian as here for packages openjdk-6 and openjdk-7 , so i guess it applies here too. If i am guessing it right ,same version exists for Ubuntu here So please disable it , to be assured for safer side . Edit (1-9-2012) It is now addressed by Ubuntu Security team as can be seen here . Security update for the package will soon be provided ,i guess. Icetea-Web package includes the Plugin , which seems to have not being affected as here. You can click the Ubuntu link as above to see the packages in it .So i guess , you are safe to use it. A: It seems that IcedTea plugin is safe (contrary to what is stated above), here I copy from the RedHat site (also mentioned above): Tomas Hoger 2012-08-27 09:09:03 EDT Code execution was confirmed with the latest Oracle and IBM Java 7 web browser plug-in. IcedTea-Web using OpenJDK7 blocks this exploit by not allowing applet to change the SecurityManager (which is allowed in Oracle and IBM Java plugin). Java 6 is currently not known to be affected. This is important for me since I need a Java enabled browser to download files from a US government sponsored site, Protein Data Bank (http://www.rcsb.org/pdb/home/home.do), and the IcedTea plug-in works there.
{ "pile_set_name": "StackExchange" }
Q: Apache SystemML DML doesn't allow for multiple return values in function I'm trying to build a simple hello world neural network in SystemlML's DML but got stuck with returning multiple values from a UDF function. I've been inspired by this code where it successfully runs, but I can't figure out the difference: EDIT as requested by Berthold (full code): script = """ # sigmoid = function(matrix[double] z) return (matrix[double] z) { z = 1/(1+exp(-z)) } sigmoidPrime = function(matrix[double] z) return (matrix[double] z) { #Gradient of sigmoid z = exp(-z)/(1+exp(-z)) } X=matrix("3 5 5 1 10 2", rows=3, cols=2) inputLayerSize = 2 outputLayerSize = 1 hiddenLayerSize = 3 W1 = rand(rows=inputLayerSize,cols=hiddenLayerSize) W2 = rand(rows=hiddenLayerSize,cols=outputLayerSize) feedForward = function (matrix[double] X, matrix[double] W1, matrix[double] W2) return (matrix[double] z3,matrix[double] Y) { z2 = X %*% W1 a2 = sigmoid(z2) z3 = (a2 %*% W2) Y = sigmoid(z3) } #feedForward = function (matrix[double] X, # matrix[double] W1, # matrix[double] W2) return (matrix[double] z2,matrix[double] z3,matrix[double] Y) { # z2 = X %*% W1 # a2 = sigmoid(z2) # z3 = a2 %*% W2 # Y = sigmoid(z3) # z2,z3,Y #} #gradient = function(matrix[double] X, # matrix[double] W1, # matrix[double] W2, # matrix[double] Y) return (matrix[double] Y) { # #Compute derivative with respect to W and W2 for a given X and y: # z2,z3,yHat = feedForward(X,W1,W2) # delta3 = -(Y-yHat) * sigmoidPrime(z3) # dJdW2 = t(a2) %*% delta3 # delta2 = (delta3 %*% t(W2))*sigmoidPrime(z2) # dJdW1 = t(X) %*% delta2 # return dJdW1, dJdW2 #} Yhat=feedForward(X,W1,W2) nrx = nrow(X) ncx = ncol(X) nrw1 = nrow(W1) ncw1 = ncol(W1) """ If I remove matrix[double] z3 it works, otherwise I get: Caused by: org.apache.sysml.parser.LanguageException: ERROR: null -- line 22, column 0 -- Assignment statement cannot return multiple values Any ideas? A: SystemML does support multiple return values in functions. See http://apache.github.io/systemml/dml-language-reference.html#user-defined-function-udf Below Python example returns 2 matrixes. DMLstr = """ M1M2 = function( matrix[double] M) return (matrix[double] M1, matrix[double] M2) { M1 = M + 1 M2 = M + 2 } X=matrix("3 5 5 1 10 2", rows=3, cols=2) [M1, M2] = M1M2 (X) """ [M1, M2] = ml.execute(dml(DMLstr).output('M1', 'M2')).get('M1','M2') print M1.toNumPy() print M2.toNumPy() Your snippet does not show the invocation of "feedforward". Can you please post?
{ "pile_set_name": "StackExchange" }
Q: How to add auto play next song option in my Android app? I want to add an automatically play next song option when previous is finished in my Android app. I have trying many ways but failed. Please, give full code, not hints. Here are the Full Class: public class AlbumPlayActivity extends AppCompatActivity implements View.OnClickListener { private List<SongListModel> songs = new ArrayList<SongListModel>(); private SongAdapter songAdapter; String URL_SONGS; String URL_ALBUM_ART; String URL_ALBUM_ART_BIG; String URL_ALBUM_ART_BLUR; String URL_MP3; ListView lvSongs; MediaPlayer mediaPlayer; NetworkImageView nivAlbumArt,nivAlbumArtBlur; private double startTime = 0; private double finalTime = 0; private Handler myHandler = new Handler(); public int currentlyPlaying; private int forwardTime = 5000; private int backwardTime = 5000; private SeekBar seekbar; ImageLoader imageLoader = AppController.getInstance().getImageLoader(); public int oneTimeOnly = 0; int songID = 0; ImageButton ibPrev, ibPlay, ibPause, ibNext, ibFastForward, ibFastRewind; TextView tvStartTime, tvEndTime; RelativeLayout llList; ImageButton ibShare; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_album_play); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayShowTitleEnabled(false); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayShowHomeEnabled(true); URL_SONGS = getIntent().getExtras().getString("URL_SONG"); URL_ALBUM_ART = getIntent().getExtras().getString("URL_ALBUM_ART"); URL_ALBUM_ART_BIG = getIntent().getExtras().getString("URL_ALBUM_ART_BIG"); URL_ALBUM_ART_BLUR = getIntent().getExtras().getString("URL_ALBUM_ART_BLUR"); imageLoader = AppController.getInstance().getImageLoader(); lvSongs = (ListView) findViewById(R.id.lvSongList); nivAlbumArt = (NetworkImageView) findViewById(R.id.nivAlbumArt); ibNext = (ImageButton) findViewById(R.id.ibNext); ibPlay = (ImageButton) findViewById(R.id.ibPlay); ibFastRewind = (ImageButton) findViewById(R.id.ibFastRewind); ibFastForward = (ImageButton) findViewById(R.id.ibFastForward); ibPrev = (ImageButton) findViewById(R.id.ibPrev); seekbar = (SeekBar) findViewById(R.id.seekBar); tvStartTime = (TextView) findViewById(R.id.tvStartTime); tvEndTime = (TextView) findViewById(R.id.tvEndTime); llList = (RelativeLayout)findViewById(R.id.llList); ibShare = (ImageButton)findViewById(R.id.ibShare); seekbar.setClickable(false); ibNext.setOnClickListener(this); ibPlay.setOnClickListener(this); ibPrev.setOnClickListener(this); ibFastRewind.setOnClickListener(this); ibFastForward.setOnClickListener(this); ibShare.setOnClickListener(this); songAdapter = new SongAdapter(this, songs); lvSongs.setAdapter(songAdapter); loadSongs(); lvSongs.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { songs.get(songID).setVisible(false); songAdapter.notifyDataSetChanged(); songID = position; stopPlaying(); URL_MP3 = "http://.../apps/content/mp3/" + songs.get(position).getSong().replace(" ", "%20"); songs.get(songID).setVisible(true); mediaPlayer = new MediaPlayer(); mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); try { mediaPlayer.setDataSource(URL_MP3); } catch (IOException e) { e.printStackTrace(); } mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(MediaPlayer mp) { mp.start(); ibPlay.setImageResource(R.drawable.ic_pause_circle_outline_white_48dp); finalTime = mp.getDuration(); startTime = mp.getCurrentPosition(); if (oneTimeOnly == 0) { seekbar.setMax((int) finalTime); oneTimeOnly = 1; } tvEndTime.setText(String.format("%d:%d", TimeUnit.MILLISECONDS.toMinutes((long) finalTime), TimeUnit.MILLISECONDS.toSeconds((long) finalTime) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long) finalTime))) ); tvStartTime.setText(String.format("%d:%d", TimeUnit.MILLISECONDS.toMinutes((long) startTime), TimeUnit.MILLISECONDS.toSeconds((long) startTime) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long) startTime))) ); seekbar.setProgress((int) startTime); myHandler.postDelayed(UpdateSongTime, 100); } }); mediaPlayer.prepareAsync(); } }); seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onStopTrackingTouch(SeekBar seekBar) { } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { if(mediaPlayer != null && fromUser){ mediaPlayer.seekTo(progress); } } }); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.ibPrev: songs.get(songID).setVisible(false); songAdapter.notifyDataSetChanged(); songID--; if(songID<0){ songID=0; } if (songID >= 0) { startPlaying("http://.../apps/content/mp3/" + songs.get(songID).getSong().replace(" ", "%20")); songs.get(songID).setVisible(true); songAdapter.notifyDataSetChanged(); } break; case R.id.ibPlay: if (mediaPlayer.isPlaying()) { if (mediaPlayer != null) { mediaPlayer.pause(); Log.i("Status:", " Paused"); ibPlay.setImageResource(R.drawable.ic_play_circle_outline_white_48dp); } } else { if (mediaPlayer != null) { mediaPlayer.start(); Log.i("Status:", " Playing"); ibPlay.setImageResource(R.drawable.ic_pause_circle_outline_white_48dp); finalTime = mediaPlayer.getDuration(); startTime = mediaPlayer.getCurrentPosition(); if (oneTimeOnly == 0) { seekbar.setMax((int) finalTime); oneTimeOnly = 1; } tvEndTime.setText(String.format("%d:%d", TimeUnit.MILLISECONDS.toMinutes((long) finalTime), TimeUnit.MILLISECONDS.toSeconds((long) finalTime) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long) finalTime))) ); tvStartTime.setText(String.format("%d:%d", TimeUnit.MILLISECONDS.toMinutes((long) startTime), TimeUnit.MILLISECONDS.toSeconds((long) startTime) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long) startTime))) ); seekbar.setProgress((int) startTime); myHandler.postDelayed(UpdateSongTime, 100); } } break; case R.id.ibShare: Intent sendIntent = new Intent(); sendIntent.setAction(Intent.ACTION_SEND); sendIntent.putExtra(Intent.EXTRA_TEXT, "Welcome to music radio"); sendIntent.setType("text/plain"); startActivity(sendIntent); break; case R.id.ibNext: songs.get(songID).setVisible(false); songAdapter.notifyDataSetChanged(); songID++; if (songID==songs.size()){ ibNext.setEnabled(false); } if (songID <= songs.size()) { startPlaying("http://..../apps/content/mp3/" + songs.get(songID).getSong().replace(" ", "%20")); songs.get(songID).setVisible(true); songAdapter.notifyDataSetChanged(); } break; case R.id.ibFastForward: int temp = (int) startTime; if ((temp + forwardTime) <= finalTime) { startTime = startTime + forwardTime; mediaPlayer.seekTo((int) startTime); } else { Toast.makeText(getApplicationContext(), "Cannot jump forward 5 seconds", Toast.LENGTH_SHORT).show(); } break; case R.id.ibFastRewind: int temp1 = (int) startTime; if ((temp1 - backwardTime) > 0) { startTime = startTime - backwardTime; mediaPlayer.seekTo((int) startTime); } else { Toast.makeText(getApplicationContext(), "Cannot jump backward 5 seconds", Toast.LENGTH_SHORT).show(); } break; } } public void loadSongs() { JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(URL_SONGS, new Response.Listener<JSONArray>() { @Override public void onResponse(JSONArray response) { nivAlbumArt.setImageUrl(URL_ALBUM_ART_BIG, imageLoader); Glide.with(AlbumPlayActivity.this).load(URL_ALBUM_ART_BLUR).asBitmap().into(new SimpleTarget<Bitmap>(700,300) { @Override public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) { Drawable drawable = new BitmapDrawable(resource); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { llList.setBackground(drawable); } } }); for (int i = 0; i < response.length(); i++) { try { JSONObject jObj = response.getJSONObject(i); SongListModel songModel = new SongListModel(); Log.i(">>REQ", jObj.toString()); songModel.setAlbum_id(jObj.getString("album_id")); songModel.setCategory_id(jObj.getString("category_id")); songModel.setId(jObj.getString("id")); songModel.setSinger_id(jObj.getString("singer_id")); songModel.setSong(jObj.getString("song")); songs.add(songModel); startPlaying("http://.../apps/content/mp3/" + songs.get(songID).getSong().replace(" ", "%20")); songs.get(songID).setVisible(true); } catch (JSONException e) { e.printStackTrace(); } } songAdapter.notifyDataSetChanged(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { } }); jsonArrayRequest.setRetryPolicy(new DefaultRetryPolicy( (int) TimeUnit.SECONDS.toMillis(20), DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)); AppController.getInstance().addToRequestQueue(jsonArrayRequest); } private void startPlaying(final String position) { stopPlaying(); mediaPlayer = new MediaPlayer(); mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); try { mediaPlayer.setDataSource(position); } catch (IOException e) { e.printStackTrace(); } mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(MediaPlayer mp) { mp.start(); currentlyPlaying=songID; // member field (int) finalTime = mp.getDuration(); startTime = mp.getCurrentPosition(); ibPlay.setImageResource(R.drawable.ic_pause_circle_outline_white_48dp); if (oneTimeOnly == 0) { seekbar.setMax((int) finalTime); oneTimeOnly = 1; } tvEndTime.setText(String.format("%d:%d", TimeUnit.MILLISECONDS.toMinutes((long) finalTime), TimeUnit.MILLISECONDS.toSeconds((long) finalTime) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long) finalTime))) ); tvStartTime.setText(String.format("%d:%d", TimeUnit.MILLISECONDS.toMinutes((long) startTime), TimeUnit.MILLISECONDS.toSeconds((long) startTime) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long) startTime))) ); seekbar.setProgress((int) startTime); myHandler.postDelayed(UpdateSongTime, 100); } }); mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mediaPlayer) { if(currentlyPlaying >= songs.size()){ } else { startPlaying(position); } } }); mediaPlayer.prepareAsync(); } private void stopPlaying() { if (mediaPlayer != null) { mediaPlayer.stop(); mediaPlayer.reset(); mediaPlayer.release(); mediaPlayer = null; myHandler.removeCallbacks(UpdateSongTime); } } @Override public void onBackPressed() { stopPlaying(); finish(); } @Override public boolean onCreateOptionsMenu (Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == android.R.id.home) { stopPlaying(); finish(); return true; } if (id == R.id.action_home) { stopPlaying(); Intent intent = new Intent(AlbumPlayActivity.this,HomeActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); finish(); return true; } return super.onOptionsItemSelected(item); } private Runnable UpdateSongTime = new Runnable() { public void run() { startTime = mediaPlayer.getCurrentPosition(); seekbar.setProgress((int) startTime); tvStartTime.setText(String.format("%d:%d", TimeUnit.MILLISECONDS.toMinutes((long) startTime), TimeUnit.MILLISECONDS.toSeconds((long) startTime) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS. toMinutes((long) startTime))) ); myHandler.postDelayed(this, 100); } }; } I am trying to modification on my apps. First I submit one method by now I submitted full class. One person trying to help me but I am not successful its not properly working. Last Time I updated my code but its player same song again and again. Please observe my code and give me the best suggestion. I am not a professional expert developer. I am a beginner in app development.. So Please give me exact code. A: You already have a list of all songs, so I suggest you provide the position of the song you want to play instead of the URL to your MediaPlayer: public class AlbumPlayActivity extends AppCompatActivity implements View.OnClickListener { private List<SongListModel> songs = new ArrayList<SongListModel>(); private SongAdapter songAdapter; String URL_SONGS; String URL_ALBUM_ART; String URL_ALBUM_ART_BIG; String URL_ALBUM_ART_BLUR; String URL_MP3; ListView lvSongs; MediaPlayer mediaPlayer; NetworkImageView nivAlbumArt,nivAlbumArtBlur; private double startTime = 0; private double finalTime = 0; private Handler myHandler = new Handler(); public int currentlyPlaying; private int forwardTime = 5000; private int backwardTime = 5000; private SeekBar seekbar; ImageLoader imageLoader = AppController.getInstance().getImageLoader(); public int oneTimeOnly = 0; int songID = 0; ImageButton ibPrev, ibPlay, ibPause, ibNext, ibFastForward, ibFastRewind; TextView tvStartTime, tvEndTime; RelativeLayout llList; ImageButton ibShare; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_album_play); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayShowTitleEnabled(false); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayShowHomeEnabled(true); URL_SONGS = getIntent().getExtras().getString("URL_SONG"); URL_ALBUM_ART = getIntent().getExtras().getString("URL_ALBUM_ART"); URL_ALBUM_ART_BIG = getIntent().getExtras().getString("URL_ALBUM_ART_BIG"); URL_ALBUM_ART_BLUR = getIntent().getExtras().getString("URL_ALBUM_ART_BLUR"); imageLoader = AppController.getInstance().getImageLoader(); lvSongs = (ListView) findViewById(R.id.lvSongList); nivAlbumArt = (NetworkImageView) findViewById(R.id.nivAlbumArt); ibNext = (ImageButton) findViewById(R.id.ibNext); ibPlay = (ImageButton) findViewById(R.id.ibPlay); ibFastRewind = (ImageButton) findViewById(R.id.ibFastRewind); ibFastForward = (ImageButton) findViewById(R.id.ibFastForward); ibPrev = (ImageButton) findViewById(R.id.ibPrev); seekbar = (SeekBar) findViewById(R.id.seekBar); tvStartTime = (TextView) findViewById(R.id.tvStartTime); tvEndTime = (TextView) findViewById(R.id.tvEndTime); llList = (RelativeLayout)findViewById(R.id.llList); ibShare = (ImageButton)findViewById(R.id.ibShare); seekbar.setClickable(false); ibNext.setOnClickListener(this); ibPlay.setOnClickListener(this); ibPrev.setOnClickListener(this); ibFastRewind.setOnClickListener(this); ibFastForward.setOnClickListener(this); ibShare.setOnClickListener(this); songAdapter = new SongAdapter(this, songs); lvSongs.setAdapter(songAdapter); loadSongs(); lvSongs.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { songs.get(songID).setVisible(false); songAdapter.notifyDataSetChanged(); songID = position; stopPlaying(); URL_MP3 = "http://your_host/apps/content/mp3/" + songs.get(position).getSong().replace(" ", "%20"); songs.get(songID).setVisible(true); mediaPlayer = new MediaPlayer(); mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); try { mediaPlayer.setDataSource(URL_MP3); } catch (IOException e) { e.printStackTrace(); } mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(MediaPlayer mp) { mp.start(); ibPlay.setImageResource(R.drawable.ic_pause_circle_outline_white_48dp); finalTime = mp.getDuration(); startTime = mp.getCurrentPosition(); if (oneTimeOnly == 0) { seekbar.setMax((int) finalTime); oneTimeOnly = 1; } tvEndTime.setText(String.format("%d:%d", TimeUnit.MILLISECONDS.toMinutes((long) finalTime), TimeUnit.MILLISECONDS.toSeconds((long) finalTime) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long) finalTime))) ); tvStartTime.setText(String.format("%d:%d", TimeUnit.MILLISECONDS.toMinutes((long) startTime), TimeUnit.MILLISECONDS.toSeconds((long) startTime) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long) startTime))) ); seekbar.setProgress((int) startTime); myHandler.postDelayed(UpdateSongTime, 100); } }); mediaPlayer.prepareAsync(); } }); seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onStopTrackingTouch(SeekBar seekBar) { } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { if(mediaPlayer != null && fromUser){ mediaPlayer.seekTo(progress); } } }); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.ibPrev: songs.get(songID).setVisible(false); songAdapter.notifyDataSetChanged(); songID--; if(songID<0){ songID=0; } if (songID >= 0) { startPlaying("http://..../apps/content/mp3/" + songs.get(songID).getSong().replace(" ", "%20")); songs.get(songID).setVisible(true); songAdapter.notifyDataSetChanged(); } break; case R.id.ibPlay: if (mediaPlayer.isPlaying()) { if (mediaPlayer != null) { mediaPlayer.pause(); Log.i("Status:", " Paused"); ibPlay.setImageResource(R.drawable.ic_play_circle_outline_white_48dp); } } else { if (mediaPlayer != null) { mediaPlayer.start(); Log.i("Status:", " Playing"); ibPlay.setImageResource(R.drawable.ic_pause_circle_outline_white_48dp); finalTime = mediaPlayer.getDuration(); startTime = mediaPlayer.getCurrentPosition(); if (oneTimeOnly == 0) { seekbar.setMax((int) finalTime); oneTimeOnly = 1; } tvEndTime.setText(String.format("%d:%d", TimeUnit.MILLISECONDS.toMinutes((long) finalTime), TimeUnit.MILLISECONDS.toSeconds((long) finalTime) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long) finalTime))) ); tvStartTime.setText(String.format("%d:%d", TimeUnit.MILLISECONDS.toMinutes((long) startTime), TimeUnit.MILLISECONDS.toSeconds((long) startTime) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long) startTime))) ); seekbar.setProgress((int) startTime); myHandler.postDelayed(UpdateSongTime, 100); } } break; case R.id.ibShare: Intent sendIntent = new Intent(); sendIntent.setAction(Intent.ACTION_SEND); sendIntent.putExtra(Intent.EXTRA_TEXT, "Welcome to music radio"); sendIntent.setType("text/plain"); startActivity(sendIntent); break; case R.id.ibNext: songs.get(songID).setVisible(false); songAdapter.notifyDataSetChanged(); songID++; if (songID==songs.size()){ ibNext.setEnabled(false); } if (songID <= songs.size()) { startPlaying("http://..../apps/content/mp3/" + songs.get(songID).getSong().replace(" ", "%20")); songs.get(songID).setVisible(true); songAdapter.notifyDataSetChanged(); } break; case R.id.ibFastForward: int temp = (int) startTime; if ((temp + forwardTime) <= finalTime) { startTime = startTime + forwardTime; mediaPlayer.seekTo((int) startTime); } else { Toast.makeText(getApplicationContext(), "Cannot jump forward 5 seconds", Toast.LENGTH_SHORT).show(); } break; case R.id.ibFastRewind: int temp1 = (int) startTime; if ((temp1 - backwardTime) > 0) { startTime = startTime - backwardTime; mediaPlayer.seekTo((int) startTime); } else { Toast.makeText(getApplicationContext(), "Cannot jump backward 5 seconds", Toast.LENGTH_SHORT).show(); } break; } } public void loadSongs() { JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(URL_SONGS, new Response.Listener<JSONArray>() { @Override public void onResponse(JSONArray response) { nivAlbumArt.setImageUrl(URL_ALBUM_ART_BIG, imageLoader); Glide.with(AlbumPlayActivity.this).load(URL_ALBUM_ART_BLUR).asBitmap().into(new SimpleTarget<Bitmap>(700,300) { @Override public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) { Drawable drawable = new BitmapDrawable(resource); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { llList.setBackground(drawable); } } }); for (int i = 0; i < response.length(); i++) { try { JSONObject jObj = response.getJSONObject(i); SongListModel songModel = new SongListModel(); Log.i(">>REQ", jObj.toString()); songModel.setAlbum_id(jObj.getString("album_id")); songModel.setCategory_id(jObj.getString("category_id")); songModel.setId(jObj.getString("id")); songModel.setSinger_id(jObj.getString("singer_id")); songModel.setSong(jObj.getString("song")); songs.add(songModel); startPlaying(songID); songs.get(songID).setVisible(true); } catch (JSONException e) { e.printStackTrace(); } } songAdapter.notifyDataSetChanged(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { } }); jsonArrayRequest.setRetryPolicy(new DefaultRetryPolicy( (int) TimeUnit.SECONDS.toMillis(20), DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)); AppController.getInstance().addToRequestQueue(jsonArrayRequest); } private void startPlaying(final int position) { stopPlaying(); mediaPlayer = new MediaPlayer(); mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); try { mediaPlayer.setDataSource("http://..../apps/content/mp3/" + songs.get(position).getSong().replace(" ", "%20")); } catch (IOException e) { e.printStackTrace(); } mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(MediaPlayer mp) { mp.start(); currentlyPlaying = position; finalTime = mp.getDuration(); startTime = mp.getCurrentPosition(); ibPlay.setImageResource(R.drawable.ic_pause_circle_outline_white_48dp); if (oneTimeOnly == 0) { seekbar.setMax((int) finalTime); oneTimeOnly = 1; } tvEndTime.setText(String.format("%d:%d", TimeUnit.MILLISECONDS.toMinutes((long) finalTime), TimeUnit.MILLISECONDS.toSeconds((long) finalTime) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long) finalTime))) ); tvStartTime.setText(String.format("%d:%d", TimeUnit.MILLISECONDS.toMinutes((long) startTime), TimeUnit.MILLISECONDS.toSeconds((long) startTime) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long) startTime))) ); seekbar.setProgress((int) startTime); myHandler.postDelayed(UpdateSongTime, 100); } }); mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mediaPlayer) { currentlyPlaying++; if(currentlyPlaying >= songs.size()) currentlyPlaying = 0; startPlaying(currentlyPlaying); } }); mediaPlayer.prepareAsync(); } private void stopPlaying() { if (mediaPlayer != null) { mediaPlayer.stop(); mediaPlayer.reset(); mediaPlayer.release(); mediaPlayer = null; myHandler.removeCallbacks(UpdateSongTime); } } @Override public void onBackPressed() { stopPlaying(); finish(); } @Override public boolean onCreateOptionsMenu (Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == android.R.id.home) { stopPlaying(); finish(); return true; } if (id == R.id.action_home) { stopPlaying(); Intent intent = new Intent(AlbumPlayActivity.this,HomeActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); finish(); return true; } return super.onOptionsItemSelected(item); } private Runnable UpdateSongTime = new Runnable() { public void run() { startTime = mediaPlayer.getCurrentPosition(); seekbar.setProgress((int) startTime); tvStartTime.setText(String.format("%d:%d", TimeUnit.MILLISECONDS.toMinutes((long) startTime), TimeUnit.MILLISECONDS.toSeconds((long) startTime) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS. toMinutes((long) startTime))) ); myHandler.postDelayed(this, 100); } };
{ "pile_set_name": "StackExchange" }
Q: In Karabiner how to send keystones with delay in-between? in Karainer, on Mac OS X+ This config gives me 5 Qs after pressing F. <item> <name>song_5Q</name> <identifier>song_5Q</identifier> <autogen>__KeyToKey__ KeyCode::F, KeyCode::Q, KeyCode::Q, KeyCode::Q, KeyCode::Q, KeyCode::Q, </autogen> But I want to add a delay of about 200 ms between each Q. How to do it please? A: Best bet would be to call an applescript that implements the delays... Doing it in Karabiner as a native function would probably make Karabiner blocking (synchronous) and introduce all sorts of delays.
{ "pile_set_name": "StackExchange" }
Q: Is there an way to see a number of invocation per firebase function in the firebase console? We are using a firebase platform for our recent projects. We recently launched and have been monitoring the usage. I can see total number of firebase invocation in the firebase console but could not find the way of seeing the number of invocation for each function.. Could you please advice if there is any way of seeing these number? We wanted to find the most used firebase functions. We can expect which firebase functions would be mostly used, but wanted to know the exact number called. A: The Firebase console doesn't offer a breakdown of invocations per function, but the Cloud console does. And since each Firebase project is also a project on the Cloud platform, you can just switch over to console.cloud.google.com to get the more detailed information. Since the Cloud console is a bit trickier to navigate, here are the steps: Go to console.cloud.google.com. Sign in if needed. Select your project from the dropdown at the top. In the search box () next to the project name, type and select Cloud Functions. You'll now see a list of the functions in your project. Click on the name of the function you want to see the invocations of. You'll now see a chart of the invocations. From one of my projects:
{ "pile_set_name": "StackExchange" }
Q: You cannot use the screensaver with this version of OS X So here's my current problem. I'm attempting to create a screensaver, all I'm doing is setting a background color like so, public override func drawRect(rect: NSRect) { super.drawRect(rect) let color = NSColor(red:0.33, green:0.78, blue:0.99, alpha:1) color.setFill() NSBezierPath.fillRect(rect) } Fairly straight forward. I also set EMBEDDED_CONTENT_CONTAINS_SWIFT = YES; Now when I go to install the .saver file I am returned with a message that says You cannot use the screensaver X with this version of OS X Any ideas? A: If you're on Mojave, then the Principal class needs to include the module name (target name) as well: <key>NSPrincipalClass</key> <string>[YourTarget].[YourClass]</string> You might also need to set Always Embed Swift Standard Libraries to YES in your Build Settings as well as check the Principle Class as above. Sources: https://github.com/JohnCoates/Aerial/issues/464 https://blog.viacom.tech/2016/06/27/making-a-macos-screen-saver-in-swift-with-scenekit/
{ "pile_set_name": "StackExchange" }
Q: Keep handler and service alive while waiting for response from separate thread? I'm using a repeating alarm to trigger a BroadcastReceiver (OnAlarmReceiver) which in turn calls WakefulIntentService.sendWakefulWork(context, PmNotificationService.class); The doWakefulWork method is displayed below protected void doWakefulWork(Intent intent) { // Load auth information from server Authentication.loadAuthenticationInformation(this); if (hasAuthInformation()) { getRequestParameters().execute(getRequestHandler()); } } The getRequestParameters().execute(getRequestHandler()); line creates an AjaxRequest object, along with a RequestHandler object, and the idea was that once the Ajax request is completed, it would send the information back to the RequestHandler. In this case the handler is the PmNotificationService class (which extends WakefulIntentService). The problem, and thus the basis of my question is the following message: 05-12 12:09:08.139: INFO/ActivityManager(52): Stopping service: com.sofurry/.services.PmNotificationService 05-12 12:09:08.558: WARN/MessageQueue(333): Handler{4393e118} sending message to a Handler on a dead thread 05-12 12:09:08.558: WARN/MessageQueue(333): java.lang.RuntimeException: Handler{4393e118} sending message to a Handler on a dead thread ... Obviously the service stops running as soon as it has sent off the request, as that request runs in another thread, and as a result hereof the Handler is dead. So my question is: Can I keep the service and thus the handler alive until I get a response (ie. wait for that other thread)? I would prefer it if I could, as the AjaxRequest object is maintained by someone else, and is used throughout the entire application. Update I obviously missed one very important point, namely that the WakefulIntentService inherits from IntentService instead of Service which means it will stop itself after it has done its work. I have currently solved it by changing the doWakefulWork method slightly. Here's the new one: @Override protected void doWakefulWork(Intent intent) { RequestThread thread = null; // Load auth information from server Authentication.loadAuthenticationInformation(this); if (hasAuthInformation()) { thread = getRequestParameters().execute(getRequestHandler()); try { thread.join(); } catch (InterruptedException ignored) {} } } I'm not sure if using thread.join() is the best way to manage this, so I'll leave the question unanswered for a few days, before I post an answer, just in case someone has a better solution for it. A: IntentService already uses a background thread for onHandleIntent(). Hence, do not use AsyncTask -- just execute your code in onHandleIntent(). Check https://groups.google.com/forum/#!topic/android-developers/YDrGmFDFUeU
{ "pile_set_name": "StackExchange" }
Q: Best way to combine a permutation of conditional statements So, I have a series of actions to perform, based on 4 conditional variables - lets say x,y,z & t. Each of these variables have a possible True or False value. So, that is a total of 16 possible permutations. And I need to perform a different action for each permutation. What is the best way to do this rather than making a huge if-else construct. Lets see a simplified example. This is how my code would look if I try to contain all the different permutations into a large if-else construct. if (x == True): if (y == True): if (z == True): if (t == True): print ("Case 1") else: print ("Case 2") else: if (t == True): print ("Case 3") else: print ("Case 4") else: if (z == True): if (t == True): print ("Case 5") else: print ("Case 6") else: if (t == True): print ("Case 7") else: print ("Case 8") else: if (y == True): if (z == True): if (t == True): print ("Case 9") else: print ("Case 10") else: if (t == True): print ("Case 11") else: print ("Case 12") else: if (z == True): if (t == True): print ("Case 13") else: print ("Case 14") else: if (t == True): print ("Case 15") else: print ("Case 16") Is there any way to simplify this? Obviously, my objective for each case is more complicated than just printing "Case 1". A: You can use a map of cases to results: cases = { (True, True, True, True): "Case 1", (True, True, True, False): "Case 2", (True, True, False, True): "Case 3", (True, True, False, False):"Case 4", (True, False, True, True): "Case 5", (True, False, True, False):"Case 6", (True, False, False, True): "Case 7", (True, False, False, False):"Case 8", (False, True, True, True): "Case 9", (False, True, True, False):"Case 10", (False, True, False, True): "Case 11", (False, True, False, False):"Case 12", (False, False, True, True): "Case 13", (False, False, True, False):"Case 14", (False, False, False, True): "Case 15", (False, False, False, False):"Case 16"} print(cases[(x,y,z,t]) If you want to do something else/different for each case, you could add a function to that map. cases = { (True, True, True, True): foo_func, (True, True, True, False): bar_func, ...} result = cases[(x,y,x,t)](*args) You can also use one of the masking solutions to make the code shorter, or if you have too many cases to write out, but for smaller sets of cases, this explicit representation will be clearer and easier to maintain.
{ "pile_set_name": "StackExchange" }
Q: How to avoid sharp jumps between speeds in css animation I need to create infinite animation that will start with fast rotation ( e.g. 1 second) then gradually slow down (within another e.g. 1 second) and then continue on the very slow speed (for the remaining e.g. 8 seconds). The problem is - rotation speed changes with very sharp jumps - on 10% and 20%. Can I control transition between animation speeds? I tried to override speed jump by adding more percentages but it just gives second jump after 20% when speed changes. html { height: 100%; } body { height: 100%; background: #333; display: flex; align-items: center; justify-content: center; } .bar { background: cyan; width: 100px; height: 10px; } .bar { animation: rotation 10s linear infinite; } @keyframes rotation { 0% { transform: rotate(0deg); } 10% { transform: rotate(1600deg); } 11% { transform: rotate(1620deg); } 12% { transform: rotate(1640deg); } 13% { transform: rotate(1660deg); } 14% { transform: rotate(1680deg); } 15% { transform: rotate(1700deg); } 16% { transform: rotate(1720deg); } 17% { transform: rotate(1740deg); } 18% { transform: rotate(1760deg); } 19% { transform: rotate(1800deg); } 20% { transform: rotate(1820deg); } 100% { transform: rotate(2160deg); } } <div class="bar"></div> A: You can use multiple animations: one for the initial spin with deceleration (take a look at the easing functions. In this case I'm using ease-out which mimics basic deceleration) and a second (delayed to run after the first finishes) to be linear. You'll have to play around with the values of degrees and duration to match the speed of rotation from the first animation with the linear speed of the second, otherwise you'll see the speed jump quickly (your problem in the first place). Here's an example: html { height: 100%; } body { height: 100%; background: #333; display: flex; align-items: center; justify-content: center; } .bar { background: cyan; width: 100px; height: 10px; } .bar { animation: rotationDecelerate 2s ease-out, rotationLinear 2s linear 2s infinite; } @keyframes rotationDecelerate { 0% { transform: rotate(0deg); } 100% { transform: rotate(2160deg); } } @keyframes rotationLinear { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } } <div class="bar"></div>
{ "pile_set_name": "StackExchange" }
Q: erlide edoc generator Does anyone know how to add automatic edoc to function in ErlIde? In java eclipse understands and and add some java doc when I put /* before function name is there similar functionality for ErlIde? Thanks in advance %%%=================================================================== %% @spec ${function_name}(${function_parameters})->${function_result} %% %% where %% ${function_parameters} %% %% @doc %% %% @end %%%=================================================================== Something this kind would be nice I guess Ps:(Sorry I was not able to make this formating in the comment I am quite new) A: We don't have this functionality yet. What default content would you expect in the generated edoc?
{ "pile_set_name": "StackExchange" }
Q: Can I pass a generic object to an apex method? I would create a generic method which can take in input a generic object (not only an SObject)... For example would create a method like: public static output MyMethod(Object inputmessage, String Objpamaeter){ inputmessage.put(Objpamaeter, 'xx'); output xx= new outputValidation(); xx.ouputparameter_1='Hi'; return xx; } where output is an object with string parameteres, while inputmessage is an custom apex object or an SObject... If an so large generalization is not possible, what solution can be taken to prevent the fragmentation of the architecture? thanks in advance... Klodjan A: I don't think you could make such a method with the current reflection support in Apex. I'd suggest creating an interface that all input classes implement. Then you could just deal with them via that common interface. E.g. public interface Validatable { bool isValid(); } The standard sObjects won't implement this interface, so you might need to wrap them in a wrapper class.
{ "pile_set_name": "StackExchange" }
Q: how to recover deleted database from phpmyadmin? How can I retrieve the phpMyAdmin database. currently I'm using a version of here is the database server information Server: Localhost via UNIX socket Server type: MariaDB Server version: 5.5.64-MariaDB - MariaDB Server Protocol version: 10 User: root@localhost Server charset: UTF-8 Unicode (utf8) A: Once Database is deleted is gone. It can only be recovered if you have stored a backup of it somewhere else.
{ "pile_set_name": "StackExchange" }
Q: Why is getItem() returning "Invalid attribute value type"? I am trying to get a single item from DynamoDB AWS and can't figure out how to specify it with the hash and range key. Here are is the describeTable and scan output: // describeTable output: { "Table": { "AttributeDefinitions": [ { "AttributeName": "timepost", "AttributeType": "N" }, { "AttributeName": "addr", "AttributeType": "S" } ], "TableName": "Scratch", "KeySchema": [ { "AttributeName": "timepost", "KeyType": "HASH" }, { "AttributeName": "addr", "KeyType": "RANGE" } ], "TableStatus": "ACTIVE", "CreationDateTime": "2017-08-24T07:08:19.650Z", "ProvisionedThroughput": { "LastIncreaseDateTime": "1970-01-01T00:00:00.000Z", "LastDecreaseDateTime": "1970-01-01T00:00:00.000Z", "NumberOfDecreasesToday": 0, "ReadCapacityUnits": 5, "WriteCapacityUnits": 5 }, "TableSizeBytes": 32, "ItemCount": 1, "TableArn": "arn:aws:dynamodb:ddblocal:000000000000:table/Scratch" } } // scan output: { "Items": [ { "addr": "1.1.1.1:443", "ms": 67, "timepost": 12321340 } ], "Count": 1, "ScannedCount": 1 } Here is my getItem() code and the error output: docClient.get({ TableName: "Scratch", Key: { timepost: {N: '12321340'}, addr: {S: '1.1.1.1:443'} }}, opComplete); err: { "message": "Invalid attribute value type", "code": "ValidationException", "time": "2017-08-26T15:56:59.938Z", "requestId": "f9d94f20-f22d-4141-be06-2eaba1eee5a1", "statusCode": 400, "retryable": false, "retryDelay": 26.507308215655236 } What am I doing wrong? A: Figured it out: docClient.get({ TableName: "Scratch", Key: { timepost: 12321340, addr: '1.1.1.1:443' }}, opComplete); This is what works for me in. I am using the version 2.102.0 of the AWS SDK for Javascript in case that makes a difference.
{ "pile_set_name": "StackExchange" }
Q: How does fuel get to the engine during acrobatics? Given that during acrobatics, extreme G-forces may be impressed upon the fuel tank, wouldn't it make it somewhat difficult for fuel to get to the fuel pump while it's being pushed against a specific direction for the duration of the stunt? Is the solution just not to do the stunt long enough to starve the engine of fuel? A: The basic problem is that no matter how the aircraft's fuel tanks are designed, if there is an air gap in the tank, then there is an attitude and/or a g-loading that puts that air gap over the inlet to the fuel line running to the engine. There are a lot of solutions to this problem. The first is exactly as you say; don't sustain any maneuver that starves the fuel pump (and by extension the engine) for a longer period than you have fuel in the lines to feed the engine. You can actually do a lot without the fuel system seeing a single hiccup in supply; the fuel tanks are designed to feed while under positive G-load (otherwise you couldn't get any fuel to the engine just sitting on the tarmac), so hard turns, rolls, loops etc that keep a force on the aircraft and its contents acting downward towards the floor of the cockpit will keep the fuel flowing into the engine. Spins and high negative-G maneuvers tend to be the things that starve the engine; if the tanks are in the wings, a hard spin, snap roll or zero-g parabola will push the fuel out away from the inlets at the wing roots. Most fuel systems except on the lightest aircraft have at least two fuel pumps per engine; one electric pump on the tank side to shove fuel into the line, and one crankshaft-powered pump that draws fuel out of the lines into the carb chamber or other fuel delivery system. The checklist often involves turning on the electric fuel pumps just before startup to prime the fuel lines, then turning them off once the engine is running smoothly, but you can keep the electric pump on if you plan on really twerking the aircraft in flight. The line between these two pumps actually holds a fair amount of fuel, plenty for a minute or more of sustained operation with the inlet at the tank totally starved, and coupled with a bleed valve on the engine side to release any air that's entered the line, the two pumps running together can usually keep an uninterrupted flow of fuel into the engine by having the electric pump shove fuel down the line as fast as it can whenever the inlet is under the liquid level. For mild aerobatic maneuvers, a "flop tube" is put into the fuel tank. This is simply a flexible hose with a weight, that keeps the hose under the liquid level, no matter what forces are acting to move the mass of liquid around in the tank. This is a simple and very effective way to keep fuel flowing to the engine while the aircraft is under load in any direction, but because the flop tube requires a significant volume of fuel to sink underneath and draw from, flop tubes can increase the "unusable fuel" capacity of the aircraft (fuel that exists in the tank, but the fuel system can't draw out in some normal circumstance). However, there's a tradeoff; the heavier the weight on the end of the flop tube, the more reliably it will stay under the fuel level regardless of attitude, but the more force with which it will impact the sides of the tank in violent maneuvers (and padding the weight further increases unusable fuel). For the real aerobatic nuts, though, the maneuvers are so violent and so long that even a flop tube, redundant fuel pumps and bleed valves might get starved as the fuel sloshes and churns and there isn't a real "liquid level" to draw from. Many of these aircraft go one step further; a bladder-style fuel container. Within the fuel tank is a flexible polymer vessel that actually holds the fuel (typically in either wingtip tanks or a fuselage tank; it's usually impractical to try this with in-wing tanks). This bladder keeps the liquid and gas in the tank shell separate as the tank empties, and may also keep the fuel under some static pressure. If there's no air to draw into the fuel lines, then no matter how the aircraft is oriented or how many Gs it's pulling in any direction, the fuel lines can't be starved. Of course, the fuel lines are only one consideration. Most "normal"-rated aircraft have float-type carburetors, which hold a reservoir of fuel with another air gap, and the fuel level in the reservoir is controlled by a float that opens the inlet from the fuel pump (this system also deals with small hiccups in the fuel flow from the tanks; the air just forms part of the air gap and the float keeps the inlet open until fuel flows in to raise the level). This type of carb will starve the engine during any maneuvers involving less than 1g of force acting towards the "floor" of the float chamber, as the float will keep the inlet closed and the reservoir will starve the fuel feed tube that allows fuel to dribble into the throttle body at the throat. For aerobatics, either a diaphragm-chamber carb (which has a flexible wall on one side of the reservoir chamber that is connected to the fuel inlet) or a fuel injection system must be used to avoid dependence on gravity to get fuel into the engine. The downside of these systems are increased complexity, and in the case of the diaphragm-chamber carb, intolerance of air this far along the fuel system (requiring an air bleed to purge any bubbles in the line before the fuel enters the reservoir).
{ "pile_set_name": "StackExchange" }
Q: Debugging nodejs while using Kinesis MultiLangDaemon/KCL Following this post I was able to connect our existing nodejs code into Kinesis logs (using KCL and MultiLangDaemon). The problem is that I can't debug the code anymore. Since MultiLangDaemon uses STDIN/STDOUT to interact with executed "script", once I call "node --debug" and get the message: "debugger listening on port 57846" I get an error from the MultiLangDaemon saying: "SEVERE: Received error line from subprocess [debugger listening on port 57846] for shard shardId-000000000000" Is there a way to execute nodejs "quietly", so it won't send this STDERR message ? Does anyone have experience with MultiLangDaemon and debugging ? Thanks, Shushu A: I got an answer in here, recommending to work with node inspector. After installing, all I had to do is to change the kinesis.properties executableName from "node" to "node-debug", and I got it working.
{ "pile_set_name": "StackExchange" }
Q: Directory in Linux(ext3) with only 2 files occupies 32000 blocks(16Mbytes) IIRC my Operating Systems classes, the size of a directory in Linux is given by the number of files it contains([wikipedia link])1 So, why a directory with only 2 files occupies 32000 blocks? # stat . File: «.» Size: 16855040 Blocks: 32968 IO Block: 4096 directorio Device: 6805h/26629d Inode: 3047425 Links: 2 Access: (0775/drwxrwxr-x) Uid: ( 501/ jboss) Gid: ( 501/ jboss) Access: 2011-08-26 12:00:20.000000000 +0200 Modify: 2011-08-26 10:58:07.000000000 +0200 Change: 2011-08-26 10:58:07.000000000 +0200 The directory may have had lots of files(thousands) at some point of the past, but not now. What's happening here? A: Your directory has probably seen lots of action and the OS hasn't reclaimed the space that has been used. You can fix this by shuffling things around, if your directory that is using up all the space was called bigdir then you could mkdir newdir mv bigdir/* newdir rmdir bigdir mv newdir bigdir Make sure that whatever accesses bigdir isn't going to while you do the shuffle.
{ "pile_set_name": "StackExchange" }
Q: Calculating correlations between response and certain explanatory variables I want to create a single column that lets me know the correlations for my dependent variable with all of the explanatory variables that I am interested in (all these columns and many more are stored in a data.frame d). By doing cor(d) I can get all the correlations and by doing cor(d$Var1, d$Var2) I can get a single number, but I want to figure out how to get only the Var1 column from the matrix returned by cor(d), with my being able to select the explanatory variables I want included. A: The cor function can actually do this as well. Suppose we have: d=data.frame(dependentVar = c(1,2,3),var1=c(-1,-2,-3),var2=c(9,0,5),junk=c(-2,-3,5)) Then this will do the trick: cor(d[,"dependentVar"], d[,c("var1","var2")]) var1 var2 [1,] -1 -0.4435328 It's less efficient (I guess), but you can also do this: cor(d)["dependentVar", c("var1","var2")] which computes the full correlation matrix, and then pulls out the subset you want. A: @DavidR is correct, though R also supports correlation between the columns of X and columns of Y as: cor(X, Y) See ?cor for more information.
{ "pile_set_name": "StackExchange" }
Q: Hacks to create new instance of rpy2 singleton? Since Rpy2 can be used in parallel, there should be some way to create a new R singleton, otherwise multiprocessing would have caused errors. Is there a way I can start a new rpy2 instance myself using a hack? A: Python's multiprocessing module lets one achieve parallelism through parallel processes. Each such process will run its own embedded R.
{ "pile_set_name": "StackExchange" }
Q: Sum n values in sparse dataset I have a sparse dataset in excel, e.g.: 1 0 2 4 5 8 2 3 0 0 0 6 Zeros represent missing values. I want to sum the first 3 nonmissing values in each row using Excel. Thanks A: For a sum against EACH row, you can do as below: Array formula - use: Ctrl+Shift+Enter =SUM(INDEX($A1:$F1, 1, 1):INDEX($A1:$F1, 1, SMALL(IF($A1:$F1, COLUMN($A1:$F1) - COLUMN($A1) + 1), 3))) Image shows second row selected, but formula I typed shows first row.
{ "pile_set_name": "StackExchange" }
Q: Setting the same key shortcuts for buttons under different tabs I have a frame which is multi tabbed and I have to set shortcuts to certain buttons under different tabs, but they have to use the same key. For example: Under tab1, I have a "Do that" button which should react to F1 key, but if I were to switch to tab2, I should have a "Do this" button which should also react to F1 button but the action on tab1 shouldn't be fired. I have tried adding keylistener to tabs/keys/panels but still, if I were to press F1 key, it's the first action that is fired. But I think the reason is that I use a switch, which controls the key events, such as case KeyEvent.VK_F1:mybutton1.doclick(); So how do I separate actions to react separately under different tabs? Is there a way to get the focused tab for example or something else? Regards. Edit:some code for Swing action: private class SwingAction extends AbstractAction { public SwingAction() { putValue(NAME, "mybutton"); putValue(SHORT_DESCRIPTION, "Some short description"); } public void actionPerformed(ActionEvent e) { mybutton.getInputMap().put(KeyStroke.getKeyStroke("F1"),"pressed"); mybutton.getActionMap().put("pressed",mybutton.doClick()); } } i get : The method put(Object, Action) in the type ActionMap is not applicable for the arguments (String, void) error, ( sorry a Java/Swing newbie here) A: use Swing Action for JButton, you can to set the same JBUtton#setAction() for any JCOmponents that implements Swing Action KeyBindings (for F1) with output to the Swing Action, inside Action you have to call JButton#doClick() don't use KeyListener for Swing JComponents, ever A: Binding a KeyStroke to a button's doClick() has the advantage of visual and auditory feedback; but, as you've observed, doClick() is not an Action. Instead, create an Action that invokes a given button's doClick() method, and bind it to the desired KeyStroke, as shown in this example.
{ "pile_set_name": "StackExchange" }
Q: Android: SharedPreferences doesn`t work fine in fragment Good day, I`m newbie in android. I would like to store some user date with SharedPreferences. I have an activity Questionnaire where user choose his birthday (using datepicker custom library called wdullaer), and here I have radiobutton group (to know user is married or not) if user is in the relationships the fragment shows and suggests to choose partner birthday. It`s work fine when I go through activities, and I return to Questionnaire activity, the SharedPreferences restores perfect and show me user birthday, radiobutton group position, and if needed fragment with partner birthday. The problem is: When I close the app and reopen, the data in activity is restored, but the data in fragment (partner birthday) is lost. Sorry for my poor english, but I hope the idea is understandable for you. The code in Fragment: public class FragmentSettings extends Fragment implements DatePickerDialog.OnDateSetListener { final static String PARTNER_YEAR = "partner_year"; final static String PARTNER_MONTH = "partner_month"; final static String PARTNER_DAY = "partner_day"; static int mYear; static int mMonth; static int mDay; private TextView mDateTextView; private SharedPreferences mSharedPreferences; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_settings, null); mDateTextView = (TextView) v.findViewById(R.id.partner_date_view); mDateTextView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Calendar now = Calendar.getInstance(); DatePickerDialog dpd = DatePickerDialog.newInstance( FragmentSettings.this, now.get(Calendar.YEAR), now.get(Calendar.MONTH), now.get(Calendar.DAY_OF_MONTH) ); dpd.setAccentColor(R.color.mdtp_accent_color); dpd.setThemeDark(true); dpd.show(getFragmentManager(), "DatePickerDialog"); } }); return v; } @Override public void onDateSet(DatePickerDialog datePickerDialog, int year, int monthOfYear, int dayOfMonth) { mYear = year; mMonth = monthOfYear; mDay = dayOfMonth; String mDate = "Your partner birthday: " + dayOfMonth + "/" + (++monthOfYear) + "/" + year; mDateTextView.setText(mDate); } public void onDataSetDefault(int year, int monthOfYear, int dayOfMonth) { String mDate = "Your partner birthday: " + dayOfMonth + "/" + (++monthOfYear) + "/" + year; mDateTextView.setText(mDate); } public void saveUserInfo() { mSharedPreferences = getActivity().getPreferences(0); SharedPreferences.Editor editor = mSharedPreferences.edit(); editor.putInt(PARTNER_DAY, mDay); editor.putInt(PARTNER_MONTH, mMonth); editor.putInt(PARTNER_YEAR, mYear); editor.commit(); Toast.makeText(getActivity(), "Saved Fragment", Toast.LENGTH_SHORT).show(); } public void restoreUserInfo() { mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext()); mYear = mSharedPreferences.getInt(PARTNER_YEAR, mYear); mMonth = mSharedPreferences.getInt(PARTNER_MONTH, mMonth); mDay = mSharedPreferences.getInt(PARTNER_DAY, mDay); if (mYear != 0 && mMonth != 0 && mDay != 0) { onDataSetDefault(mYear, mMonth, mDay); } } @Override public void onResume() { super.onResume(); restoreUserInfo(); } @Override public void onDestroyView() { super.onDestroyView(); saveUserInfo(); } } The code in questionnaire: public class SettingsActivity extends AppCompatActivity implements DatePickerDialog.OnDateSetListener { final static String USER_YEAR = "user_year"; final static String USER_MONTH = "user_month"; final static String USER_DAY = "user_day"; final static String USER_STATUS = "user_status"; final static String USER_SEX = "user_sex"; //Need to store in SharedPreferences static int mYear; static int mMonth; static int mDay; int mSexId; int mStatusId; private TextView mDateTextView; private RadioGroup mRadioSexGroup; private RadioButton mMaleButton; private RadioButton mFemaleButton; private RadioGroup mRadioStatusGroup; private RadioButton mInRelationshipButton; private RadioButton mSingleButton; private View mFragment; private String mDate; private Button mButton; private SharedPreferences mSharedPreferences; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_settings); mDateTextView = (TextView) findViewById(R.id.date_view); mButton = (Button) findViewById(R.id.save_button); mFragment = findViewById(R.id.partner_container); mFragment.setVisibility(View.GONE); mRadioSexGroup = (RadioGroup) findViewById(R.id.radioSex); mMaleButton = (RadioButton) findViewById(R.id.male); mFemaleButton = (RadioButton) findViewById(R.id.female); mRadioStatusGroup = (RadioGroup) findViewById(R.id.user_status); mInRelationshipButton = (RadioButton) findViewById(R.id.in_relationship); mSingleButton = (RadioButton) findViewById(R.id.status_single); mDateTextView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Calendar now = Calendar.getInstance(); DatePickerDialog dpd = DatePickerDialog.newInstance( SettingsActivity.this, now.get(Calendar.YEAR), now.get(Calendar.MONTH), now.get(Calendar.DAY_OF_MONTH) ); dpd.setAccentColor(R.color.mdtp_accent_color); dpd.setThemeDark(true); dpd.show(getFragmentManager(), "DatePickerDialog"); } }); mInRelationshipButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { mFragment.setVisibility(View.VISIBLE); } else { mFragment.setVisibility(View.INVISIBLE); } } }); mButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { saveUserInfo(); startActivity(new Intent(SettingsActivity.this, HomeActivity.class)); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_settings, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the HomeActivity/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @Override public void onDateSet(DatePickerDialog datePickerDialog, int year, int monthOfYear, int dayOfMonth) { mYear = year; mMonth = monthOfYear; mDay = dayOfMonth; mDate = "Your Birthday: " + dayOfMonth + "/" + (++monthOfYear) + "/" + year; mDateTextView.setText(mDate); } public void onDataSetDefault(int year, int monthOfYear, int dayOfMonth) { mDate = "Your Birthday: " + dayOfMonth + "/" + (++monthOfYear) + "/" + year; mDateTextView.setText(mDate); } public void saveUserInfo() { mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); SharedPreferences.Editor editor = mSharedPreferences.edit(); editor.putInt(USER_DAY, mDay); editor.putInt(USER_MONTH, mMonth); editor.putInt(USER_YEAR, mYear); mSexId = mRadioSexGroup.getCheckedRadioButtonId(); mStatusId = mRadioStatusGroup.getCheckedRadioButtonId(); editor.putInt(USER_SEX, mSexId); editor.putInt(USER_STATUS, mStatusId); editor.commit(); } public void restoreUserInfo() { mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); mYear = mSharedPreferences.getInt(USER_YEAR, mYear); mMonth = mSharedPreferences.getInt(USER_MONTH, mMonth); mDay = mSharedPreferences.getInt(USER_DAY, mDay); if((mSharedPreferences.getInt(USER_SEX, mSexId)) == R.id.male){ mMaleButton.setChecked(true); } else if ((mSharedPreferences.getInt(USER_SEX, mSexId)) == R.id.female){ mFemaleButton.setChecked(true); } else { mMaleButton.setChecked(false); mFemaleButton.setChecked(false); } if(mSharedPreferences.getInt(USER_STATUS, mStatusId) == R.id.in_relationship){ mInRelationshipButton.setChecked(true); }else if((mSharedPreferences.getInt(USER_STATUS, mStatusId)) == R.id.status_single){ mSingleButton.setChecked(true); } else { mInRelationshipButton.setChecked(false); mSingleButton.setChecked(false); } if (mYear != 0 && mMonth != 0 && mDay != 0) { onDataSetDefault(mYear, mMonth, mDay); } } @Override protected void onPause() { super.onPause(); saveUserInfo(); } @Override protected void onResume() { super.onResume(); restoreUserInfo(); } } Anyway thank you ! A: My guess is that you are saving to different SharedPreferences than you are retrieving from. You save with this code: mSharedPreferences = getActivity().getPreferences(0); Then you restore with this one: mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext()); Try using the second version on both places.
{ "pile_set_name": "StackExchange" }
Q: Adding Ordinal Contractions to $i Possible Duplicate: php display number with ordinal suffix I'm attempting to add ordinal contractions i.e.(st/nd/rd/th) to an increment. Somehow I need to get the last digit of $i to test it against my if statements... Here is my code so far: $i = 1; while($i < 101 ){ if($i == 1){$o_c = "st";}else{$o_c = "th";} if($i == 2){$o_c = "nd";} if($i == 3){$o_c = "rd";} echo $i.$o_c."<br/>"; $i++; } A: You can use the modulus (%) operator to get the remainder when dividing by 10. $i = 1; while($i < 101 ){ $remainder = $i % 10; if($remainder == 1){$o_c = "st";}else{$o_c = "th";} if($remainder == 2){$o_c = "nd";} if($remainder == 3){$o_c = "rd";} echo $i.$o_c."<br/>"; $i++; }
{ "pile_set_name": "StackExchange" }
Q: UI not updating PropertyChanged with MVVM Is it ever possible that UI skips updating itself although the Visibility of the UI component is binded to ViewModel property and PropertyChanged for that property is implemented? View/XAML: <Border Visibility="{Binding ShowLoadingPanel, Converter={StaticResource BoolToHiddenConverter}}"> <TextBlock Text="LOADING..." /> </Border> ViewModel: Public Property ShowLoadingPanel As Boolean Get Return _showLoadingPanel End Get Set(value As Boolean) _showLoadingPanel = value OnPropertyChanged("ShowLoadingPanel") End Set End Property When running the following from ViewModel: ShowLoadingPanel = True RunBigTask() 'runs a task that takes a long time ShowLoadingPanel = False ...the Border defined in XAML doesn't become visible. But if I add something requiring user interaction, for example like: ShowLoadingPanel = True MsgBox("Click to continue") RunBigTask() 'runs a task that takes a long time ShowLoadingPanel = False ... then the border becomes visible as desired. How is that possible? A: You should really run your long running task in a background thread because it is blocking your UI thread from updating the Visibility... as it is, the Visibility should update when the long running task is complete. It is quite common for users to use a BackgroundWorker object to do this. You can find a complete working example on the BackgroundWorker Class page on MSDN. A common alternative to the BackgroundWorker would be to use a Task object to run your long running process asynchronously. You can find a full working example of using a Task on the Task Class page on MSDN. A: You are blocking the Dispatcher, preventing the layout from being updated. When you open a Message Box, you push a nested message loop that allows the Dispatcher to continue processing its queue until the Message Box is closed. The layout updates are happening during that period. The same thing happens when you call ShowDialog() on a regular Window: your code blocks, but the Dispatcher keeps running so the UI updates as expected. Your code does not resume until the nested message loop is popped, which happens automatically when you close a modal dialog (like your Message Box).
{ "pile_set_name": "StackExchange" }
Q: Android Hierarchy Viewer is not showing performance indicators for a view I am working with Android 2.2. While checking the views using HierarchyViewer, no performance indicators are being displayed. It shows 'n/a' agianst each of the three measures. Why is this happening? A: You need Android 2.3 or later to use this feature.
{ "pile_set_name": "StackExchange" }
Q: R - graph frequency of observations over time with small value range I'd trying to graph the frequency of observations over time. I have a dataset where hundreds of laws are coded 0-3. I'd like to know if outcomes 2-3 are occurring more often as time progresses. Here is a sample of mock data: Data <- data.frame( year = sample(1998:2004, 200, replace = TRUE), score = sample(1:4, 200, replace = TRUE) ) If i plot plot(Data$year, Data$score) I get a checkered matrix where every single spot is filled in, but I can't tell which numbers occur more often. Is there a way to color or to change the size of each point by the number of observations of a given row/year? A few notes may help in answering the question: 1). I don't know how to sample data where certain numbers occur more frequently than others. My sample procedure samples equally from all numbers. If there is a better way I should have created my reproducible data to reflect more observations in later years, I would like to know how. 2). this seemed like it would be best to visualize in a scatter plot, but I could be wrong. I'm open to other visualizations. Thanks! A: Here's how I would approach this (hope this is what you need) Create the data (Note: when using sample in questions, always use set.seed too so it will be reproducible) set.seed(123) Data <- data.frame( year = sample(1998:2004, 200, replace = TRUE), score = sample(1:4, 200, replace = TRUE) ) Find frequncies of score per year using table Data2 <- as.data.frame.matrix(table(Data)) Data2$year <- row.names(Data2) Use melt to convert it back to long format library(reshape2) Data2 <- melt(Data2, "year") Plot the data while showing different color per group and relative size pre frequency library(ggplot2) ggplot(Data2, aes(year, variable, size = value, color = variable)) + geom_point() Alternatively, you could use both fill and size to describe frequency, something like ggplot(Data2, aes(year, variable, size = value, fill = value)) + geom_point(shape = 21) A: Here's another approach: ggplot(Data, aes(year)) + geom_histogram(aes(fill = ..count..)) + facet_wrap(~ score) Each facet represents one "score" value, as noted in the title of each facet. You can easily get a feeling for the counts by looking at the hight of the bars + the colour (lighter blue indicating more counts). Of course you could also do this only for the score %in% 2:3, if you don't want score 1 and 4 included. In such a case, you could do: ggplot(Data[Data$score %in% 2:3,], aes(year)) + geom_histogram(aes(fill = ..count..)) + facet_wrap(~ score) A: So many answers... You seem to want to know if the frequency of outcomes 2-3 is increasing over time, so why not plot that directly: set.seed(1) Data <- data.frame( year = sample(1998:2004, 200, replace = TRUE), score = sample(0:3, 200, replace = TRUE)) library(ggplot2) ggplot(Data, aes(x=factor(year),y=score, group=(score>1)))+ stat_summary(aes(color=(score>1)),fun.y=length, geom="line")+ scale_color_discrete("score",labels=c("0 - 1","2 - 3"))+ labs(x="",y="Frequency")
{ "pile_set_name": "StackExchange" }
Q: How to debug heap in a Native Activity on Android? Is there a way to debug the heap in C++ in a Native Activity for overrun/underrun errors? There is zero Java usage in my application. Something I know about is the MALLOC_CHECK_ which doesn't seem to be applicable to GNU libstdc++. I'm looking for something that would work in that context. A: The solution that worked for me is to get my iOS build working and turn on all the memory diagnosis tools. Albeit this is not an ideal situation for most, it solved the issue I was having.
{ "pile_set_name": "StackExchange" }
Q: Executing Hierarchical Query showing all data I was trying Hierarchical select Query in oracle but Can't get the desire out put from there and don't under stand am i writing the wrong query or there is wrong data in my table my desire out put is like I_ID NAME MGR_ID LEVEL PATH 1 SMITH 0 0 /SMITH 2 ALLEN 1 1 /SMITH/ALLEN 3 WARD 1 1 /SMITH/WARD 5 MARTIN 1 1 /SMITH/MARTIN 4 JONES 2 2 /SMITH/ALLEN/JONES 7 CLARK 2 2 /SMITH/ALLEN/CLARK 6 BLAKE 3 2 /SMITH/WARD/BLAKE 8 SCOTT 7 3 /SMITH/ALLEN/CLARK/SCOTT 9 KING 7 3 /SMITH/ALLEN/CLARK/KING 10 TURNER 8 4 /SMITH/ALLEN/CLARK/SCOTT/TURNER 12 JAMES 8 4 /SMITH/ALLEN/CLARK/SCOTT/JAMES 11 ADAMS 10 5 /SMITH/ALLEN/CLARK/SCOTT/TURNER/ADAMS 13 FORD 11 6 /SMITH/ALLEN/CLARK/SCOTT/TURNER/ADAMS/FORD 14 MILLER 13 7 /SMITH/ALLEN/CLARK/SCOTT/TURNER/ADAMS/FORD/MILLER Please help me out for reference please check A: I used query similar to yours, and grouped the result to select only one row with max level for each i_ids. Query: select * from ( select i_id, name, mgr_id, max(plevel) - 1 "level", max(path) keep (dense_rank last order by plevel) path from ( select i_id, name, mgr_id, level plevel, SYS_CONNECT_BY_PATH(name, '/') path from emp connect by prior i_id = mgr_id ) group by i_id, name, mgr_id ) order by "level", i_id Results: | I_ID | NAME | MGR_ID | LEVEL |PATH | |------|--------|--------|-------|--------------------------------------------------| | 1 | SMITH | 0 | 0 |/SMITH | | 2 | ALLEN | 1 | 1 |/SMITH/ALLEN | | 3 | WARD | 1 | 1 |/SMITH/WARD | | 5 | MARTIN | 1 | 1 |/SMITH/MARTIN | | 4 | JONES | 2 | 2 |/SMITH/ALLEN/JONES | | 6 | BLAKE | 3 | 2 |/SMITH/WARD/BLAKE | | 7 | CLARK | 2 | 2 |/SMITH/ALLEN/CLARK | | 8 | SCOTT | 7 | 3 |/SMITH/ALLEN/CLARK/SCOTT | | 9 | KING | 7 | 3 |/SMITH/ALLEN/CLARK/KING | | 10 | TURNER | 8 | 4 |/SMITH/ALLEN/CLARK/SCOTT/TURNER | | 12 | JAMES | 8 | 4 |/SMITH/ALLEN/CLARK/SCOTT/JAMES | | 11 | ADAMS | 10 | 5 |/SMITH/ALLEN/CLARK/SCOTT/TURNER/ADAMS | | 13 | FORD | 11 | 6 |/SMITH/ALLEN/CLARK/SCOTT/TURNER/ADAMS/FORD | | 14 | MILLER | 13 | 7 |/SMITH/ALLEN/CLARK/SCOTT/TURNER/ADAMS/FORD/MILLER |
{ "pile_set_name": "StackExchange" }
Q: iPhone code signing error I have been working with 2 developer ids for a certain project now. I had developed the app using the 1st Id and tested it even. I need to submit the app to the app store using the 2nd Id, now i have all the right certificates and provisioning profiles in the right place. And i have deleted all certificates and provisioning profiles of the 1st Id. But still i Get this error [BEROR]Code Sign error: The identity 'iPhone Distribution: Sam Sim' doesn't match any valid certificate/private key pair in the default keychain iPhone Distribution: Sam Sim is of the 1st Developer Id which I have removed from keychain. Why cant xcode find the 2nd identity even though its present in the keychain EDIT: might I also add that the first id is an Individual developer id where as the second is a Corporate developer id Please help, Thanks A: Did you change the build settings for the target or project Target->Info->Build->Code Singing
{ "pile_set_name": "StackExchange" }
Q: Custom Java annotations to introduce method parameters and execute code Question Basically, I want to create a custom annotation for methods. When used, a method parameter and a line of code is added. The question is: Is this possible and how? Example I want to simplify the following method: @GetMapping("/thing") public ResponseEntity getThing(@CookieValue("Session-Token") String sessionToken) { User user = authenticator.authenticateSessionTokenOrThrow(sessionToken); ... // user is successfully authenticated, get the "thing" from the database } to @GetMapping("/thing") @User public ResponseEntity getThing() { ... // user is successfully authenticated, get the "thing" from the database } How can I implement the custom annotation @User so that the above two methods behave in the exact same way? For the sake of the example, please ignore the fact that the above code is for the Spring Boot framework. A: Say you have a class with methods like this class MyHandlerClass implements Whatever { @GetMapping("/thing") @User public ResponseEntity getThing() { ... // user is successfully authenticated, get the "thing" from the database } You can use annotation processing to generate a class like this class AuthenticatingMyHandlerClass extends MyHandlerClass { @GetMapping("/thing") public ResponseEntity getThing(@CookieValue("Session-Token") String sessionToken) { User user = authenticator.authenticateSessionTokenOrThrow(sessionToken); ResponseEntity ret = super.getThing(sessionToken); doSomethingWith(ret); return ret; } Then you use the generated class instead of the main class for handling requests and will have any code you added as well.
{ "pile_set_name": "StackExchange" }
Q: Expanding Libre Office with Python I'd like to expand LibreOffice with my own Python scripts. I want to right-click on a word and run a Python script that would send its output to a different window (not change the doc I am working at). For example, I would click on an author name, and the script would search in a local DB for further information about him. Or I'd run a script and it would output some encyclopedia result. How do I expand LibreOffice? A: Following Adobe's suggestion, I went to the openoffice forum. Here is an acceptable answer from there: Intercept Right Click and cause it to run your Python scrpt, which should be treated as any other macro. Information on the OpenOffice Python/Uno bridge is at http://www.openoffice.org/udk/python/python-bridge.html some further discussion at http://forum.openoffice.org/en/forum/viewtopic.php?f=20&t=12643 Edit: A similar problem is under discussion here http://forum.openoffice.org/en/forum/viewtopic.php?f=20&t=63716
{ "pile_set_name": "StackExchange" }
Q: Methodnames in Output-Assembly I am compiling a project with Visual Studio 2013 against .NET 4.5 and then checking it again with ILDASM. What I noticed is that the build in Release still contains method names and variable names, I thought these should be removed in a release-build or do I need an obsfuscator to do that? A: You need an obsfuscator to hide method and member names, local variable names should be stripped by the compiler, but anything that can turn up using reflection is preserved that includes class and interface names, public and private methods, public and private fields. A: As for method names, the compiler doesn't know if your assembly will be used or not in another project, so the preservation of method names is logical. Though variable names can't be used anywhere than in the method where they're defined, I guess it is useful for debugging (be it Debug or Release) and they really take insignificant space. And my advice, don't use obfuscator, unless your application contains security critical codes (and then, I'd still advise obfuscating just this code, not the other methods). It is way better for debugging and reading exceptions.
{ "pile_set_name": "StackExchange" }
Q: Optimal DB structure for additional fields entity I have a table in a DB (Postgres based), which acts like a superclass in object-oriented programming. It has a column 'type' which determines, which additional columns should be present in the table (sub-class properties). But I don't want the table to include all possible columns (all properties of all possible types). So I decided to make a table, containg the 'key' and 'value' columns (i.e. 'filename' = '/file', or 'some_value' = '5'), which contain any possible property of the object, not included in the superclass table. And also made one related table to contain the available 'key' values. But there is a problem with such architecture - the 'value' column should be of a string data type by default, to be able to contain anything. But I don't think converting to and from strings is a good decision. What is the best way to bypass this limitation? A: The design you're experimenting with is a variation of Entity-Attribute-Value, and it comes with a whole lot of problems and inefficiencies. It's not a good solution for what you're doing, except as a last resort. What could be a better solution is what fallen888 describes: create a "subtype" table for each of your subtypes. This is okay if you have a finite number of subtypes, which sounds like what you have. Then your subtype-specific attributes can have data types, and also a NOT NULL constraint if appropriate, which is impossible if you use the EAV design. One remaining weakness of the subtype-table design is that you can't enforce that a row exists in the subtype table just because the main row in the superclass table says it should. But that's a milder weakness than those introduced by the EAV design. edit: Regarding your additional information about comments-to-any-entity, yes this is a pretty common pattern. Beware of a broken solution called "polymorphic association" which is a technique many people use in this situation.
{ "pile_set_name": "StackExchange" }
Q: Check if Clipboard Open I have used the code Application.ShowClipboard to open the clipboard on opening Word. However, this code also closes the clipboard if it is already open. Therefore, I need to know how to check if the clipboard is already open to know whether to execute the code. If Clipboard is open Then Application.ShowClipboard Else Any ideas? A: It seems the Clipboard is part of the Applciation.Commandbars collection. Check to see if Application.CommandBars("ClipBoard").Visible = False and then ShowClipboard else, do nothing. Note: This was tested on Word in Office 365. Sub CheckForClipboard() If Application.CommandBars("Office Clipboard").Visible = False Then Application.ShowClipboard Else 'Do nothing End If End Sub
{ "pile_set_name": "StackExchange" }