source
sequence
text
stringlengths
99
98.5k
[ "worldbuilding.stackexchange", "0000126943.txt" ]
Q: Why would people living inside a nebula go into space? Assuming a sci-fi style nebula, like the thick clouds seen in Star Trek, extending several light years and hosting star systems inside, one of which gave rise to intelligent life up to current human intelligence level. The homeworld of that lifeform has a few natural satellites that are small asteroids captured eons ago. Big enough to be seen as moving lights in the sky, not big enough to be able to discern any feature, other planets of their system are hardly able to be seen due to the luminosity and colors of the nebula. The nebula is a thick flesh-colored cloud of gas. Would that civilization have any incentive to go out into space and why? EDIT: Please do not comment about how unrealistic that kind of nebula is and the problems it would create would it exist in real life. That is not the question I am asking and you will notice the lack of a 'hard-science' tag. Thank you very much. A: We didn't really have much incentive to start space travel, besides war-driven purposes. We have trouble even nowadays convincing the public the value of space travel. We tend to do things that aren't easily explicable with logic, like exploration. Perhaps the people of your story share the same basic human characteristics as us. They realize the implications of Newtonian mechanics in that a bomb can be deployed in the motherland and land in the enemy's on the other side of the world. Perhaps they're just as curious as we are (and would be) about the shifting phantasm gas clouds and the irregular sporadic points of lights in the skies. A: Communications satellites are still totally valid, and therefore plausible. Once in low orbit, resource acquisition seems a reasonable goal. Outside intervention, a la Krikkit, is always a great plot device. Not all electromagnetic signals would be filtered, perhaps inciting curiosity about their origin. And there's always some jackass that wants to see how far they can go. Just some suggestions.
[ "stackoverflow", "0045227663.txt" ]
Q: I am trying to create a socket in python 3 but i get this error, even when i copy code stragte from the web I am new an am learning network programming and I have a problem, whenever I try to create a socket, even how a tutorial tells me to, I get this error when I run the code, and also it has a problem with how I imported sockets and threading. This project is a basic server that will send all the errors and high resource usage from a desk workers machine to an old tower I have, this is for monitoring purposes and because we just upgraded to windows 10 in the office and I am getting a lot of complaints about slow and not working programs and machines. Thanks a bunch. The Error: harrison@dev-box:~/Desktop/dns# python3 socket.py Traceback (most recent call last): File "socket.py", line 1, in <module> import socket File "/root/Desktop/dns/socket.py", line 4, in <module> sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) AttributeError: module 'socket' has no attribute 'AF_INET' The Code import socket import threading sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.bind(('0.0.0.0', 504)) sock.listen(1) log = open("log.txt", "w") def handler(connection, address): while True: data = c.recv(1024) print(data) for connection in connections: connection.send(bytes(data + "Hello World")) if not data: connection.remove(c) c.close() break while True: connection, address = sock.accept() cThread = threading.Thread(target=handler, args=(connection, address)) cThread.daemon = True cThread.start() log.write(connection + "/n" + address + "/n") data, addr = sock.recv() A: You have to rename your socket.py into something else like mysocket.py, which will avoid to conflict with the default python library socket.
[ "ru.stackoverflow", "0000448937.txt" ]
Q: Проблема с установкой phalcone Делаю так: sudo apt-get install php5-dev libpcre3-dev gcc make php5-mysql git-core autoconf /home/phalcon# git clone --depth=1 git://github.com/phalcon/cphalcon.git /home/phalcon# cd cphalcon/build /home/phalcon/cphalcon/build# sudo ./install Ответы: Build complete. Don't forget to run 'make test'. Installing shared extensions: /usr/lib/php5/20121212/ Installing header files: /usr/include/php5/ Далее echo 'extension=phalcon.so' | sudo tee -a /etc/php5/mods-available/phalcon.ini cd /etc/php5/mods-available sudo php5enmod phalcon /etc/init.d/php5-fpm restart sudo service nginx restart Но в результате пусто http://smartcook.info/resource/ Еще пробовал вот так: sudo apt-add-repository ppa:phalcon/stable sudo apt-get update sudo apt-get install php5-phalcon В общем топорно решил вопрос снес все поставил заново строкой sudo apt-get install php5-cli php5-common php5-mysql php5-fpm php-pear php5-phalcon A: Возможно что ваша проблема заключается в установке приоритета php экстеншена. Попробуйте в папке /etc/php5/fpm/conf.d создать файл 21-phalcon.ini в котором определить расширение для phalcon. При вызове php -m секция phalcon должна отображаться в списке [PHP Modules]. P.s. https://forum.phalconphp.com/discussion/1851/phalcon-extension-not-loaded
[ "math.stackexchange", "0002237595.txt" ]
Q: Help finding the values for $a$ and $b$ that make the function continuous and differentiable everywhere. Finding the values for $a$ and $b$ that make the function continuous and differentiable everywhere. $$L(t) = \begin{cases} \dfrac at & t \le 1 \\ 3t+b & t > 1 \end{cases}$$ Thanks for helping. A: HINTS Continuity: $\dfrac a{(1)} = 3(1)+b$ Differentiability: $\dfrac{-a}{(1)^2} = 3$
[ "stackoverflow", "0013460121.txt" ]
Q: iOS - Updating label during animation transition? I have a UIView on the screen that contains a few labels. I am trying to have a transition where flips the view, and as soon as I am half way through the nimation I want to be able to update the labels. How Can I achieve this? [UIView transitionWithView:self.myView duration:.7 options:UIViewAnimationOptionTransitionFlipFromBottom animations:^{ // It doesn't update the labels here, until I scoll the tableview (containing the view) //[self.myView update]; } completion:^(BOOL finished){ // It doesn't look nice here because it doesn't look smooth, the label flashes and changes after the animation is complete //[self.myView update]; }]; A: The problem was that I had shouldRasterize enabled which was not allowing the content to be updated during an animaton. Solution was to turn off rasterization before the animation and turn it back on after animation completion. The reason why I didn't get rid of rasterization is that the view is inside a tableView, and rasterization still helps while scrolling through the tableView. self.layer.shouldRasterize = NO; [UIView transitionWithView:self duration:animationDuration options:UIViewAnimationOptionTransitionFlipFromBottom animations:^{/*update the content here, I did it outside of the transition method though*/} completion:^(BOOL finished){ if (finished) { self.layer.shouldRasterize = YES; } }];
[ "stackoverflow", "0010750146.txt" ]
Q: Linq select to new object I have a linq query var x = (from t in types select t).GroupBy(g =>g.Type) which groups objects by their type, as a result I want to have single new object containing all of the grouped objects and their count. Something like this: type1, 30 type2, 43 type3, 72 to be more clear: grouping results should be in one object not an object per item type A: Read : 101 LINQ Samples in that LINQ - Grouping Operators from Microsoft MSDN site var x = from t in types group t by t.Type into grp select new { type = grp.key, count = grp.Count() }; forsingle object make use of stringbuilder and append it that will do or convert this in form of dictionary // fordictionary var x = (from t in types group t by t.Type into grp select new { type = grp.key, count = grp.Count() }) .ToDictionary( t => t.type, t => t.count); //for stringbuilder not sure for this var x = from t in types group t by t.Type into grp select new { type = grp.key, count = grp.Count() }; StringBuilder MyStringBuilder = new StringBuilder(); foreach (var res in x) { //: is separator between to object MyStringBuilder.Append(result.Type +" , "+ result.Count + " : "); } Console.WriteLine(MyStringBuilder.ToString()); A: The answers here got me close, but in 2016, I was able to write the following LINQ: List<ObjectType> objectList = similarTypeList.Select(o => new ObjectType { PropertyOne = o.PropertyOne, PropertyTwo = o.PropertyTwo, PropertyThree = o.PropertyThree }).ToList(); A: All of the grouped objects, or all of the types? It sounds like you may just want: var query = types.GroupBy(t => t.Type) .Select(g => new { Type = g.Key, Count = g.Count() }); foreach (var result in query) { Console.WriteLine("{0}, {1}", result.Type, result.Count); } EDIT: If you want it in a dictionary, you can just use: var query = types.GroupBy(t => t.Type) .ToDictionary(g => g.Key, g => g.Count()); There's no need to select into pairs and then build the dictionary.
[ "stackoverflow", "0004458863.txt" ]
Q: How to align view to right of the screen in Android? How to align view to right of the screen in Android ? i have used <LinearLayout android:id="@+id/heading" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="horizontal"> <ImageView android:id="@+id/widget30" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/logo_cpw"> </ImageView> <EditText android:id="@+id/widget28" android:layout_width="134px" android:layout_height="35px" android:text="EditText" android:textSize="18sp" android:background="@drawable/rounded_edit_text_effects" android:gravity="right" android:layout_alignParentRight="true"> </EditText> </LinearLayout> But it is not aligning to the right ? any help ? A: Try replacing LinearLayout with RelativeLayout.
[ "math.stackexchange", "0003684685.txt" ]
Q: $\int^x_2 (\log u)^{-2} du\ll x(\log x)^{-2}$ I came across this estimation in a book: $$ \int^x_2 (\log u)^{-2} du \ll x(\log x)^{-2}. $$ I tried to prove it by first integrating by parts: $$ \int^x_2 (\log u)^{-2} du = x(\log x)^{-2}-2(\log 2)^{-2} + 2\int^x_2 (\log u)^{-3} du, $$ but was then stuck. Could someone show me how to establish the estimation? A: By L'Hospital's rule $$ \mathop {\lim }\limits_{x \to + \infty } \frac{{\int_2^x {\frac{{du}}{{\log ^2 u}}} }}{{\frac{x}{{\log ^2 x}}}} = \mathop {\lim }\limits_{x \to + \infty } \frac{{\frac{1}{{\log ^2 x}}}}{{\frac{1}{{\log ^2 x}} - \frac{2}{{\log ^3 x}}}} = \mathop {\lim }\limits_{x \to + \infty } \frac{1}{{1 - \frac{2}{{\log x}}}} = 1. $$ Thus we in fact have $$ \int_2^x {\frac{{du}}{{\log ^2 u}}} \sim \frac{x}{{\log ^2 x}}. $$
[ "stackoverflow", "0008896814.txt" ]
Q: how to send smtp mail in java 1.5? So this is an old app, I don't have access to javax mail components. What are my options to send out email from a java app, please? A: You can download the JAR file containing the javax.mail APIs from Maven Central - http://mvnrepository.com/artifact/com.sun.mail/javax.mail/1.4.4 (Or if you are using Maven or Ivy, just add the dependency.)
[ "stackoverflow", "0000774537.txt" ]
Q: How to get list of intermediate sums in a functional way? Using LINQ? Given a list of objects i need to return a list consisting of the objects and the sum of a property of the objects for all objects in the list seen so far. More generally given var input = new int[] {1,2,3} I would like to have the output of // does not compile but did not want to include extra classes. var output = { (1,1), (2,3), (3,6) }; What is the "right" functional way to do this? I can do it in a standard iterative approach of course but I am looking for how this would be done in a functional, lazy way. Thanks A: I think this is the shortest approach: int sum = 0; var result = input.Select(i => new { i, S = sum += i }); A: in functional terms this is a combination of : zip take two sequences and create a sequence of tuples of the elements and map Take a function f and a sequence and return a new sequence which is f(x) for each x in the original sequence The zip is trivial in c# 4.0 Taking the simplistic implementation from there we have static class Enumerable { public static IEnumerable<TResult> Zip<TFirst, TSecond, TResult>( this IEnumerable<TFirst> first, IEnumerable<TSecond> second, Func<TFirst, TSecond, TResult> func) { var ie1 = first.GetEnumerator(); var ie2 = second.GetEnumerator(); while (ie1.MoveNext() && ie2.MoveNext()) yield return func(ie1.Current, ie2.Current); } } We then need the map. We already have it, it's what we call Select in c# IEnumerable<int> input = { 1,2,3,4 }; int a = 0; var accumulate = input.Select(x => { a += x; return a; }); But it is safer to bake this into it's own method (no currying in c#) and allow support for arbitrary types/accumulations. static class Enumerable { public static IEnumerable<T> SelectAccumulate<T>( this IEnumerable<T> seq, Func<T,T,T> accumulator) { var e = seq.GetEnumerator(); T t = default(T); while (e.MoveNext()) { t = accumulator(t, e.Current); yield return t; } } } Then we can put them together like so var input = new int[] {1,2,3}; var mapsum = input.Zip( input.SelectAccumulate((x,y) => x+y), (a,b) => new {a,b}); This will iterate over the sequence twice, but is more general. You could choose to do the accumulator yourself within a standard select and a simple closure but it is no longer so useful as a 'building block' which is one of the driving forces behind functional programming. Tuple support is a pain except within a method as the anonymous types don't traverse method boundaries without quite a bit of hassle. A few basic tuples should be included in c# 4.0. assuming a tuple class/struct called Pair<T,U> you could do: public static IEnumerable<Pair<T,T>> ZipMapAccumulate<T>( this IEnumerable<T> input, Func<T,T,T> accumulator) { return input.Zip( input.SelectAccumulate((x,y) => accumulator (x,y)), (a,b) => new Pair<T,T>(a,b)); } //get an int specific one public static Func<IEnumerable<int>, IEnumerable<Pair<int,int>>> ZipMapSum() { return input => Enumerable.ZipMapAccumulate( input, (i,j) => i + j); } Where c# linq becomes much more cumbersome than languages like f# is the poor support for operators, currying and tuples unless you keep everything inside one function and 'reconstruct it' each and every time for each type.
[ "stackoverflow", "0026678557.txt" ]
Q: A simple regex match I have (from long ago) problems with regex matching... (I simply can't understand and remeber this damn thing...) However, i'd like to find a string that is the end or a table row and the beginning of another row: <tr>(-line-break or spaces or both...)</tr> I am trying with Regex.Match(_mainTable, @"</tr>*<tr>") but it returns Empty A: the * is a quantifier. That means zero or more of the previous match, which in your expression is the > that appears before the * .. what you what is to match "any spaces" the is indicated by the abreviation \s which is a shortcut for: any character in the set [ \t\r\n] so your code should be Regex.Match(_mainTable, @"</tr>\s*<tr>")
[ "stackoverflow", "0029634824.txt" ]
Q: sails.js Sessions - rememberme functionality I have been trying to implement rememberme functionality using sails. I want a session to persist until the browser is closed. However, if a rememberme checkbox is ticked when the user logins in I want the session to persist for 30 days. I used the remember me passport strategy from here: https://github.com/jaredhanson/passport-remember-me but it ends up sitting on top of the sails session and the one called first ends up superseding the other. A: You can set the cookie age just before calling the login function. I did it in my login controller -> passport.callback. passport.callback(req, res, function (err, user, challenges, statuses) { ... if (req.param('remember', false) == true) { req.session.cookie.maxAge = 1000 * 60 * 60 * 24 * 30; } req.login(user, function (err) { ... } } This doesn't really feel right and, if you are sending some other cookies when logging in, it will affect their lifetime as well. But it works and I went with it since finding documentation for sails-related stuff is like digging oil. Also, I noticed that Passport was not destroying sessions properly upon and had to do it manually by calling req.session.destroy(); in the logout controller.
[ "stackoverflow", "0004119556.txt" ]
Q: match end of line javascript regex I'm probably doing something very stupid but I can't get following regexp to work in Javascript: pathCode.replace(new RegExp("\/\/.*$","g"), ""); I want to remove // plus all after the 2 slashes. A: Seems to work for me: var str = "something //here is something more"; console.log(str.replace(new RegExp("\/\/.*$","g"), "")); // console.log(str.replace(/\/\/.*$/g, "")); will also work Also note that the regular-expression literal /\/\/.*$/g is equivalent to the regular-expression generated by your use of the RegExp object. In this case, using the literal is less verbose and might be preferable. Are you reassigning the return value of replace into pathCode? pathCode = pathCode.replace(new RegExp("\/\/.*$","g"), ""); replace doesn't modify the string object that it works on. Instead, it returns a value. A: This works fine for me: var str = "abc//test"; str = str.replace(/\/\/.*$/g, ''); alert( str ); // alerts abc
[ "stackoverflow", "0042856816.txt" ]
Q: How to get from a hashset all the elements that are of a particular subclass in c#? Lets say we have the classes Animal, Dog and Cat. Dog and Cat both extend Animal. public class Animal{} public class Dog : Animal{} public class Cat : Animal{} Then we make a hashset of animals and populate it with both cats and dogs. HashSet<Animal> animals = new HashSet<Animal>(); animals.Add(new Dog()); animals.Add(new Cat()); animals.Add(new Dog()); animals.Add(new Cat()); What is the best way to get a hashset or list of all the dogs (and nothing but the dogs) contained in the hashset animals? A: You can use LINQ for this. var dogs = animals.Where(x => x.GetType() == typeof(Dog)).ToList(); or shorter and with null handling var dogs = animals.Where(x => x is Dog).ToList(); 101 LINQ examples
[ "stackoverflow", "0032033090.txt" ]
Q: Why do 2 .col divs stack on top of each other and how to repeat this on the opposite side in boostrap? .box1,.box2,.box3,.box4,.box5,.box6, .box7 { border: 1px red solid; } .box1 { padding: 140px 10px 0 10px; background: #000 url("../img/...") center center; background-size: cover; color: #fff; border-radius: 0; height: 250px; } .box2 { padding: 71.6px 10px 0 10px; background: #000 url("../img/...") center center; background-size: cover; color: #fff; border-radius: 0; margin-bottom: 5px; } .box3 { padding: 71.6px 10px 0 10px; background: #000 url("../img/...") top center; background-size: cover; color: #000; border-radius: 0; margin-top: 5px; } <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css" rel="stylesheet"/> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/> <div class="row"> <div class="col-sm-6"> <div class="col-sm-12 box1"> <h3>Here is Heading for Box1</h3> </div> </div> <div class="col-sm-6"> <div class="col-sm-12 box2"> <h3>Here is Heading for Box2</h3> </div> </div> <div class="col-sm-6"> <div class="col-sm-12 box3"> <h3>Here is Heading for Box3</h3> </div> </div> </div> <div class="row"> <div class="col-sm-4"> <div class="col-sm-12 box4"> <h3>here is the heading</h3> </div> </div> <div class="col-sm-4"> <div class="col-sm-12 box5"> <h3>here is the heading</h3> </div> </div> <div class="col-sm-4"> <div class="col-sm-12 box6"> <h3>here is the heading</h3> </div> </div> <div class="col-sm-4"> <div class="col-sm-12 box7"> <h3>here is the heading</h3> </div> </div> </div> Here is the link to the Wish Pic for the layout: http://i.imgur.com/1pEMddV.jpg As you can see in the attached picture, I am looking to create a layout with 2 rows in Bootstrap. I have been able to create the first row - but I cannot get the second row layout to work. I am struggling with .box4 and .box5 being on top of each other while both being on the left of .box6. Although now I have no idea how, as you can see from the attached code, I have been able to make the upper row work (having .box2 on top of .box3). I have been trying to disect the code over the last few days and I am really struggling as to how the first row is working and the second one isnt. Any help is much appreciated. ****Please note**** - .boxNumber classes are given in addition to .col classes for further styling purposes. - There are .col classes within .col classes because of the spacing in between the boxes (columns) / for styling purposes. - I have added a border to each box for visualisation purposes Please preview the embedded conde on a screen with width larger than 768px. If someone might be able to tell me how the first row is working I might be able to figure out the second row. A: This might help you. Bootstrap Grid. .box1 { background: red; } .box2 { background: lightblue; } .box3 { background: yellow; } .box4 { background: teal; } .box5 { background: black; } .box6 { background: blue; } .box7 { background: grey; } p { font-size: 20px; text-align: center; color: white; } <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" /> <div class="container-fluid"> <div class="col-sm-6 box1"> <p>It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using</p> </div> <div class="row"> <div class="col-sm-6"> <div class="col-lg-12 box2"> <p>It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using</p> </div> <div class="col-lg-12 box3"> <p>It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using</p> </div> </div> </div> </div> <hr> <div class="container-fluid"> <div class="row"> <div class="col-sm-4"> <div class="col-md-12 box4"> <p>It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using</p> </div> <div class="col-md-12 box5"> <p>It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using</p> </div> </div> <div class="col-sm-4"> <div class="col-lg-12 box6"> <p>It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using</p> </div> </div> <div class="col-sm-4"> <div class="col-lg-12 box6"> <p>It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using</p> </div> </div> </div> </div>
[ "chess.meta.stackexchange", "0000000686.txt" ]
Q: That was quick: "Is Auto Chess good for the future of chess?" closed already. Why? Is it really the case that just two votes are sufficient to close a question these days? I may not like the subject matter, but it would be a terrible thing if we can't discuss the evolution of gaming formats in a calm, qualitative way, without having degrees in data science to introduce the necessary analytics so that the question isn't "opinion-based". There is a complete misconception about this term. To me, an opinion-based question is something like "Is coffee better than tea?" The Auto Chess question here is like "Are drones good for the future of society?" It's the kind of question which one can imagine encountering in a University Entrance Exam. Answers may display clear, logical thinking, evenhandedly discussing pros and cons, bearing in mind that we probably don't have statistical evidence. Sometimes I think (and I apologize if I do fellow members here an injustice) that if a person doesn't like a subject, they will reach for the nearest convenient excuse to block that discussion, even if it is inappropriate. This case is particularly egregious since it refers to a newcomer. What a nice welcome for this person! And as usual, the Hammer of Closing has been wielded without no argument as to how this particular question is "opinion-based". So ironically, without any supporting evidence, this closing decision is "just an opinion". Glorfindel in particular I expected better of you! (You may take this as a compliment.) EDIT: There is a big difference between a "discussion-based question" and a "discussion focused on diverse opinion" (which I read as intended as a euphemism for polarized argument). I see nothing wrong with discussion-based questions. If you look at some other thriving Stack Exchanges, here are some random discussion-type questions which I think are totally cool. This is exactly the kind of thing we need more of in chess.com: WORLDBUILDING What species of animal could take over earth if humans went extinct? WRITING How can I get 2 characters to bond while standing alternate watches? OPEN SOURCE Does the three clause BSD license hinder academic citations? WORKPLACE How do I tell our HR that I don't want to perform in our Christmas party? Sometimes a question needs editing but this one is honestly focused and fine. I didn't leave a comment because the banner above the question contains a link to the help center explaining why questions like that are closed. That gives the stark rule in the abstract, but the whole issue here is the mapping between this rule and this question. Justification of the opinion that this mapping is correct (which it may well be) is reasonably required of anyone choosing to wield the Close Hammer. This is doubly true for a newcomer's post. EDIT2: Thanks for your detailed response, Glorfindel. I really appreciate you taking the time. You haven’t yet addressed my distinction between discussion-based questions and what I rephrased as polarised argument. I don’t think you have shown sufficient grounds to map the question to the policy that you cited. It doesn’t apply. But you do introduce a surprising idea - that chess is different from other hobby Stack Exchanges, and you are trying to be closer to an engineering Stack Exchange of some kind. This to me seems very strange. And I don’t actually see this spelled out in the CSE “terms and conditions” that I’ve read. Please let’s remember that chess is just “a bit of fun”. I am not suggesting go crazy but it is perfectly reasonable that a question may have multiple answers and yet not be “opinion-based”. The problem, which has been observed over and over again on Stack Exchange, is that in practice most answers won't display this behaviour; they tend to generate low-quality answers (mostly) by new users who aren't too familiar with the Stack Exchange format. Then we have to moderate those answers, so on Stack Exchange we tend to tackle the root problem, which in this case is the question. Yes, it may be an interesting or even good question, it just isn't well-suited for the Stack Exchange. And this idea rather undercuts your paragraph about problems at the SE level. These other hobby SEs manage to thrive without descending into “low-quality”. I suspect that this strange view is one cause of the difficulties CSE has had expanding as a forum. We never escaped from Beta under our own merits, let’s remember, it’s just that the powers-that-be got tired of waiting. The arrival of Auto Chess is an interesting topical phenomenon, and it deserves a question in CSE about its long term impact, positive and negative, on our hobby. But I realise now that I have a broader concern with the peculiar reluctance to accept open-ended questions at all in CSE. If you are concerned about hypothetical low-quality answers, then isn’t there a mechanism you have for mandating a minimum point level on responders to a certain question? Bottom line: Chess is only a hobby not engineering and IMHO we should model ourselves more on other responsible and successful hobby SEs. EDIT3: my final comment on this matter. In my opinion we need to be extremely rigorous and self-critical in closing any question, particularly when newcomers are involved. It is all too easy to not like a subject and flail around for a vague reason like the "opinion-based" hammer. It's just not good enough. The absence of explanation to the poor newcomer of why this particular reason was applicable is particularly shocking. The fact that Remillion came up with a better reason is no excuse for the earlier "opinion-based" reflex, although Glorfindel may feel that Remillion let him off the hook in some sense. Glorfindel has not engaged with my point that to explain the relationship between Auto Chess and real Chess (which is more complex than Remillion's sound bite suggests) would be a useful topic for one (1) CSE question. Far better to answer that question properly in the real CSE than superficially in the meta area here. Why should the moderator prejudge the issue here? It's so odd to insist on that. Glorfindel has also not engaged with my more general suggestion that we should model ourselves on the much busier hobby websites than ours, in order to encourage more interesting and diverse content, and bring new users in. Of course there are subjects which would probably be irrelevant to us, e.g. politics. But that's no excuse for failing to give the benefit of the doubt to honest questions whose answer can shed light on chess. I'm sorry to have repeated myself a little here, but I feel many of my recent points were not addressed in the moderatorial response. However, this is my last post on this matter. A: I have a slightly different opinion on the topic in question: it is not suited for Chess SE at all, and should be migrated to Gaming SE. The whole Auto Chess genre reads and plays nothing like chess. It's a different system altogether, with the only similarity being "chess" in the name. Asking about its impact on the chess community is like asking what impact an industrial lead poisoning incident would have on the sale of pencil lead. Gaming SE would naturally be a better environment for this topic. A: Discussion-type questions don't fly well on Stack Exchange, this has been pointed out over and over again; maybe not here but certainly on Meta Stack Exchange, e.g. here: Give each site a parallel site for polling, recommendations and subjective-ish stuff. I didn't leave a comment because the banner above the question contains a link to the help center explaining why questions like that are closed: Opinion-based - discussions focused on diverse opinions are great, but they just don't fit our format well. Many good questions generate some degree of opinion based on expert experience, but answers to this question will tend to be almost entirely based on opinions, rather than on facts, references, or specific expertise. It’s often possible to rewrite opinion-based questions to focus on a more fact-based line of questioning. If you see a way to do this, consider editing the question. I don't see a way to rescue this particular question from being primarily opinion-based (if I did, I would have done so already), but if you do, feel free to edit it and I'll consider reopening it. It's the kind of question which one can imagine encountering in a University Entrance Exam. Answers may display clear, logical thinking, evenhandedly discussing pros and cons, bearing in mind that we probably don't have statistical evidence. Yes, it might be possible to formulate such a quality answer to this type of question. The problem, which has been observed over and over again on Stack Exchange, is that in practice most answers won't display this behaviour; they tend to generate low-quality answers (mostly) by new users who aren't too familiar with the Stack Exchange format. Then we have to moderate those answers, so on Stack Exchange we tend to tackle the root problem, which in this case is the question. Yes, it may be an interesting or even good question, it just isn't well-suited for the Stack Exchange. You mention some questions with a similar nature on our sister sites. Worldbuilding and Writing see many of those open-ended questions, and they're used to moderate those kind of posts precisely because they see many of them. Still, they're kind of different: they ask the answerers to respond to a piece of fiction with other pieces of fiction. The Workplace has a back it up rule, and so do other sites that by their nature tend to subjective questions, like Interpersonal Skills and Parenting; Chess Stack Exchange is not one of those sites. I'm not sure if the question on Open Source is similar to the Auto Chess one; I think it's more akin to this question (but YMMV).
[ "stackoverflow", "0007175446.txt" ]
Q: Proper mysql syntax I have no clue as to how to properly write this in raw sql, so I'll try and supply as much clear information as I can. Goal in "english" I would like to select the value column.. in site_tmplvar_contentvalues.. where contentid = 8 and tmplvarid = 1 A: SELECT `value` FROM site_tmplvar_contentvalues WHERE contentid=8 and tmplvarid=1
[ "superuser", "0001179537.txt" ]
Q: The SSL CA cert (path? access rights) on Ubuntu 16? Problem with the SSL CA cert (path? access rights?). I got a SSL cert from Commodo and it installed ok. Everything seems to be working correctly and I have restarted my server and Apache2. Service apache2 status shows no errors. This was used: sudo apt-get update && sudo apt-get upgrade -fy && sudo apt-get dist-upgrade -fy The issues I see online either deal with Amazons Linux (using yum) or CentOS. They said to restart the server. I am using Ubuntu 16.04 and not sure what to do next? This affects packages being downloaded such as this example: I tried to do a command such as: I made a composer.json file { "require": { "aws/aws-sdk-php": "3.*" } } composer install [RuntimeException] Failed to clone https://github.com/jmespath/jmespath.php.git via https, ssh protocols, aborting. - https://github.com/jmespath/jmespath.php.git Cloning into '/var/www/ssl/s3/test/vendor/mtdowling/jmespath.php'... fatal: unable to access 'https://github.com/jmespath/jmespath.php.git/': Problem with the SSL CA cert (path? access rights?) - [email protected]:jmespath/jmespath.php.git Cloning into '/var/www/ssl/s3/test/vendor/mtdowling/jmespath.php'... Permission denied (publickey). fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists. A: In my opinion SSH key is not authorized in this scenario and you need to create public SSH key and ask the admin of Git repository to add SSH public key. You can refer below URL for more information: https://stackoverflow.com/questions/7430311/saving-ssh-key-fails/8600087#8600087 A: I encountered the git clone error on a small Debian distro (Voyage Linux), and it was because the standard root CAs weren't installed, meaning that git (and even simple things like curl https://google.com) couldn't verify the SSL certificates of HTTPS sites. The solution at lxadm, which worked for me, was just to install ca-certificates: sudo apt install ca-certificates
[ "stackoverflow", "0006914257.txt" ]
Q: rails sorting blog posts by title I realize that this could be a rare occurrence (that two or more users would have the same blog post title) but this is something my client wants so, I have to figure it out. I have a query @blog_posts (which is a query on Posts that changes based on location, etc). I need a way to to list out all the posts titles and how many times that title occurs within the query @blog_posts Like this: How to clean a car (2) I love baseball (1) Is there a standard practice for grouping and sorting? In summary, I need to count the occurrences in the query @blog_posts = Post.where(...) (for example) -- not all posts in existence. A: Sounds like you basically want to count occurrences: this answer could be adapted to your purposes. If you're on 1.8.7 or newer, consider group_by: ruby-1.9.2-p180 :002 > posts = ["How to clean a car", "How to clean a car", "I love baseball"] => ["How to clean a car", "How to clean a car", "I love baseball"] ruby-1.9.2-p180 :007 > posts.group_by {|e| e}.map {|k, v| {k => v.length}} => [{"How to clean a car"=>2}, {"I love baseball"=>1}]
[ "stackoverflow", "0005372859.txt" ]
Q: No transaction starts within Spring @Transactional method I run into strange problem while developing application using Spring (3.0.5), Hibernate (3.6.0) and Wicket (1.4.14). The problem is: i cannot save or modify any object into database. By 'cannot' I mean that all changes in object or calls to EntityManager.persist(foo) are simply, silently ignored. Selects work. Sample case is simple - on some wicket page i try to save object into database, like follows public class ComicDetailsPage extends PublicBasePage { @Override protected void onConfigure() { System.out.println("In onConfigure"); super.onConfigure(); comicDAO.insert("abc"); } @SpringBean(name="comicDAO") private ComicDAO comicDAO; (....) Here is comicDAO @Service public class ComicDAO { @PersistenceContext private EntityManager em; (...) @Transactional public void insert(String title) { Comic c = new Comic(); c.setTitle(title); em.persist(c); } @Transactional public Comic add1toTitle(int pk) { System.out.println("Beginning fetching"); Comic c = em.find(Comic.class, pk); System.out.println("Fetched updating"); c.setTitle(c.getTitle()+"1"); System.out.println("Updated persisting"); em.persist(c); System.out.println("Persisted returning"); return c; } I turned on logging and here is relevant part of logs (both Hibernate and Spring are set to TRACE). I added ** to lines I think are important here. In onConfigure 01:53:19.330 [qtp2119047503-15] DEBUG o.s.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'txManager' **01:53:19.330 [qtp2119047503-15] DEBUG org.hibernate.impl.SessionImpl - opened session at timestamp: 13006687993** **01:53:19.330 [qtp2119047503-15] DEBUG org.hibernate.transaction.JDBCTransaction - begin** 01:53:19.330 [qtp2119047503-15] DEBUG org.hibernate.jdbc.ConnectionManager - opening JDBC connection 01:53:19.335 [qtp2119047503-15] DEBUG org.hibernate.transaction.JDBCTransaction - current autocommit status: true 01:53:19.335 [qtp2119047503-15] DEBUG org.hibernate.transaction.JDBCTransaction - disabling autocommit 01:53:19.336 [qtp2119047503-15] TRACE org.hibernate.jdbc.JDBCContext - after transaction begin 01:53:19.336 [qtp2119047503-15] DEBUG org.hibernate.impl.SessionImpl - opened session at timestamp: 13006687993 01:53:19.336 [qtp2119047503-15] TRACE org.hibernate.impl.SessionImpl - setting flush mode to: AUTO 01:53:19.336 [qtp2119047503-15] TRACE org.hibernate.impl.SessionImpl - setting cache mode to: NORMAL 01:53:19.337 [qtp2119047503-15] TRACE org.hibernate.engine.IdentifierValue - id unsaved-value: 0 01:53:19.337 [qtp2119047503-15] TRACE org.hibernate.event.def.AbstractSaveEventListener - transient instance of: pl.m4ks.comics.entity.Comic 01:53:19.337 [qtp2119047503-15] TRACE org.hibernate.event.def.DefaultPersistEventListener - saving transient instance **01:53:19.338 [qtp2119047503-15] TRACE org.hibernate.event.def.AbstractSaveEventListener - saving [pl.m4ks.comics.entity.Comic#<null>]** **01:53:19.341 [qtp2119047503-15] DEBUG org.hibernate.event.def.AbstractSaveEventListener - delaying identity-insert due to no transaction in progress** 01:53:19.341 [qtp2119047503-15] TRACE org.hibernate.impl.SessionImpl - closing session 01:53:19.341 [qtp2119047503-15] TRACE org.hibernate.jdbc.ConnectionManager - connection already null in cleanup : no action 01:53:19.341 [qtp2119047503-15] DEBUG org.hibernate.transaction.JDBCTransaction - commit **01:53:19.341 [qtp2119047503-15] TRACE org.hibernate.impl.SessionImpl - automatically flushing session** 01:53:19.341 [qtp2119047503-15] TRACE org.hibernate.jdbc.JDBCContext - before transaction completion 01:53:19.341 [qtp2119047503-15] TRACE org.hibernate.impl.SessionImpl - before transaction completion 01:53:19.342 [qtp2119047503-15] DEBUG org.hibernate.transaction.JDBCTransaction - re-enabling autocommit 01:53:19.342 [qtp2119047503-15] DEBUG org.hibernate.transaction.JDBCTransaction - committed JDBC Connection 01:53:19.342 [qtp2119047503-15] TRACE org.hibernate.jdbc.JDBCContext - after transaction completion 01:53:19.342 [qtp2119047503-15] DEBUG org.hibernate.jdbc.ConnectionManager - transaction completed on session with on_close connection release mode; be sure to close the session to release JDBC resources! 01:53:19.342 [qtp2119047503-15] TRACE org.hibernate.impl.SessionImpl - after transaction completion 01:53:19.342 [qtp2119047503-15] TRACE org.hibernate.impl.SessionImpl - closing session 01:53:19.342 [qtp2119047503-15] TRACE org.hibernate.jdbc.ConnectionManager - performing cleanup 01:53:19.342 [qtp2119047503-15] DEBUG org.hibernate.jdbc.ConnectionManager - releasing JDBC connection [ (open PreparedStatements: 0, globally: 0) (open ResultSets: 0, globally: 0)] 01:53:19.342 [qtp2119047503-15] TRACE org.hibernate.jdbc.JDBCContext - after transaction completion 01:53:19.342 [qtp2119047503-15] DEBUG org.hibernate.jdbc.ConnectionManager - transaction completed on session with on_close connection release mode; be sure to close the session to release JDBC resources! 01:53:19.342 [qtp2119047503-15] TRACE org.hibernate.impl.SessionImpl - after transaction completion Of course No object is saved into database. The last file - my applicationCOntext.xml <?xml version="1.0" encoding="UTF-8"?> <beans (...)> <context:component-scan base-package="pl.m4ks.comics"/> <context:annotation-config /> <bean id="dataSource" class="org.springframework.jdbc.datasource.SimpleDriverDataSource"> <property name="driverClass" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:8889/comics" /> <property name="username" value="root"/> <property name="password" value="root" /> </bean> <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> <property name="persistenceUnitName" value="main" /> <property name="dataSource" ref="dataSource" /> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <property name="dataSource"> <ref bean="dataSource"/> </property> <property name="packagesToScan"> <value>pl.m4ks.comics</value> </property> </bean> <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory"> <ref bean="sessionFactory" /> </property> </bean> <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" /> <tx:annotation-driven transaction-manager="txManager" proxy-target-class="true"/> </beans> I have no idea what can be the problem and how to solve it. I don't want to manage transaction in my code - this is what Spring is for. A: a) You are defining both a Hibernate SessionFactory and a JPA EntitymanagerFactory. Which is it going to be? Either use Hibernate's Session API or JPA's Entitymanager API with Hibernate as provider, but not both. b) You have defined a HibernateTransactionManager, but since you are using EntityManager in your code, you need a JpaTransactionManager instead: <bean id="myTxManager" class="org.springframework.orm.jpa.JpaTransactionManager"> <property name="entityManagerFactory" ref="myEmf"/> </bean Here's a commented version of your applicationContext.xml: <?xml version="1.0" encoding="UTF-8"?> <beans (...)> <context:component-scan base-package="pl.m4ks.comics"/> <context:annotation-config /> <bean id="dataSource" class="org.springframework.jdbc.datasource.SimpleDriverDataSource"> <property name="driverClass" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:8889/comics" /> <property name="username" value="root"/> <property name="password" value="root" /> </bean> <!-- use either this: --> <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> <property name="persistenceUnitName" value="main" /> <property name="dataSource" ref="dataSource" /> </bean> <!-- or this --> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <property name="dataSource"> <ref bean="dataSource"/> </property> <property name="packagesToScan"> <value>pl.m4ks.comics</value> </property> </bean> <!-- (but not both) --> <!-- this is correct for AnnotationSessionFactoryBean, but not if you use LocalContainerEntityManagerFactoryBean --> <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory"> <ref bean="sessionFactory" /> </property> </bean> <!-- not necessary, <context:annotation-config /> automatically includes this --> <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" /> <tx:annotation-driven transaction-manager="txManager" proxy-target-class="true"/> </beans> And a design note: DAOs shouldn't be transactional. You should use a service layer that manages the transactions. See this question (and many others) for reference.
[ "mathoverflow", "0000188707.txt" ]
Q: Hausdorff spaces with trivial automorphism group Is the singleton space the only Hausdorff space $X$ such that the set of automorphisms $\varphi: X\to X$ equals $\{\textrm{id}_X\}$? A: Not at all. Those spaces are called rigid and there are plenty of examples in the literature. The opposite notion is homogeneity which is a better studied property. The first (non-trivial) rigid space was constructed by Kuratowski in "Sur la puissance de l'ensemble des nombres de dimension au sens de M Frechet" (Fund.Math 8, 1926, 201-208). I also recommend "Decompositions of rigid spaces" by van Engelen and van Mill (PAMS 89, 1983, 533-536), where they give two nice examples: a rigid space that can be decomposed into two homeomorphic homogeneous subspaces and a homogeneous space that can be decomposed into two homeomorphic rigid subspaces. By the way, these two examples are even separable and metrizable. A: It's easy (if a little tedious, just a little) to construct a non-trivial metric dendroid (like an infinite tree or precisely--a one-dimensional compact metric AR) such that the ramification degree of each point is finite; for each natural number $\ n=1\ 2\ \ldots\ $ there exists exactly one point which has ramification $\ n+2$; the set of all points of ramification $\ > 2\ $ is dense. Then for every homeomorphism of our dendroid onto itself each point which has ramification $\ > 2\ $ is fixed. It follows that every such homeomorphism is the identity of our dendroid. A construction is obtained by starting with an interval--that's your initial stage of the induction, then at each stage add several short intervals which have one end at the middle of each existing intervals; at the center of $n$-th interval you add $\ n\ $ interval so that ramification will be the unique $\ n+2.\ $ You iterate this at infinitum. You folow it up with ending the end-point at each combinatorially infinite branch (but their geodesic metric length is finite), thus we get a compact. REMARK   An interval of a tree is meant any maximal interval such that all its internal points have ramification $\ 2.\ $ Each interval of a tree at any next stage, which was set-theoretically contained in the previous tree, is one of the two halves of the respective larger interval of that previous tree. Regardless of the stage at which theses intervals occur, they are all numbered $\ 1\ 2\ \ldots$. With each stage there is a bunch of intervals which are consecutively indexed above the previous tree, and below the next one. (Non-triviality of a dendroid means, by definition, that it has more than one point). The above dendroid (like any non-trivial dendroid) has non-constant continuous maps into itself, different from identity. Indeed, this is true for arbitrary AR which has more than one point. Thus the given example, while rigid, is not strongly rigid.
[ "security.stackexchange", "0000188788.txt" ]
Q: Firefox accuses of malware, but virustotal have 0 matches I sometimes download PDFs on libgen and sometimes Firefox will acuse them of being malware with the advice "this file contains virus or malware" but gives no details. I've run several of these files through virustotal and none give any problems in any of the scanners. Some of them are djvu which I presumed was only a format to hold static images with no interaction, so it'd be much harder to host a malware. So is there a way to know what is firefox finding in those files? Is firefox somehow better than all the antivirus tested on virustotal? If someone wants to test some file please let me know so I can send the link A: Firefox is not an anti-malware scanner, it uses a blacklist which it updates from various feeds e.g. Google safe browsing, phishtank, etc. Since Firefox is pretty new in such a field, they tend to be "excessively paranoid", e.g. based on many bad URL and derive the blocking result, as mentioned by @Steffen Ullrich. As a Firefox user, you can help by clicking the button on the warning screen. When there are enough clicks, hopefully, Firefox will notice it and unblock it. Unlike malicious file detection, URL blacklisting is never easy to do it "correctly", due to the dynamic nature.
[ "scifi.stackexchange", "0000093265.txt" ]
Q: Melkor or Morgoth? Despite being the ultimate Big Bad Guy1 in the Lord of the Rings books, Sauron was not the biggest baddest guy in the Tolkien legendarium. In fact he was only a servant of Melkor/Morgoth, who was a former Vala and when at his greatest was much more powerful than Sauron ever was. I hate slashes! What's with this Melkor/Morgoth? Both names refer to the same being. Are they his names in different languages (like Gandalf and Olorin, or Saruman and Curunir), and if so, which languages? Why are they used so interchangeably? What's the difference between Melkor and Morgoth? 1 Warning: TV Tropes link. A: Both names refer to the same person; Melkor is the first name he was known by, while Morgoth is a name given to him by his enemies. Melkor, the original name, is the one he had from the very beginning, when he was part of the music of Iluvatar. The name is Quenya in origin, and means "he who arises in might", as he was accounted the mightiest of the Ainur who entered into Arda (and were thus called the Valar). He was called by this name until the Two Trees in Valinor died by his hand (with the aid of the spider creature Ungoliant), the Silmarilli were stolen and he fled from Valinor to Middle-earth. After that momentous event, he was given the name Morgoth (or, fully, Morgoth Bauglir) by Feanor. Morgoth is in Sindarin, and means "Dark Foe" or some similar variant (You can see the root "Mor", for dark, repeated in many names, such as Mordor. "Goth" can be found in Gothmog, lord of the Balrogs). "Bauglir", similarly, means "Tyrant" or "Oppressor". The Feanor rose, and lifting up his hand before Manwe he cursed Melkor, naming him Morgoth, the Black Foe of the World; and by that name only was he known to the Eldar ever after. The Silmarillion, ch. 9. So properly, Melkor is the only true name he has. "Morgoth" is an appelation given to him by his enemies, declaring him their foe to the end of time. A: This is discussed in the Silmarillion. In short, Melkor is his proper name (from the Quenya word meaning "One who arises in Might") but the Elves won't say it for, ahem, reasons. Of the Enemies Last of all is set the name of Melkor, He who arises in Might. But that name he has forfeited; and the Noldor, who among the Elves suffered most from his malice, will not utter it, and they name him Morgoth, the Dark Enemy of the World. Great might was given to him by Ilúvatar, and he was coeval with Manwë. - Silmarillion - Of the Flight of the Noldor and from the index of names at the rear of the book Melkor: The Quenya name for the great rebellious Vala, the beginning of evil, in his origin the mightiest of the Ainur; afterwards named Morgoth, Bauglir, the Dark Lord, the Enemy, etc. The meaning of Melkor was 'He who arises in Might'; the Sindarin form was Belegur, but it was never used, save in a deliberately altered form Belegurth 'Great Death'. Passim (after the rape of the Silmarils usually called Morgoth) Silmarillion - Index of Names and from his Letter 211 In the cosmogonic myth Manwe is said to be ‘brother’ of Melkor, that is they were coeval and equipotent in the mind of the Creator. Melkor became the rebel, and the Diabolos of these tales, who disputed the kingdom of Arda with Manwë. (He was usually called Morgoth in Grey-elven.) A: As the other answers have already pointed out, both names refer to the same guy, and "Melkor" was dropped in favor of "Morgoth" because the former had positive connotations, while the latter is unmistakably negative in connotation. Incidentally, the same idea applies to Sauron: He was first called Mairon, which means "The Admirable", but after he fell from grace and joined Morgoth, he was renamed Sauron, which means "Abhorred" in Qenya, and Gorthaur, which means "Terrible Dread" in Sindarin. They are used somewhat interchangeably because they are both valid. However, more often than not, "Melkor" refers to the character before he pissed off the Elves (it was an Elf, Fëanor, who renamed him), and "Morgoth" refers to him after he pissed off the Elves. We can see this especially clearly in the following passage from the introduction to Unfinished Tales of Númenor and Middle-earth, in which Christopher Tolkien is justifying his decision to publish stories that were, as the title implies, unfinished when his father died. Those who would not have forgone the images of Melkor with Ungoliant looking down from the summit of Hyarmentir [upon Aman]... [or the image] of Beren lurking in wolf's shape beneath the throne of Morgoth... - Unfinished Tales of Númenor and Middle-earth, Introduction, p. 1 The context isn't particularly important - we're only interested in the nomenclature regarding the issue of Melkor versus Morgoth. If you haven't read The Silmarillion, the key thing to take away from this is simple: The scene where Melkor and Ungoliant look down from the mountain and see Aman below them happens before Fëanor names him Morgoth. The scene in which Beren, disguised as a wolf, sneaks into his fortress and confronts him, happens after Fëanor names him Morgoth. In this instance, as in most others, the main difference between the two names is timing. If he is being called Melkor, you're probably reading something that happened before he pissed off the Elves, and inspired Fëanor to give him a contemptuous new name. If he is being called Morgoth, you're probably reading something that happened after he pissed off the Elves, and inspired Fëanor to give him a contemptuous new name. This is especially true of texts that purport to be written by the Elves, because they refused to call him by his original name after he annoyed them. However, it also holds up in almost every other case as well.
[ "meta.stackexchange", "0000021535.txt" ]
Q: Colons in link URLs, redux So according to comments on this meta, colons in URLs are automatically encoded if they occur after string position 7. Unfortunately, this has the side effect of breaking any link which uses the scheme://domain:port syntax because the colon separating the domain and port gets URL encoded (but, deceivingly, still displays properly in the status bar for most browsers when hovering over the link). Example of problem: my answer on this question Would it be possible to change the colon-encoding algorithm to only encode colons that follow the first / or ? character after the domain portion? Edit: The urlencoded colon appears to work okay in Opera, but not in Firefox, Chrome, or IE. A: We now encode any colons at position 7 or greater, which are not followed by 2 or more numbers.
[ "serverfault", "0000283539.txt" ]
Q: RSync over SSH - permission denied even though the user is in the root group I have a need to copy files between servers through the web. I'm using RSYNC over ssh to do so. The problem is, I need to be able to transfer files, no matter where the files is. I created a user rsync and : usermod -G root -a rsync to give him the right to read/write anywhere on both servers. During the transfer, I see this error: rsync: mkstemp "/root/.myFile.RDr2HY" failed: Permission denied (13) I don't understand what's happening. edit: I just found out that the destination folder didn't have the write access for the root group. How would I give 100% access to this rsync user ? If I change its uid to 0, rsync stop working. A: What you've done, usermod -G root -a rsync, is to add the rsync user to the root group. This has no effect whatsoever on most systems, because the root group is not special. There are systems where being in the root group is necessary to escalate privileges to the root user, but it is never sufficient (the root group is the group of users who may use sudo, or some equivalent setup). In terms of security, giving a user the permission to write files anywhere is exactly equivalent to giving that user root powers. (The user can overwrite /bin/su, or /etc/passwd, or /usr/sbin/sshd, or any number of other programs and databases that would let her set up a backdoor for herself.) If you need to access arbitrary files over ssh, allow ssh logins as root. Not with a password (or else a long, randomly generated one), just with a key (which you'll need to protect carefully, of course). In /etc/sshd_config, put PermitRootLogin yes
[ "stackoverflow", "0015413797.txt" ]
Q: google V8 build error LNK1104: cannot open file 'ws2_32.lib' I'm trying to build google's V8 JavaScript Engine with MS Visual Studio 2012 on a 64bit system, but it always outputs the error LINK : fatal error LNK1104: cannot open file 'ws2_32.lib' I have done everything according to https://code.google.com/p/v8/wiki/BuildingWithGYP. I have used the python way instead of cygwin to generate the project files. How do i set up my linker that it finds the ws2_32.lib? //EDIT For some reason GYP made project files for vs2010 and not vs2012 so I had to update them. Now it works. (weird, I tried this before and it didn't work) A: GYP created VS2010 project files so I had to update them to VS2012.
[ "stackoverflow", "0021911109.txt" ]
Q: git difftool --dir-diff: how to copy back changed files I use git-diffall before, but the author said it was obsolete by the git difftool --dir-diff command. The command git difftool --dir-diff cannot copy back what I change code in the difftool which like git-diffall's --copy-back option do. I searched the web, only find this, it seems complex...: [PATCH] difftool --dir-diff: copy back all files matching the working tree what do you do when you use difftool and made some changes about the code? Thanks A: The command git difftool --dir-diff cannot copy back what I change code in the difftool which like git-diffall's --copy-back option do. Modified files are copied back, as long as one of the sides you're diffing is the working tree. That is: git difftool --dir-diff other-commit will show other-commit on the left and the modified files in the current working tree on the right. After the tool exits, the files for the right will be copied back to your working tree. (Tested with v1.8.3.2.) It only makes sense to copy them back when they were originally your working copy: copying files from an arbitrary diff would overwrite your working tree. However, if you want your working tree to be the version from commit2, to compare it with commit1 and to have those changes left in your tree, you could make that clear by checking that version out first: git checkout commit2 -- specific-file git difftool --dir-diff commit1
[ "gamedev.stackexchange", "0000094021.txt" ]
Q: How can I compute which chunk a coordinate is in? I am working on a video game. Everything (terrain, entities, particles) is stored in 100 by 100 chunks. Here is the array structure for the chunks: public static final int chunkSize = 100; public static Chunk [][][] chunks; The world is 20,000 by 20,000. Given a random coordinate (such as (-1244, 1353)), how can I quickly and efficiently determine what chunk the coordinate is in? Once I know what chunk a coordinate is in, I can determine which chunks to load around a player. A: If a chunk is C world units along an axis, you can convert a world unit W along that axis to a chunk index along that axis by floor(W/C) (or simply rely on integer division to drop the fractional part of the result). Now, you have to be careful since you can't actually have "negative" indices into the chunk array, which is what you'd get if you have a negative world coordinate. Thus, you will first want to offset your coordinate system so that there aren't any negative values. If your lowest value on your world axis is -10,000 for example, adding 10,000 to the input will appropriately translate the coordinate system. In general if your world is WorldWidth wide, evenly distributed around the origin, then you'd add 0.5 * WorldWidth. Overall you'd end up with something like this to get a chunk from a world position: Chunk GetChunkForWorldPosition(Vector3 position) { float offset = WorldWidth * 0.5; int x = (int)Math.Floor((position.x + offset) / ChunkSizeX); int y = (int)Math.Floor((position.y + offset) / ChunkSizeY); int z = (int)Math.Floor((position.z + offset) / ChunkSizeZ); return chunks[x][y][z]; }
[ "stackoverflow", "0028761186.txt" ]
Q: Does XML deserialize lock the file from reading? I have an xml file which is used by multiple process for reading. Here is the code snippet used for deserializing the xml. I want to make sure the below code does not read lock the file. public Address TestReadLock(string myXmlFile) { using (StreamReader sr = new StreamReader(myXmlFile)) { XmlReaderSettings xrs = new XmlReaderSettings(); xrs.ValidationType = ValidationType.None; xrs.XmlResolver = null; using (XmlReader reader = XmlReader.Create(sr, xrs)) { return (Address)xmlSerializer.Deserialize(reader); } } } I tried testing this by creating a dll of above function and loaded the file through powershell and VS in a loop at same time it worked fine. public void Main() { for (int i = 0; i < 1000; i++) { Address myaddress = TestReadLock(@C:\MyDetails.xml") } } Based on my understanding the above code should read lock the file nad while testing it is not the case Is there a possibility like testing I did is wrong or my understanding is not correct? A: new StreamReader(string) uses FileAccess.Read and FileShare.Read - it will not prevent other readers. If you want different control: use FileStream directly to control the access / sharing.
[ "stackoverflow", "0000132040.txt" ]
Q: image archive VS image strip i've noticed that plenty of games / applications (very common on mobile builds) pack numerous images into an image strip. I figured that the advantages in this are making the program more tidy (file system - wise) and reducing (un)installation time. During the runtime of the application, the entire image strip is allocated and copied from FS to RAM. On the contrary, images can be stored in an image archive and unpacked during runtime to a number of image structures in RAM. The way I see it, the image strip approach is less efficient because of worse caching performance and because that even if the optimal rectangle packing algorithm is used, there will be empty spaces between the stored images in the strip, causing a waste of RAM. What are the advantages in using an image strip over using an image archive file? A: Caching will not be as much of an issue as you think, if the images in the strip are likely to appear at the same time - i.e. are all part of an animation. As far as packing algorithms are concerned, most generic algorithms produce similar levels of efficiency - to get huge increases in packing efficiency you normally have to write an algorithm that is optimised for the dataset involved. As is usually the case with optimization of any kind - caching or packing - don't worry about it until it's been proved to be an issue, and then you need to approach the problem with a good understanding of the context.
[ "math.stackexchange", "0002918060.txt" ]
Q: Claim $\lim_{\delta \to 0} E\int_{|y| \le 1}\int_{\mathbb{R}^d}| u(x)-u(x+\delta y)|^2\rho(y) \,dx\,dy = 0$ Let $(\Omega,\mathcal{F},P)$ be a probability space, with $u \in L^2( \Omega \times\mathbb{R}^d)$. Let $\rho$ be the standard mollifier approximation to Dirac's delta dunction defined on $\mathbb{R}^d$ supported in $\{ y \,|\, |y|\le 1\} \subset \mathbb{R}^d$. I would like to show $$\lim_{\delta \to 0} E\int_{|y| \le 1}\int_{\mathbb{R}^d}| u(x)-u(x+\delta y)|^2\rho(y) \,dx\,dy = 0$$ I know $\int_{\mathbb{R}^d}| u(x)-u(x+\delta y)|^2 \to 0$ as $\delta \to 0$ uniformly using transalation continuity in $L^p$ , and thus we have $\lim_{\delta \to 0} \int_{|y| \le 1}\int_{\mathbb{R}^d}| u(x)-u(x+\delta y)|^2\rho(y) \,dx\,dy = 0$. After this how can I interchange the limit with expection? Maybe somehow Dominated convergence theorem can be used. A: Using $$|u(x)-u(x+\delta y)|^2 \leq 2|u(x)|^2 + 2|u(x+\delta y)|^2$$ we find $$\int_{\mathbb{R}^d} |u(x)-u(x+\delta y)| \, dx \leq 2 \int_{\mathbb{R}^d} |u(x)|^2 \, dx + 2 \int_{\mathbb{R}^d} |u(x+\delta y)|^2 \, dx = 4 \int_{\mathbb{R}^d} |u(x)|^2 \, dx.$$ Thus, $$\begin{align*} \int_{|y| \leq 1} \int_{\mathbb{R}^d} |u(x)-u(x+\delta y)|^2 \varrho(y) \, dx \, dy \leq 4 \left( \int_{\mathbb{R}^d} |u(x)|^2 \, dx\right) \int_{|y| \leq 1} \varrho(y) \,dy. \end{align*}$$ As $u \in L^2(\Omega \times \mathbb{R}^d)$ the right-hand side is an integrable dominating function (which does not depend on $\delta$). Since you have already shown that the left-hand side converges to $0$ as $\delta \to 0$ we can apply the dominated convergence theorem to conclude that $$\mathbb{E} \int_{|y| \leq 1} \int_{\mathbb{R}^d} |u(x)-u(x+\delta y)|^2 \varrho(y) \, dx \, dy \xrightarrow[]{\delta \to 0} 0.$$
[ "math.stackexchange", "0001069387.txt" ]
Q: Show that $\mathbb Q(\sqrt p) \not\simeq\mathbb Q(\sqrt q)$ I'd like to show that for $p,q$ distinct primes, the extensions $\mathbb Q(\sqrt p),\mathbb Q(\sqrt q)$ are not isomorphic. I don't really have knowledge of the "high-level language" of algebraic number theory, so my approach is going to be very bit-wise, if you will. Here's my try: If there were such an isomorphism, call it $\varphi$. I know that we must have: $$\left\{\begin{align}&\varphi\mid_{\mathbb Q} = \text{id} \\ &\varphi(\sqrt p) =\pm\sqrt p \end{align}\right.$$ So essentially the existence of $\varphi$ means that for any $a+b'\sqrt p$ there exist $c,d$ such that $\varphi(a+b'\sqrt p) = a+b\sqrt p = c+d\sqrt q$ (where $b$ might be a sign change of $b'$). Take, to simplify $a=0, b=1$. Let $\alpha = \sqrt p - d\sqrt q = c$, from above. We can rearrange to obtain $$\begin{align}&(\alpha-\sqrt p)^2 = d^2q \Rightarrow \\ \Rightarrow& \ \alpha^2 - 2\alpha\sqrt p + p - d^2q = 0 \\ \Rightarrow& \ \sqrt p -\frac{c^2+p-d^2q}{2c} = \sqrt p - \lambda = 0\end{align}$$ But then it has to be that $(x^2-p) \mid (x-\lambda)$, which cannot be. This proof however doesn't satisfy me for two reasons. First of all, I'd like to have stopped at the polynomial I found in $\alpha$, shown that it was irreducible in $\mathbb Q(\sqrt2)$, and argued in terms of extension degrees. However I don't know how to show that. The second reason is that I'm not using the primality of $p,q$ other than having it imply the irreducibility of $x^2-p$. It seems to me from the way the exercise is worded that if they were compound and $x^2-p,x^2-q$ were still irreducible, we might have a homomorphism. Can someone clarify? A: I'm not convinced by your claim that $\phi(\sqrt{p}) = \pm \sqrt{p}$ (is this a typo for $\pm \sqrt{q}$?) However, we do know that $\phi(\sqrt{p}) = a + b \sqrt{q}$ for some $a , b \in \mathbb{Q}$. So $p = \phi(p) = \phi(\sqrt{p}^2) = \phi(\sqrt{p})^2 = (a + b \sqrt{q})^2 = a^2 + b^2q + 2ab \sqrt{q}$ So either $a = 0$ or $b=0$. If $b=0$ then we have $p = a^2$, if $a=0$ then we have $p = b^2q$; neither of these can occur as $p$ is prime and distinct from $q$. Contradiction. With regards to your point about using primality of $p$, we do have $\mathbb{Q}(\sqrt{pa^2}) \cong \mathbb{Q}(\sqrt{p})$ for any integer $a$ and prime $p$, for example. A: What would be $\phi(\sqrt p)$? Let $$\phi(\sqrt p)=a+b\sqrt q$$ Then $$p=p\phi(1)=\phi(p)=a^2+qb^2+2ab\sqrt q$$ therefore $$2ab=0$$ We conclude that $a^2=p$ or $qb^2=p$, and both options are contradictions.
[ "stackoverflow", "0017125450.txt" ]
Q: Add rows to dataframe based on criteria I have this dataframe: percentDf <- data.frame(category=c("a", "a", "b", "c", "c", "d"), percent=c(50, 50, 100, 30, 70, 100)) percentDf category percent 1 a 50 2 a 50 3 b 100 4 c 30 5 c 70 6 d 100 In rows where the value in percent is 100, I need to replicate that row, and add it underneath. This should be the dataframe outputted: percentDfComplete <- data.frame(category=c("a", "a", "b", "b", "c", "c", "d", "d"), percent=c(50, 50, 100, 100, 30, 70, 100, 100)) percentDfComplete category percent 1 a 50 2 a 50 3 b 100 4 b 100 5 c 30 6 c 70 7 d 100 8 d 100 What is the best way to do this? A: I'd just pick them up first and then rbind them and them order them. out <- rbind(percentDf, percentDf[percentDf$percent == 100, ]) out[order(out$category), ] Alternatively, you can first find which rows have percent = 100 and append and sort and index your data.frame. percentDf[sort(c(seq_len(nrow(percentDf)), which(percentDf$percent == 100))), ] Note: If you have in your original data.frame two rows with b 100 then you'll get each of the rows duplicated here.
[ "stackoverflow", "0046756336.txt" ]
Q: Create an EdgeNGram analyzer supporting both sides in Azure Search When defining a custom analyzer for Azure Search there is an option of defining a token filter from this list. I am trying to support search of both prefix and infix. For example: if a field contains the name: 123 456, I want the searchable terms to contain: 1 12 123 23 3 4 45 456 56 6 When using the EdgeNGramTokenFilterV2 which seems to do the trick, there is an option of defining a "side" property, but only "front" and "back" are supported, not both. the "front" (default) value generates this list: 1 12 123 4 45 456 and back generates: 123 23 3 456 56 6 I tried using two token two EdgeNGramTokenFilterV2s, but this creates terms from combining the two filters such as: "2" or "5": 1 12 123 23 3 4 45 456 56 6 2 // Unwanted 5 // Unwanted I also tried using a "reverse" token, but this reverses everything and the results are still wrong. I am using only one search field ("Name") and would prefer it to stay like this. (Thought of the option of using a different field named "name_reverse" with a different analyzer, but this is very inefficient and will cause a lot of headache when connecting the search engine to the data source. For easier reference, this is the current index creation request: { "name": "testindexboth", "fields": [ {"name": "id", "type": "Edm.String", "key": true }, {"name": "Name", "type": "Edm.String", "searchable": true, "analyzer": "myAnalyzer"} ], "myAnalyzer": [ { "name": "myAnalyzer", "@odata.type": "#Microsoft.Azure.Search.CustomAnalyzer", "tokenizer": "standard_v2", "tokenFilters":["front_filter", "back_filter"] }], "tokenFilters":[ { "name":"front_filter", "@odata.type":"#Microsoft.Azure.Search.EdgeNGramTokenFilterV2", "maxGram":15, "side": "front" }, { "name":"back_filter", "@odata.type":"#Microsoft.Azure.Search.EdgeNGramTokenFilterV2", "maxGram":15, "side": "back" } ] } Is there an option of combining both, without getting them scramble up the results? A: Add two fields to your index, with two different custom analyzers: one for prefix, one for suffix. When querying, query against both fields.
[ "stackoverflow", "0044393246.txt" ]
Q: MS Access VBA Stored Procedure return value to text box I'm having one of those moments and have forgot how to return a value from a SQL SP to a textbox? I'm calling a SQL SP from MS Access 2013 using the below code and this returns the value to a listbox no problem - what property do I use to return the SP value to a text box? Working Code: With CurrentDb.QueryDefs("qMasterPass") .SQL = "exec SKULookup " & txtSKUSearch Set Me.List38.Recordset = .OpenRecordset End With Non-working code - what should be where the ? are: With CurrentDb.QueryDefs("qMasterPass") .SQL = "exec SKULookup " & txtSearch Set Me.Text7.?????? = .OpenRecordset End With Thanks A: Assuming your recordset has 1 record with 1 column, you could do this: With CurrentDb.QueryDefs("qMasterPass") .SQL = "exec SKULookup " & txtSearch Me.Text7.Text = .OpenRecordset.Fields(0).Value End With
[ "stackoverflow", "0052009533.txt" ]
Q: Return specific array value field in aggregate I have a issue in MongoDB i'm trying to build a very complex aggregate query, and its work almost as i want it, but i still have trobles, and the problems is i need to move a spefiect field so i can use it later. My aggregate look like this right now. db.getCollection('travel_sights').aggregate([{ '$match': { 'preview.photo' : { '$exists':true }, '_id': { '$in' : [ObjectId("5b7af9701fbad410e10f32f7")] } } },{ '$unwind' : '$preview.photo' }, { '$lookup':{ 'from' : 'media_data', 'localField' : '_id', 'foreignField':'bind', 'as':'media' } }]) and it will return data like this. { "_id" : ObjectId("5b7af9701fbad410e10f32f7"), "preview" : { "photo" : { "id" : ObjectId("5b7affea1fbad441494a663b"), "sort" : 0 } }, "media" : [ { "_id" : ObjectId("5b7affea1fbad441494a663b") }, { "_id" : ObjectId("5b7b002d1fbad441494a663c") }, { "_id" : ObjectId("5b7b00351fbad441494a663d") }, { "_id" : ObjectId("5b7d9baa1fbad410de638bbb") }, { "_id" : ObjectId("5b7d9bae1fbad410e10f32f9") }, { "_id" : ObjectId("5b7d9bb11fbad441494a663e") }, { "_id" : ObjectId("5b7d9bb41fbad4ff97273402") }, { "_id" : ObjectId("5b7d9bb71fbad4ff99527e82") }, { "_id" : ObjectId("5b7d9bbb1fbad410de638bbc") }, { "_id" : ObjectId("5b7d9bbe1fbad410e10f32fa") }, { "_id" : ObjectId("5b7d9bc11fbad441494a663f") }, { "_id" : ObjectId("5b7d9bc41fbad4ff97273403") }, { "_id" : ObjectId("5b7d9bc71fbad4ff99527e83") }, { "_id" : ObjectId("5b7d9bca1fbad410de638bbd") }, { "_id" : ObjectId("5b7d9bcd1fbad441494a6640") }, { "_id" : ObjectId("5b7d9bd01fbad4ff97273404") } ] } { "_id" : ObjectId("5b7af9701fbad410e10f32f7"), "preview" : { "photo" : { "id" : ObjectId("5b7b002d1fbad441494a663c"), "sort" : 0 } }, "media" : [ { "_id" : ObjectId("5b7affea1fbad441494a663b") }, { "_id" : ObjectId("5b7b002d1fbad441494a663c") }, { "_id" : ObjectId("5b7b00351fbad441494a663d") }, { "_id" : ObjectId("5b7d9baa1fbad410de638bbb") }, { "_id" : ObjectId("5b7d9bae1fbad410e10f32f9") }, { "_id" : ObjectId("5b7d9bb11fbad441494a663e") }, { "_id" : ObjectId("5b7d9bb41fbad4ff97273402") }, { "_id" : ObjectId("5b7d9bb71fbad4ff99527e82") }, { "_id" : ObjectId("5b7d9bbb1fbad410de638bbc") }, { "_id" : ObjectId("5b7d9bbe1fbad410e10f32fa") }, { "_id" : ObjectId("5b7d9bc11fbad441494a663f") }, { "_id" : ObjectId("5b7d9bc41fbad4ff97273403") }, { "_id" : ObjectId("5b7d9bc71fbad4ff99527e83") }, { "_id" : ObjectId("5b7d9bca1fbad410de638bbd") }, { "_id" : ObjectId("5b7d9bcd1fbad441494a6640") }, { "_id" : ObjectId("5b7d9bd01fbad4ff97273404") } ] } { "_id" : ObjectId("5b7af9701fbad410e10f32f7"), "preview" : { "photo" : { "id" : ObjectId("5b7b00351fbad441494a663d"), "sort" : 0, "primary" : false } }, "media" : [ { "_id" : ObjectId("5b7affea1fbad441494a663b") }, { "_id" : ObjectId("5b7b002d1fbad441494a663c") }, { "_id" : ObjectId("5b7b00351fbad441494a663d") }, { "_id" : ObjectId("5b7d9baa1fbad410de638bbb") }, { "_id" : ObjectId("5b7d9bae1fbad410e10f32f9") }, { "_id" : ObjectId("5b7d9bb11fbad441494a663e") }, { "_id" : ObjectId("5b7d9bb41fbad4ff97273402") }, { "_id" : ObjectId("5b7d9bb71fbad4ff99527e82") }, { "_id" : ObjectId("5b7d9bbb1fbad410de638bbc") }, { "_id" : ObjectId("5b7d9bbe1fbad410e10f32fa") }, { "_id" : ObjectId("5b7d9bc11fbad441494a663f") }, { "_id" : ObjectId("5b7d9bc41fbad4ff97273403") }, { "_id" : ObjectId("5b7d9bc71fbad4ff99527e83") }, { "_id" : ObjectId("5b7d9bca1fbad410de638bbd") }, { "_id" : ObjectId("5b7d9bcd1fbad441494a6640") }, { "_id" : ObjectId("5b7d9bd01fbad4ff97273404") } ] } and what you can se the last data have preview.photo.primary on it, and this field i want to return when i'm done with my aggregate query. My final query look like this: db.getCollection('travel_sights').aggregate([{ '$match': { 'preview.photo' : { '$exists':true }, '_id': { '$in' : [ObjectId("5b7af9701fbad410e10f32f7")] } } },{ '$unwind' : '$preview.photo' }, { '$lookup':{ 'from' : 'media_data', 'localField' : '_id', 'foreignField':'bind', 'as':'media' } },{ '$unwind':'$media' },{ '$project' : { 'preview' : 1, 'media': 1, } }, { '$group': { '_id':'$media._id', 'primary': { '$first':'$preview' } } }]) The problem here is when i want $preview return so i can find the primary about it, its allways only return the first where the value not exists, if i use $push the problem is i get every thing. is there a way so i can pick the right primary value in my return? have trying $addFields to but whitout eny kind of lock. Travel_sights data: { "_id" : ObjectId("5b7af9701fbad410e10f32f7"), "city_id" : ObjectId("5b6d0cb6222d4c70b803eaeb"), "activated" : true, "deleted" : false, "url" : "url is here", "name" : "title of it here", "updated_at" : ISODate("2018-08-22T17:22:27.000Z"), "content" : "content here", "preview" : { "photo" : [ { "id" : ObjectId("5b7affea1fbad441494a663b"), "sort" : 0 }, { "id" : ObjectId("5b7b002d1fbad441494a663c"), "sort" : 0 }, { "id" : ObjectId("5b7b00351fbad441494a663d"), "sort" : 0, "primary" : true }, { "id" : ObjectId("5b7d9baa1fbad410de638bbb"), "sort" : 0 }, { "id" : ObjectId("5b7d9bae1fbad410e10f32f9"), "sort" : 0 }, { "id" : ObjectId("5b7d9bb11fbad441494a663e"), "sort" : 0 }, { "id" : ObjectId("5b7d9bb41fbad4ff97273402"), "sort" : 0, "primary" : false }, { "id" : ObjectId("5b7d9bb71fbad4ff99527e82"), "sort" : 0, "primary" : false }, { "id" : ObjectId("5b7d9bbb1fbad410de638bbc"), "sort" : 0 }, { "id" : ObjectId("5b7d9bbe1fbad410e10f32fa"), "sort" : 0 }, { "id" : ObjectId("5b7d9bc11fbad441494a663f"), "sort" : 0 }, { "id" : ObjectId("5b7d9bc41fbad4ff97273403"), "sort" : 0, "primary" : false }, { "id" : ObjectId("5b7d9bc71fbad4ff99527e83"), "sort" : 0, "primary" : false }, { "id" : ObjectId("5b7d9bca1fbad410de638bbd"), "sort" : 0, "primary" : false }, { "id" : ObjectId("5b7d9bcd1fbad441494a6640"), "sort" : 0, "primary" : false }, { "id" : ObjectId("5b7d9bd01fbad4ff97273404"), "sort" : 0 } ] } } 3 sample foto bind data here: { "_id" : ObjectId("5b7affea1fbad441494a663b"), "file-name" : "55575110311__0F115282-B5A0-4654-AA44-B7DC2C682992.jpeg", "options" : [ ObjectId("5b6fb855222d4c70b8041093") ], "type" : "images", "files" : [ { "width" : 70, "height" : 53 }, { "width" : 400, "height" : 300 }, { "width" : 800, "height" : 600 }, { "width" : 1600, "height" : 1200 } ], "bind" : [ ObjectId("5b7af9701fbad410e10f32f7") ] } { "_id" : ObjectId("5b7b002d1fbad441494a663c"), "file-name" : "55575110748__E7B07EFD-9F7E-40D6-8B57-38F708E4C0C0.jpeg", "options" : [ ObjectId("5b6fb855222d4c70b8041093") ], "type" : "images", "files" : [ { "width" : 70, "height" : 53 }, { "width" : 400, "height" : 300 }, { "width" : 800, "height" : 600 }, { "width" : 1600, "height" : 1200 } ], "bind" : [ ObjectId("5b7af9701fbad410e10f32f7") ], "description" : "this is secoudn demo!", "title" : "demo 3" } { "_id" : ObjectId("5b7b00351fbad441494a663d"), "file-name" : "paris2.jpg", "options" : [ ObjectId("5b6fb855222d4c70b8041093") ], "type" : "images", "files" : [ { "width" : 70, "height" : 53 }, { "width" : 400, "height" : 300 }, { "width" : 800, "height" : 600 }, { "width" : 1600, "height" : 1200 } ], "bind" : [ ObjectId("5b7af9701fbad410e10f32f7") ], "description" : "this is a demo1 :)", "title" : "demo" } A: You can filter out the element from the array where the primary field exists using $filter aggregation and then easily $group with the media._id field and get the $first document value. Finally your query will be db.getCollection("travel_sights").aggregate([ { "$match": { "preview.photo" : { "$exists":true }, "_id": { "$in" : [ ObjectId("5b7af9701fbad410e10f32f7") ] } }}, { "$addFields": { "preview.photo": { "$arrayElemAt": [ { "$filter": { "input": "$preview.photo", "as": "photo", "cond": { "$ne": [ "$$photo.primary", undefined ] } }}, 0 ] } }}, { "$lookup":{ "from" : "media_data", "localField" : "_id", "foreignField": "bind", "as": "media" }}, { "$unwind":"$media" }, { "$project" : { "preview" : 1, "media": 1, }}, { "$group": { "_id": "$media._id", "primary": { "$first": "$preview" } }} ])
[ "stackoverflow", "0039854548.txt" ]
Q: Import identical excel files into access with multiple worksheets So, I'm trying to find ways to facilitate recombining data in excel sheets using access. What I am trying to do is take multiple excel files that are all identically formatted and concatenate them into a contiguous table. Right now I have a VBA function that will allow me to target one excel worksheet across a directory of excel files and combine them into one access table. My question is, how can I go about doing that same thing, but for EVERY worksheet in the directory in one shot, instead of running and modifying the code for every worksheet. TL;DR You have 100 excel files, each with 7 worksheets in them. The formatting is identical, but the data is different. How do I take all 100 files and combine their worksheets into 7 respective MS Access tables? ****** ISSUE HAS BEEN SOLVED. WORKING CODE AS FOLLOWS ******* Module 1 named SingleModule: Option Compare Database Public Function importExcelSheets(Directory As String, TableName As String, WkShtName As String) As Long On Error Resume Next Dim strDir As String Dim strFile As String Dim I As Long I = 0 If Left(Directory, 1) <> "\" Then strDir = Directory & "\" Else strDir = Directory End If strFile = Dir(strDir & "*.XLSX") While strFile <> "" I = I + 1 strFile = strDir & strFile Debug.Print "importing " & strFile DoCmd.TransferSpreadsheet acImport, , TableName, strFile, True, WkShtName strFile = Dir() Wend importExcelSheets = I End Function Module 2 named MultipleModule: Public Function importMultipleExcelFiles(Directory As String) As Long For x = 1 To 7 Dim TableName As String Dim WkShtName As String TableName = Choose(x, "Table1", "Table2", "Table3", "Table4") WkShtName = Choose(x, "Table1!", "Table2!", "Table3!", "Table4!") Call SingleModule.importExcelSheets(Directory, TableName, WkShtName) Next x End Function Use the following command in the Immediate Window to execute (Make sure you change the filepath): ? importMultipleExcelFiles("C:\Excel File Directory") SIDE NOTE: You can target one worksheet using the following command on SingleModule in the Immediate Window: ? importExcelSheets("C:\FilePath", "TableName", "WkShtName!") A: Sorry, I didn't see how your TableName was going into the procedure. Use the FOR-NEXT with the CHOOSE function, when you're calling the importExcelSheets function. for x= 1 to 7 TableName = choose(x, "Table1", "Table2"...) WkShtName = choose(x, "ContactDetails!", ...) importExcelSheets Dir, TableName, WkshtName next x
[ "android.stackexchange", "0000169482.txt" ]
Q: Why phone encryption without screen lock is possible under Marshmallow? Since phone encryption is irreversible, I'd like to ask before applying it to my phone for the first time. I have a slide-screen unlock set under my Moto E3 / Android 6.0 Marshmallow. No PIN, no pattern. How it is possible that my phone / Android allows me to encrypt my phone in this situation? Here are all the warnings I can see. First screen warns me that: I need to power up my battery to something around maximum, I need to connect my phone to charger, phone encryption takes 1+ hour. Second screen warns me that: phone encryption is irreversible, phone encryption takes 1+ hour. But, on both screens I can tap Encrypt Phone button without any problems. What am I missing? Shouldn't I be rather warned that phone encryption is not possible in my case, because I failed to set PIN-lock or pattern-lock for my screen / phone? Shouldn't Android 6.0 rather disallow me to continue with phone encryption in this case? A: I have a Galaxy S5 (Android Marshmallow), and when I hit the encrypt phone button, my phone stopped me and forced me to have a password or pin in order to continue. If you use finger print or face recognition, you will need to enter the password or pin on device restart. So the answer is Yes your phone will disallow you from continuing with phone encryption without a password or pin, your phone will just ask you nicely for a password as a part of the encryption process rather than send you back into the settings to make a password.
[ "stackoverflow", "0002457440.txt" ]
Q: out of memory issue in asp.net mvc application I have got one weird issue. I am working on an asp .net mvc application. I have a refresh button that build some data and view models in the controller code, and returns the partial view back. Well this refresh does work good the very first time. But when i try to click my refresh button again, a javascript alert comes saying "out of memory at line 56" I checked my task manager to see on whats happening. I have a 3GB memory and when this error alert shows up the used memory is 1.41 GB. Its normal usage as it looks like. But I don't know why it shows the javascript error alert. This problem happens in my local workstation where I am doing development of this application. Any thoughts or comments to trouble shoot or solve this issue is appreciated. I ma using IE7. A: Any infinite loops in there? Javascript doesn't like those. Another possibility - is there any Flash on the page? Apparently there have been issues related to that in the past where updating your version of Flash fixes the problem.
[ "stackoverflow", "0006063213.txt" ]
Q: Getting Physical Path in SWF File I'm using UILoaders to load different .swf files into the main .swf and am having a problem when I try to load a specific .swf file after a series of steps. I wanted to know if there was a way to see which is the current path that the application is in so that I can know if my relative paths are working or if I have to change them. I want to do something in the likes of this.path, or anything that works that way. Thanks. A: you can get the current url of your swf this way : root.loaderInfo.url;
[ "mathematica.stackexchange", "0000068875.txt" ]
Q: 10.0.2 mapping Association to Dataset warning Bug introduced in 10.0.2 and fixed in 10.0.3 In 10.0.2 ExampleData[{"Dataset", "Titanic"}][All, <| "gender" -> #sex|> &] Outputs the expected result, but also throws: MapAt::partw: Part {1,All,2} of Association[gender->Atom[Enumeration[female,male]]] does not exist. Whereas all is ok with: ExampleData[{"Dataset", "Titanic"}][All, {"gender" -> #sex} &] A: This is a bug in the 10.0.2 version of the type inferencer, which now goes inside pure functions†. It's 'harmless' in that the type inference will just give up and fall back on deduction (which is what it was going to do anyway). I've fixed this for version 10.0.3, but in the meantime, here's a patch that will prevent the message: Begin["TypeSystem`Inference`PackagePrivate`"]; exprType[e_Association] := If[AssociationQ[Unevaluated[e]], Struct@MapUn[exprType, e], TypeSystem`UnknownType]; End[]; You can safely put this in your init.m so it gets applied to all new kernels -- it won't slow anything down. P.S. Perhaps we should have an 'errata' mechanism that allows us to apply micropatches like this via paclet download after a version has shipped. That would be nice. † here is an example of type inference going into pure functions: << TypeSystem` t = Type[<|"x" -> Integer, "y" -> Real|>] Function[#x + #y] ** t Function[#x + #y + #z] ** t Edit: thanks for finding and 'reporting'!
[ "stackoverflow", "0002734386.txt" ]
Q: Returning searched results in an array in Java without ArrayList I started down this path of implementing a simple search in an array for a hw assignment without knowing we could use ArrayList. I realized it had some bugs in it and figured I'd still try to know what my bug is before using ArrayList. I basically have a class where I can add, remove, or search from an array. public class AcmeLoanManager { public void addLoan(Loan h) { int loanId = h.getLoanId(); loanArray[loanId - 1] = h; } public Loan[] getAllLoans() { return loanArray; } public Loan[] findLoans(Person p) { //Loan[] searchedLoanArray = new Loan[10]; // create new array to hold searched values searchedLoanArray = this.getAllLoans(); // fill new array with all values // Looks through only valid array values, and if Person p does not match using Person.equals() // sets that value to null. for (int i = 0; i < searchedLoanArray.length; i++) { if (searchedLoanArray[i] != null) { if (!(searchedLoanArray[i].getClient().equals(p))) { searchedLoanArray[i] = null; } } } return searchedLoanArray; } public void removeLoan(int loanId) { loanArray[loanId - 1] = null; } private Loan[] loanArray = new Loan[10]; private Loan[] searchedLoanArray = new Loan[10]; // separate array to hold values returned from search } When testing this, I thought it worked, but I think I am overwriting my member variable after I do a search. I initially thought that I could create a new Loan[] in the method and return that, but that didn't seem to work. Then I thought I could have two arrays. One that would not change, and the other just for the searched values. But I think I am not understanding something, like shallow vs deep copying???.... A: The return value from getAllLoans is overwriting the searchedLoanArray reference, which means that both loanArray and searchedLoanArray are pointing at the same underlying array. Try making searchedLoanArray a local variable, and then use Arrays.copyOf. If you're trying not to use standard functions for your homework, manually create a new Loan array of the same size as loanArray, and then loop and copy the values over.
[ "money.stackexchange", "0000028660.txt" ]
Q: Found an old un-cashed paycheck. How long is it good for? What to do if it's expired? I just found a paycheck from my old work that is dated August 5th, 2013. It's for over $300 and I'm wondering if it will still go through. I'm worried that it will bounce or there will be some issue with depositing it. I'm also annoyed that the accountant didn't say anything for all that money that was missing... and the company was audited a few months later and no flags were raised. Note: There is not a listed expiration on the paycheck, the company and I use the same bank (Wells Fargo), and we're both in the US. It's Saturday March 1st 2014, over 6 months later, the bank is closed today, and I'm freaking out over potentially losing over 300 dollars. My question is.. Should it go through? If it doesn't, would it be wrong to ask my (old) work for the money? EDIT: I decided to deposit it online (via mobile banking app) and I should get a response if it went through or not on Monday. It if doesn't go through then I'll take the next step and go to the bank to see what can be done. UPDATE: It went through, no problems! A: The two banks involved may have different policies about honoring the check. It might not be written on the check. Your bank may decide that the stale check has to be treated differently and will withhold funds for a longer period of time before giving you access to the money. They will give time for the first bank to refuse to honor the check. They may be concerned about insufficient funds, the age of the check, and the fact that the original account could have been closed. If you are concerned about the age of the check. You could go to your bank in person, instead of using deposit by ATM, scanner, or smart phone. This allows you to talk to a knowledgeable person. And if they are going to treat the check differently or reject the check, they can let you know right away. The audit may not have been concerned about the fact that the check hadn't been cashed because when they did the audit the check was still considered fresh. Some companies will contact you eventually to reissue the check so you they can get the liability off their books. If the bank does refuse the check contact the company to see how you can get a replacement check issued. They may want proof the check can't be cashed so they don't have to worry about paying you twice. A: The check is just barely over 6 months old. I suspect it will go through with no issues. A: This varies by jurisdiction somewhat but speaking as a Canadian, a small business owner, and accountant (unregistered but some courses and accounting for multiple businesses) this is the answer if you were in Canada. In Canada the cheque cashing limit is 6 months. Therefor any bank will refuse to cash this cheque. It would be totally morally and legally acceptable to ask for a replacement cheque from your employer. In Canada they would generally have no problem issuing a replacement; in other jurisdictions with differing time limits they might want to cancel the original cheque first.
[ "stackoverflow", "0061719790.txt" ]
Q: glfw how to destroy window in mainloop I am trying to develop a program using glfw where the window closes in the main loop. However, I get this weird run time error: X Error of failed request: GLXBadDrawable Major opcode of failed request: 152 (GLX) Minor opcode of failed request: 11 (X_GLXSwapBuffers) Serial number of failed request: 158 Current serial number in output stream: 158 Here is the code I'm trying to run #include <GL/glfw3.h> int main() { GLFWwindow* window; if(!glfwInit()) return -1; window = glfwCreateWindow(400, 400, "window", nullptr, nullptr); if(!window) { glfwTerminate(); return -1; } glfwMakeContextCurrent(window); while(!glfwWindowShouldClose(window)) { glfwDestroyWindow(window); glfwSwapBuffers(window); glfwPollEvents(); } glfwTerminate(); return 0; } Is there any way to destruct the window from inside the main loop? A: Yes, you can call glfwDestroyWindow in the main loop. Here's how I did it. #include <GLFW/glfw3.h> int main() { GLFWwindow* window; if(!glfwInit()) return -1; window = glfwCreateWindow(400, 400, "My Window", NULL, NULL); if(!window) { glfwTerminate(); return -1; } glfwMakeContextCurrent(window); while(!glfwWindowShouldClose(window)) { if (glfwGetKey(window, GLFW_KEY_Q) == GLFW_PRESS) { glfwDestroyWindow(window); break; } glfwSwapBuffers(window); glfwPollEvents(); } glfwTerminate(); return 0; } Press the Q key to destroy the window. Try running this code to see if it will work. I ran this code and the process simply returned 0 without printing any error messages. I don't see why it shouldn't work for you.
[ "dba.stackexchange", "0000142159.txt" ]
Q: Import .sql file into multiple databases How to import .sql file into multiple databases at one shot. I have tried this: mysql -uroot -p -all-databases < test.sql But it asks for database name. Whatever there in test.sql file should reflect in all the databases/Schemas. A: If you're running on Linux/Unix, you can do it with a bit of shell: for DB in `mysql -u root -r --silent -p -e 'show databases;' | egrep -v "_schema$|^mysql$|^sys$"` do mysql -uroot -p $DB < test.sql done Will obviously be easier if you temporarily set it up to be passwordless.
[ "stackoverflow", "0016502659.txt" ]
Q: How do I control all the link tags in html from one location? I am modifying my code for my website. I want all the links to open in a new window. However, instead of adding: target="_blank" for all the links, I was wondering if I could somehow control all link tags from one location. A: You can try adding a base tag to the head of the html <base target="_blank"> http://jsbin.com/ezeyij/1/edit Note: This also affects the target of forms as well.
[ "stackoverflow", "0016567681.txt" ]
Q: Can anyone think of a better way of stopping a user from clicking on anything? Currenlty when a page is posting back or something else is going on I display a big grey div over the top of the whole page so that the user can't click the same button multiple times. This works fine 99% of the time, the other 1% is on certain mobile devices where the user can scroll/zoom away from the div. Instead of trying to perfect the CSS so that it works correctly (this will be an on going battle with new devices) I've decided to just stop the user from being able to click anything. Something like $('a').click(function(e){e.preventDefault();}); would stop people from clicking anchor tags and navigating to the link but it wouldn't stop an onclick event in the link from firing. I want to try to avoid changing the page too radically (like removing every onclick attribute) since the page will eventually have to be changed back to its original state. What I would like to do is intercept clicks before the onclick event is executed but I don't think that this is possible. What I do instead is hide the clicked element on mouse down and show it on mouseup of the document, this stops the click event firing but doesn't look very nice. Can anyone think of a better solution? If not then will this work on every device/browser? var catchClickHandler = function(){ var $this = $(this); $this.attr('data-orig-display', $this.css('display')); $this.css({display:'none'}); }; var resetClickedElems = function(){ $('[data-orig-display]').each(function(){ $(this).css({display:$(this).attr('data-orig-display')}).removeAttr('data-orig-display'); }); }; $('#btn').click(function(){ $('a,input').on('mousedown',catchClickHandler); $(document).on('mouseup', resetClickedElems); setTimeout(function(){ $('a,input').off('mousedown',catchClickHandler); $(document).off('mouseup', resetClickedElems); }, 5000); }); JSFiddle: http://jsfiddle.net/d4wzK/2/ A: You could use the jQuery BlockUI Plugin http://www.malsup.com/jquery/block/
[ "stackoverflow", "0041182532.txt" ]
Q: Where should I implement onClick method in a NavigationDrawer Activity? I have a navigation drawer and a fragment that generates a list of products. The problem is that when I click on a product it tryes to find onClick method in base activity not in fragment's java class. Should I implement onClick method in the base activity or is there any way to implement it in fragment's class. This is product's layout "item_order.xml": <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:clickable="true" android:onClick="orderClick" android:id="@+id/tOrder" android:padding="4dp"> .... </RelativeLayout> Here is the base class: protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_waiter); //set fragment OrdersFragment fragment=new OrdersFragment(); android.support.v4.app.FragmentTransaction fragmentTransaction=getSupportFragmentManager().beginTransaction(); fragmentTransaction.replace(R.id.fragment_container,fragment); fragmentTransaction.commit(); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) .setAction("Action", null).show(); } }); DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawer.setDrawerListener(toggle); toggle.syncState(); NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener(this); OrdersFragment.wa=this; } Here is the fragment: public class OrdersFragment extends Fragment { private Database db; private ArrayList<Order> orders=new ArrayList<Order>(); private OrderAdapter adapter; private ListView listOrders; public static WaiterActivity wa; public OrdersFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_orders, container, false); // Inflate the layout for this fragment db = new Database(); db.createNewOrderListener(this); ListView listOrders = (ListView) view.findViewById(R.id.ordersList); adapter = new OrderAdapter(this.getContext(), R.layout.item_order, orders); listOrders.setAdapter(adapter); return view; } A: I think you are talking about list view item selection. Firstly remove onClick from you xml. Create a function orderClick in you base activity and Then in you fragment add onItemClick listener to your list view. listOrders.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { if (getActivity() instanceof "your base activity"){ (("your base activity")getActivity()).orderClick(); } } });
[ "stackoverflow", "0016470776.txt" ]
Q: Can a primary key in Cassandra contain a collection column? Can a primary key in Cassandra contain a collection column? Example: CREATE TABLE person ( first_name text, emails set<text>, description text PRIMARY KEY (first_name, emails) ); A: Collection types cannot be part of the primary key, and neither can the counter type. You can easily test this yourself, but the reason might not be obvious. Sets, list, maps are hacks on top of the storage model (but I don’t mean that in a negative way). A set is really just a number of columns with the same key prefix. To be a part of the primary key the value must be scalar, and the collection types aren’t. A: It's been a while but as this is on first page in Google when you look for using a map in the primary key, I thought it was worth to update it. Cassandra now allows (I think since 2.1) to use a collection in a Primary Key provided it is frozen. A frozen value serializes multiple components into a single value. Non-frozen types allow updates to individual fields. Cassandra treats the value of a frozen type as a blob. The entire value must be overwritten. With frozen, the collection becomes essentially immutable not allowing for modifications in-place, therefore, becoming suitable for a Primary Key. Here is an example using a frozen list. CREATE TABLE test_frozen ( app_id varchar, kind varchar, properties frozen <list<text>>, PRIMARY KEY ((app_id, kind), properties)); Since 2.1, Cassandra also allows to create an index on columns of type map, set or list - though that not's necessarily a good idea. A: I'd say no: because the collection is mutable, and you can't have a primary key that keeps changing in time.
[ "stackoverflow", "0000693761.txt" ]
Q: How can I add a custom toolbar button to Internet Explorer? How can I add a simple toolbar button to IE that gets the current url and redirect to another url? A: Powering up with Internet Explorer Extensibility Adding Toolbar Buttons at MSDN A: If you don't want to get deep into all the IE extension stuff, you could go with a bookmarklet and just use javascript to get the same behaviour you are looking for: javascript:if(location.href="http://www.google.com"){ location.href="http://www.yahoo.com"} This also has the advantage working on many different browsers. Bookmarklet Info
[ "stackoverflow", "0025903661.txt" ]
Q: How to make overflow tabs as dropdown in bootstrap using jQuery? I am trying to build an responsive admin panel in which selected content will be shown as New Tab, I am trying to make tabs to go under drop down menu when tab overflows. My <body> is divided into two panels (left and right). In Left panel, I have kept all files and folder list. Whenever user clicked on any file then that file contents will be shown on right panel as new tab. When more tabs are opened then tabs which are overflow in right panel then those tabs should move under dropdown menu. I am looking for a method supporting jQuery and bootstrap. A: tab's bootstrap <ul id="myTab" class="nav nav-tabs nav-justified"> <li class="active"><a href="#home" data-toggle="tab">Home</a></li> <li><a href="#profile" data-toggle="tab">Profile</a></li> </ul> <div id="myTabContent" class="tab-content"> <div class="tab-pane fade in active" id="home"> <p>...</p> </div> <div class="tab-pane fade" id="profile"> <p>...</p> </div> </div> $('#myTab a').click(function (e) { if($(this).parent('li').hasClass('active')){ $( $(this).attr('href') ).hide(); } else { e.preventDefault(); $(this).tab('show'); } }); this menu accordion this a show content left to right $('#left .folder').click(function(){ //$('#right .item').text($(this).text()); $('#right .item').text('some text'); })
[ "french.stackexchange", "0000031529.txt" ]
Q: Différence entre « quelque chose est quelque part » et « il y a quelque chose quelque part » Un homme est dans la cour. Il y a un homme dans la cour. Peut-on employer ces deux propositions indifféremment l'une à la place de l'autre ? A: On peut être sûr d'une chose: dans la langue parlée les français utilisent « Il y a un homme dans la cour. » et s'ils utilisent l'autre possibilité ce ne peut être qu'assez rarement. Mais je ne vois aucune autre particularité; quant à ce de quoi il en retourne dans la langue écrite je n'en ai aucune idée. Évidemment il y a un cas particulier pour lequel « un » n'est plus l'article indéfini mais l'adjectif numéral cardinal; dans ce cas où le nombre importe on utilise, bien sûr, la seconde possibilité, mais aussi la première.
[ "apple.stackexchange", "0000197460.txt" ]
Q: Why keyboard shortcut "ctrl + left" doesn't work? I'm used to switch between my desktop spaces using ctrl + arrows. But ctrl + ← doesn't work while ctrl + → works fine. Here is my settings: A: To solve this problem: Change keys for shortcut to ⌘CMD + ← (or anything else). But it won't work after that yet. Reboot your mac. ⌘CMD + → now is working. Change keys to ctrl + ←.
[ "stackoverflow", "0016508880.txt" ]
Q: Create matrix with elements returned by a function I have two vectors x and y with some values and I need to generate the matrix which elements would be returned by a function f(x,y) applied to those 2 vectors. That is the matrix M will have a typical element M[i,j] <- f(x[i], y[j]) What is the most efficent way to do this if I want to avoid loops? I can generate matrix columns or rows by using sapply function, i.e. M[i, ] <- sapply(y, f, x = x[i]) But I still need to apply loop in other dimension which is very slow, because the dimension of x is huge. Is it possible to use apply family of function and avoid loops completely? A: That is exactly what the outer function does: outer(x, y, f) If f is not vectorized, you need: outer(x, y, Vectorize(f))
[ "stackoverflow", "0003259939.txt" ]
Q: System.Net.Mail send message without recipient I am using System.Net.Mail.MailMessage to create and send an email message. For various reasons I do not want to use the .To.Add() or the .CC.Add() or the .Bcc.Add() methods to add recipients to the email. I want to add them via the .Headers.Add() method. (This gives greater control over the recipients). However, when I come to send the message I get an exception stating "A recipient must be specified". It obviously does not realise that I have added recipients via the Headers. Can anyone think of a workaround for this? Could I somehow override the method that is validating the message and throwing the exception? Thanks very much. A: Why not just add a junk recipient to the bcc field?
[ "stackoverflow", "0012454217.txt" ]
Q: Using bundler to manage non-gems There is a github repo I want to fetch code from which isn't a gem. It is a bunch of javascript files, and it has no gem version. Can I add this to the Gemfile and define where it should be stored (under the lib/assets) directory, or will I have to manage this with a git submodule? A: I vote for: Keep the Gemfile clean, go for the submodules.
[ "stackoverflow", "0061720479.txt" ]
Q: View y_true of batch in Keras Callback during training I am attempting to implement a custom loss functoin in Keras. It requires that I compute the sum of the inverse class frequencies for each y in B It is the 1/epsilon(...) portion of the below function The functoin is from this paper - Page 7 Note: I most definitely could be misinterpreting what the paper is describing to do. Please let me know if I am I am currently trying to use a Keras Callback and the on_batch_start/end methods to try and determine the class frequency of the input batch (which means accessing y_true of the batch input), but am having little luck. Thank you in advance for any help you can offer. Edit: By "little luck" I mean I cannot find a way to access the y_true of an individual batch during training. Example: batch_size = 64, train_features.shape == (50000, 120, 20), I cannot find a way to access the y_true of an individual batch during training. I can access the keras model from on_batch_start/end (self.model), but I cannot find a way to access the actual y_true of the batch, size 64. from tensorflow.python.keras.callbacks import Callback class FreqReWeight(Callback): """ Update learning rate by batch label frequency distribution -- for use with LDAM loss """ def __init__(self, C): self.C = C def on_train_begin(self, logs={}): self.model.custom_val = 0 def on_batch_end(self, batch, logs=None): print('batch index', batch) print('Model being trained', self.model) # how can one access the y_true of the batch? LDAM Loss Function zj = "the j-th output of the model for the j-th class" EDIT2 Loss Function - for testing when loss is called def LDAM(C): def loss(y_true, y_pred): print('shape', y_true.shape) # only prints each epoch, not each batch return K.mean(y_pred) + C # NOT LDAM, just dummy for testing purposes return loss Preparing Data, Compiling Model & Training (x_train, y_train), (x_test, y_test) = tf.keras.datasets.cifar10.load_data() y_train = to_categorical(y_train, 10) y_test = to_categorical(y_test, 10) m = 64 # batch_size model = keras.Sequential() model.add(Conv2D(32, (3, 3), padding='same', input_shape=x_train.shape[1:])) model.add(Activation('relu')) model.add(Conv2D(32, (3, 3))) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Dropout(0.25)) model.add(Flatten()) model.add(Dense(512)) model.add(Activation('relu')) model.add(Dropout(0.5)) model.add(Dense(10)) model.add(Activation('softmax')) model.compile(loss=LDAM(1), optimizer='sgd', metrics=['accuracy']) x_train = x_train.astype('float32') x_test = x_test.astype('float32') x_train /= 255 x_test /= 255 model.fit(x_train, y_train, batch_size=m, validation_data=(x_test, y_test), callbacks=[FreqReWeight(1)]) A: Solution Ended up asking a more specific question regarding this. Answer to both can be found here
[ "stackoverflow", "0025658936.txt" ]
Q: injecting data from URL to inputbox I want to add some data from url to an input-box with an unique name ( not id ) , Because I don't have any accesses on the page I can't edit it with ids or sth. <input type="text" name="test"> and sth like that : site.com/index.php?test=text123 A: Ok from what I understand, You want to put get data from URL into your input fields. First, when you open the tab, put the 'document' of the tab into a global variable var url = "www.url.com"; //the url of the page to open in tab var tabInstance= window.open(url); tabDocument = tabInstance.document; //tabDocument is a global variable Now, assuming the data you want to put into the tab is in the URL of the page that is opening the tab function populateInputFields(){ var data = parseURLParams(document.URL); //get url data in json format. if(!data) return; //if no get parameters found //iterate json for(var key in data){//for each key in the json data var value = data[key]; //get the 'value' for corresponding key var element = tabDocument.getElementsByTagName(key)[0];//get the input element if(element && element.tagName == 'input'){//check if element exists and is of type input element.value = value; } } } Implementation of parseURLParams take from here: How to read GET data from a URL using JavaScript? function parseURLParams(url) { var queryStart = url.indexOf("?") + 1, queryEnd = url.indexOf("#") + 1 || url.length + 1, query = url.slice(queryStart, queryEnd - 1), pairs = query.replace(/\+/g, " ").split("&"), parms = {}, i, n, v, nv; if (query === url || query === "") { return; } for (i = 0; i < pairs.length; i++) { nv = pairs[i].split("="); n = decodeURIComponent(nv[0]); v = decodeURIComponent(nv[1]); if (!parms.hasOwnProperty(n)) { parms[n] = []; } parms[n].push(nv.length === 2 ? v : null); } return parms; }
[ "stackoverflow", "0045027591.txt" ]
Q: Simplify replace with regex How can I replace this rather clumsy code with a regex? Dim InvoiceNumber As String = filename.Split("_")(1).Replace("-00", "/").Replace("-0", "/0").Replace("-", "/") Examples of the filenames to be processed: 617809_53070664_EB867_20170710 617809_53069537_308CB588_20170710 617809_53069392_307RS0635_20170710 617809_53060543-001_307RS0630_20170710 I need to get: 53070664 53069537 53069392 53060543/1 A: You can try this approach ( run the sample ) string pattern = @"\d+_(\d+)(?:-0{0,}(\d+))?_.*"; string input = @"617809_53070664_EB867_20170710 617809_53069537_308CB588_20170710 617809_53069392_307RS0635_20170710 617809_53060543-001_307RS0630_20170710 "; foreach (Match m in Regex.Matches(input, pattern)) { if(m.Groups[2].Value!="") Console.WriteLine(m.Groups[1]+"/"+m.Groups[2]); else Console.WriteLine(m.Groups[1]); } }
[ "stackoverflow", "0010399822.txt" ]
Q: Time (DateTime) Format Conditionally Show Minutes The jquery FullCalendar plugin has a neat format for time. If it the time is 7:00pm, the format shows up as 7p. If it the time is 7:30am, the format shows up as 7:30a. Question: Is there any way to use standard formatting to accomplish this with c# sharp? Obviously I can create logic to do this myself, but I'm hoping there is a format string that will accopmlish this. ie (doesn't work): MyDateTime.ToString("h{:mm}t"); A: Formatting strings do not have conditionals - there is no way to specify a condition within a format string. You will need to use a standard if and format accordingly. if(MyDateTime.Minutes == 0) { return MyDateTime.ToString("h"); } return MyDateTime.ToString"h:mmt"); Or, in one line: return MyDateTime.ToString((MyDateTime.Minutes == 0)?"h":"h:mmt");
[ "stackoverflow", "0003601798.txt" ]
Q: JTDS Driver: Could not find a Java charset equivalent to collation 2C04D01000 Looking a solution for strange JTDS error message: Could not find a Java charset equivalent to collation 2C04D01000. I tried to pass file.encoding and user.encoding parameters without any success. A: The only way I've found for the issue is to use Microsoft JDBC driver instead of JTDS.
[ "stackoverflow", "0035996070.txt" ]
Q: getting mean and standard deviation from best-fit normal distribution using seaborn library I have a set of data and I used seaborn library to plot the histogram, apply kernel density estimate and fit a normal distribution to the data. However I would like to extract the mean and standard deviation of the best-fit normal distribution. How could I get these values as outputs from the function distplot of this library? My code: import seaborn as sns from scipy.stats import norm sns.set_style("darkgrid") sns.set_context("paper", font_scale=1, rc={"lines.linewidth": 1.5, "axes.linewidth": 1.0, "axes.labelsize": 15, "xtick.labelsize": 10, "ytick.labelsize": 10, "font.family":'serif','font.serif':'Ubuntu'}) fig, axes = plt.subplots(1, 1, figsize=(10, 10)) sns.distplot(C, fit=norm, kde=True, fit_kws ={"color": "#fc4f30", "lw": 1.5}, kde_kws={"color": "y", "lw": 1.5}, hist_kws={"histtype": "stepfilled", "linewidth": 1, "alpha": 0.1, "color": "b"}, norm_hist=True, ax=axes[0,0]) A bug in seaborn library is that, it doesn't generate the label for the fitted normal distribution but it does for histogram or kernel density. How can I get the normal distribution parameters and make a label for it in the plot? A: Don't get them as outputs from the plot; use the estimator object you are passing to it: norm.fit(C)
[ "stackoverflow", "0006037789.txt" ]
Q: Django Custom Template Tag with Context Variable Argument I have a custom template tag which shows a calendar. I want to populate certain items on the calendar based on a dynamic value. Here's the tag: @register.inclusion_tag("website/_calendar.html") def calendar_table(post): post=int(post) imp=IMP.objects.filter(post__pk=post) if imp: ...do stuff In my template, it works fine when I pass a hard coded value, such as {% load inclusion_tags %} {% calendar_table "6" %} However when I try something like {% calendar_table "{{post.id}}" %} , it raises a error a ValueError for the int() attempt. How can I get around this? A: You want {% calendar_table post.id %}; the extra {{ and }} are what are causing you the heartburn. Note that, in your custom tag, you need to take the string ("post.id") that gets passed and resolve it against the context using Variable.resolve. There's more information on that in the Django docs; in particular, look here: http://docs.djangoproject.com/en/1.3/howto/custom-template-tags/#passing-template-variables-to-the-tag
[ "stackoverflow", "0046371006.txt" ]
Q: The purpose of `serial:true` for concourse I have a question about what serial: true does with respect to jobs. It seems a little redundant since serial_groups already seems to control the serial execution of multiple jobs. But at the same time inside of the plan there are constructs like do that run steps of a plan in a series. The documentation says this: serial: boolean Optional. Default false. If set to true, builds will queue up and execute one-by-one, rather than executing in parallel. In in the "Concepts" section, concourse seems to define a "build" as An instance of execution of a job's plan is called a build In that case, if you don't specify build steps inside of a do, will they run concurrently? A: serial: true means that a specific job will only run one build at a time, however putting multiple jobs in a single serial_group means that all of the jobs in that group will run serial in relation to one another. For example, if I define job job1 as serial: true, and quickly execute four builds of job1, then the first build will run, and builds 2, 3, and 4 will wait in pending state. When build 1 finishes, build 2 will kick off, and builds 3, and 4 will waiting in pending state, and so on. If a define job1, job2, and job3 in a serial_group, and I kick all of them off at the same time, then one of those jobs, lets say job2, will run, and the rest will wait in pending state. Then another job, lets say job1 will run, and job3 wil wait in pending state until job2 finishes, and then job3 will run.
[ "rpg.stackexchange", "0000160377.txt" ]
Q: Does a monster's Proficiency Bonus increase when its CR increases due to it being in a lair or coven? Some monsters have a note saying that their CR is increased when in its Lair or Coven. Since the Proficiency bonus is directly tied to the CR/XP-rating, does this mean that it increase when in a Lair or Coven? If it does it would have effect, for example on spellcasting. Example: The Green Hag (MM p.177). Its 'normal' CR is 3 (proficiency bonus +2), but when part of a coven is raised to CR 5 (proficiency bonus +3). The Hag has Innate Spellcasting (Charisma) and a Charisma Modifier of +2. Her spell save DC is 8+2+2=12. When using CR 5, it would be 8+2+3=13. A: I did a bit of research on this, and from what I can tell- the answer to both lairs and covens is no. Here's why. First, a hag coven is when one of each kind of hag get together, and is gives them each an enhanced spell list, which they can use as 12th level spellcasters, but if any one falls, the others lose this power bonus. In this case, the CR increase is to show how much more powerful the hags will be together with that high of a spellcasting level. As this is an effect of the Hags power together, instead of a leveled-up hag, this does not increase their proficiency bonus, and this reasoning is backed up by the fact that each hag has a coven variant on dnd beyond, and if you look them, for example the afore mentioned green hag's both regular and coven forms, none of their stats have changed other than their spell list and CR. Now, when we look at lair bonuses, it is because when a monster is in it's lair it has lair actions that make it harder to fight. Now this, like for the hags, is a higher CR to represent a harder fight, not necessarily a leveling-up of the monster, especially since in this case the monster isn't getting any stronger, it just has the home-field advantage if you will. Because of this, like for the hags coven, these CR increases do not increase proficiency bonus.
[ "stackoverflow", "0024662119.txt" ]
Q: IDL undefined procedure I'm using IDL 8.3 on Mac 10.9.3 I am running a script that calls in a procedure. The procedure I am calling in is contained in a directory that I included in IDL's path (I did this by going under IDL->preferences->IDL->paths and adding the directory). However, when I attempt to run the script, I get the error message: "% Attempt to call undefined procedure/function: 'procedure.pro'. % Execution halted at: $MAIN$". The weird thing is is that it still lists all the syntax errors in the procedure that is supposedly 'undefined'. Also, when I type the procedure.pro name into the IDL prompt, it lights up teal/blue color (meaning it recognizes the procedure). I tried making a very simple simple.pro, put it into the same directory I mentioned before, typed it into the IDL prompt (it turned teal/blue), and it ran perfectly with no errors. I am unsure why the procedure.pro file is 'undefined' since it is contained it its path, and I proved with simple.pro that .pro files in this path will run correctly. A: well, the procedure I was attempting to call in contained other procedures/functions that weren't included in IDL's original library. I just had to download these separate procedures/functions, and the syntax errors went away, along with the 'unidentified procedure' error message.
[ "stackoverflow", "0029779047.txt" ]
Q: Wrap a list to new line in Bootstrap 3 In my Bootstrap navbar, I have a logo in the header and then an inline list. On large screens, the logo and list are on the same line. On smaller screens, I want the logo centered on the first line and the list to center on a second line. But, the list keeps going to vertical stacked instead of remaining inline. How can I prevent the inline list from going vertical as the screen shrinks? Here is a jsfiddle of my current navbar: https://jsfiddle.net/DTcHh/6936/ I need the links on the right to get closer and closer to the logo as the screen shrinks. Then, when there's no more room, I need those links centered on a new line below the logo, which should be centered on the first line. Desired effect on small screens: https://drive.google.com/file/d/0B08LN9pHRwLuSkRvV3YwYVk5aWs/view?usp=sharing html: <body> <div class="navbar navbar-default navbar-fixed-top" role="navigation"> <div class="container"> <div class="navbar-header navbar-logo"> <a href="#"><img src="http://placehold.it/140x75" class="img-responsive navlogo" alt="logo here"></a> </div> <div class="navbar-links"> <ul class="list-inline nav navbar-nav navbar-right navbar-list"> <li><a href="#" style="color: black; font-weight: bold;">FAQ</a></li> <li><a href="#" style="color: black; font-weight: bold;">Contact</a></li> <li><a href="#" style="color: black; font-weight: bold">Policies</a></li> <li><a href="#" style="background-color: #9e1d2a; color: white">For Users</a></li> <li style="padding-top: 0px; padding-left: 15px"><a data-toggle="collapse" href="#nav-search-collapse"><i class="glyphicon glyphicon-search"></i></a></li> </ul> </div> </div> <div class="collapse" id="nav-search-collapse"> <ul class="list-inline navbar-list-form"> <li><form class="navbar-form" role="form" method="get" action="#"> <div class="input-group"> <input type="Search" placeholder="Search Data" class="form-control" name="q"> <div class="input-group-btn"> <button class="btn btn-primary"> <span class="glyphicon glyphicon-search"></span> </button> </div> </div> </form></li> <li><form class="navbar-form" role="form" method="get" action="#"> <div class="input-group"> <span class="input-group-addon">wwww.</span> <input type="Search" class="form-control" name="w_searched"> <div class="input-group-btn"> <button class="btn btn-primary"> <span>Search</span> </button> </div> </div> </form></li> </ul> </div> </div> </body> css: .navbar-list { padding-top: 5px; } .navbar-list li{ font-size: 16px; } #nav-search-collapse { width:100%; margin: 0 auto; text-align:center; } .navbar-list-form { display:inline-block; padding: 0; } @media (min-width: 0px) and (max-width: 1000px) { .navbar-header{ float: left; width: 100%; } .navbar-links { float: left; width: 100%; } } A: Adding this to your CSS will give you what you are looking for (you are required to define minimum width up-till which all links appear on same newline, it's your decision) @media (max-width: 1000px) and (min-width: 0px) { .navbar-links { text-align: center; } .nav>li { display: inline; } .nav>li>a { display: inline; } } JSFiddle
[ "stackoverflow", "0044658266.txt" ]
Q: What is the reason of the huge difference of looping time between tFileStream read and write I try to read and write stock data to a file. Same looping count makes a huge difference. The actual writing loop takes almost 30 minutes. Is this just because of the physical limit of writing speed of the drive? Is there any way to improve the writing process? uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ComCtrls, Vcl.StdCtrls, System.Generics.Collections; type tSymbol = record CloseList: TList<Integer>; OpenList: TList<Integer>; VolumeList: TList<Integer>; end; TForm1 = class(TForm) Button1: TButton; ProgressBar1: TProgressBar; Memo1: TMemo; Button2: TButton; procedure Button1Click(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure Button2Click(Sender: TObject); private ReadList, WriteList: TList<tSymbol>; end; procedure TForm1.Button1Click(Sender: TObject); // it takes 45 seconds. var _FileStream: TFileStream; i, j: Integer; begin Memo1.Lines.Add(FormatDateTime('hh:mm:ss', Time)); ProgressBar1.Min := 0; ProgressBar1.Max := 999; _FileStream := TFileStream.Create('test', fmCreate); for i := 0 to 999 do begin for j := 0 to 999 do begin _FileStream.Write(WriteList.List[i].CloseList.List[j], 4); _FileStream.Write(WriteList.List[i].OpenList.List[j], 4); _FileStream.Write(WriteList.List[i].VolumeList.List[j], 4); end; ProgressBar1.Position := i; end; _FileStream.Free; Memo1.Lines.Add(FormatDateTime('hh:mm:ss', Time)); end; procedure TForm1.Button2Click(Sender: TObject); // it takes 6 seconds. var _FileStream: TFileStream; _Close, _Open, _Volume: Integer; _Symbol: tSymbol; i, j: Integer; begin Memo1.Lines.Add(FormatDateTime('hh:mm:ss', Time)); ProgressBar1.Min := 0; ProgressBar1.Max := 999; _FileStream := TFileStream.Create('test', fmOpenRead); for i := 0 to 999 do begin _Symbol.CloseList := TList<Integer>.Create; _Symbol.OpenList := TList<Integer>.Create; _Symbol.VolumeList := TList<Integer>.Create; for j := 0 to 999 do begin _FileStream.Read(_Close, 4); _Symbol.CloseList.Add(_Close); _FileStream.Read(_Open, 4); _Symbol.OpenList.Add(_Open); _FileStream.Read(_Volume, 4); _Symbol.VolumeList.Add(_Volume); end; ReadList.Add(_Symbol); ProgressBar1.Position := i; end; _FileStream.Free; Memo1.Lines.Add(FormatDateTime('hh:mm:ss', Time)); end; procedure TForm1.FormCreate(Sender: TObject); var _Symbol: tSymbol; i, j: Integer; begin ReadList := TList<tSymbol>.Create; WriteList := TList<tSymbol>.Create; _Symbol.CloseList := TList<Integer>.Create; _Symbol.OpenList := TList<Integer>.Create; _Symbol.VolumeList := TList<Integer>.Create; for i := 0 to 999 do begin for j := 0 to 999 do begin _Symbol.CloseList.Add(0); _Symbol.OpenList.Add(0); _Symbol.VolumeList.Add(0); end; WriteList.Add(_Symbol); end; end; procedure TForm1.FormDestroy(Sender: TObject); begin ReadList.Free; WriteList.Free; end; A: Use buffered file I/O. Read/write the file in larger chunks, managing individual values within each chunk as needed. Delphi even has a TBufferedFileStream class in 10.1 Berlin and later. Also, when filling a list, pre-allocate the list's capacity ahead of time to avoid the overhead of having to re-allocate the list's internal array while adding new items to the list. Try something more like this: uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ComCtrls, Vcl.StdCtrls, System.Generics.Collections; type tSymbol = record CloseList: TList<Integer>; OpenList: TList<Integer>; VolumeList: TList<Integer>; constructor Create(InitialCapacity: Integer); procedure Cleanup; end; TForm1 = class(TForm) Button1: TButton; ProgressBar1: TProgressBar; Memo1: TMemo; Button2: TButton; procedure Button1Click(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure Button2Click(Sender: TObject); private ReadList, WriteList: TList<tSymbol>; end; constructor tSymbol.Create(InitialCapacity: Integer); begin CloseList := TList<Integer>.Create; CloseList.Capacity := InitialCapacity; OpenList := TList<Integer>.Create; OpenList.Capacity := InitialCapacity; VolumeList: TList<Integer>.Create; VolumeList.Capacity := InitialCapacity; end; procedure tSymbol.Cleanup; begin CloseList.Free; OpenList.Free; VolumeList.Free; end; procedure TForm1.Button1Click(Sender: TObject); var FS: TFileStream; i, j, idx: Integer; Block: array of Int32; begin Memo1.Lines.Add(FormatDateTime('hh:mm:ss', Time)); ProgressBar1.Position := 0; ProgressBar1.Min := 0; ProgressBar1.Max := 1000; ProgressBar1.Step := 1; FS := T{Buffered}FileStream.Create('test', fmCreate); try SetLength(Block, 3 * 1000); for i := 0 to WriteList.Count-1 do begin with WriteList[i] do begin idx := 0; for j := 0 to 999 do begin Block[idx+0] := CloseList[j]; Block[idx+1] := OpenList[j]; Block[idx+2] := VolumeList[j]; Inc(idx, 3); end; end; FS.WriteBuffer(Block[0], SizeOf(Int32) * Length(Block)); ProgressBar1.StepIt; end; //FS.FlushBuffer; finally FS.Free; end; Memo1.Lines.Add(FormatDateTime('hh:mm:ss', Time)); end; procedure TForm1.Button2Click(Sender: TObject); var FS: TFileStream; Symbol: tSymbol; i, j, idx: Integer; Block: array of Int32; begin Memo1.Lines.Add(FormatDateTime('hh:mm:ss', Time)); for I := 0 to ReadList.Count-1 do ReadList[I].Cleanup; ReadList.Clear; ProgressBar1.Position := 0; ProgressBar1.Min := 0; ProgressBar1.Max := 999; ProgressBar1.Step := 1; FS := T{Buffered}FileStream.Create('test', fmOpenRead or fmShareDenyWrite); try SetLength(Block, 3 * 1000); ReadList.Capacity := 1000; for i := 0 to 999{(FS.Size div 12000) - 1} do begin FS.ReadBuffer(Block[0], SizeOf(Int32) * Length(Block)); Symbol := tSymbol.Create(1000); try idx := 0; for j := 0 to 999 do begin Symbol.CloseList.Add(Block[idx+0]); Symbol.OpenList.Add(Block[idx+1]); Symbol.VolumeList.Add(Block[idx+2]); Inc(idx, 3); end; ReadList.Add(Symbol); except Symbol.Cleanup; raise; end; ProgressBar1.StepIt; end; finally FS.Free; end; Memo1.Lines.Add(FormatDateTime('hh:mm:ss', Time)); end; procedure TForm1.FormCreate(Sender: TObject); var Symbol: tSymbol; i, j: Integer; begin ReadList := TList<tSymbol>.Create; WriteList := TList<tSymbol>.Create; WriteList.Capacity := 1000; for i := 0 to 999 do begin Symbol := tSymbol.Create(1000); try for j := 0 to 999 do begin Symbol.CloseList.Add(0); Symbol.OpenList.Add(0); Symbol.VolumeList.Add(0); end; WriteList.Add(Symbol); except Symbol.Cleanup; raise; end; end; end; procedure TForm1.FormDestroy(Sender: TObject); var i: Integer; begin if ReadList <> nil then begin for i := 0 to ReadList.Count-1 do ReadList[i].Cleanup; ReadList.Free; end; if WriteList <> nil then begin for i := 0 to WriteList.Count-1 do WriteList[i].Cleanup; WriteList.Free; end; end; That being said, you might consider merging your 3 integer values together into another record, that way you are not wasting time and resources having to allocate so many individual lists: uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ComCtrls, Vcl.StdCtrls, System.Generics.Collections; type tSymbolValues = record Close: Integer; Open: Integer; Volume: Integer; end; tSymbol = record Values: TList<tSymbolValues>; constructor Create(InitialCapacity: Integer); procedure Cleanup; end; TForm1 = class(TForm) Button1: TButton; ProgressBar1: TProgressBar; Memo1: TMemo; Button2: TButton; procedure Button1Click(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure Button2Click(Sender: TObject); private ReadList, WriteList: TList<tSymbol>; end; constructor tSymbol.Create(InitialCapacity: Integer); begin Values := TList<tSymbolValues>.Create; Values.Capacity := InitialCapacity; end; procedure tSymbol.Cleanup; begin Values.Free; end; procedure TForm1.Button1Click(Sender: TObject); var FS: TFileStream; i, j, idx: Integer; Block: array of Int32; begin Memo1.Lines.Add(FormatDateTime('hh:mm:ss', Time)); ProgressBar1.Position := 0; ProgressBar1.Min := 0; ProgressBar1.Max := 1000; ProgressBar1.Step := 1; FS := T{Buffered}FileStream.Create('test', fmCreate); try SetLength(Block, 3 * 1000); for i := 0 to WriteList.Count-1 do begin with WriteList[i] do begin idx := 0; for j := 0 to Values.Count-1 do begin with Values[j] do begin Block[idx+0] := Close; Block[idx+1] := Open; Block[idx+2] := Volume; Inc(idx, 3); end; end; end; FS.WriteBuffer(Block[0], SizeOf(Int32) * Length(Block)); ProgressBar1.StepIt; end; //FS.FlushBuffer; finally FS.Free; end; Memo1.Lines.Add(FormatDateTime('hh:mm:ss', Time)); end; procedure TForm1.Button2Click(Sender: TObject); var FS: TFileStream; Symbol: tSymbol; Values: tSymbolValues; i, j, idx: Integer; Block: array of Int32; begin Memo1.Lines.Add(FormatDateTime('hh:mm:ss', Time)); for I := 0 to ReadList.Count-1 do ReadList[i].Cleanup; ReadList.Clear; ProgressBar1.Position := 0; ProgressBar1.Min := 0; ProgressBar1.Max := 999; ProgressBar1.Step := 1; FS := T{Buffered}FileStream.Create('test', fmOpenRead or fmShareDenyWrite); try SetLength(Block, 3 * 1000); ReadList.Capacity := 1000; for i := 0 to 999{(FS.Size div 12000) - 1} do begin FS.ReadBuffer(Block[0], SizeOf(Int32) * Length(Block)); Symbol := tSymbol.Create(1000); try idx := 0; for j := 0 to 999 do begin Values.Open := Block[idx+0]; Values.Close := Block[idx+1]; Values.Volume := Block[idx+2]; Symbol.Values.Add(Values); Inc(idx, 3); end; ReadList.Add(Symbol); except Symbol.Cleanup; raise; end; ProgressBar1.StepIt; end; finally FS.Free; end; Memo1.Lines.Add(FormatDateTime('hh:mm:ss', Time)); end; procedure TForm1.FormCreate(Sender: TObject); var Symbol: tSymbol; Values: tSymbolValues; i, j: Integer; begin ReadList := TList<tSymbol>.Create; WriteList := TList<tSymbol>.Create; WriteList.Capacity := 1000; for i := 0 to 999 do begin Symbol := tSymbol.Create(1000); try for j := 0 to 999 do begin Values.Open := 0; Values.Close := 0; Values.Volume := 0; Symbol.Values.Add(Values); end; WriteList.Add(Symbol); except Symbol.Cleanup; raise; end; end; end; procedure TForm1.FormDestroy(Sender: TObject); var i: Integer; begin if ReadList <> nil then begin for I := 0 to ReadList.Count-1 do ReadList[i].Cleanup; ReadList.Free; end; if WriteList <> nil then begin for I := 0 to WriteList.Count-1 do WriteList[i].Cleanup; WriteList.Free; end; end;
[ "stackoverflow", "0007512915.txt" ]
Q: Text array to email body I have a backup log file from robocopy and would like to take last lines from that file and send it as email body. Log example: Total Copied Skipped Mismatch FAILED Extras Dirs : 85262 85257 1 0 4 0 Files : 637048 637047 0 0 1 0 Bytes :1558.929 g1558.929 g 0 0 165 0 Times : 19:30:49 19:01:06 0:00:00 0:29:43 Speed : 24448224 Bytes/sec. Speed : 1398.938 MegaBytes/min. Ended : Wed Sep 21 15:42:01 2011 Script code: $report2_tail = Get-Content .\backup2.log )[-12 .. -1] $encoding = [System.Text.Encoding]::UTF8 Send-mailmessage -Smtpserver smtp.server.address -encoding $encoding -from "Backup-Replication<[email protected]>" -to "[email protected]" -subject "End of Replication Report" -body " backup Replication Report ------------------------------------------------------------ $report2_tail " Script works fine but the message body is in one line and looks like this: Total Copied Skipped Mismatch FAILED Extras Dirs : 85262 85257 1 0 4 0 Files : 637048 637047 0 0 1 0 Bytes :1558.929 g1558.929 g 0 0 165 0 Times : 19:30:49 19:01:06 0:00:00 0:29:43 Speed : 24448224 Bytes/sec. Speed : 1398.938 MegaBytes/min. Ended : Wed Sep 21 15:42:01 2011 What is a best way to solve the problem ? Regards Marcin A: Pipe Get-Content result to the Out-String cmdlet: $report2_tail = Get-Content .\backup2.log )[-12 .. -1] | Out-String Send-mailmessage ... -subject "End of Replication Report" -body $report2_tail
[ "stackoverflow", "0000307531.txt" ]
Q: why do tweens stop randomly? With code like the following, sometimes the child controls correctly finish their animation and sometimes they stop at random places in the middle. Why don't they work correctly? var t:Tween; t = new Tween(child1,"x",Elastic.easeOut,0,100,2,true); t = new Tween(child1,"y", Elastic.easeOut,0,100,2,true); t = new Tween(child2,"x",Strong.easeOut,300,400,1,true); t = new Tween(child2,"y", Strong.easeOut,300,400,1,true); A: Additionally, try using an free/open source tween engine rather than the one packaged with Flash. Two very popular ones are TweenLite and Tweener. They offer greater performance and more functionality/options. A: Each tween must be assigned to a separate variable in global scope. The following code behaves reliably: var t1:Tween = new Tween(child1,"x",Elastic.easeOut,0,100,2,true); var t2:Tween = new Tween(child1,"y", Elastic.easeOut,0,100,2,true); var t3:Tween = new Tween(child2,"x",Strong.easeOut,300,400,1,true); var t4:Tween = new Tween(child2,"y", Strong.easeOut,300,400,1,true); It would appear that when a variable is re-used, the tween that is no longer referenced may get garbage collected or otherwise halted in the middle of its work. The same problem can occur if you use separate variables but declare them in the local scope of a function instead of in the global scope of your frame. A: You can also create an array in the scope of your class, then just push tweens onto that array. Although this might cause the tweens in the array to never get garbage collected, even after they finish, so you might want to empty the array yourself at points in which you know all the tweens have finished.
[ "electronics.stackexchange", "0000104276.txt" ]
Q: What would be the input current of buck regulator I have a basic question about measuring input current. The buck regulator I have chosen is rated to deliver 3.3V/2A from +12V input. My question is - Is the input current 2A (load current) + few mA (needs for operation)? Or because of stepdown from 12V to 3.3V, based on load current, the input current is 500mA + few mA? Is the 2A output current taken entirely from the input or step down conversion delivers 2A after consuming few mA. A: It's closer to your second option, but not quite. A buck regulator will take a few mA for its operation, which could be considered to be constant. Say 15mA at 12V. Let's ignore that for the moment. If perfect, it would output the same power as input. Your output of 3.3V at 2A is 6.6W, so a perfect buck regulator would need 550mA from the 12V supply (6.6W/12V). (Image from the Wikipedia page) To see this, consider that a perfect switch has no losses, a perfect diode either conducts like a wire (no power is lost) or blocks perfectly, and a perfect inductor with zero resistance and zero eddy current losses dissipates no power (it simply stores energy and barfs it up again). So from conservation of energy, input power (averaged over a cycle in steady state) must equal output power. In a real buck regulator implementation, there are, however, losses that are at least roughly proportional to the output power due to resistance in the inductor and switch, voltage drop in the diode and so on. Say the efficiency is 80%. It will then require 6.6W/0.80 = 7.5W input power, or 625mA, plus the 15mA it needs just sitting there, so 640mA total (usually the quiescent current will be folded into the overall efficiency figure so we don't need to add it). Because of the 15mA (or whatever it is for your real regulator) the efficiency of the regulator (output power divided by input power) will decrease for lower output currents. A: I just to add to the other answers, which cover the basics fairly well, but ignore the input current waveform, which can be important in some applications. The current is drawn from the 12V supply in pulses, and the average current during the pulse is indeed the same as (or greater than) the load current. The duty cycle of the pulses is about 3.3V/12V = 27.5%, so the overall average current (ignoring the efficiency issues) is on the order of 2A × 27.5% = 0.55A. Some power sources, such as solar panels, are current-limited; they cannot supply more than their short-circuit current under any circumstances, even for short periods of time. For example, suppose you wanted to power your regulator from a 10W, 12V solar panel. Such a panel will supply up to about 0.833A to a resistive load, and will have a short-circuit current of about 1A. If you try to draw more than 1A at the 3.3V output of your buck regulator, the voltage will start to droop. The solar panel simply cannot "charge" the inductor with more current than this. With this sort of source, you must have an input decoupling capacitor (in parallel with the panel) that can supply the pulse current needed by the buck regulator without excessive voltage droop. This allows the solar panel to provide just the average current required, with a small amount of "ripple" caused by the switching of the regulator. To continue the example, let's say your regulator operates at 100kHz, and you want to limit the ripple to 1V. The capacitor needs to supply the difference in current between what the panel can supply and what the regulator reuqires: $$I_{CAP} = 2 A - 0.833 A = 1.166 A (max)$$ It needs to do this for the on-time of the buck regulator: $$t_{ON} = t_{PERIOD} \cdot Duty Cycle = 10 \mu s \cdot 27.5\% = 2.75 \mu s$$ The capacitor required is: $$C = \frac{I_{CAP} \cdot t_{ON}}{\Delta V} = \frac{1.166 A \cdot 2.75 \mu s}{1 V} = 3.2 \mu F (min)$$
[ "stackoverflow", "0024767499.txt" ]
Q: Python - if statement returning True when I don't want it to The code I've just written is used so that it adjusts the value of each item in a list each time the end users scrolls, so that essentially the value of each item matches the y coordinate of its corresponding object when blitted on to the surface. The logic behind my code looks at whether or not the difference between the original y coordinate and the new y coordinate of a object when scrolled remains the same, if not then it should proceed to the for loop, else move on the code following the if statement. For some reason, the if statement keeps returning True even though there is no difference between the two control variables I am using. I am not sure if I am overlooking something subtle which means that it will keep returning True or my logic just hasn't worked the way I expected it to; my bet is on the latter. #example y values in list yIndex = [122, 152, 212, 242] scroll_y = 63 #initial y scroll coordinate originalScroll_y = 63 while True: for event in pygame.event.get(): #code checking whether user has scrolled if event.type == pygame.MOUSEBUTTONDOWN: if event.button == 4 and scroll_y != 63: originalScroll_y = scroll_y scroll_y = min(scroll_y + 15, 63) if event.button == 5: originalScroll_y = scroll_y scroll_y = max(scroll_y - 15, finalY + 470) elif event.type == MOUSEBUTTONUP and event.button == 1 and isinstance(page, MainPage): x, y = pygame.mouse.get_pos() control = originalScroll_y - scroll_y control2 = 0 #e.g. if control = 15 and control2 = 15, it returns True instead #of False if control != control2: for k, j in enumerate(yIndex): j -= control yIndex[k] = j control2 = control for i in yIndex: if y >= (i - 10) and y <= (i + 20): if i in indexedContacts: buttonSound.play() sleep(0.5) scroll_y = 63 page = EditPage() page.style() page.contactFields() break A: You have a nested if statement so control2 is set to 0 elif event.type == MOUSEBUTTONUP and event.button == 1 and isinstance(page, MainPage): x, y = pygame.mouse.get_pos() control = originalScroll_y - scroll_y control2 = 0 # set to 0 here if control != control2: # is 0 here Control2 will never be 15 or any value other than 0 in that if statement.
[ "stackoverflow", "0045810006.txt" ]
Q: Using jQuery to Focus a Field on Hover after a Delay I'm trying to cause a field to be focused when hovered, but only after a 3 second delay. Clearly I'm doing it wrong: var timer; function focusTimer() { timer = setTimeout(function () { $('#input').focus(), 3000; }) } $('#input').hover(function () { if (timer) { clearTimeout(timer); } focusTimer(); }); #input:focus { width: 500px; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input id="input"> A: You are doing it wrong. You're placing the 3000 inside the function. move it to outside timer = setTimeout(function () { $('#input').focus(), 3000; ^^^^^^^ }) Should be timer = setTimeout(function () { $('#input').focus(); },3000); Snippet var timer; function focusTimer() { timer = setTimeout(function () { $('#input').focus(); },3000) } $('#input').hover(function () { if (timer) { clearTimeout(timer); } focusTimer(); }); #input:focus { width: 500px; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input id="input">
[ "superuser", "0000043509.txt" ]
Q: How to install Windows 7? I have an ISO of Windows 7 Professional through MSDNAA. I don't want to simply upgrade my current Vista. I want a fresh install and then remove Vista completely. I honestly have no idea how to being doing this. The biggest issue is: in what hard-disk space will Windows 7 end up and how do I get rid of Vista? A: Burn the ISO image to disc, boot from it and go through the Win7 setup. During setup it'll ask you where you want to install Windows and should present you with the partition information already on your drive. Delete the partition with Vista and create a new one for Win7. That'll get rid of Vista.
[ "electronics.stackexchange", "0000160094.txt" ]
Q: Short circuit current in transformer When transformer secondary is short circuited, what would be the value of current flowing through short circuited side? Shouldn't it be infinity ideally? If yes, is it only due to large cross-section & highly conductive copper wires that wires don't get melted? For e.g. suppose I have 1 kVA, single phase, 250/125 V transformer. Now if I short circuit 125V side and set full load primary current i.e. 1000/250 = 4 A in primary then what would be value of secondary current? A: I have 1 kVA, single phase, 250/125 V transformer. If you can adjust the primary voltage so that the input current is 4 amps RMS when the secondary is shorted, the secondary current will be 8 amps for a 2:1 step-down transformer. NB - you will probably find that the easiest way to do this is use the output of a variac and raise the primary voltage carefully whilst noting the primary current. Typically the variac output will only need to be around 10V RMS to get full primary current with secondary shorted out. The primary-secondary turns ratio determines both step-down voltage ratio and step-up current ratio.
[ "stackoverflow", "0056964163.txt" ]
Q: Project Euler #27: Is there a more optimal way to solve this problem? I am doing the Quadratic Primes question. My solution is pretty much just loop through every possible option and return the best. I know that nested loops are not optimal and there's probably a smarter way to find the answer. But I can't think of one that isn't brute force. Here's my code: var isPrime = function(num) { if (num <= 1) { return false; } // The check for the number 2 and 3 if (num <= 3) { return true; } if (num % 2 == 0 || num % 3 == 0) { return false; } for (var i = 5; i * i <= num; i = i + 6) { if (num % i == 0 || num % (i + 2) == 0) { return false; } } return true; } var main = function () { var max = 0; var a = 0; var b = 0; for (var i = -999; i < 1000; i++) { for (var j = -1000; j <= 1000; j++) { var n = 0; while(1) { var temp = Math.pow(n, 2) + (n * i) + j; if (isPrime(temp)) { if (n > max) { max = n; a = i; b = j; } } else { break; } n++; } } } return a * b; } console.log(main()); Thanks! A: Although the algorithm runs very quickly even in JavaScript, there is some area for optimization. Take a look at the formula: x = n2 + an + b. n will be odd (1, 3, 5, ...) and even (2, 4, 6, ...). Our goal is to make sure that x is always odd, because no even integer other than 2 is prime. Reminder of rules odd * odd = odd (3 * 7 = 21) odd * even = even (3 * 6 = 18) even * even = even (4 * 8 = 32) odd + odd = even (3 + 7 = 10) odd + even = odd (3 + 6 = 9) even + even = even (4 + 6 = 10) n2 If n is odd, n squared will be also odd: 12 = 1, 32 = 9, 52 = 25, ... If n is even, n squared will be also even: 22 = 4, 42 = 8, 62 = 36, ... So we have alternating odd and even values. a*n If a is odd, then: for odd n, a*n is odd for even n, a*n is even so we again have alternating odd and even values. If a is even, then a*n is always even. n2 + a*n So far, we have n2 + an, which: for odd a is equal to odd + odd = even or even + even = even; so it's always even for even a is equal to odd + even = odd or even + even = even; so it's alternating odd and even b There is just one coefficient left - b. It is a constant, which added to the previous value should yield odd values. That means we have to ignore even a, because a constant added to alternating odd and even values will also give alternating values, so the formula x will fail after just a few steps. Since a must be odd, n + an is even. Therefore, to make x odd, we must take an odd b: even + odd = odd. Summary We have to focus only on odd a and odd b values, which will limit the number of cases to check by roughly 4 (= 2 * 2).
[ "stackoverflow", "0050315803.txt" ]
Q: css navigate through background image I have a simple html document. A div inside the body, which contains the following css rules: html,body { height: 100%; margin: 0; } #game { width: 1000px; height: 1000px; background-image:url(../img/test.jpg); background-attachment: scroll; background-repeat: no-repeat; } HTML: <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Title</title> <link rel="stylesheet" href="css/style.css"> </head> <body> <div id="game"> <div class="moneybar"> <div class="moneyscore brown" id="score">0</div> </div> </div> </body> </html> What I want to achieve: when on Mobile, if I have a 480px screen, I only see a portion of the background image. And that's fine. But I also want to 'navigate' (drag/scroll) the rest of the background . Problem: the background does not 'move', 'scroll' ... I don't know which term to use. I am making a simple game, so if I place a building on the top of the map (which is the full screen background image), I should be able to navigate down and see other buildings. I hope I have been clear enough. A: It's not clear to me from your question precisely what result you are looking to achieve. But if I have understood correctly then you simply need to remove: html, body { height: 100%; } Working Example: body { margin: 0; padding: 0; } .game { width: 1000px; height: 1000px; background: radial-gradient(blue, green , yellow, orange, red); } .game .scorebar { position: fixed; bottom: 0; left: 0; width: 100%; height: 36px; line-height: 36px; color: rgb(255, 255, 255); font-size: 24px; text-align: center; font-weight: bold; font-family: arial, helvetica, sans-serif; background-color: rgb(127, 0, 0); } <div class="game"> <div class="scorebar">Score Bar</div> </div>
[ "stackoverflow", "0002604159.txt" ]
Q: Neural Network: Handling unavailable inputs (missing or incomplete data) Hopefully the last NN question you'll get from me this weekend, but here goes :) Is there a way to handle an input that you "don't always know"... so it doesn't affect the weightings somehow? Soo... if I ask someone if they are male or female and they would not like to answer, is there a way to disregard this input? Perhaps by placing it squarely in the centre? (assuming 1,0 inputs at 0.5?) Thanks A: You probably know this or suspect it, but there's no statistical basis for guessing or supplying the missing values by averaging over the range of possible values, etc. For NN in particular, there are quite a few techniques avaialble. The technique i use--that i've coded--is one of the simpler techniques, but it has a solid statistical basis and it's still used today. The academic paper that describes it here. The theory that underlies this technique is weighted integration over the incomlete data. In practice, no integrals are evaluated, instead they are approximated by closed-form solutions of Gaussian Basis Function networks. As you'll see in the paper (which is a step-by-step explanation, it's simple to implement in your backprop algorithm. A: Neural networks are fairly resistant to noise - that's one of their big advantages. You may want to try putting inputs at (-1.0,1.0) instead, with 0 as the non-input input, though. That way the input to the weights from that neuron is 0.0, meaning that no learning will occur there. Probably the best book I've ever had the misfortune of not finishing (yet!) is Neural Networks and Learning Machines by Simon S. Haykin. In it, he talks about all kinds of issues, including the way you should distribute your inputs/training set for the best training, etc. It's a really great book!
[ "stackoverflow", "0027818036.txt" ]
Q: How to remove legends in javafx line chart I am trying to plot javafx bar graph using line chart. Each bar line is drawn using a vertical line drawn with two points and line symbol removed. There could be many series(Bar line) in my application but want to show only two legends only. Currently legends were shown as many series been added. Somehow i am able to show only two legends and hided others. But now problem exist with spaces used by hided legends. My current code is as below:- package graph; import javafx.application.Application; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.scene.Node; import javafx.scene.Scene; import javafx.scene.chart.NumberAxis; import javafx.scene.chart.XYChart; import javafx.scene.control.Tooltip; import javafx.stage.Stage; import com.sun.javafx.charts.Legend; public class BarGraphUsingLineChart extends Application { final NumberAxis xAxis = new NumberAxis(); final NumberAxis yAxis = new NumberAxis(); final MyLineChart<Number,Number> lineChart = new MyLineChart<Number,Number>(xAxis,yAxis); private boolean valid=true; private boolean invalid=true; @Override public void start(Stage stage) { stage.setTitle("Bar Chart Using Lines"); xAxis.setLabel("Month"); lineChart.setTitle("BAR CHART DEMO"); ObservableList<XYChart.Series<Number,Number>> graphData = FXCollections.observableArrayList(); for(int i=1; i<=10;i++) { if(i%2==0) { graphData.add(drawBarline(i*10, i*5, true)); } else{ graphData.add(drawBarline(i*10, i*5, false)); } } // Dont show symbol of line charts lineChart.setCreateSymbols(false); Scene scene = new Scene(lineChart,800,600); lineChart.setData(graphData); stage.setScene(scene); stage.getScene().getStylesheets().add("/graph/BarChart.css"); updateStyleSheet(); stage.show(); } private XYChart.Series<Number, Number> drawBarline(Number xAxis, Number yAxis, boolean valid) { XYChart.Series<Number, Number> channel_Series = new XYChart.Series<Number, Number>(); channel_Series.getData().add(new XYChart.Data<Number, Number>(yAxis, xAxis )); channel_Series.getData().add(new XYChart.Data<Number, Number>(yAxis, 0.0 )); if(valid) { channel_Series.setName("Valid"); } else { channel_Series.setName("Invalid"); } return channel_Series; } private void updateStyleSheet() { for(Node symbol : lineChart.lookupAll(".chart-legend-item")){ if(valid) { ((Legend)symbol.getParent()).getItems().get(0).setText("Valid"); valid=false; } else if(invalid){ ((Legend)symbol.getParent()).getItems().get(1).setText("Invalid"); invalid=false; } else { symbol.setVisible(false); } } // Beloc code removes all the legends //lineChart.setLegendVisible(false); for (XYChart.Series<Number, Number> s : lineChart.getData()) { if(("Valid").equals(s.getName())) { s.getNode().setStyle("-fx-stroke: #0000FF; "); } else { s.getNode().setStyle("-fx-stroke: #FF0000; "); } for (XYChart.Data<Number, Number> d : s.getData()) { Tooltip.install(d.getNode(), new Tooltip("Frequency: "+ d.getXValue()+ " THz, Power: "+ d.getYValue().doubleValue()+" unit")); } } } public static void main(String[] args) { launch(args); } } BarChart.css contains are as below:- .default-color0.chart-legend-item-symbol{ -fx-background-color: #0000FF; } .default-color1.chart-legend-item-symbol{ -fx-background-color: #FF0000; } Please help me to remove legends or shrink the components where legends are been added. Thanks alot A: Since you are already dealing with Legend, you can work with its items, removing those you don't need, so the legend shows only two items. Using streams, you can mark the first two items as "Valid"/"Invalid" and the rest as "Remove", for instance, and finally you just remove these last items. private void updateStyleSheet() { Legend legend = (Legend)lineChart.lookup(".chart-legend"); AtomicInteger count = new AtomicInteger(); legend.getItems().forEach(item->{ if(count.get()==0){ item.setText("Valid"); } else if(count.get()==1){ item.setText("Invalid"); } else { item.setText("Remove"); } count.getAndIncrement(); }); legend.getItems().removeIf(item->item.getText().equals("Remove")); ... }
[ "math.stackexchange", "0000857187.txt" ]
Q: Arranging the word 'MISSISSIPPI' "How many ways are there to arrange the letters in the word 'MISSISSIPPI' in such a way that there are no three consonants in a row?" I am thinking like this. The following are 'slots' for the letters of our word: _ _ _ _ _ _ _ _ _ _ _. There are 21 consonants in total (English). The first slot as 21 possibilities, the second also has 21, but the third has only 5 possibilities. So how many ways can I place vowels within this word... I don't know. I can try to enumerate all of the place the I's can go, but there has to be a better way than doing that. A: MISSISSIPPI has seven consonants and four vowels (which all happen to be I). Write X for any consonant, and first think of how many possible patterns of the type IXXIXIXXIXX, with seven Xes and four Is exist, with no three Xs in a row. Then think about how to assign the letters MSSSSPP to the Xs. Note that the two subproblems are quite similar to each other. The final step is a simple multiply. Edit: A bit more on the first subproblem. You'll have to do a bit of hand counting here, I think. There are only four Is, so consecutive Xs can form at most five groups. But there must be at least four groups of Xs, since no group can have more than two Xs. So the configuration of Xs is either XX XX X X X or permutation thereof, of XX XX XX X or permutations thereof. It should be easy to count the permutations in each case. In the first, case, the Is must go one between each group, but in the second, three Is are needed to fill the gaps, and the fourth I can be placed next to one of the other three, or at the beginning or end – five possibilities there. A: One way you could do this is first arrange the four I's in a row, creating 5 gaps in which the consonants can be placed. If we let $x_i$ be the number of consonants in gap $i$, then $x_1+\cdots +x_5=7$ where $0\le x_i\le2$ for each $i$. If you calculate the number of solutions to this equation, and then multiply by the number of ways to arrange the consonants SSSSPPM in order, I believe you will get the answer you obtained. A: The number of solutions to $x_1+x_2+x_3+x_4+x_5 = 7$ with $0 \leq x_i \leq 2$ is same as the coefficient of $x^7$ in $(1+x+x^2)^5$. This can be expanded using binomial theorem as $(1+x(1+x))^5$. Since $x^7$ will occur only in the terms $\binom{5}{4}x^4(1+x)^4$ and $\binom{5}{5}x^5(1+x)^5$, the required coefficient is $\binom{5}{4}\binom{4}{3} + \binom{5}{5}\binom{5}{2} = 30$. Since there are $\binom{7}{4,2,1} = 105$ ways to place $SSSSPPM$ in these 7 places, the required answer is 3150.
[ "wordpress.stackexchange", "0000183763.txt" ]
Q: How to add an attribute to a user? I have looked for an answer, and couldn't find a clear and relevant answer yet. I want to add more attribute to the users not to display, but only store information about them. The information will be used for a background function. I know that usermeta is used to add more attributes, and I know how to access the already existing information, but I don't know how to add/create new attributes. This piece of information can be a null string by default for every user and modified if the user enters information. I'd appreciate any kind of help since I'm new at Wordpress. Thanks! A: The easiest trick is to use the user_contactmethods - the fields don't actually have to be contacts, but WordPress will do all the leg work for you (displaying the fields & saving the data): function wpse_183763_user_contactmethods( $methods, $user ) { $methods['my_field_1'] = 'My Label For Field 1'; $methods['my_field_2'] = 'My Label For Field 2'; return $methods; } add_filter( 'user_contactmethods', 'wpse_183763_user_contactmethods', 10, 2 ); If you add this code to a plugin or your functions.php, you'll see the new fields when editing your profile. To get the values, just use the meta API: // With a user ID echo get_user_meta( $user_id, 'my_field_1', true ); // Or with a WP_User object echo $user->my_field_1;
[ "boardgames.stackexchange", "0000014862.txt" ]
Q: If a creature planeswalker is dealt damage by a creature with infect, what happens? If a planeswalker than has been turned into a creature (not a planeswalker that turns itself into a creature with "prevent all damage" like Gideon) takes Infect damage, what happens? I know that Infect damage is applied as -1/-1 counters, and I know that the planeswalker will have both damaged marked on it, as well as have it's loyalty reduced, but what I'm unsure of is if the -1/-1 counters further reduce the loyalty or if they only impact the power / toughness. As a follow-on, do the -1/-1 counters stay on the planeswalker when it is no longer a creature? And if so, could this be used to prevent a Gideon from using it's "become a creature" ability (or at least kill it if it does)? A: Loyalty counters are different and separate from the -1/-1 counters produced by infect. -1/-1 counters affect power and toughness only. If an infected Planeswalker reverts to a non-creature, the -1/-1 counters will have no effect. They will remain until otherwise removed, or until the permanent changes zones. Non-creature Planeswalker vs Infect Damage Lose loyalty equal to the infect damage per rule 119.3c. Do not gain infect counters. Rule 119.3d only applies to creatures. Creature Planeswalker vs Infect Damage Lose loyalty equal to the infect damage per rule 119.3c. Gain -1/-1 counters equal to the infect damage per rule 119.3d. Example Gideon, Champion of Justice has five loyalty counters and five -1/-1 counters. If he resolves his zero ability to become a creature, Gideon will die the next time state-based actions are checked. Planeswalkers are not subject to the same state-based action where a player with ten poison counters automatically loses the game. Planeswalkers cannot gain poison counters. A: If it's both a creature and a planeswalker, it would gain -1/-1 counters and lose loyalty counters. 119.3c Damage dealt to a planeswalker causes that many loyalty counters to be removed from that planeswalker. 119.3d Damage dealt to a creature by a source with wither and/or infect causes that many -1/-1 counters to be put on that creature. The removal of loyalty counters is not conditional. As a follow-on, do the -1/-1 counters stay on the planeswalker when it is no longer a creature? Yes. Counters will cease to exist if the object changes zone[CR 121.2]. Otherwise, they stay until something explicitly removes them. And if so, could this be used to prevent a Gideon from using it's "become a creature" ability (or at least kill it if it does)? Yes. If he had -1/-1 counters equaling his toughness, he'd die virtually immediately after transforming into a creature. Note that Gideon, Champion of Justice's indestructibility would not help, since the State-Based action in question kills rather than destroys[CR 704.5f]. Note that Gideon Jura's ability to prevent damage prevents the gain of -1/-1 counters from infect damage. You'd have to turn him into a creature another way or give him the -1/-1 counters some other way.
[ "stackoverflow", "0045269111.txt" ]
Q: Property in Cell Factory Hi I have a little problem in this Cell Factory : private Callback<TableColumn<Member, String>, TableCell<Member, String>> setPhotoCellFactory() { Callback<TableColumn<Member, String>, TableCell<Member, String>> callback = new Callback<TableColumn<Member, String>, TableCell<Member, String>>() { @Override public TableCell<Member, String> call(TableColumn<Member, String> param) { TableCell<Member, String> cell = new TableCell<Member, String>() { @Override protected void updateItem(String item, boolean empty) { System.out.println(item); super.updateItem(item, empty); ImageView imageview = new ImageView(); imageview.setFitHeight(TABLE_IMAGE_MEMBER_HEIGHT); imageview.setFitWidth(TABLE_IMAGE_MEMBER_WIDTH); if(item != null) { imageview.setImage(new Image(item)); setGraphic(imageview); } else { if(!empty) { imageview.setImage(new Image(ImageFiles.GENERIC_MALE.toString())); setGraphic(imageview); } else { setGraphic(null); } } } }; return cell; } }; return callback; } In Member object when Photo is null getter return Image corresponding a his gender. In this callback it seems that getter is not used. How can I acces member property in this case ?? @EDIT In Member class : public String getPhoto() { if (photo.getValue() != null && !photo.getValue().equals("")) { return photo.get(); } else if (getGender().equals(Gender.F)) { return ImageFiles.GENERIC_FEMALE.toString(); } else { return ImageFiles.GENERIC_MALE.toString(); } } adding CellValueFactory : this.simPhotoColumn.setCellValueFactory(data -> data.getValue().photoProperty()); A: OK I was found the solution. My error that I was searching how set image in CellFactory. The response is to set custom CellValueFactory. I was replaced this : this.simPhotoColumn.setCellValueFactory(data -> data.getValue().photoProperty()); by : this.memberPhoto.setCellValueFactory(getPhotoValueFactory()); private Callback<TableColumn.CellDataFeatures<Member, String>, ObservableValue<String>> getPhotoValueFactory() { Callback<TableColumn.CellDataFeatures<Member, String>, ObservableValue<String>> callback = param -> new ReadOnlyObjectWrapper<>(param.getValue().getPhoto()); return callback; }
[ "stackoverflow", "0052073960.txt" ]
Q: str() method on numpy array and back Is there any built-in method to get back numpy array after applying str() method, for example, import numpy as np a = np.array([[1.1, 2.2, 3.3], [4.4, 5.5, 6.6]]) a_str = str(a) #to get back a? a = some_method(a_str). Following two methods don't work: from ast import literal_eval a = literal_eval(a_str) # Error import numpy as np a = np.fromstring(a_str) # Error Update 1: Unfortunatelly i have very big data already converted with str() method so I connot reconvert it with some other method. A: The main issues seem to be separators and newlines characters. You can use np.array2string and str.splitlines to resolve them: import numpy as np from ast import literal_eval a = np.array([[1.1, 2.2, 3.3], [4.4, 5.5, 6.6]]) a_str = ''.join(np.array2string(a, separator=',').splitlines()) # '[[ 1.1, 2.2, 3.3], [ 4.4, 5.5, 6.6]]' b = np.array(literal_eval(a_str)) # array([[ 1.1, 2.2, 3.3], # [ 4.4, 5.5, 6.6]]) Note that without any arguments np.array2string behaves like str. If your string is given and unavoidable, you can use this hacky method: a_str = str(a) res = np.array(literal_eval(''.join(a_str.replace('\n', ' ').replace(' ', ',')))) array([[ 1.1, 2.2, 3.3], [ 4.4, 5.5, 6.6]]) As per @hpaulj's comment, one benefit of np.array2string is ability to specify threshold. For example, consider a string representation of x = np.arange(10000). str(x) will return ellipsis, e.g. '[ 0 1 2 ..., 9997 9998 9999]' np.array2string(x, threshold=11e3) will return the complete string
[ "math.stackexchange", "0000423184.txt" ]
Q: Prove the Equality of Two Integrals This is what I've done so far: $V_1 = \pi\int_0^af(x)^2dx = -\pi\int_0^by^2 (1/f'(x))\ dy = -\pi\int_0^by^2 (1/f'(g(y)))\ dy = -\pi\int_0^by^2 g'(y)\ dy$ Integrating by parts: $u=y^2,\ du=2y\ dy, \ v=g(y), \ dv = g'(y)\ dy$ $y^2g(y)|_0^b -2\pi\int_0^by\ g(y)\ dy = -ab^2 -2\pi\int_0^by\ g(y)\ dy = -ab^2-V_2$ so it looks like $V_1 = -ab^2-V_2$ which looks wrong. I've also tried other ways of integrating, substituting and I always end up with a proof that $V_1 \ne V_2$. Can someone point me to the right direction? A: You've made two mistakes. $y^2g(y)|_0^b=b^2\cdot0-0^2\cdot a=0$, not $b^2a$. So that leaves you with $V_1=-V_2$ after your integration by parts. But it also seem you're neglecting the minus sign before the integrating by parts. Actually, you are neglecting the $\pi$ too in part as the expression should be $-\pi\, y^2g(y)|_0^b+2\pi\int_0^by\,g(y)\,dy$. Make these two corrections and you have it.
[ "movies.stackexchange", "0000089228.txt" ]
Q: How did Hela know that the Gauntlet was a fake? So in Thor: Ragnarok, we see Hela mentioning that the Gauntlet in Odin's treasure room is a fake. How did she know that it was a fake, considering the fact that she was locked away by Odin for about as long as atleast the age of Thor (1500 years)? Also, Thor would have met Eitri in the last 1500 years, and he was the one who made the Gauntlet. So how did that happen? A: It's just a retcon to cleanup the confusion for having two gauntlets, no need to overthink about it. From CinemaBlend: That came about because in Thor 1, the reason that it's in this movie is because someone who went through that movie, frame by frame, looking for Easter eggs was like 'Oh! The Infinity Gauntlet!' And then from that point on, they were like, 'That damn Infinity Gauntlet, what are we going to do with that thing?' It's like, there, but it also [exists] somewhere else in the universe. How do we deal with that? And then we realized like, Odin... Hela goes through and she goes, 'Fake. All of that stuff that's in here is fake.' Basically the thing we were trying to go for was that Odin somewhere along the line realized that everyone knew that the Infinity Gauntlet was on Asgard and in the safe keeping of Odin, then no one would come looking for it. So he made a fake one, and let everyone believe... Basically, a fake launch code. We brought that over -- like here's an opportunity to take something off the plate of Markus and McFeely, who are doing Avengers 3 and 4, and have plenty else to worry about with I don't know -- what -- 60-plus characters in one movie? In-Universe, Hela knows a lot about Odin's secrets which Thor and others didn't have any idea about. So we have to assume that she knows this secret too.
[ "math.stackexchange", "0003356373.txt" ]
Q: Show that $\left( \bigoplus _i V_i \right)^* = \prod_i V_i ^*$ canonically I am trying to prove that given a sequence of finite dimensional vector spaces $V_i$ (though I think we can be more general, but whatever), I have a canonical isomorphism that gives me: $$\left( \bigoplus _i V_i \right)^* = \prod_i V_i ^*$$ where $\bigoplus _i V_i$ is the set of sequences whose $i$-th term belongs to $V_i$ that are definitely zero, and $\prod_i V_i$ the set of all sequences whose $j$-th term belongs to $V_j$. It is trivial with a finite number of terms, but I don't get how to extend it to infinite products, and why you need sequences that are definitely zero. A: If $f \in \left ( \oplus_{i \in I} V_i \right )^*$, then for each $i$, $f \upharpoonright V_i \in V_i^*$. Then the product $(f \upharpoonright V_i)_{i \in I}$ lives in $\Pi_{i \in I} V_i^*$. Notice there is nothing saying that all but finitely many of the $f \upharpoonright V_i$ should be $0$, so $(f \upharpoonright V_i)_{i \in I}$ does not live in $\oplus_{i \in I} V_i^*$, in general! As for the other direction, given $(f_i)_{i \in I} \in \Pi_{i \in I}V_i^*$, define (for some $J \subseteq I$ finite) $f(\sum a_j v_j) = \sum_{j \in J} a_j f_j(v_j)$ . Since $(f_i)_{i \in I}$ tells us what to do to each $V_i$, we know (by linearity) what we have to do to a sum of elements of the $V_i$. I leave it to you to check that these maps are mutually inverse. Edit: More formally, we see $\left ( \oplus_{i \in I} V_i \right )^*\cong \Pi_{i \in I} V_i^*$ since we have maps $\varphi : \left ( \oplus_{i \in I} V_i \right )^* \to \Pi_{i \in I} V_i^*$ and $\psi : \Pi_{i \in I} V_i^* \to \left ( \oplus_{i \in I} V_i \right )^*$ given by $\varphi(f) = (f \upharpoonright V_i)_{i \in I}$ $\psi((f_i)_{i \in I}) = F$ To define $F : \oplus_{i \in I} V_i \to K$, it suffices to define it on each summand, and then extend linearly. We put $F(v_j) = f_j(v_j)$ for $v_j \in V_j$. Again, I leave it to you to verify these maps are mutually inverse (and indeed that they are linear maps). But why does this only work with $\oplus V_i$? For $f \in (\Pi_{i \in I} V_i)^*$, we can also consider $f \upharpoonright V_i$, and we can also form the product $(f \upharpoonright V_i)_{i \in I} \in \Pi_{i \in I} V_i^*$. Unfortunately, this new operation is not injective. For simplicity, say each $V_i$ is finite dimensional, so that $|V_i| = |V_i^*|$. Then when $K$ is the underlying field of the vector space: $|(\Pi_{i \in I} V_i)^*| = |K|^{|\Pi_{i \in I} V_i|} > |\Pi_{i \in I} V_i| = |\Pi_{i \in I} V_i^*|$ Restricting ourselves to only finite sums solves this cardinality issue, and allows the function defined above to be injective (indeed bijective). Hope this helps! ^_^
[ "stackoverflow", "0049170053.txt" ]
Q: Using awk to filter a CSV file with quotes in it I have a text file with comma separated values. A sample line can be something like "Joga","Bonito",7,"Machine1","Admin" The " seen are part of the text and are needed when this csv gets converted back to a java object. I want to filter out some lines from this file based on some field in the csv. The following statement doesnt work. awk -F "," '($2== "Bonito") {print}' filename.csv I am guessing that this has something to do with the " appearing in the text. I saw an example like: awk -F "\"*,\"*" I am not sure how this works. It looks like a regex, but the use of the last * flummoxed me. Is there a better option than the last awk statement I wrote? How does it work? A: First a bit more through test file: $ cat file "Joga","Bonito",7,"Machine1","Admin" "Joga",Bonito,7,"Machine1","Admin" Using regex ^\"? ie. starts with or without a double quote: $ awk -F, '$2~/^\"?Bonito\"?$/' file "Joga","Bonito",7,"Machine1","Admin" "Joga",Bonito,7,"Machine1","Admin"
[ "stackoverflow", "0009743958.txt" ]
Q: How do you assign a function to a value in Scala? In Scala, how do you assign a function of a particular signature to an appropriately typed value? def foo = println("foo") def bar = println("bar") val fnRef : ()=>Unit = //the function named foo or the function named bar A: While I feel like an unforgivably-terrible person for submitting this as an official answer, I do so at the OP's request. This problem can be solved like so: def foo = println("foo") val fnRef = () => foo or, as some other brave soul said before deleting his answer: def foo = println("foo") val fnRef = foo _ The second is perhaps slightly preferable, since mine (the former) is mildly hacky and actually creates a whole new function that simply calls the existing function when applied, whereas the latter is basically a partial/delayed application of the existing function because, while semantically identical, the latter is more-idiomatic Scala (as Rex Kerr points out).
[ "webapps.stackexchange", "0000040836.txt" ]
Q: Submitting bugs and enhancement requests to Google Documents webapp Question Does Google provide a public bug tracking system, issue tracking system, or enhancement tracking system (similar to, say, Bugzilla) into which their users could submit reports to actual Google developers and not just other users (note: see below the Dead-End Reference Material that specifically excludes Googles support forums)? Dead-End Reference Material: The following are links to my web sleuthing that turned out to not be answers to this question: Note that I already know about the various Google-app-specific Google support forums (e.g. https://webapps.stackexchange.com/a/2583/14529), and that is not the answer I am looking for. Google search: how to submit bug requests to google documents Is there any where to submit feature requests for Gmail (or other Google apps)? https://webapps.stackexchange.com/a/35171/14529 Report Gmail Bug A: No, there's no public bug tracking system for those Google products. Sometimes Google employees participate in discussions in forums, like here: http://productforums.google.com/forum/#!topic/docs/2E9tLNWdhAw Note that Google Employees have the small Google icon next to their name. If you are a Google Apps for Business customer, you might be eligible for contacting Google support via phone or email: http://contact.googleapps.com/?&rd=1
[ "stackoverflow", "0047795832.txt" ]
Q: How to update data at text box into db? I display the list(Item, Category, and Job) from database in table and user can click the list on the table and the data will display in the text box. The user can add, update and delete the list in the text box. After that click the button that wants to function. In this php I decided do 2 functions which add dan update the list(Item, Category, and Job). Finally i successful to update. This is Updated code: First I display 3 textboxes on the table. User can add the new list(Item, Category, Job) on the textbox. after that, user also can click the list on the another that I list all the data from my database on the 3 textbox as I show at the top position and change the list(Category and Job) on the textbox that wants to update. <form id="form1" name="Checklist" method="post" action="Checklist2.php"> <table width="305" height="116" align="center" border="0"> <tr> <td width="37%">Item : <br></td> <td width="63%"><input type="text" name="Item" id="Item"></td> </tr> <tr> <td>Category : </td> <td> <input type="text" name="Category" id="Category"> </td> </tr> <tr> <td>Job : </td> <td> <input type="text" name="Job" id="Job"> </td> </tr> </table> <div align="center"> <input type="image" value="submit" src="AddD.png" alt="submit Button" onmouseover="this.src='AddO.png'" onmouseout="this.src='AddD.png'" name="Add_btn" id="Add_btn"> <input type="image" value="submit" src="UpdateD.png" alt="submit Button" onmouseover="this.src='UpdateO.png'" onmouseout="this.src='UpdateD.png'" name="Update_btn" id="Update_btn"> &nbsp; <a href="DeleteChecklist2.php" onMouseOut="MM_swapImgRestore()" onMouseOver="MM_swapImage('Image3','','Delete1O.png',1)"> <img src="Delete1D.png" name="Image3" width="145px" height="50px" border="0" name="Delete_btn" id="Delete_btn"> </a> </div> </form> //This is the PHP code of add and delete button <?php try { $con = new PDO("mysql:host=localhost;dbname=gcmes", "root", ""); if(isset($_POST['Add_btn'])) { $Item = $_POST["Item"]; $Category = $_POST["Category"]; $Job = $_POST["Job"]; if(empty($Item)||empty($Category)||empty($Job)) { echo "<script type='text/javascript'>alert('Please fill in the required fields to add!')</script>"; } else { $insert=$con->prepare("INSERT INTO details(Item,Category,Job) VALUES(:Item,:Category,:Job)"); $insert->bindParam(':Item',$Item); $insert->bindParam(':Category',$Category); $insert->bindParam(':Job',$Job); $insert->execute(); echo "<script type='text/javascript'>alert('Successful Added ! '); window.location.href = 'Checklist2.php';</script>"; }//else }//if addbutton if(isset($_GET['Update_btn'])) { $Item = $_GET['Item']; $Category = $_GET['Category']; $Job = $_GET['Job']; if(empty($Category)||empty($Job)) { echo "<script type='text/javascript'>alert('Please fill in the required fields to update!')</script>"; } else { $st=$con->prepare("UPDATE details SET Category = :Category, Job = :Job WHERE Item = :Item"); $st->bindParam(":Category",$Category); $st->bindParam(":Job",$Job); $st->bindParam(":Item",$Item); $st->execute(); }//else }//if updatebutton }//try catch(PDOException $e) { echo "error".$e->getMessage(); } ?> //This is the table list all the data from database <table id="table" border="0" align="center"> <tr> <th>No</th> <th>Category</th> <th>Job</th> </tr> <?php try { $con = new PDO("mysql:host=localhost;dbname=gcmes", "root", ""); $sql = $con->query("SELECT * FROM details"); foreach($sql as $row) { $Item = $row["Item"]; $Category = $row["Category"]; $Job = $row["Job"]; echo' <tr> <td>' . $Item . '</td> <td>' . $Category . '</td> <td>' . $Job . '</td> </tr> '; } echo"</table>"; } catch(PDOException $e) { echo "error".$e->getMessage(); } ?> This is a script when user click the data at table(above code) will displayed in textbox : <script> var table = document.getElementById('table'); for(var i = 1; i < table.rows.length; i++) { table.rows[i].onclick = function() { //rIndex = this.rowIndex; document.getElementById("Item").value = this.cells[0].innerHTML; document.getElementById("Category").value = this.cells[1].innerHTML; document.getElementById("Job").value = this.cells[2].innerHTML; }; } </script> Thank you all! A: A few things to cover here. Issue 1: Your INSERT setup is incorrect. You have: $insert=$con->prepare("INSERT INTO details(Item,Category,Job) VALUES(:Item,:Category,:Job)"); $insert->bindParam('Item',$Item); $insert->bindParam('Category',$Category); $insert->bindParam('Job',$Job); $insert->execute(); It should be like this (note the : additions in bindParam): $insert=$con->prepare("INSERT INTO details(Item,Category,Job) VALUES(:Item,:Category,:Job)"); $insert->bindParam(':Item',$Item); $insert->bindParam(':Category',$Category); $insert->bindParam(':Job',$Job); $insert->execute(); Issue 2: The second is your UPDATE is both incorrect, and not using prepare properly. You have this: $st=$con->prepare("UPDATE details SET Category='$Category', Job='$Job'"); $st->bindParam(1,$Category); $st->bindParam(2,$Job); $st->execute(); Where you are injecting the variables into the query itself, negating the use of prepare entirely. Then you try to bindParam to non-existent placeholders. Lastly, you are updating the ENTIRE table with the same information because you forgot a WHERE clause. So try this instead: $st=$con->prepare("UPDATE details SET Category = :Category, Job = :Job WHERE Item = :Item"); $st->bindParam(":Category",$Category); $st->bindParam(":Job",$Job); $st->bindParam(":Item",$Item); $st->execute(); Issue 3: And lastly, as I mentioned in comments... you can pass the Item as a hidden form element so the user cannot easily change it: <tr> <td width="37%">Item : <br></td> <td width="63%"> <input type="hidden" name="Item" id="Item"> <span id="ItemDisplay"><!-- Item will be visible here --></span> </td> </tr> // js addition: document.getElementById("Item").value = this.cells[0].innerHTML; document.getElementById("ItemDisplay").innerHTML = this.cells[0].innerHTML; Issue 4: Before you have your html of the update button, you have a close form tag, which is breaking your html form submission parameters: </form><!-- THIS shouldnt be here --> <?PHP // big block of php ?> <div align="center"> <input type="image" value="submit" src="AddD.png" alt="submit Button" onmouseover="this.src='AddO.png'" onmouseout="this.src='AddD.png'" name="Add_btn" id="Add_btn"> <input type="image" value="submit" src="UpdateD.png" alt="submit Button" onmouseover="this.src='UpdateO.png'" onmouseout="this.src='UpdateD.png'" name="Update_btn" id="Update_btn"> </div> </form><!-- this one is the CORRECT one to keep --> Remove that early </form> tag.
[ "stackoverflow", "0045700152.txt" ]
Q: How to 'Unstack' list in R when some of the entries in the list are not equally repeating like others in list? This question is an extension of an earlier question (Filter values from list in R). I have a long list similar to the one presented below. One of the names "issues.fields.customfield_10400" in the list is repeating lesser number of times compared to all others. Checking of presence/absence of a value for this "name" is one of the task I am trying to handle. NULL value is perfectly fine. DF = structure(list(name = structure(c(7L, 3L, 1L, 6L, 4L, 2L, 5L, 7L, 3L, 1L, 6L, 4L, 2L, 5L, 7L, 3L, 1L, 6L, 4L, 5L, 7L, 3L, 1L, 6L, 4L, 5L), .Label = c("issues.fields.created", "issues.fields.customfield_10400", "issues.fields.issuetype.name", "issues.fields.status.name", "issues.fields.summary", "issues.fields.updated", "issues.key" ), class = "factor"), value = structure(c(18L, 13L, 4L, 4L, 11L, 7L, 10L, 17L, 14L, 3L, 6L, 11L, 7L, 9L, 16L, 13L, 2L, 2L, 11L, 8L, 15L, 14L, 1L, 5L, 11L, 12L), .Label = c("2017-05-05T13:09:12.381-0700", "2017-06-07T07:03:11.155-0700", "2017-07-26T11:15:03.074-0700", "2017-08-01T09:00:44.956-0700", "2017-08-14T13:47:21.612-0700", "2017-08-14T13:47:30.419-0700", "AA1234567", "Acquire replacement files from XYZ", "Add measurement ", "Ingest changed file location ", "Open", "Re-classify \"Generic Assays\" (n=24)", "Sub-task", "Task", "TEST-1030", "TEST-1192", "TEST-1357", "TEST-1358"), class = "factor")), .Names = c("name", "value"), row.names = c(NA, 26L), class = "data.frame") name value 1 issues.key TEST-1358 2 issues.fields.issuetype.name Sub-task 3 issues.fields.created 2017-08-01T09:00:44.956-0700 4 issues.fields.updated 2017-08-01T09:00:44.956-0700 5 issues.fields.status.name Open 6 issues.fields.customfield_10400 AA1234567 7 issues.fields.summary Ingest changed file location 8 issues.key TEST-1357 9 issues.fields.issuetype.name Task 10 issues.fields.created 2017-07-26T11:15:03.074-0700 11 issues.fields.updated 2017-08-14T13:47:30.419-0700 12 issues.fields.status.name Open 13 issues.fields.customfield_10400 AA1234567 14 issues.fields.summary Add measurement 15 issues.key TEST-1192 16 issues.fields.issuetype.name Sub-task 17 issues.fields.created 2017-06-07T07:03:11.155-0700 18 issues.fields.updated 2017-06-07T07:03:11.155-0700 19 issues.fields.status.name Open 20 issues.fields.summary Acquire replacement files from XYZ 21 issues.key TEST-1030 22 issues.fields.issuetype.name Task 23 issues.fields.created 2017-05-05T13:09:12.381-0700 24 issues.fields.updated 2017-08-14T13:47:21.612-0700 25 issues.fields.status.name Open 26 issues.fields.summary Re-classify "Generic Assays" (n=24) When I unstack the list I get the following error message. Error in (function (..., row.names = NULL, check.rows = FALSE, check.names = TRUE, : arguments imply differing number of rows: Can someone suggest on how to handle this kind of situation? I need to create dataframe as given below. res = structure(list(issues.fields.created = structure(c(4L, 3L, 2L, 1L), .Label = c("2017-05-05T13:09:12.381-0700", "2017-06-07T07:03:11.155-0700", "2017-07-26T11:15:03.074-0700", "2017-08-01T09:00:44.956-0700" ), class = "factor"), issues.fields.issuetype.name = structure(c(1L, 2L, 1L, 2L), .Label = c("Sub-task", "Task"), class = "factor"), issues.fields.status.name = structure(c(1L, 1L, 1L, 1L), .Label = "Open", class = "factor"), issues.fields.customfield_10400 = structure(c(2L, 2L, 1L, 1L), .Label = c("", "AA1234567"), class = "factor"), issues.fields.summary = structure(c(3L, 2L, 1L, 4L), .Label = c("Acquire replacement files from XYZ", "Add measurement ", "Ingest changed file location", "Re-classify \"Generic Assays\" (n=24)" ), class = "factor"), issues.fields.updated = structure(c(2L, 4L, 1L, 3L), .Label = c("2017-06-07T07:03:11.155-0700", "2017-08-01T09:00:44.956-0700", "2017-08-14T13:47:21.612-0700", "2017-08-14T13:47:30.419-0700" ), class = "factor"), issues.key = structure(c(4L, 3L, 2L, 1L), .Label = c("TEST-1030", "TEST-1192", "TEST-1357", "TEST-1358" ), class = "factor")), .Names = c("issues.fields.created", "issues.fields.issuetype.name", "issues.fields.status.name", "issues.fields.customfield_10400", "issues.fields.summary", "issues.fields.updated", "issues.key"), row.names = c(NA, 4L), class = "data.frame") issues.fields.created issues.fields.issuetype.name issues.fields.status.name 1 2017-08-01T09:00:44.956-0700 Sub-task Open 2 2017-07-26T11:15:03.074-0700 Task Open 3 2017-06-07T07:03:11.155-0700 Sub-task Open 4 2017-05-05T13:09:12.381-0700 Task Open issues.fields.customfield_10400 issues.fields.summary 1 AA1234567 Ingest changed file location 2 AA1234567 Add measurement 3 Acquire replacement files from XYZ 4 Re-classify "Generic Assays" (n=24) issues.fields.updated issues.key 1 2017-08-01T09:00:44.956-0700 TEST-1358 2 2017-08-14T13:47:30.419-0700 TEST-1357 3 2017-06-07T07:03:11.155-0700 TEST-1192 4 2017-08-14T13:47:21.612-0700 TEST-1030 A: Use the unstack function mentioned in the title: us = unstack(DF, value ~ name) data.frame(lapply(us, `length<-`, max(lengths(us)))) This gives issues.fields.created issues.fields.customfield_10400 issues.fields.issuetype.name issues.fields.status.name 1 2017-08-01T09:00:44.956-0700 AA1234567 Sub-task Open 2 2017-07-26T11:15:03.074-0700 AA1234567 Task Open 3 2017-06-07T07:03:11.155-0700 <NA> Sub-task Open 4 2017-05-05T13:09:12.381-0700 <NA> Task Open issues.fields.summary issues.fields.updated issues.key 1 Ingest changed file location 2017-08-01T09:00:44.956-0700 TEST-1358 2 Add measurement 2017-08-14T13:47:30.419-0700 TEST-1357 3 Acquire replacement files from XYZ 2017-06-07T07:03:11.155-0700 TEST-1192 4 Re-classify "Generic Assays" (n=24) 2017-08-14T13:47:21.612-0700 TEST-1030 The missing values are filled with NA -- the standard code in R -- instead of blanks.
[ "ru.stackoverflow", "0001132105.txt" ]
Q: Деплой Python Телеграмм-бота на AWS Нужно задеплоить Телеграмм-бота на AWS (желательно на Американский или Немецкий сервер). Бота написал с помощью PyTelegramBotApi на Python. Опыта в деплое нет, методом тыка разобраться не получилось. Искал информацию в интернете, на ютубе - только устаревшее, 3-х летней давности видео. У бота есть БД (SQLite3), дополнительных файлов в его директории на 50 мб. Просьба - помочь мне с деплоем: либо видео скинуть, либо связаться лично, либо расписать, как это делать. A: Вы можете разместить своего бота на heroku.com В youtube есть подробные инструкции, плюс есть подробные инструкции на сайте heroku.com. План действий: Посмотреть примеры на ютуб Зарегистриоваться на heroku.com. Следуя инструкциям на сайте, залить бота на heroku.com.
[ "stackoverflow", "0035375860.txt" ]
Q: How to make a space between a line in Java? System.out.print("I have a question, can you assist me?"); System.out.println(); System.out.println("How can I make a gap between these two statements?"); I tried to use println(), thinking that it would create a blank line, but it didn't. A: Try: public class Main { public static void main(String args[]) { System.out.println("I have a question, can you assist me?\n"); System.out.println("How can I make a gap between these two statements?"); } } P.S. \n is newline separator and works ok at least on Windows machine. To achieve truly crossplatform separator, use one of methods below: System.out.print("Hello" + System.lineSeparator()); // (for Java 1.7 and 1.8) System.out.print("Hello" + System.getProperty("line.separator")); // (Java 1.6 and below)
[ "stackoverflow", "0025262941.txt" ]
Q: Rendering videos in an SDL2 application I've been looking for a way to play videos at some point in my application, I was thinking of ways to incorporate them into a texture or just plain render them but I'm literally stumped here, any suggestion? I'm not in a position to choose, but I'd really appreciate sample codes. A: You could do it with OpenGL for example: play AVI files I'd include the source of the link but since it's a full fledged tutorial that would be too long. Different approach Another option would be to just have the media player start. Most players have start parameters that you can use. for example: #include <windows.h> int main() { HINSTANCE hRet = ShellExecuteA( HWND_DESKTOP, // Parent "open", // Operation "C:\\yourMovieDirectory\\yourMovie.avi", // Path to file NULL, // Parameters NULL, // Default dir. SW_SHOW); // Opening option if( (LONG)hRet <= 32 ) { MessageBox( HWND_DESKTOP , "Error detected while attempting to start the movie!") , "Error" , MB_OK ); } return 0; } You need the shell32.lib for the ShellExecute() function HINSTANCE is a handle to an instance. C++ Windows Types
[ "stackoverflow", "0003585258.txt" ]
Q: Does Asp.Net MVC automatically loads the HttpGet Action result on session timeout I have an asp.net mvc register view. This is the first page. If someone sits on it long enough for the session to expire, then start entering data and submit the form, it is automatically going into my HttpGet Action Result for register. Is this default behavior? Can it be changed so the user does not get a session timeout on the first page of the website? A: If someone sits on it long enough for the session to expire, then start entering data and submit the form, it is automatically going into my HttpGet Action Result for register. HTTP POST does not have anything to do with sessions (which are technology-stack specific). A form can be submitted in 5 minutes or in 5 years it's the same.
[ "bitcoin.stackexchange", "0000029569.txt" ]
Q: debug window of wallets For all noobs and cryptocurrencies, is there anywhere a tutorial on how to use the wallet? I've noticed several wallets that are just the same thing with a different name, but so far the only thing i get to know is that they give an address. They all have an overview with the balance on the account at 0 coins, that's fine. Then a tag of sending and asking coins, I can also get to understand what that does, even when it's empty and the only way to find other addresses is person to person. Now the crazy stuff that makes me wonder do i have to be a programmer to use these things? What is that thing (Out of Sync) next to the wallet in red letters? How do I fix that? How can I "Sync" what exactly? Since when I install primecoin wallet for example, it starts downloading a bunch of crazy stuffs updating a bunch of weeks and after is finally done, it just tells me that the wallet is out of sync, and there's nothing i can do about it and I googled. And people just mention but never explain a scary debug window with a console that i have no idea what it does or what should I do with that, and they only post code stuffs that if I copy paste won't work, at least not in all wallets and in those that accepted that code, it does absolutely nothing that I can know of.... Is there a newbie guide on how to get to use a wallet? primecoin, dogecoin, rainbowcoin, aimcoin... they all look just the same, and people talk about mining some few coins just by keeping them open. Can someone help me? Please explain in baby steps I know nothing about scripts or pools or codes, or encryption, and is really frustrating me because I want to learn. A: I've notices several wallets that are just the same thing with a different name, but so far the only thing i get to know is that they give an address They do much more than just giving you an address. They also download and store the Blockchain which contains all transactions ever made. Those data are needed to check, if one of your addresses received a payment. Those data are also needed to send data to a different address. they all have an overview with the balance on the account at 0 coins, that's fine then a tag of sending and asking coins, I can also get to understand what that does even when is empty and the only thing i guess i have to find other addresses is person to person, now the crazy stuff that makes me wonder do i have to be a programmer to use these things? You're right, you will get addresses from other persons or from the internet. You do not need to be a programmer. With a wallet it's like sending an e-mail, but instead of sending text, you send bitcoin. For sending bitcoin, you need to receive some first. That can be done by buying them in online trades or at an ATMs. what is that thing (Out of Sync) next to the wallet in red letters? how do I fix that? How can I "Sync" what exactly? since when i install primecoin wallet for example, it starts downloading a bunch of crazy stuffs updating a bunch of weeks and after is finally done, it just tells me that the wallet is out of sync, and there's nothing i can do about it and i google As I said before, the crazy stuff which is downloaded is the blockchain. For Bitcoin it can take really long, because currently its size is about 20 GB. There are different types of wallet. The full node, for example Bitcoin-Core, which I guess is the one you downloaded, is mostly for the professional user. It contains the complete blockchain, and needs very long to sync. An other type is the SPV (Simplified Payment Verification) for example Electrum. This one dont need to download the complete blockchain, it will only download the headers, which save a lot of traffic and storage. Those are also available for smartphones and are often used by the average users. A third type is the web-wallet, like blockchain.info for those you wont need to download any data, you can access them through you browser. and people just mention but never explain a scary debug window with a console that i have no idea what it does or what should i do with that, and they only post code stuffs that if i copy paste won't work, at least not in all wallets and in those that accepted that code, does absolutely nothing that i can know of.... This is only for developers and those post a mostly related to the bitcoin-core wallet and its JSON-RPC interface. You don't need those for normal usage. is there a newbie guide on how to get to use a wallet? primecoin, dogecoin, rainbowcoin, aimcoin... they all look just the same, and people talk about mining some few coins just by keeping them open :S All those wallets have the same appearance and mostly the same functionality. There are some guides around. Coindesk offers a very good beginner guide which contains many of your questions and explaining all the important stuff.
[ "stackoverflow", "0026339654.txt" ]
Q: Using the sizeof operator with very large objects According to page 135 K&R (as well as this wikipedia page), the sizeof operator can be used to compute the size of an object and returns the size in bytes as an unsigned integer of type size_t. Since the max value of an unsigned integer is 2^32, what would happen if I was to call sizeof on an object that had a larger size in bytes than 2^32, like say something with a size of 2^34 bytes. What would sizeof return? And is there a way to get around this size limit? A: I think you're reading it wrong. "An unsigned integer" does not mean "the type unsigned int". It can also, for instance, be unsigned long long which can be (much) larger. Also, of course, there's no requirement or specification that says that unsigned int is limited to 32 bits. A: sizeof returns the size in bytes as an unsigned integer of type size_t size_t is an alias for one of the unsigned integer types (unsigned int, unsigned long long, unsigned short, etc.). Which particular unsigned integer type is implementation-defined. size_t is guaranteed to be able to store the theoretical maximum size of an object on your system. So if your size_t is a 32-bit unsigned integer, then it is impossible to create an object bigger than 2^32 bytes on your system. Conversely, if you can create an object bigger than 2^32 bytes, then size_t must be bigger than a 32-bit unsigned integer, big enough to be able to store the size of any object you can create.
[ "math.stackexchange", "0001785609.txt" ]
Q: The image of an injective function whose domain is a topological space also a topology Let $(X, T )$ be a topological space, and let $f : X → Y$ be an injective (but not necessarily surjective) function. QUESTIONS. (1) Is $T_f := \{ f(U) : U ∈ T \}$ necessarily a topology on $Y$ ? (2) Is it necessarily a topology on the range of $f$? I would appreciate if someone could provide feedback and suggestions on my attempt. $T_f$ is not necessarily a topology on Y, for instance consider h:$\mathbb R \rightarrow \mathbb R$ $h(x)=e^x$. Then The space $(Y,T_f)$ is not a topology since it does not contain Y (misses zero and all of the negative reals) But I think $T_f$ will be a topology on the range of f since 1. It contains the empty set, 2.It contains range f by definition. 3. It is closed under finite intersections because T is closed under inite intersections and since f is injective $f(\cap_{\alpha \in I} U)$ will be contained in $T_f$ and similarly for unions. Do I have the right idea ? A: Answer to (1) is no. Your example works fine, but you can generalize. If $f$ is any non-surjective function, then $Y\notin T_f$, so $T_f$ is not a topology on $Y$. To prove (2), you just need to verify the axioms for a topology, one by one. One thing that will be useful is that since $f$ is injective, it commutes across union and intersection (these are simply set operations, and $f$ just relabeling elements in $X$ with elements in $Y$).
[ "stackoverflow", "0001576632.txt" ]
Q: json technology attached with java script? what is the use of stringifier in it? How do we use arrays and object notation in it ? Well how do we post , is JSon a platform dependent or independent language? A: JSON is not a language. It is a data interchange format only. From the official site JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999. JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language. A JSON stringifier converts JavaScript data structures into JSON text. Read more on stringifier.