text
stringlengths
64
89.7k
meta
dict
Q: IE 8 Crashes when displaying PDF in IFrame served from Django I have a web application which displays pdf's in an IFrame. I recently made a change to start serving up the PDF using Django instead of allowing Apache to serve the PDF. Initially, I used the FileWrapper approach to return the file. This worked fine on all browsers except for IE 8 which crashed (maybe other versions of IE, didn't test). I figured out how to fix this but it was a bit of a pain to figure out so I am posting the answer here. A: The solution was to use mod_xsendfile as suggested in this post with the following tweaks: mimeType,_ = mimetypes.guess_type(filePath) response = django.http.HttpResponse(mimetype = mimeType) response['Accept-Ranges'] = 'bytes' response['X-Sendfile'] = filePath return response In addition to working correctly with IE / iframes, it allows the file download to be resumable.
{ "pile_set_name": "StackExchange" }
Q: How do I retrieve a simple numeric value from a named numeric vector in R? I am using R to calculate some basic statistic results. I am using the quantile() function,to calulate quantiles on a data frame column as follows. > quantile(foobars[,1]) 0% 25% 50% 75% 100% 189000 194975 219500 239950 1000000 I want to be able to individually access the calculated quantiles. However, I can't seem to find out how to do that. When I check the class of the returned result, it a 1 dimensional numeric. I tried this: > q <- quantile(foobars[,1]) > q[3] 50% 219500 Which seems to return a tuple (quantile level + number). I am only interested in the number (219500 in this case. How may I access only the number into a simple (numeric) variable? A: You are confusing the printed representation of the numeric value with the actual value. As far as R is concerned, q contains a named numeric vector: > dat <- rnorm(100) > q <- quantile(dat) > q 0% 25% 50% 75% 100% -2.2853903 -0.5327520 -0.1177865 0.5182007 2.4825565 > str(q) Named num [1:5] -2.285 -0.533 -0.118 0.518 2.483 - attr(*, "names")= chr [1:5] "0%" "25%" "50%" "75%" ... All the "named" bit means is that the vector has an attached attribute "names" containing the (in this case) quantile labels. R prints these for a named vector as they are considered helpful to have in printed output if present. But, they in no way alter the fact that this is a numeric vector. You can use these in computations as if they didn't have the "names" attribute: > q[3] + 10 50% 9.882214 If the names bother you, the unname() function exists to remove them: > q2 <- unname(q) > q2 [1] -2.2853903 -0.5327520 -0.1177865 0.5182007 2.4825565 For completeness, I should probably add that you can extract the "names" using the names() function, which also has an assignment version ('names<-'()). So another way to remove the names from a vector is to assign NULL to the names: > q3 <- q > names(q3) [1] "0%" "25%" "50%" "75%" "100%" > names(q3) <- NULL > names(q3) NULL
{ "pile_set_name": "StackExchange" }
Q: strtotime within existing PHP function I have and existing PHP function that updates MySQL records like this. I need to set a date field but am having trouble formatting the PHP correctly. Currently this is working fine: update_post_meta( $post_id, 'adverts_email', '[email protected]'); the [email protected] is regular text. For the expiration date I want to use strtotime('+20 days'); to write it out in a unix timestamp format like 1449203160 which translates out to human form as Dec 4, 2015 @ 4:26. I 've tried many variations of .'strtotime('+20 days');'. or '.strtotime('+20 days');.' with and without the ; and it does not work. I am unsure if the issue is the syntax or the strtotime use when I should use DATETIME or some other method or a combination of two problems? Broke: update_post_meta( $post_id, '_expiration_date', 'strtotime('+20 days');'); A: As mentioned, the syntax highlighting shows the problem. Here's solution that should work: update_post_meta( $post_id, '_expiration_date', strtotime('+20 days')); This assumes that the _expiration_date field is a integer/unix timestamp, but it's more likely that the field is DATETIME or TIMESTAMP type. As such, this might work better: update_post_meta( $post_id, '_expiration_date', date('Y-m-d H:i:s', strtotime('+20 days')));
{ "pile_set_name": "StackExchange" }
Q: rvest error: "Error in class(out) <- "XMLNodeSet" : attempt to set an attribute on NULL" I'm trying to scrape a set of web pages with the new rvest package. It works for most of the web pages but when there are no tabular entries for a particular letter, an error is returned. # install the packages you need, as appropriate install.packages("devtools") library(devtools) install_github("hadley/rvest") library(rvest) This code works OK because there are entries for the letter E on the web page. # works OK url <- "https://www.propertytaxcard.com/ShopHillsborough/participants/alph/E" pg <- html_session(url, user_agent("Mozilla/5.0 (Windows NT 5.1; rv:31.0) Gecko/20100101 Firefox/31.0")) pg %>% html_nodes(".sponsor-info .bold") %>% html_text() This doesn't work because there are no entries for the letter F on the web page. The error message is "Error in class(out) <- "XMLNodeSet" : attempt to set an attribute on NULL" # yields error message url <- "https://www.propertytaxcard.com/ShopHillsborough/participants/alph/F" pg <- html_session(url, user_agent("Mozilla/5.0 (Windows NT 5.1; rv:31.0) Gecko/20100101 Firefox/31.0")) pg %>% html_nodes(".sponsor-info .bold") %>% html_text() Any suggestions. Thanks in advance. A: You could always wrap the pg…html_nodes…html_text in try and test for the class afterwards: tmp <- try(pg %>% html_nodes(".sponsor-info .bold") %>% html_text(), silent=TRUE) if (class(tmp) == "character") { print("do stuff") } else { print("do other stuff") } EDIT: one other option is to use the boolean() XPath operator and do the test that way: html_nodes_exist <- function(rvest_session, xpath) { xpathApply(content(rvest_session$response, as="parsed"), sprintf("boolean(%s)", xpath)) } pg %>% html_nodes_exist("//td[@class='sponsor-info']/span[@class='bold']") which will return TRUE if those nodes exist and FALSE if they don't (that function needs to be generalized to be able to use session and ["HTMLInternalDocument" "HTMLInternalDocument" "XMLInternalDocument" "XMLAbstractDocument"] objects and work with both CSS selectors as well as XPath, but it's a way to avoid try.
{ "pile_set_name": "StackExchange" }
Q: Centos find command enigma I have a directory structure like below (Centos 7 and Mac both same issue) mkdir -p test/lemon-ip-ip/2020-04-08 mkdir -p test/king-ip-ip/2020-04-08 now I need to find only "test/lemon-ip-ip/2020-04-08" using the find command for this, I did this find test/lemon-ip-ip -maxdepth 1 -name ????-??-?? this gives the right answer test/lemon-ip-ip/2020-04-08 this is what I want and worked fine till now. However, when I created the directory "king-ip-ip/" this command find test/king-ip-ip -maxdepth 1 -name ????-??-?? gives the wrong output test/king-ip-ip/ test/king-ip-ip/2020-04-08 this is returning parent directly too "test/king-ip-ip/" this happens only with this specific string when I change the directory to say "test/king-ip/" again this works fine. I can't change the directory name. Could someone let me know what is causing this issue? I need the final output to be test/king-ip-ip/2020-04-08 Thanks, Raj A: The cause of this is that the pattern ????-??-?? matches any 4, 2 and 2 characters with dashes in between. Such strings include 2020-04-08, aaaa-bb-cc and king-ip-ip. While you're not asking for alternatives, my suggestion would be one of these, depending on the details of how you're using it: # Don't use find at all echo test/king-ip-ip/????-??-?? # Only search files strictly inside the directory, not the dir itself find test/king-ip-ip/* -maxdepth 0 -name '????-??-??' find test/king-ip-ip -maxdepth 1 -depth 1 -name '????-??-??' # Only match numbers, not other characters find test/king-ip-ip -maxdepth 1 -name '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]'
{ "pile_set_name": "StackExchange" }
Q: How does Firestore's `documentSnapshot.toObject(className::class.java)` reassign `val` values that were set in the primary constructor? I've been developing a Kotlin back-end service, and stumbled across the Firestore documentSnapshot.toObject(className::class.java) method. Take the following Kotlin data class: data class Record( val firstName: String = "", val lastName: String = "", val city: String = "", val country: String = "", val email: String = "") And the following code from my Repository class: if (documentSnapshot.exists()) { return documentSnapshot.toObject(Record::class.java)!! } Now, from what I understand the method documentSnapshot.toObject(className::class.java) requires and invokes a no-param default constructor, e.g. val record = Record(). This invocation would invoke the primary constructor and assign the default values stated in it (in the case of the data class Record, the empty strings "") to the fields. Then, it uses public setter methods to set the instance's fields with the values found in the document. How this is possible, given that the fields have been marked as val in the primary data class constructor? Is reflection at play here? Is val not truly final in Kotlin? A: Firebase indeed uses reflection to set/get the values. Specifically, it uses JavaBean pattern to identify properties, and then gets/sets them either using their public getter/setter, or using public fields. Your data class is compiled into the equivalent of this Java code: public static final class Record { @NotNull private final String firstName; @NotNull private final String lastName; @NotNull private final String city; @NotNull private final String country; @NotNull private final String email; @NotNull public final String getFirstName() { return this.firstName; } @NotNull public final String getLastName() { return this.lastName; } @NotNull public final String getCity() { return this.city; } @NotNull public final String getCountry() { return this.country; } @NotNull public final String getEmail() { return this.email; } public Record(@NotNull String firstName, @NotNull String lastName, @NotNull String city, @NotNull String country, @NotNull String email) { Intrinsics.checkParameterIsNotNull(firstName, "firstName"); Intrinsics.checkParameterIsNotNull(lastName, "lastName"); Intrinsics.checkParameterIsNotNull(city, "city"); Intrinsics.checkParameterIsNotNull(country, "country"); Intrinsics.checkParameterIsNotNull(email, "email"); super(); this.firstName = firstName; this.lastName = lastName; this.city = city; this.country = country; this.email = email; } ... } In this case, Firebase uses the public getters to get the property values when i needs to writes them to the database, and the fields when it needs to set the property values when it reads them from the database.
{ "pile_set_name": "StackExchange" }
Q: How to play an encrypted video file in Android I searched through a lot of questions on SO but I can't find the answer, that's why I ask the following question: An Android app should be able to play an encrypted video file (stored on the SD card and retrieved from a webserver). The file has to be stored on the SD card so that the app can play the video file without having an active internet connection. Because the video files may not be copied, the plan is to encrypt them server side when uploading the files to a webserver. What is the best option? 1) I have seen suggestions for running a local webserver which decrypts the file (and how to do this?) 2) or should we decrypt the file, save it as a temporary file and set this temporary file as the source for the videoplayer? 3) something completely different? A: You are trying to implement a DRM scheme, and a naive one at that. Look into DRM schemes and report back if you cannot implement the impossible. All you can hope for is obfuscation, and there are plenty of ways of doing that (none of them are secure of course).
{ "pile_set_name": "StackExchange" }
Q: How do I bind to the click event from within the click event when I need to do it repeatedly? I've got code so that when you click on a word, it is replaced by another word. <script> $(document).ready(function() { $('.note_text').click(function(){ $(this).remove(); $('#note_div').append('<span class="note_text">new</span>'); // re-applying behaviour code here }); }); </script> <div id="note_div"> <span class="note_text">preparing</span> </div> I need the appended word to have the same click behaviour. What is the best way to do this? A: change $('.note_text').click(function(){ to $('.note_text').live('click',function(){ This will cause anything on your page that ever gets the class 'note_text' to have the behaviour set by .live
{ "pile_set_name": "StackExchange" }
Q: Local homeomorphisms which are not covering map? I am trying to find examples of maps between topological space which are local homeomorphism but not covering maps. Especially, how twisted has to be such a counterexample : can it be a local diffeomorphism between connected manifolds which is not a covering map ? I found here(When is a local homeomorphism a covering map?) a nice proposition which state that a local homeo from a compact space to a connected Hausdorff space is a covering map. I am interested in all type of counterexamples, from non-Hausdorff spaces to surfaces, to get a better picture of the differences between covering maps and local homeomorphisms. Thank you ! A: There's an error in your statement: you need the domain to be compact, and the range to be connected. Easy counterexample: restrict the exponential map $\mathbb{R} \rightarrow S^1$ to some interval like (0, 1.5) so that the fibers have different cardinalities. A: Here is an example of a local homeomorphism which is not just a covering map with points from the domain removed (nor is it of the form $\bigsqcup U_i \to X$ where $U_i \subseteq X$ are open subspaces). Let $X= \Bbb{Z}_{\geq 0}$ with open sets $U_n = [n, \infty)\cap X$ for $n \in \Bbb{Z}$. The open sets are nested $X = U_0\supsetneq U_1 \supsetneq \cdots$, so that any open cover of $X$ contains $X$ itself. Here is a picture: Because any open cover of $X$ contains $X$ itself, its covering spaces are all of the form $\bigsqcup_{i \in I} X \to X$. Yet we can easily construct a local homeomorphism not of this form by gluing two copies of $X$ together along any of the $U_i$. (The result is a connected space which is not homeomorphic to $X$, so it cannot be extended to a covering map.) EDIT: It is also easy to get a local homeomorphisms onto a simply connected manifold $M$ which does not extend to a covering map, though the space which maps to $M$ won't be a manifold. For example, the sphere with two north poles mapping onto the usual sphere is a local homeomorphism. More generally, one can glue a number of copies of $M$ along some open set, obtaining a local homeomorphism onto $M$ whose fibers are already too large to extend to a connected cover. (This does not contradict the proposition mentioned above because it was also necessary that the domain of the local homeomorphism be Hausdorff; if we glue two copies of a manifold together along an open set then the boundary points of that open set are not separated from those in the other copy.) A: To your question: can it be a diffeomorphism between connected manifolds ? Of course it can't be; a diffeomorphism is automatically a homeomorphism and hence a covering map. I suspect what you meant to ask if it can be locally a homeomorphism between connected manifolds. For this, the quotient map from the line with double origin to the ordinary line, identifying the two origins, will do. This is also a non-Hausdorff example that you were looking for.
{ "pile_set_name": "StackExchange" }
Q: Can't access my index.html (via Apache) from other computer (LAN nor Internet)? Please help lets make it simple to answer. I installed Apache 2.2. Now when I do 127.0.0.1 in Firefox, I get the "It works" page. When I do 10.0.1.10 (my servers internal IP) on another PC on the SAME network, I won't get anything :-(. I forwarded port 80 on my router and made sure Firewall doesn't block Apache. If I type my external IP:80 I still can't get into my "index.html". My settings (more less default) Network Domain: localhost Server Name: localhost I also got a FTP via FileZilla running on that PC. It works perfectly, even over Internet. I have also set up a DynDns hostname. If I do ftp://mydyndns.hostname.com I get to my ftp server. What am I missing? Some more Windows setup? Thanks a lot in advance! A: I installed Linux on my computer and found all servers run better on it :) Thanks everyone...
{ "pile_set_name": "StackExchange" }
Q: Вычисление максимально возможного веса людей в лифте Задача похожа на предыдущий вопрос, только здесь цель другая, изначально задача была неправильно понята. В предыдущей задаче надо было вычислить максимальное количество людей вместимых в лифт, а в этом надо максимально нагрузить лифт. Изначально задача была не правильно понята Дано список людей с именем и весом, максимальный вес который выдержит лифт. Вычислить максимальный вес которое может поместиться и вывести их список, какие люди поместятся чтобы максимально нагрузить лифт. Не понимаю как определить комбинацию людей которые могут быть. Ведь может быть разные комбинации, 1, 2, 3 или 1, 2, 4, или 1, 3, 5, 6. Хочу сначала узнать все возможные комбинации вместимых людей и потом выводить максимальное. Но как узнать комбинации этих людей или как по другому решаются такие задачи public class MaxLift { public static void main(String[] args) { Man[] men = new Man[10]; men[0] = new Man("0", 110); men[1] = new Man("1", 30); men[2] = new Man("2", 34); men[3] = new Man("3", 67); men[4] = new Man("4", 33); men[5] = new Man("5", 65); men[6] = new Man("6", 19); men[7] = new Man("7", 80); men[8] = new Man("8", 98); men[9] = new Man("9", 45); int liftMaxWeight = 200; TreeSet<List<Man>> set = new TreeSet<>();//add comparator for (int i = 0; i < men.length; i++) { List<Man> list = new ArrayList<>(); list.add() } //sout } private static class Man { String name; int weight; public Man(String name, int weight) { this.name = name; this.weight = weight; } } } A: Вычисление максимального возможного веса при заполнении лифта людьми с указанными весами, можно выполнить используя упрощённое решение для задачи о рюкзаке 0-1 O(n W) по времени O(W) в памяти решение (n - количество людей, W - грузоподъёмность), на Питоне: #!/usr/bin/env python3 """Find max weight given people weights, elevator capacity.""" weights = 110, 30, 34, 67, 33, 65, 19, 80, 98, 45 capacity = 200 # m[c] — max possible weight using items seen so far under *c* capacity m = [0] * (capacity + 1) prev = m[:] # previous value (without the current item) for w in weights: for c in range(capacity + 1): m[c] = prev[c] if w > c else max(prev[c], prev[c-w] + w) prev, m = m, prev print('Max weight:', prev[-1]) Вывод: Max weight: 200 (можно заполнить до максимальной нагрузки). Что совпадает с ответом, получаемым адаптацией более общего решения из вопроса Задача о рюкзаке (ранце) python. <script src="https://cdn.rawgit.com/brython-dev/brython/3.4.0/www/src/brython.js"></script><body onload="brython()"><script type="text/python"> import json from browser import document def max_weight(weights, capacity): m = [0] * (capacity + 1) prev = m[:] # previous value (without the current item) for w in weights: for c in range(capacity + 1): m[c] = prev[c] if w > c else max(prev[c], prev[c-w] + w) prev, m = m, prev return prev[-1] @document["mybutton"].bind("click") def on_click(event=None): capacity = int(document["capacity"].value) weights = json.loads(document["json"].value) print(f"{capacity}, {weights} -> {max_weight(weights, capacity)}") on_click('dummy on start') </script><label for="json">Weights: </label><input id="json", value="[110, 30, 34, 67, 33, 65, 19, 80, 98, 45]"> <label for="capacity">Max&nbsp;weight: <input id="capacity" value="200"> <button id="mybutton">Запустить</button></body>
{ "pile_set_name": "StackExchange" }
Q: Load and unload a page into a div from a navigation button Can anyone tell me in the simplest code possible, how to load and unload an html page into a div named "myDiv", with a simple click? When i press another button on my navigation menu, i will then unload "myDiv" and replace with another page. Whats the setup for this? edit I have 3 pages (page1.html, page2.html, page3.html) My navigation is as follows: <ul> <li><a href="page1.html"></a></li> <li><a href="page2.html"></a></li> <li><a href="page3.html"></a></li> </ul> I am trying to load those pages into "myDiv", each page replacing the previous loaded page everytime i click a different page button. Thats all. I hope i made what im trying to do clear as crystal and hopefully not leaving anything important out. A: Assuming you can use javascript/jQuery (you don't give a lot of info on your environment)... Have a look at the jQuery load() method. http://api.jquery.com/load/ <div id="myDiv"></div> <button id="myButton">Click Me</button> <script type="text/javascript"> $( document ).ready( function() { $( '#myButton' ).click( function() { $( '#myDiv' ).load( 'test.html' ); }); }); </script> That should do your load. I'll leave the rest to you :) EDIT: OK, something more along the lines of what you're looking for... Assuming you can modify the markup and add a class attribute to your a elements... <ul> <li><a href="page1.html" class="dynamicLoad"></a></li> <li><a href="page2.html" class="dynamicLoad"></a></li> <li><a href="page3.html" class="dynamicLoad"></a></li> </ul> <script type="text/javascript"> $( document ).ready( function() { $( 'a.dynamicLoad' ).click( function( e ) { e.preventDefault(); // prevent the browser from following the link e.stopPropagation(); // prevent the browser from following the link $( '#myDiv' ).load( $( this ).attr( 'href' ) ); }); }); </script> So any 'a' element with the class of dynamicLoad will trigger this when clicked. We don't want the browser to try and follow the link, so we use preventDefault() and stopPropagation(). The only other difference is that we're not statically loading "test.html". We're determining what html page to load by using jQuery's $( this ), which represents the element that triggered the function. Use the attr() method, which returns the value of a specific attribute of the element. In this case, the href attribute. Questions?
{ "pile_set_name": "StackExchange" }
Q: How to make flex child height to wrap content What I basically want is to make each child element's height to wrap its content. Here is my code: <style> .parent{ display: flex; } .child{ padding: 5px; margin: 10px; background: green; height: auto; } </style> <div class="parent"> <div class="child">child1</div> <div class="child">child2</div> <div class="child">child3</div> <div class="child" style="height:50px">child1</div> </div> Output: Expected output: A: You just need to set align-items: flex-start on parent element because default value is stretch. .parent { display: flex; align-items: flex-start; } .child { padding: 5px; margin: 10px; background: green; height: auto; } <div class="parent"> <div class="child">child1</div> <div class="child">child2</div> <div class="child">child3</div> <div class="child" style="height:50px">child1</div> </div>
{ "pile_set_name": "StackExchange" }
Q: Netbeans javac throws exception in LayerGeneratingProcessor for @Override. Where's the problem? Im using NB7 I don't know which file is causing the problem since i can't find any stracktraces. I've checked the .netbeans\7.0\var\log\ directory, but there's no useful information there (afaik) I added to build-impl.xml the compilerarg -verbose and got ... [loading java\lang\annotation\RetentionPolicy.class(java\lang\annotation:RetentionPolicy.class)] Round 1: input files: {...} annotations: [java.lang.Override, java.lang.SuppressWarnings] last round: false error: Exception thrown while constructing Processor object: org/openide/filesystems/annotations/LayerGeneratingProcessor D:\..\nbproject\build-impl.xml:603: The following error occurred while executing this line: D:\..\nbproject\build-impl.xml:242: Compile failed; see the compiler error output for details. BUILD FAILED (total time: 8 seconds) Turns out the "LayerGeneratingProcessor" is an Abstract class. Does anyone know how to stop it from being constructed ? A: Solved Problem was that the tickbox 'Enable annotation processing', under 'Project properties, build, compiling ', was enabled while nothing was configured for this setting.
{ "pile_set_name": "StackExchange" }
Q: How to change a variable stored property in a structure in Swift? On apple website, https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Properties.html it states that we can change a variable property in a structure. I am trying to change the person's last name. However I recieve an error at that line of code. Thank you for helping me. import UIKit struct people { let firstName : String var lastName : String } let person = people(firstName: "InitialFirstName", lastName: "InitialLastName") person.lastName = "ChangedLastName" //<-- error println(person.firstName) println(person.lastName) Error: Playground execution failed: TestPlayground2.playground:12:17: error: cannot assign to 'lastName' in 'person' person.lastName = "ChangedLastName" ~~~~~~~~~~~~~~~ ^ A: You can only modify a property of a struct if that struct is declared as var, and not let. Even though your property is var, because the struct is let it is immutable. var person = people(firstName: "InitialFirstName", lastName: "InitialLastName") person.lastName = "ChangedLastName" //No problem! Note that this is different behavior from classes. A class's mutable properties can be changed even if if the instance of the class is a constant. A: Unlike class which is reference type struct is value type. You have to declare the instance as mutable var person = people(firstName: "InitialFirstName", lastName: "InitialLastName")
{ "pile_set_name": "StackExchange" }
Q: How to shorten my code to write a simple text file? My data as variables: Brazil = 55 USA = 12 Greece = 32 India = 56 Now, I wanted to produce the text file as shown below: Brazil 55 USA 12 Greece 32 India 56 with open ('result.txt','w') as fo: fo.write('Brazil' + ' ' + str(Brazil) + '\n') fo.write('USA' + ' ' + str(USA) + '\n') fo.write('Greece' + ' ' + str(Greece) + '\n') fo.write('India' + ' ' + str(India) + '\n') My code works, but how can I shorten it? I am using Python 2.7 A: import collections vals = collections.OrderedDict([("Brazil", 55), ("USA", 12), ("Greece", 32), ("India", 56)]) with open('result.txt', 'w') as fo: for country,score in vals.iteritems(): fo.write("%s %d\n" %(country, score)) A: Same answer as inspectorG4dget but using the newer style string formating (which I think is a bit clearer and easier to use): import collections vals = collections.OrderedDict([("Brazil", 55), ("USA", 12), ("Greece", 32), ("India", 56)]) with open('result.txt', 'w') as fo: for country,score in vals.iteritems(): fo.write("{} {}".format(country, score))
{ "pile_set_name": "StackExchange" }
Q: console.log prints changed state before changing I'm trying to rearrange div's with React/Redux via Drag&Drop and there is a strange behavoir that i cant explain. I have the following reducer (reduced version for readability) There are 5 "console.log" around the middle of the code. When i log state or structs the chrome console will print the already rearrange version. why? export default function reducer( state={ structures: [], elementUniqueCounter: 0, hoveredElement: null, DnD: { dragContent: null, dragOverContent: null, dragContentTop: true, dragStructure: null, dragOverStructure: null, dragStructureTop: true, content: null, mousepositon: {} } }, action) { let DnD = Object.assign({}, state.DnD); let structs = state.structures.slice(); switch (action.type) { case "STOP_DRAG_CONTENT": let cindex_source; let index_source; let cindex_target; let index_target; let foundTarget = false; let foundSource = false; structs.map(function (struct, index) { struct.content.map(function (content, cindex) { if(content.id === DnD.dragOverContent.props.id) { cindex_target = cindex; index_target = index; foundTarget = true; } if(content.id === DnD.dragContent.props.id) { cindex_source = cindex; index_source = index; foundSource = true; } }); }); console.log(state); console.log(index_source); console.log(cindex_source); console.log(index_target); console.log(cindex_target); if(index_source !== undefined && cindex_source !== undefined && index_target !== undefined && cindex_target !== undefined) { let copy = structs[index_source].content.slice(cindex_source, cindex_source+1)[0]; copy.content = DnD.content; structs[index_source].content.splice(cindex_source, 1); if (DnD.dragContentTop) { structs[index_target].content.splice(cindex_target+1, 0, copy); } else { structs[index_target].content.splice(cindex_target, 0, copy); } } DnD = { dragContent: null, dragOverContent: null, dragContentTop: true, dragStructure: null, dragOverStructure: null, dragStructureTop: true, content: null, mousepositon: {} }; return {...state, DnD: DnD, structures: structs}; } return state } A: It's not that it is printing the rearranged version before it happens. It is that it is printing an object that you are mutating. By the time you look at the object in the console the mutation has already occurred. The use of splice is mutating. structs[index_source].content.splice(cindex_source, 1); if (DnD.dragContentTop) { structs[index_target].content.splice(cindex_target+1, 0, copy); } else { structs[index_target].content.splice(cindex_target, 0, copy); } EDIT: The above mutation is actually mutating the nested properties of state.structures. This is happening because .slice() returns a shallow copy of the original object. The slice() method returns a shallow copy of a portion of an array into a new array object selected from begin to end (end not included). The original array will not be modified. The objects in the shallow copy are just pointers to the objects in state.structures. So when you use .splice(), you mutate those referenced values. Here is a snippet to illustrate this. Run it an look at the console.log. const people = [ { name: "Joe", age: "52" }, { name: "Sally", age: "48" } ]; const clonedPeople = people.slice(); console.log("people === clonedPeople: ", people === clonedPeople); console.log("people[0] === clonedPeople[0]: ", people[0] === clonedPeople[0]); const deeplyClonedPeople = JSON.parse(JSON.stringify(people)); console.log("people[0] === deeplyClonedPeople[0]: ", people[0] === deeplyClonedPeople[0]); Hope this helps!
{ "pile_set_name": "StackExchange" }
Q: How to change a simple network dataframe to a correlation table? I have a dataframe which is in this format from to weight 0 A D 3 1 B A 5 2 C E 6 3 A C 2 I wish to convert this to a correlation-type dataframe which would look like this - A B C D E A 0 0 2 0 3 B 5 0 0 0 0 C 0 0 0 0 6 D 0 0 0 0 0 E 0 0 0 0 0 I thought a possible (read naïve) solution would be to loop over the dataframe and then assign the values to the correct cells of another dataframe by comparing the rows and columns. Something similar to this: new_df = pd.DataFrame(columns = sorted(set(df["from"])), index =sorted(set(df["from"]))) for i in range(len(df)): cor.loc[df.iloc[i,0], df.iloc[i,1]] = df.iloc[i,2] And that worked. However, I've read about not looping over Pandas dataframes here. The primary issue is that my dataframe is larger than this - a couple thousand rows. So I wish to know if there's another solution to this since this method doesn't sit well with me in terms of being Pythonic. Possibly faster as well, since speed is a concern. A: IIUC, this is a pivot with reindex: (df.pivot(index='from', columns='to', values='weight') .reindex(all_vals) .reindex(all_vals,axis=1) .fillna(0) ) Output: to A B C D E from A 0.0 0.0 2.0 3.0 0.0 B 5.0 0.0 0.0 0.0 0.0 C 0.0 0.0 0.0 0.0 6.0 D 0.0 0.0 0.0 0.0 0.0 E 0.0 0.0 0.0 0.0 0.0
{ "pile_set_name": "StackExchange" }
Q: exposing a sparql endPoint publicly? I have a website power by a tomcat server. My application tap on a tripleStore that i would like to make public trough a sparql endpoint at www.mywebsiteaddress/sparql. What configuration do i need on my webserver to do that ? I use Jena Fuseki on the background which is running on the Port 3030 and my webserver is on the port 80. My idea is that, when the webserver get a request on the port 80 about ..../sparql it redirect to fuseki sprql endPoint A: This is more of a webservice / access control problem than anything SPARQL related. However, since SPARQL endpoints are supposed to be created as per the SPARQL spec, i think this a valid question, as I'm sure people will encounter it again in the future. So, to answer your question, "public" usually means that certain headers are set in order to allow a request to hit the endpoint when it is not coming from the same domain. From there, you can specifically allow certain types of interactions with the endpoint. If you wanted to kinda just allow everything, you could set the following headers: 'Access-Control-Allow-Origin: *' "Access-Control-Allow-Credentials: true" 'Access-Control-Allow-Headers: X-Requested-With' 'Access-Control-Allow-Headers: Content-Type' 'Access-Control-Allow-Methods: POST, GET, OPTIONS, DELETE //http://stackoverflow.com/a/7605119/578667 'Access-Control-Max-Age: 86400' Depending on how you built the endpoint, it'll either have some settings somewhere where you can adjust the headers, or, you'll have find the headers settings for the application framework itself if you're using one. But, in general, the above headers would make it "public"
{ "pile_set_name": "StackExchange" }
Q: Is it safe to plant shrubs or flowers in the soil above my septic tank? I have a septic system that has a tank underneath my front lawn. This is an eye-sore as the access points are clearly visible to anyone coming down our driveway. I would like to plant some shrubs/flowers around the access points to hide them. Is it safe to do this? I don't want to plant trees or anything crazy. NOTE: I am not going to actually cover the access points. I just want to hide them. A: It's not a problem. Your septic tank should be full enclosed and the vent/access pipes should be sealed. It's unlikely that roots from small shrubs will make their way in and cause clogs.
{ "pile_set_name": "StackExchange" }
Q: Write to text file with javascript on GoDaddy server I have tried numerous different codes that I have found here along with the following code below I got from docs.microsoft.com. They all give me the same error though. The error I get is "ActiveXObject is not defined". Can someone please tell me how to fix this issue. How do I define the object or is this yet another problem that is related to my host, GoDaddy?!?! This is for a Plesk/Windows server hosted by GoDaddy. This is a link is to just one of the codes from stackoverflow that I have tried: Use JavaScript to write to text file? Microsoft Code <script> var fso, tf; fso = new ActiveXObject("Scripting.FileSystemObject"); tf = fso.CreateTextFile("G:\mysite\file.txt", true); // Write a line with a newline character. tf.WriteLine("Testing 1, 2, 3.") ; // Write three newline characters to the file. tf.WriteBlankLines(3) ; // Write a line. tf.Write ("This is a test."); tf.Close(); </script> A: You can't write to a file on the server with client-side JavaScript (if clients could write arbitrary files on servers then Google's homepage would be vandalised every second). The code you've found could write to the hard disk of the computer the "page" was loaded on, but only if the "page" was an HTA application and not a web page. The standard way to send data to an HTTP server from JavaScript is to make an HTTP request. You can do this with an Ajax API like fetch. You then need a server-side program (written in the language of your choice) that will process the request and write to the file (although due to race conditions, you are normally better off using a database than a flat file).
{ "pile_set_name": "StackExchange" }
Q: Facebook Ads, possible to add dynamic parameters in URL for FB to populate later? I need to add ad_group id to ad's URL. However, I can only obtain the id after creating the ad, not before. Is it possible for me to specify a parameter in the URL so that it can be populated by FB when the ad is created? I know double click of Google supports this. A: A solution has been released recently: https://www.linkedin.com/pulse/new-facebook-ads-url-dynamic-parameters-trishan-naidoo/ Dynamic Parameters & Values There are currently 8 parameters that can be dynamically inserted into ad URLs: Site Source Name [site_source_name] - This parameter has 4 possible values depending on whether the ad appeared on Facebook ('fb'), Instagram ('ig'), Messenger ('msg') or the Audience Network ('an'). Note: Facebook's help documentation incorrectly lists {{site_source_name}} as the dynamic parameter but my testing shows that it only works with square brackets. Placement {{placement}} - This parameter has 6 possible values depending on whether the ad appeared on the desktop feed, mobile feed or the right column on Facebook, the Messenger inbox or within the Instagram Feed or Instagram Stories. Campaign, Ad Set & Ad Names {{campaign.name}} {{adset.name}} {{ad.name}} - This parameter will dynamically insert the name of the campaign, ad set or ad according to how you have named each when setting up ads. Campaign, Ad Set & Ad IDs {{campaign.id}} {{adset.id}} {{ad.id}} - This parameter will dynamically insert the automatically assigned ID of the campaign, ad set or ad. To find out IDs, you will need to customise your columns to add the relevant ID column. A: No, there is no way to automatically add the adgroup ID to the referral params of an adgroup - typically developers use their own system's reference for tracking purposes in the url tags, or add the creative ID, something like that
{ "pile_set_name": "StackExchange" }
Q: Why does the == operator work for Nullable when == is not defined? I was just looking at this answer, which contains the code for Nullable<T> from .NET Reflector, and I noticed two things: An explicit conversion is required when going from Nullable<T> to T. The == operator is not defined. Given these two facts, it surprises me that this compiles: int? value = 10; Assert.IsTrue(value == 10); With the code value == 10, either value is being magically converted to an int (hence allowing int's == operator to be used, or the == operator is being magically defined for Nullable<int>. (Or, I presume less likely, Reflector is leaving out some of the code.) I would expect to have to do one of the following: Assert.IsTrue((value.Equals(10)); // works because Equals *is* defined Assert.IsTrue(value.Value == 10); // works because == is defined for int Assert.IsTrue((int?)value == 10); // works because of the explicit conversion These of course work, but == also works, and that's the part I don't get. The reason I noticed this and am asking this question is that I'm trying to write a struct that works somewhat similarly to Nullable<T>. I began with the Reflector code linked above, and just made some very minor modifications. Unfortunately, my CustomNullable<T> doesn't work the same way. I am not able to do Assert.IsTrue(value == 10). I get "Operator == cannot be applied to operands of type CustomNullable<int> and int". Now, no matter how minor the modification, I would not expect to be able to do... CustomNullable<T> value = null; ...because I understand that there is some compiler magic behind Nullable<T> that allows values to be set to null even though Nullable<T> is a struct, but I would expect I should be able to mimic all the other behaviors of Nullable<T> if my code is written (almost) identically. Can anyone shed light on how the various operators of Nullable<T> work when they appear not to be defined? A: Given these two facts, it surprises me that this compiles Given only those two facts, that is surprising. Here's a third fact: in C#, most operators are 'lifted to nullable'. By "lifted to nullable", I mean that if you say: int? x = 1; int? y = 2; int? z = x + y; then you get the semantics of "if either x or y is null then z is null. If both are not null then add their values, convert to nullable, and assign the result to z." The same goes for equality, though equality is a bit weird because in C#, equality is still only two-valued. To be properly lifted, equality ought to be three-valued: x == y should be null if either x or y is null, and true or false if x and y are both non-null. That's how it works in VB, but not in C#. I would expect I should be able to mimic all the other behaviors of Nullable<T> if my code is written (almost) identically. You are going to have to learn to live with disappointment because your expectation is completely out of line with reality. Nullable<T> is a very special type and its magical properties are embedded deeply within the C# language and the runtime. For example: C# automatically lifts operators to nullable. There's no way to say "automatically lift operators to MyNullable". You can get pretty close by writing your own user-defined operators though. C# has special rules for null literals -- you can assign them to nullable variables, and compare them to nullable values, and the compiler generates special code for them. The boxing semantics of nullables are deeply weird and baked into the runtime. There is no way to emulate them. Nullable semantics for the is, as and coalescing operators are baked in to the language. Nullables do not satisfy the struct constraint. There is no way to emulate that. And so on. A: Well, if you can use reflector why don't you compile this code: int? value = 10; Console.WriteLine(value == 10); and then open it in reflector? You'll see this (make sure to select 'None' as .net version to decompile to): int? value; int? CS$0$0000; &value = new int?(10); CS$0$0000 = value; Console.WriteLine((&CS$0$0000.GetValueOrDefault() != 10) ? 0 : &CS$0$0000.HasValue); So basically the compiler does the heavy lifting for you. It understands what '==' operation means when used with nullables and compiles the necessary checks accordingly.
{ "pile_set_name": "StackExchange" }
Q: Count rows by time interval of 10 minutes postgresql i've been trying to find a solution for this query but i'm hitting the wall from the begining i'm trying to count the number of bought and sold items per 10 mins intervals date_action ACTION 2018-03-16 00:00:00 bought 2018-03-16 00:03:00 sold 2018-03-16 00:04:00 bought 2018-03-16 00:27:00 sold 2018-03-16 00:29:00 sold the output that i'm trying to get should be something like that time_interval ACTION count 2018-03-16 00:00:00 bought 2 2018-03-16 00:00:00 sold 1 2018-03-16 00:20:00 bought 1 2018-03-16 00:20:00 sold 2 i'm new to stack overflow so i hope that my uestion is clear A: Truncating to 10 minute intervals takes a bit of work, but here is one method: select (date_trunc(date_action, 'hour') + (date_part('minute', date_action) / 6) * interval '10 minute' ) as time_interval, action, count(*) from t group by time_interval, action order by time_interval, action;
{ "pile_set_name": "StackExchange" }
Q: Storyboard Scene Editor vanished I'm still new to Xcode and developing iOS apps...when I was editing my storyboard, I somehow removed the menu that displays the list of scenes (which defaults to the right side of the file navigator). How do you bring this menu/view back up? A: If I understand what you want you must just click on the button at the bottom in yellow highlight:
{ "pile_set_name": "StackExchange" }
Q: PCF8591 with Analog Joystick I/O error when reading input PYTHON I have been trying to create a retropie unit, and I'm in the midst of writing a script to inject uinput events for the analog axis values. This is the code I've written so far, but the issue is that I get IOERROR: (Errno 121) Remote I/O error. When I use the command i2cdetect -y 1, the module shows up at address 0x48. from evdev import UInput, ecodes as e; import smbus; from time import sleep; def analogRead(pin): global bus; return bus.read_byte(0x48+pin); bus = smbus.SMBus(1); ui = UInput(); bus.write_byte_data(0x48,0x40 | (0 & 0x03) | (1 & 0x03) | (2 & 0x03), 0 | 1 | 2); sleep(0.2); bus.read_byte(0x48); sleep(0.2); bus.read_byte(0x49); sleep(0.2); bus.read_byte(0x50); sleep(0.2); while True: if analogRead(0) <= 10: ui.write(e.EV_KEY, e.KEY_S, 0); ui.write(e.EV_KEY, e.KEY_W, 1); elif analogRead(0) >= 245: ui.write(e.EV_KEY, e.KEY_S, 1); ui.write(e.EV_KEY, e.KEY_W, 0); else: ui.write(e.EV_KEY, e.KEY_S, 0); ui.write(e.EV_KEY, e.KEY_W, 0); if analogRead(1) <= 10: ui.write(e.EV_KEY, e.KEY_D, 0); ui.write(e.EV_KEY, e.KEY_A, 1); elif analogRead(1) >= 245: ui.write(e.EV_KEY, e.KEY_D, 1); ui.write(e.EV_KEY, e.KEY_A, 0); else: ui.write(e.EV_KEY, e.KEY_D, 0); ui.write(e.EV_KEY, e.KEY_A, 0); EDIT: This issue occurs every time I attempt to run the python script. The goal is to use a single pcf8591, and read three separate inputs: y-axis, x-axis, and the button press. REVISED CODE: from evdev import UInput, ecodes as e; import smbus; from time import sleep; bus = smbus.SMBus(1); ui = UInput(); bus.read_byte(0x48); The revised, smaller sample, allows me to get a value of 128, which I assume references the first analog output, the y-axis. How can I access the other two analog inputs( button and x-axis )? I tried to increment the address by one to 0x49, but that is what produces my IOERROR. A: SMBus's write_byte_data is the function I needed. I had to specify which register I was using per analog input. The I/O error I had was the result of only having a single pcf8591 located at 0x48.
{ "pile_set_name": "StackExchange" }
Q: Differentiation between Abstraction - Encapsulation and Polymorphism - Overloading I am reading different articles on these terminologies but I am unable to understand actual difference between these terminologies. I need some real example e.g some code example, to understand how abstraction and encapsulation works. Somebody also please tell me the difference between polymorphism and overloading. Help would be highly appreciated. A: Hi there you may try to read this maybe it will help: Short answer: They are the same. Long Answer, (and yet less revealing): Polymorphism is simply the ability to have many different methods (Or functions, for those who are used to C-Type programs) to have the same name but act differently depending on the type of parameters that were passed to the function. So for example, we may have a method called punch, which accepts no parameters at all, and returns an integer: public int punch() { return 3; } We could also have a method named punch that accepts a String and returns a boolean. public boolean punch(String poorGuyGettingPunched) { if(poorGuyGettingPunched.equals("joe")) { System.out.println("sorry Joe"); return true; } else return false; } That is called polymorphism... And strangely enough, it is also called overloading.
{ "pile_set_name": "StackExchange" }
Q: OpenGL Coordinate system confusion Maybe I set up GLUT wrong. I want verticies to be relative to their size in pixels. Right now if I create a hexagon, it takes up the whole screen even though the units are 6. #include <iostream> #include <stdlib.h> //Needed for "exit" function #include <cmath> //Include OpenGL header files, so that we can use OpenGL #ifdef __APPLE__ #include <OpenGL/OpenGL.h> #include <GLUT/glut.h> #else #include <GL/glut.h> #endif using namespace std; //Called when a key is pressed void handleKeypress(unsigned char key, //The key that was pressed int x, int y) { //The current mouse coordinates switch (key) { case 27: //Escape key exit(0); //Exit the program } } //Initializes 3D rendering void initRendering() { //Makes 3D drawing work when something is in front of something else glEnable(GL_DEPTH_TEST); } //Called when the window is resized void handleResize(int w, int h) { //Tell OpenGL how to convert from coordinates to pixel values glViewport(0, 0, w, h); glMatrixMode(GL_PROJECTION); //Switch to setting the camera perspective //Set the camera perspective glLoadIdentity(); //Reset the camera gluPerspective(45.0, //The camera angle (double)w / (double)h, //The width-to-height ratio 1.0, //The near z clipping coordinate 200.0); //The far z clipping coordinate } //Draws the 3D scene void drawScene() { //Clear information from last draw glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glLoadIdentity(); //Reset the drawing perspective glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glBegin(GL_POLYGON); //Begin quadrilateral coordinates //Trapezoid glColor3f(255,0,0); for(int i = 0; i < 6; ++i) { glVertex2d(sin(i/6.0*2* 3.1415), cos(i/6.0*2* 3.1415)); } glEnd(); //End quadrilateral coordinates glutSwapBuffers(); //Send the 3D scene to the screen } int main(int argc, char** argv) { //Initialize GLUT glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH); glutInitWindowSize(400, 400); //Set the window size //Create the window glutCreateWindow("Basic Shapes - videotutorialsrock.com"); initRendering(); //Initialize rendering //Set handler functions for drawing, keypresses, and window resizes glutDisplayFunc(drawScene); glutKeyboardFunc(handleKeypress); glutReshapeFunc(handleResize); glutMainLoop(); //Start the main loop. glutMainLoop doesn't return. return 0; //This line is never reached } How can I make it so that the coordinates: (0,0), (10,0), (10,10), and (0,10) define a polygon starting at the top left of the screen and is a width and height of 10 pixels? A: If you want the objects to be scaled that sort of way, you should use an orthographic projection. Right now, with perspective, things are scaled not only by their size, but by their Z-axis position. So use this function instead of gluPerspective: gluOrtho2D(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top); That function basically defines the space you can see, which is like a big rectangular prism. That makes far things appear the same size as near things. As for the exact scaling, it will also change relative to the viewport size. To get the pixels exactly right, you would have to constantly change the projection, or keep the viewport size fixed. For it to work out as 1:1, if your viewport is x pixels wide, the orthographic projection should be x pixels wide as well.
{ "pile_set_name": "StackExchange" }
Q: Executable file generated using GCC under cygwin I am using Cygwin and have GCC (version 4.3.4 20090804 (release) 1 ) installed as Cygwin package. When I built C code using GCC under Cygwin shell, the generated executable output file is a executable of type (PE32 executable for MS Windows (console) Intel 80386 32-bit) and it can only be executed/run under Cygwin shell, not as standalone .exe on Windows shell/command prompt. If I try to run it standalone on Windows command prompt it gives an error window saying "The program can't run because cygwin.dll is missing from your computer". How can one make this .exe standalone, which can be executed on a command prompt of any other system or even in my own system? I thought GCC under Cygwin would build a Linux executable (ELF 32-bit LSB executable), but it's not so. How can I use the gcc-cygwin combination to generate a *.out kind of Linux executable file? Also, I cannot run a Linux executable generated on a Linux-gcc combination to execute under Cygwin. Any pointers would be helpful. A: Despite widespread rumours, Cygwin is not a Linux emulator, i.e. it doesn't produce or run Linux executables. For that you'll need a virtual machine or coLinux. Instead, Cygwin is a compatibility layer, which aims to implement as much as possible of the POSIX and Linux APIs within Windows. This means that programs have to be compiled specifically for Cygwin, but it also means that it's better integrated with Windows, e.g. it lets you mix POSIX and Windows APIs in the same program. It's the cygwin1.dll that provides that compatibility layer. If you build non-Cygwin executables using gcc-3's -mno-cygwin switch or one of the MinGW compilers, then of course you can't use any POSIX/Linux-specific APIs, and any such calls will need to be replaced with Windows equivalents. A: Cygwin is an emulation layer. It allows UNIX code to run on Windows, if you compile it to use the emulation layer. To Windows it looks like any normal DLL and makes OS calls as normal. But when you compile against it, it shows the same functions as UNIX (well, POSIX technically, but UNIX it is) 1) When you build with cygwin, it automatically brings in this cygwin1.dll. This is the code that you need to make it look like UNIX. There are flags to make it not use this cygwin dll, meaning ignore the UNIX stuff and use native Windows calls. the -mno-cygwin flag will make the binary a native Windows binary, not using cygwin emulation. As others have said, you also need the -mwindows to make actual GUI apps using cygwin gcc. 2) To compile on one platform to run on another platform, you need what's called a cross compiler. You also need the libraries and headers for the other system. For what you want you'd need a cygwin-Linux cross compiler, Linux headers and libraries. It would probably be much easier to run Linux in a virtual machine than to set this up. 3) Remember that Cygwin just looks like UNIX to UNIX source code, not to Linux binaries. Once you compile things, the function calls are windows DLL calls. A cygwin program is still a Windows program (which is why you need a Windows style DLL to run it). Cygwin provides code for UNIX functions/system calls such as fork(), but even the method of calling them is now different. fork() now calls into a Windows DLL, not into a Linux kernel. It's still a very different system. A: Not a complete answer, but I think I am able to give some pointers. 1) http://www.cygwin.com/cygwin-ug-net/programming.html says you should use -mswindows parameter. Take a look of MinGW. 2) You need a cross gcc to do this. By default cygwin gcc produces binaries linked against cygwin.dll. 3) That it because it is a linux binary. Easiest way is to recompile software in cygwin.
{ "pile_set_name": "StackExchange" }
Q: At what point of Game Dev pipeline it is good idea to start adding Oculus Rift Support? I am still in pre-dev phase - creating Assets, editing storyline, doing OOP analysis. I plan to make game in UE 4 and would like for game to have VR support. Would it be good idea to start right away with Oculus Rift(like "mobile first" approach) or add it when I have working game prototype? Thanks A: There is no correct or incorrect answer to this question. There are so many factors to consider, that the only one who can actually answer that question is yourself. Keep the following in mind: The more integrated the headset is into gameplay, the sooner you probably need to add support: Not every game can benefit from a headset, and some are even unplayable with headsets. If the headset is a necessary item to fully experience your game idea, you probably want to add support at the prototype stage. The more complex the assets in your game are, the earlier you want to add support. Rendering stuff for a headset requires you to draw everything twice (or even three times, if you also want a centered POV to display on the non-headset monitor). It would be a huge waste of time if you develop your assets extremely detailed and with very heavy shaders, only to see that when you render them twice, you're getting very poor performance, and then you have to remake everything with less detail. Remember that the headset is not only a display, but a controller that lets you choose the orientation and position of the camera. You should keep this in mind since the very conception of the game, and make sure your game makes sense with such a controller. Headset programming has very high demands on framerate and response time. You may not want to consider this until optimization, but if you're creating the low level aspects of your renderer so you're rendering things a few frames behind they're actually displayed, adding headset support as an afterthought will pose many challenges. (Added from Phillip's comment) Many headset users seem to report that the game taking control of the camera is very uncomfortable. If you're making a game for which you're planning to support headsets, you may want to consider designing it so the game can be played without having the game take control of the camera. (Added from Lars Viklund's comment) Many graphical techniques that look good on a flat display won't look quite as good on a headset. Things like effects, where you can sometimes get away with a billboard in a flat monitor won't necessarily look as good on a headset. Other elements, such as the game GUI may need a complete rethinking when using headsets. A headset will let you move your head around in all directions. This may have an impact on your audio model. Maybe you could get away with a simple stereo audio system when working on a flat screen, but you probably need full 3D audio support if you want your game to be as immersive as possible. All around, headset support, even though programming-wise may be as easy as ticking a checkbox in whatever game engine you use, has very deep implications on gameplay, art and the entire engineering of your game. The earliest you think about all this, and optimally test your ideas with an actual headset, the quicker you will find flaws and be able to solve whatever problems you may find. I believe headset support is something you build your game around, falling back to monitor when no headset is available; not something you add at the very end as an afterthought. Because of this, and -especially- if this is your first headset game, I would recommend you add headset support as early as it is practically possible.
{ "pile_set_name": "StackExchange" }
Q: Как получить данные определенного тега OPC при помощи python? Передо мной встала задача получить данные с OPC-сервера. На машине установлен python 3.7, либу скачивал с гита разработчика mkwiatkowski Я подключил библиотеку OpenOPC. Я могу получить список item, но как обратиться к конкретному значению прибора я не знаю. Вот дерево моего ОРС-сервера Я делал запрос как показано на картинке ниже: На официальном сайте OpenOPC есть пример кода обращения к тегу opc.read('Random.Int4') (19169, 'Good', '06/24/07 15:56:11') Мне не понятно откуда откуда взялось .Int4 Главный мой вопрос состоит в том, как мне обратиться и считать значение например с 'COM4.TRM_210(adr=32)Ср_р-р, 2 зона.Оперативные параметры прибора.Тнэ Зона 2' (Тнэ Зона 2 - это уже само значение). Спасибо Вам! A: помогли коллеги с другого форума. Ответ на мой вопрос: import OpenOPC tagsValue = []; tagsValue.append(opc.list('COM4.TRM_202(adr=104)T_слой_Ср_р-ра.Оперативные параметры')[3]) opc = OpenOPC.client() servers = opc.servers() print(servers) try: opc.connect(servers[0]) except: print("не удалось подключиться к ОРС - серверу") val = opc.read(tagsValue, update=1, include_error=True) print(val) opc.close() Надеюсь кому-нибудь помогу этим.
{ "pile_set_name": "StackExchange" }
Q: how to cmpare the values of Arraylists how can we compare the values of two array lists for example : ArrayList a = new ArrayList<String>(); a.add("1"); a.add("2"); a.add("3"); ArrayList b = new ArrayList<String>(); b.add("3"); b.add("2"); b.add("1"); System.out.println(areEqual(a, b)); should print true , because all values of a are in b. Thanks in advance A: The list interface contains this function boolean containsAll(Collection<?> c) which appears to do what you want. http://download.oracle.com/javase/6/docs/api/java/util/List.html#containsAll(java.util.Collection) A: if ( a.containsAll(b) && (a.size() == b.size() ) ) EDIT: If a contains more elements than b, containsAll will still return true , so if you want to test for absolute equality, then a size comparison is necessary. EDIT #2: This assumes that the a and b contains unique entries. If there were duplicates, like @Robin and @Matti have referred to, it would be much more complicated depending on the OPs definition of equality.
{ "pile_set_name": "StackExchange" }
Q: Show / hide Elements on form submit hello I am a php beginner and I have the following problem with my code, I need to add 2 numbers and echo the result as a 3rd number (sum) The sum number must not be shown before clicking the submit button, only the input boxes for the 2 numbers, and when the sum is displayed the 2 input boxes must be hidden and only the sum shown <html> <body> <form method="post" id="form1"> First Number: <input type="text" name="number1" /><br> Second Number: <input type="text" name="number2" /><br> <input type="submit" name="submit" value="Add" > </form> <?php $number1 = $_POST['number1']; $number2 = $_POST['number2']; $sum = $number1+$number2; echo "Sum = ".$sum; ?> </script> </body> </html> A: You need to check with isset function to understand if the form is submitted or not. Like following, <body> <?php if( !isset($_POST['submit'])){ ?> <form method="post" id="form1"> First Number: <input type="text" name="number1" /><br> Second Number: <input type="text" name="number2" /><br> <input type="submit" name="submit" value="Add" > </form> <?php } ?> <?php if(isset($_POST['submit'])){ $number1 = $_POST['number1']; $number2 = $_POST['number2']; $sum = $number1+$number2; echo "Sum = ".$sum; } ?> </script> </body> </html>
{ "pile_set_name": "StackExchange" }
Q: How are "non-princely" titles assigned to British royals? For instance, Prince William is also "Duke of Cambridge." His grandfather, Prince Philip is Duke of Edinburgh, Earl of Marioneth, and Baron Greenwich, among others. How do they come by these non-royal titles and why? They're all "lesser" than "Prince." A: Royal dukedoms are personal gifts of the British monarch, and traditionally assigned to family members. The titles are not necessarily passed on to the holder's offspring; they may become vacant when the holder dies or accedes to a more senior title. Some titles, such as Duke of Cambridge, are almost entirely honorific. Others come with significant lands and revenues. Prince Charles is Duke of Cornwall; this title comes with 570 km^2 of land, generating an income of £19 million per annum. When the title is vacant, this revenue is collected by the monarch. Having the lands and responsibilities of a dukedom is considered a mark of adulthood. In times past, it would have helped train the holder for other royal duties and perhaps eventually becoming King; and hopefully ensured that the reigning monarch had a reliable manager for a portion of the royal lands. The custom of awarding dukedoms to younger royals is to some extent a relic of this practice. Prior to House of Lords reform in 1999, a royal dukedom entitled the holder to a seat in the upper house of the British Parliament, although in modern times members of the royal family seldom voted or attended debates. After the 1999 reforms, royal dukes no longer have seats in the Lords. Finally, the awarding of titles can symbolise the commitment of the royal family to all parts of the UK. The Duke of Cambridge was until recently a pilot at an air rescue service based in Cambridge; the Duke of Edinburgh has maintained some other ties to the city, for instance serving for many years as Chancellor of Edinburgh University. A: Titles can be passed onto sons. Such titles are in the gift of the Monarch. There is a tradition of awarding a title, usually a Dukedom upon the younger sons of the monarch when they marry. These titles can then be passed down to their children. So Prince Edward, who is also Earl of Wessex, can pass his title on to his son, who is currently styled Viscount Severn. If he hadn't been given the Earldom, his son would not have had a title. The bestowing of several titles on, for example, Prince Phillip, is part of the system. It looks pretty silly from the outside, but I'm told that members of the aristocracy take it seriously, and it would have been considered an insult for him to have received less.
{ "pile_set_name": "StackExchange" }
Q: Erro HTTP Status 405 Servlet Estive fazendo o exercício "5.5 Primeira Servlet" da apostila sobre Java Web FJ21 da Caelum,fiz o código,reiniciei o Tomcat como foi pedido mas quando abro o link "http://localhost:8080/fj21-agenda/oi" para acessar a pagina ocorre o erro: HTTP Status 405 - HTTP method GET is not supported by this URL type Status report message HTTP method GET is not supported by this URL description The specified HTTP method is not allowed for the requested resource. CÓDIGOS: public class OiMundo extends HttpServlet { @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub super.service(request, response); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<head>"); out.println("<title>Primeira Servlet</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>Oi mundo Servlet!</h1>"); out.println("</body>"); out.println("</html>"); }} <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>fj21-agenda</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <servlet> <servlet-name>servletOiMundo</servlet-name> <servlet-class>br.com.caelum.servlet.OiMundo</servlet-class> </servlet> <servlet-mapping> <servlet-name>servletOiMundo</servlet-name> <url-pattern>/oi</url-pattern> </servlet-mapping> </web-app> A: Basta retirar a chamada para a super classe: super.service(request, response); Quando você realiza o override do método service, tudo que você precisa tem de estar dentro do seu override, não é necessário repassar a chamada para o método padrão do HttpServlet.
{ "pile_set_name": "StackExchange" }
Q: No ruby alternatives on 11.04 / 11.10? Running update-alternatives --config ruby fails: # uname -a Linux test06 2.6.38-8-virtual #42-Ubuntu SMP Mon Apr 11 04:06:34 UTC 2011 x86_64 x86_64 x86_64 GNU/Linux # cat /etc/lsb-release DISTRIB_ID=Ubuntu DISTRIB_RELEASE=11.04 DISTRIB_CODENAME=natty DISTRIB_DESCRIPTION="Ubuntu 11.04" # apt-get install ruby1.9.1-full Reading package lists... Done Building dependency tree Reading state information... Done ruby1.9.1-full is already the newest version. 0 upgraded, 0 newly installed, 0 to remove and 25 not upgraded. # update-alternatives --config ruby update-alternatives: error: no alternatives for ruby. # ls -l /etc/alternatives/ru* ls: cannot access /etc/alternatives/ru*: No such file or directory 2 days ago (January 15th, 2012) I wrote a Puppet manifest that used update-alternatives to setup the correct Ruby version. Today, update-alternatives fails as described above. Where did the Ruby alternatives go? A: Well you need more than 1 version of ruby installed for there to possibly be an alternative to "ruby" (generally /usr/bin/ruby If you only have ruby1.9.1 installed, (ruby1.9.X), then there is no alt. available Ex. here on 11.10, - for some media apps I need both 1.9.2 & 1.8 installed so update-alternatives reflects that & allows me to switch as needed $ sudo update-alternatives --config ruby [sudo] password for doug: There are 2 choices for the alternative ruby (providing /usr/bin/ruby). Selection Path Priority Status ------------------------------------------------------------ 0 /usr/bin/ruby1.8 50 auto mode 1 /usr/bin/ruby1.8 50 manual mode * 2 /usr/bin/ruby1.9.1 10 manual mode Press enter to keep the current choice[*], or type selection number: By default in 11.04/11.10 the package "ruby" provides ruby1.8
{ "pile_set_name": "StackExchange" }
Q: Kommaregeln bei doppeldeutigen Sätzen Seit ich in meinen drei Fremdsprachen bis zu den Kommaregeln durchgedrungen bin, vermische ich die Regeln in unterschiedlichen Sprachen, sodass ich mich kaum traue ein Komma zu setzen. Die übelste Verwirrung stiften Sätze nach diesem Muster: Die Orangen die zum Teil verfault waren schenkte er den Kindern. Wie muss ich das Komma setzen, um auszusagen "er verschenkte nur die zum Teil verfaulten"? Wie muss ich das Komma setzen, wenn das teils verfault sein nur Zusatzinformation ist, er aber durchaus auch frische Orangen verschenkte? Ich habe die Kommaregeln gelesen und interpretiere sie so, dass die Interpunktion gleich wäre, was ich nicht glauben kann. A: Doch, es ist so. Im Deutschen gibt es nicht so etwas wie im Englischen, wo das Komma gesetzt wird, wenn es eine (unwichtige) Nebeninformation ist, beziehungsweise wo das Komma weggelassen wird, wenn es eine definierende Funktion hat (defining clause vs non-defining clause)1. In der gesprochenen Sprache existiert das Problem sowieso. Im Englischen kann man zwar theoretisch mit einer Pause das Komma vor einem defining-clause andeuten, aber das heißt nicht, dass es dadurch klar wäre. Deswegen (und unabhängig von der Sprache): Bei einem zweideutigen Satz umformulieren! Klarstellen, wie es gemeint ist. Er schenkte den Kindern die zum Teil verfaulten Orangen. Er schenkte den Kindern Orangen. Einige von denen waren verfault. Bezüglich des Kommas: Die Orangen, die zum Teil verfault waren, schenkte er den Kindern. 1Einige nette Beispiele für's Englische: The passengers who fastened their seatbelts survived. (Which passengers survived? Only the pasengers wearing the seatbelts.) The passengers, who fastened their seatbelts, survived. (Because all the passengers were wearing their seatbelts, they survived.) The students who did all the exercises succeeded. (Which students succeeded? Only the students doing all the exercises.) The students, who did all the exercises, succeeded. (All students succeeded. Why? Because they did all the exercises.) A: Es ist aber so. Relativsätze (und Nebensätze überhaupt) werden im Deutschen immer durch Komma abgetrennt, unabhängig davon, ob sie nur Hintergrundinformationen geben oder eine Einschränkung enthalten. Der Beispielsatz wird daher immer folgendermaßen interpungiert: Die Orangen, die zum Teil verfault waren, schenkte er den Kindern.
{ "pile_set_name": "StackExchange" }
Q: LINQ: Associations not functioning correctly for use with innerjoins Can anyone help, I have been using linq2sql with great success using my associations (foreign keys) to provide inner joins etc... for example this, works great, the color is stored in a table called Color which has association so i pick it up via Color.Description - Excellent. Same for StructureType its actually an association so i pick it up via the structureType association and the field Description which is in the StructureType table from v in Houses select new { Id = v.Id, Color = v.Color.Description, StructureType= v.StructureType.Description, Price = v.StructureGroup.StructureGroupTariffs. // doesn't provide anything more only Any, All etc } The problem being is that Price i am trying to link, so houses has a Association to StructureGroup which has a association to StructureGroupTariffs but i don't get any more options.. StructureGroupTariffs in an Interlinking table that links StuctureGroup to Tariffs, I actually did a test here with the interlinking table in Linq and it works! like so from g in StructureGroupTariffs select new { Price = g.Tariff.Price } So i am a little confused, why (see above) this Price = v.StructureGroup.StructureGroupTariffs. only returns methods like Any, All etc but not the association.... Can anyone help please A: StructureGroupTariffs is an EntitySet not an EntityRef, i.e. it contains many objects rather than a single object. You can't extract the 'many' into the 'single' that you are assembling in your query. EDIT I suspect that your House table has a StructureGroup and that there is a Tariffs table, in between is a StructureGroupTariffs table that holds FK references to each of the other tables allowing there to be many tariffs for each structure group (irrespective of whether there actually are many tariffs). Hence Linq using an EntitySet to refer to the StructureGroupTariffs.
{ "pile_set_name": "StackExchange" }
Q: XAML reuse specific UI elements With Xamarin, I have a small UI element which acts as a content divider: <BoxView StyleClass="contentDivider" HeightRequest="2" WidthRequest="1000" Margin="3, 0"/> Since I use this a number of times I wanted to be able to have the code written down once, and reuse that code - just like a class with its instance (DRY). It's most likely me being a blind bat and not being able to find how it's done. So, how can I reuse XAML elements? A: You can do this with ContentViews (https://docs.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/controls/layouts#contentview), which probably works better for larger reuse cases (using more XAML in the ContentView). Yet, for such a small single element example as yours, you could really just consider using a global style (https://docs.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/styles/xaml/application) which its looks like you already have with StyleClass="contentDivider", as long as you only want to override properties on a single element (like your BoxView). Just add HeightRequest, WidthRequest and Margin to your style and your done. <Style x:Key="contentDivider" TargetType="BoxView"> <Setter Property="HeightRequest" Value="20" /> <Setter Property="WidthRequest" Value="20" /> <Setter Property="Margin" Value="0,99,0,0" /> ... etc </Style>
{ "pile_set_name": "StackExchange" }
Q: "file_get_contents" does not work as expected I setup a function to get the output of another page. But i am only getting back the file contents. I cant figure out why? Here is my code: $from = date('d.m.Y'); $to = date('d.m.Y', strtotime('+30 day', time())); $postdata = http_build_query( array( 'set' => $from, 'to' => $to ) ); $opts = array('http' => array( 'method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => $postdata ) ); $context = stream_context_create($opts); $list = file_get_contents($_SERVER['DOCUMENT_ROOT'] . 'Events.php', false, $context); A: file_get_contents() on filesystem will read the file as a text file. You have to call it through its uri instead to get it to execute. it is not 1 function, but two, alternating what it does given filesystem (pretty much fopen the file, read the entirety of the file, return the content), and what it does given a url (do a GET call on the url, get its contents, return the entirety of its contents) so just replace $_SERVER['DOCUMENT_ROOT'] with $_SERVER['HTTP_HOST'] and you should be ok
{ "pile_set_name": "StackExchange" }
Q: Windows: copy file to new folder if there is no duplicate A month ago I've made a backup of d:\source to f:\backup1 using robocopy: robocopy d:\source\ f:\backup1\ /zb /XJ /COPY:DAT /e /v /R:1 /W:1 Now I want to make a new backup f:\backup2 of d:\source and copy only files that don't exist in f:\backup1 or they have been changed (there is no duplicate in f:\backup1). How to do that using cmd.exe ? A: First run robocopy in list-mode ("dry-run") using the first backup folder to build the list of updated/new files, then manually copy the files from that list one by one: setlocal enableDelayedExpansion set "source=d:\source" set "backup1=f:\backup1" set "backup2=f:\backup2" for /f "tokens=*" %%a in (' robocopy "%source%" "%backup1%" /s /e /njh /njs /nc /ns /ndl /l ') do ( echo %%a set "file=%%a" set "dir=%%~dpa" md "!dir:%source%=%backup2%!" 2>nul copy /y /b "%%a" "!file:%source%=%backup2%!" >nul ) N.B. this simplified code won't handle file names with !
{ "pile_set_name": "StackExchange" }
Q: how to access querystring in ASP.Net MVC View? How do I access the querystring value in a View? A: It is not a good design to access query parameters in a view. The view should use the model provided by the controller. So the controller reads query parameters and passes them to the view. If you want to ignore this rule you could always do this in your view: <%= Request["SomeParameter"] %> But I would strongly discourage you from doing so. A: In View, you can access it directly. No need to write any code in Controller, though you can. For example - If your querystring has parameter named id, something like ?id=1 Razor syntax: @Request.QueryString["id"] A: I would read the querystring value in your Controller, and then set that value to a property in your ViewBag. The ViewBag property can then be read in from your view. e.g: ViewBag.MyQSVal = Request.QueryString["myValue"]; Then, in your View: @if(ViewBag.MyQSVal == "something"){ ... }
{ "pile_set_name": "StackExchange" }
Q: How can I identify open DNS resolvers in my network? This article highlights how open DNS resolvers are being used to create DDOS attacks across the internet. How can I identify whether any of our DNS servers are open? If I find that we are running open DNS servers, how would I close them to prevent them being abused for DDOS attacks? A: An Open DNS server is one that answers DNS requests from anyone for anything. As a general rule, the DNS servers you run should only respond to the requests you want them to. In a typical organisation, for example, you want machines inside your network, such as your laptop to be able to resolve anything, and machine outside your network to only be able to resolve your public facing services, such as your web server and inbound mail. Of course, your organisation might not be typical. To identify if your DNS servers are responding to requests you don't want them to, make such requests and see what happens! Using a machine outside your network, point a copy of dig at your resolvers, and try querying things. To secure your DNS servers, consult the documentation for your particular brand of DNS server, and configure them to do what you want. A: Identify an Open DNS server by your own querying via NMAP: x.x.x.x = DNS server IP nmap -sU -p 53 -sV -P0 --script "dns-recursion" x.x.x.x Possible output would be: PORT STATE SERVICE VERSION 53/udp open domain ISC BIND "version" *|_dns-recursion: Recursion appears to be enabled* Online services: If you prefer make use of online services, openresolver project is very good, it checks also subnets of /22 width, so check it out ---> http://www.openresolverproject.org After an Open DNS server discovery with online tools is a good idea to do a double check getting a proof about recursion ---> http://www.kloth.net/services/dig.php Example output, watch the "ra" flag means recursion available: ; <<>> DiG 9.7.3 <<>> @x.x.x.x domain.cn A ; (1 server found) ;; global options: +cmd ;; Got answer: ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: xxx ;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 5, ADDITIONAL: 0 DISABLING RECURSION (source knowledgelayer softlayer com) Disable Recursion in Windows Server 2003 and 2008 Access the DNS Manager from the Start menu: Click the Start button. Select Administrative Tools. Select DNS. Right click on the desired DNS Server in the Console Tree. Select the Proprerties tab. Click the Advanced button in the Server Options section. Select the Disable Recursion checkbox. Click the OK button. Disable Recursion in Linux Locate the BIND configuration file within the operating system. The BIND configuration file is usually located in one of the following paths: /etc/bind/named.conf /etc/named.conf Open the named.conf file in your preferred editor. Add the following details to the Options section: allow-transfer {"none";}; allow-recursion {"none";}; recursion no; Restart the device. A: There are a few sites out there that scan the internet for open DNS resolvers and publish lists of them to help ISP's detect and shut down the resolvers. Here is one, you can use it to search for ip's whithin your network that are open resolvers: http://dns.measurement-factory.com/surveys/openresolvers.html As for secureing them it's fairly simple - just restrict the dns resolvers to only allow queries from inside your network. Either configure the dns to only reply queries from addresses that are inside your network, or use firewall/packet filter rules to restrict access to port 53. Team Cymru has a guide here: http://www.team-cymru.org/Services/Resolvers/instructions.html Just make sure you don't filter out your authoritative nameservers, the internet needs to reach those for your domains to work!
{ "pile_set_name": "StackExchange" }
Q: Elasticsearch: bulk update multiple documents saved in a Java String? I can create the following string saved in a Java String object called updates. { "update":{ "_index":"myindex", "_type":"order", "_id":"1"} } { "doc":{"field1" : "aaa", "field2" : "value2" }} { "update":{ "_index":"myindex", "_type":"order", "_id":"2"} } { "doc":{"field1" : "bbb", "field2" : "value2" }} { "update":{ "_index":"myindex", "_type":"order", "_id":"3"} } { "doc":{"field1" : "ccc", "field2" : "value2" }} Now I want to do bullk update within a Java program: Client client = getClient(); //TransportClient BulkRequestBuilder bulkRequest = client.prepareBulk(); //?? how to attach updates variable to bulkRequest? BulkResponse bulkResponse = bulkRequest.execute().actionGet(); I am unable to find a way to attach the above updates variable to bulkRequest before execute. I notice that I am able to add UpdateRequest object to bulkRequest, but it seems to add only one document one time. As indicated above, I have multiple to-be-updated document in one string. Can someone enlighten me on this? I have a gut feel that I may do things wrong way. Thanks and regards. A: The following code should work fine for you. For each document updation , you need to create a separate update request as below and keep on adding it to the bulk requests. Once the bulk requests is ready , execute a get on it. JSONObject obj = new JSONObject(); obj.put("field1" , "value1"); obj.put("field2" , "value2"); UpdateRequest updateRequest = new UpdateRequest(index, indexType, id1).doc(obj.toString()); BulkRequestBuilder bulkRequest = client.prepareBulk(); bulkRequest.add(updateRequest); obj = new JSONObject(); obj.put("fieldX" , "value1"); obj.put("fieldY" , "value2"); updateRequest = new UpdateRequest(index, indexType, id2).doc(obj.toString()); bulkRequest = client.prepareBulk(); bulkRequest.add(updateRequest); bulkRequest.execute().actionGet();
{ "pile_set_name": "StackExchange" }
Q: Can't configure gr-ais http://www.reddit.com/r/RTLSDR/comments/1mcikt/for_the_nautical_set_rtlsdr_with_grais_and_opencpn/ following the above, I get this error scott@scott-P5QC:~/gr-ais/build$ cmake ../ -- Build type not specified: defaulting to release. -- Boost version: 1.54.0 -- Found the following Boost libraries: -- filesystem -- system -- Found Doxygen: /usr/bin/doxygen (found version "1.8.6") CMake Error at CMakeLists.txt:94 (find_package): Could not find a configuration file for package "Gnuradio" that is compatible with requested version "3.7.6". The following configuration files were considered but not accepted: /usr/lib/x86_64-linux-gnu/cmake/gnuradio/GnuradioConfig.cmake, version: 3.7.2.1 -- Configuring incomplete, errors occurred! See also "/home/scott/gr-ais/build/CMakeFiles/CMakeOutput.log". scott@scott-P5QC:~/gr-ais/build$ A: The application that you're trying to build requires Gnuradio 3.7.6 but only 3.7.2 is available from Ubuntu repositories on a 14.04 system. You'll have to build Gnuradio from source: Open a terminal window, move to the directory you would like the source files to be stored (e.g. cd src/), remove old build-gnuradio file, and run this command: $ wget http://www.sbrac.org/files/build-gnuradio && chmod a+x ./build-gnuradio && ./build-gnuradio Source: Installing GNU Radio From Source
{ "pile_set_name": "StackExchange" }
Q: App to make a video from photos? I was wondering what could be a good app (with a GUI ;) ) for making a video from a bunch of photos or images, to create a time-lapse video, or a stop-motion animation, or even a video like this one. The idea is to set a really small time between each photo, but also to be able to change this time every so often, or add some effects, to make the succession smoother in particular. What would be perfect is a function that allows automatic cropping of the photos as well as exposure adjustment so they all have the same background and so the time-lapse video looks smoother. I know about the slide show app "Imagination" but the interval can not go under one second. Edit: here is my progress, also thanks to the first answer: I tried Luciole, it is really simple and promising, but pretty buggy, and I only could export an average video in .dv format (mpg2 and avi don't work). Apparently, it has difficulties when changing the fps. I also tried StopMotion: also pretty buggy, I had to go into preferences and modify the encoding commands to get a result, but it's the best result I got so far. But none of those has effects to make transitions smoother... I tried several diaporama apps: Imagination doesn't handle more than 1 image per second; PhotoFilmStrip (repo version and latest version from website): same problem even though you can go down to 0.1 second per image, it still behaves wierdly (going back to 1 second automatically); Videoporama: doesn't start at all on 12.04. Any other suggestions? A: ffDiaporama Movie Creator seems to be another excellent option for your needs. From the site: ffDiaporama is an application for creating video sequences consisting of titles, fixed or animated. images or photos, fixed or animated. movie clips music These sequences are assembled into a slide show by means of transitions of sequence to produce complete videos The following options are available: Refocusing of images and photos Cutting of video clips Notes (addition of text) for images, photos, sequences and animations Graphical filters on the images and the videos (conversion into black and white, dust removal, equalization of colors, etc.) Creation of animation by zoom, rotation or Ken Burns Effect on images or photos Correction of the images and the videos during animations (luminosity, contrast, gamma, colors, etc.) Transitions between sequences with definition of the transition type, sequence by sequence. Addition of a background sound (wav, mp3 or ogg) with customizable effects for volume, fade in/out and passage in pause, sequence by sequence. Generation of usable videos for most current video equipment (DVD player/smartphone, multimedia box, hard drive, etc.) but also publishable on the main video-sharing Websites (YouTube, Dailymotion, etc.) Video formats from QVGA (320×240) to Full HD (1920×1080) by way of the DVD and HD 720 formats. Image geometry (aspect ratio) : 4:3, 16:9 or 2.35:1 (cinema) Possible formats for rendering : avi, mpg, mp4, mkv Here are a couple of screenshots from my desktop: This is the main GUI with the timeline and all the toolbars shown. This is the "Slide Properties" Window, on which you can define certain parameters, such as the slide duration, pan, crop and other properties. You can access this feature by double-clicking on the slide when in the timeline. You may also wish to take a look at this answer: https://askubuntu.com/a/124848/9598 on which I explain a way to do some pro-style videos with kdenlive Good luck! A: Another option is OpenShot video editor. It is in the repositories. File > Import Image Sequence
{ "pile_set_name": "StackExchange" }
Q: Using Neo4j and Lucene in a distributed system I am looking into Neo4j as a stripped-down document store. A key aspect of document storage is search, and I know Neo4j includes full text search via legacy indices provided by Lucene. I would be very interested in hearing the limitations of Neo4j search capabilities in a distributed environment. Does it provide a distributed index? In what ways is it inferior to Solr or ElasticSearch? How far can I take it before I must install Solr? -- EDIT -- We are trying to integrate two distinct search efforts. The first is standard text content search. For instance, using the Enron emails, we want to search for every email that matches "bananas" or "going to the store" and get those document bodies in response. This is where people often turn to Solr. The second case is more complicated, we have attached a great deal of meta-data to each document. We may have decided that "these" emails were the result of late-night drunk-dialing. Now I want to search for all emails that may have been the result of late-night drunk-dialing. For this kind of meta-data, we believe a graph database is in order. In a perfect world, I can use one platform to perform both queries. I appreciate that Neo4j (nor OrientDB, Arango, etc) are designed as full text search databases, but I'm trying to understand the limitations thereof. In terms of volume, we are dealing at a very large scale with batch-style nightly updates. The data is content heavy, with some documents running into hundreds of pages of text, but mostly on the order of a page or two. A: I once worked on a health social network where we needed some sort of search and connection search functionalities we first went on neo4j we were very impressed by the cypher query language we could get and express any request however when you throw there billion of nodes you start to pay the price and we started considering another graph db, this time we've made a lot of research, tests and OrientDB was clearly the winner, OrientDB is highly scalable but the thing is that you have to code by yourself, your "search algorithm" if you want to do some advanced things (what is the common point between this two nodes) otherwise you have the SQL like query language (i don't know/remember if he has a name) but you can do some interesting stuff with it So in conclusion i would definitely go on OrientDB
{ "pile_set_name": "StackExchange" }
Q: Azure DevOps: docker-compose over SSH normal messages interpreted as error docker-compose, normal messages interpreted as errors in Azure DevOps I have Release pipeline in Azure DevOps where I'm connecting to to server trough SSH and running docker-compose up command along with others. Problem is that normal messages are interpreted as errors so release fails even when everything was successful. After this release everything is up and running. Does anyone know why these messages were interpreted as errors? A: I found out that docker writes those messages to stderr instead of stdout. In Azure DevOps pipeline in SSH task there is option Fail on STDERR which is checked by default. When I uncheck this option release no longer fails on this step even messages are marked as error. What really bothers me is that now even when some real error occurs, it will be ignored. I really don't know why they designed is like this, but that's for another topic. Links: https://github.com/docker/compose/issues/5296
{ "pile_set_name": "StackExchange" }
Q: Is it worth collecting jQuery-related scripts to run them at the end of the document? I want to place jQuery just before the closing </body>-Tag like it's recommended. But because I'm using a Content Management System, inline scripts that require jQuery will be executed before the closing body tag. My question now is: Is it worth to collect jQuery-based scripts in an array and run them at the end of the document when jQuery is loaded (EXAMPLE) OR just load jQuery in the head section? A: You could adopt the approach described here the idea is to create a q global variable soon in the header and use a temporary window.$ function to collect all the code/functions/plugin jQuery dependent. window.q=[]; window.$=function(f){ q.push(f); }; and after you load jQuery you will pass all the functions to the real $.ready function. $.each(q,function(index,f){ $(f) }); in this way you will be able to safely include your jquery code before the jQuery lib inclusion If this could be better than loading jQuery in the head it may depends on how much code you have to push into q temporary function. jQuery placed into <head> section would require a single blocking script. But if you have much code to inject everywhere inside the document you may have a lot of huge blocking scripts that stop the rendering process. On the contrary loading a lot of scripts after dom ready event it could easily make your page faster to load so this approach it's better and the benefits can be more evident. So there's no a definitive answer valid for all code and all pages: even if this kind of technique anyway is generally good and preferable (because you have the benefit of a as-later-as-possible script execution), you should ever make some test with both the approaches and look at loading and rendering time. The article at the beginning has some consideration on the performance but also explains why stackoverflow didn't use it.
{ "pile_set_name": "StackExchange" }
Q: csrf error when using django-registration Am using django-registration for user account activation. in my registration_form.html I have {% extends "base.html" %} {% block title %} Register {% endblock %} {% load i18n %} {% block menu %} <li class="home-page"><a href="/utriga"><span></span></a></li> <li><a href="/utriga/about">About Us</a></li> <li><a href="/utriga/downloads">Downloads</a></li> <li><a href="/utriga/blog">Blog</a></li> <li class="current " ><a href="/utriga/post">Advertise</a></li> <li><a href="/utriga/contact">Contact Us</a></li> {% endblock %} {% block content %} <form method="post" action="."> {{ form.as_p }} <input type="submit" value="{% trans 'Submit' %}" /> </form> {% endblock %} The problem is that it worked for a while and then stopped, Giving the error page. Forbidden (403) CSRF verification failed. Request aborted. Help Reason given for failure: CSRF token missing or incorrect. I dont understand why it worked before and stopped even though I changed nothing. Is load i18n, the problem ? Help please A: You are missing the csrf token in the form. Place {% csrf_token %} inside the form and see if it works.
{ "pile_set_name": "StackExchange" }
Q: Dificuldade na metodologia de programação e migração do mysqli para o PDO Olá, pessoal. Sempre programei na parte do Back-End (com PHP) utilizando o mysqli, porém após ler alguns artigos e comentários, cheguei a conclusão que preciso mudar minha método de programar para o PDO (Por motivos de Segurança e organização dos códigos) e futuramente passar a utilizar o paradigma de Orientação à Objetos, ao invés do meu já tradicional padrão estruturado. Minha dúvida é a seguinte, sempre fiz o código com mysqli da forma abaixo: <?php //SELECT QUE RETORNA OS DADOS PARA O AJAX $select_empresas = "SELECT * from tbl_lista_empresas order by EMPRESA"; $lista_empresas = mysqli_query($conecta, $select_empresas); if(!$lista_empresas) { die("Erro no Banco - Erro no Select na tabela lista_empresas"); exit; } $retorno_empresas = array(); //PASSANDO OS DADOS DO SELECT PARA UM ARRAY while($linha_empresas = mysqli_fetch_object($lista_empresas)) { $retorno_empresas[] = $linha_empresas; } echo json_encode($retorno_empresas); ?> Geralmente recebo uma requisição do AJAX, e (quase sempre é desse mesma forma), realizo uma consulta no PHP com mysqli, passo o resultado da consulta para um ARRAY e retorno o resultado da consulta para o AJAX no formato JSON. E assim eu recebo os dados no AJAX //Função que faz a alteração dos dados do funcionário function alterar_empresas(alterarempresas) { $.ajax({ url: "../banco/banco-sistema/pagina-cadastrar-empresas/alterar-empresas.php", type: "post", data: alterarempresas.serialize(), cache: false }).done(function(retornoempresas) { $.each($.parseJSON(retornoempresas), function(chave, valor) { $("input#cod").val(valor.COD); $("input#empresa").val(valor.EMPRESA); $("select#tributacao").val(valor.TRIBUTACAO); }); }).fail(function() { console.log("Erro ao atualizar"); }).always(function(retornoempresas) { console.log(retornoempresas); }); } Basicamente sempre utilizo esse padrão de programação. Minha dúvida talvez seja simples pra vocês, como eu faria esse mesmo processo no PHP utilizando PDO e como eu pegaria esses dados no retorno do AJAX (presumo que seja da mesma forma no AJAX). Minha dúvida é principalmente na parte do While no PHP. Obrigado! A: Não existe muito mistério. //Abre a conexão $PDO = db_connect(); //SQL para contar o total de registros $sql_count = "SELECT COUNT(*) AS total FROM users ORDER BY name ASC"; //SQL para selecionar os registros $sql = "SELECT id, name, email, gender, birthdate FROM users ORDER BY name ASC"; //Conta o total de registros. $stmt_count = $PDO->prepare($sql_count); $stmt_count->execute(); $total = $stmt_count->fetchColumn(); //Seleciona os registros $stmt = $PDO->prepare($sql); $stmt->execute(); //Lista os usuário while ($user = $stmt->fetch(PDO::FETCH_ASSOC)){ echo $user['email'] } Créditos: https://github.com/marciellioliveira/crud-php-pdo/blob/master/index.php
{ "pile_set_name": "StackExchange" }
Q: Exim - handling email from multiple domains as one My local registrar allows registration of domains ending with .com.uy and has recently started offering .uy domains (freely offering .uy addresses to their existing .com.uy customers). In my case, I own two domains, namely domain.com.uy and domain.uy. Email is currently working nicely at @domain.uy on my server, which currently has SPF, DKIM and DMARC setup. A SSL cert has been setup for that and so far exim4 is working flawlessly. However, I would like users to be able to receive emails on their inbox regardless of whether emails are being sent to the .com.uy or the .uy version. Bob, whose email address is [email protected], would start receiving emails sent to [email protected]. Outgoing email should work the way it currently does (ie appear as [email protected]). My question is, what is the appropriate way of allowing users to receive emails regardless of which hostname email is being sent ([email protected] should be the same as [email protected] in terms of email reception). I have been reading about Address Rewriting not because I've been suggested to but because I thought it could work. However, I haven't changed anything yet because I would like to get some opinions on that. I also have read this but did not really understand it. I would like this to be server side(not requiring configuration on the end user), server wide (i.e. not requiring per-user configuration) and clean enough to avoid any possible problems with SPAM filters. I have root SSH access to the server and full control on its DNS records. Thanks in advance Edit: Aparently adding a rewrite in exim.conf works as expected when sending emails from my domain.uy but is currently failing with remote emails. [001.641] ~~> RCPT TO:<[email protected]> [002.307] <~~ 550-Please turn on SMTP Authentication in your mail client. www3.checktls.com 550-(checktls.com) [69.61.187.232]:59092 is not permitted to relay through this 550 server without authentication. [002.307] Cannot proof e-mail address (reason: RCPT TO rejected) Sorted it out by adding my domain to the list of domains. A: Rewrite does exactly what you want. Respectively to the flags all mentions of one domain in the message will be replaced by the other domain. That behavior can be simulated by redirect router that remove and add the headers, result will be exactly the same.
{ "pile_set_name": "StackExchange" }
Q: How can I manipulate the DOM after my directive's content has been loaded on the page? I am writing my own chat interface, to help me better understand angularJs and socket.io. My chat window is fixed, with overflow set to auto. I am using the following directive to manipulate the DOM to scroll, so that as each message is pushed onto the model array, it will be visible at the bottom of the window. app.directive('plnkScroll', [function () { return { restrict: 'A', link: function (scope, element, attrs) { angular.element(element)[0].scrollIntoView(); } }; }]); In theory, this works. However, if the message is long enough to take up more than one line, it does not scroll so that the entire line is clearly visible. This is because the scrollIntoView method is being executed on the DOM while the angular expression has yet to be evaluated (in this case, {{item.text}}) Is it possible to execute this function after the Angular expression has been evaluated and the model data has been injected into the DOM? here is my plunker, to help illustrate what I am doing. p.s. using jQuery is not an option for me, I would like to do things "the angular way". A: your can use $timeout excute your code after directive element append to parent. app.directive('plnkScroll', ['$timeout',function ($timeout) { return { restrict: 'A', link: function (scope, element, attrs) { $timeout(function(){ angular.element(element)[0].scrollIntoView(); },50); } }; }]);
{ "pile_set_name": "StackExchange" }
Q: Default pure virtual implementation C++ Possible Duplicate: pure virtual function with implementation I have a base class which has a function called time(). My idea is to have a pure virtual function which all the classes that inherits from it must implement. However I also want to add the default behavior; Whoever calls time() function needs to print "hello". Is that possible? A: The easiest way to achieve something like this would be to have something like the following: class base { virtual void time_impl()=0; public: void time() { //Default behaviour std::cout << "Hello\n"; //Call overridden behaviour time_impl(); } }; class child : public base { void time_impl() override { //Functionality } }; This way, when any child's time function is called, it calls the base classes time function, which does the default behaviour, and then make the virtual call to the overridden behaviour. EDIT: As Als says in the comments, this is called the Template method pattern which you can read about here: http://en.wikipedia.org/wiki/Template_method_pattern Althought for C++ that is a rather confusing name (as templates are something else, and "methods" don't mean anything in C++ (rather member function). EDIT: Someone commented about the use of override, this is a C++11 feature, if you have it USE IT, it will save many headaches in the long run: http://en.wikipedia.org/wiki/C%2B%2B11#Explicit_overrides_and_final And also, the _impl function should be private, UNLESS you want the user to be to bypass the default behaviour, but I would argue that's a poor design in most use-cases. Working test case http://ideone.com/eZBpyX
{ "pile_set_name": "StackExchange" }
Q: How to "Scroll To Top" in Native Base Component? I'm using Expo and implement Native Base on it, I'm trying to do "Scroll to Top" whenever "MainTabNavigator" Icon <Ionicons/> Should the handle implemented in <Content>or in the <Ionicons/> (in MainTabNavigator)? A: try this <Container> <Content ref={c => (this.component = c)}> <Text style={styles.text}>test</Text> <Text style={styles.text}>test</Text> <Text style={styles.text}>test</Text> ... ... ... ... <Button onPress={() => this.component._root.scrollToPosition(0, 0)}> <Text>Back to top</Text> </Button> </Content> </Container>
{ "pile_set_name": "StackExchange" }
Q: excel check whether a combination of cells in a row exists in a range I've looked around and I can't find it. So lets say I have an array of these unique strings: Dim uniques(10) As String Now each of these Strings are represented in the A column on the spreadsheet. Also I have a range of Integers going from 1 - 365 representing unique values in column B. The ith day i My conundrum is: I want to know whether there exists a row where A is uniques(1) and b is i and I want to itterate this process through all uniques and all possible i's I'm looking for an efficient way to do this, anything better than looping through the range in question, for each unique, for each day. For the record my actual data is counting every day of the year and the number of days since a certain event has happened so my number of rows can grow as large as 365^2 and maybe even more if the event happened more than a year ago. COUNTIFS seems to work pretty good. I wish I I could just go: numOfOccurences = Sheet1.Countifs(countrange,dayrange,uniques(1),irange,i) And if numOfOccurences is greater than 0 then I know it exists. Or is there a function that breaks a Range into rows in a vba array? So that it looks like this {[A2,B2],[A3,B3],...} I could do some damage with that because both the columns come sorted, A then B. I'm just not looking forward to making the function myself. All ideas are appreciated A: Something like this works. It might not be optimal but shows how to iterate through the rows in a range: Sub test() Dim count As Long, i As Long Dim myRow As Range Dim uniques As Variant uniques = Array("a", "b", "c", "d", "e", "f", "g", "h", "i") 'for example i = 12 'for example For Each myRow In Range("A1:B365").Rows If myRow.Cells(1, 1).Value = uniques(1) And myRow.Cells(1, 2).Value = i Then count = count + 1 End If Next myRow MsgBoxS count End Sub
{ "pile_set_name": "StackExchange" }
Q: Return multiple variables in a loop using dict() I have edited the previous section, anything under the line below has been answered and is outdated now: def foo(): x = dict() i = 0 while i < 10: x[i] = i*2 i + = 1 yield x[i] How do I call a specific instance of x[i] in a new function? def foo(): x = dict() i = 0 while i < 10: x[i] = i*2 i + = 1 return x[i] I want this to return x[1],x[2],x[3]...x[10], but right now it only returns the final variable. The reason I want to do this is because in my actual code, I won't know how many times the loop will iterate def main(): variable = foo() print variable I'm just using this to prove to myself that it returned some values A: For that, consider using the yield expression: def foo(): x = dict() i = 0 while i < 10: x[i] = x*2 i += 1 yield x[i] for i in foo(): print i As @Ismail said, it should be i += 1 not x += 1 Also, what is x*2 supposed to do? Did you mean i*2? Example of using the yield expression def next_one(i,n): while i < n: yield i i += 1 >>> for i in next_one(1,10): ... print i ... 1 2 3 4 5 6 7 8 9 [Answer to question update] You could do it something as follows using the next() operator: def next_one(i,n): while i < n: yield i i += 1 def main(variable): print next(variable) variable = next_one(1,10) main(variable) main(variable) main(variable) [OUTPUT] 1 2 3 Demo: http://repl.it/R6J
{ "pile_set_name": "StackExchange" }
Q: Auto-generate VB.NET forms using SQL Server 2008 I want to automatically generate VB.NET forms using tables from a SQL Server database (one form / database table). It is perhaps possible with writing custom custom code for it, but if there is already some feature that does the job that would be great (database has 40+ tables, manually doing this is a tedious task). Any answers, help, links, tips is greatly appreciated. Regards, Ayub A: It takes just a minute to fix, all functionality allready exists in Visual Studio. Fire up Visual Studio, click on Add new datasource... to start the Data Source Configuration Wizard: Select Database and follow the wizard: When connected to the database, select the tables you are interrested in and press the Finnish button: Now, this will create a strongly named dataset in your solution, if you double click the xsd file you'll see the tables you selected in the schema editor, but leave that for now: Now, select "Show Data Sources" from the data-menu and you will see all tables you selected in the wizard. To the left of each field its an icon that tells what type of control that field will be represented by on the resulting form: Now you can deside how the data will be presented on the form, as a datagridview or in detail mode, just use the dropdown on the table name (only when in form-design-mode). If you have selected details-mode on the table, then you can change what control the field will be represented by (must be in form-design-mode, not code-mode): Then just drag the table from the data source view to an empty form and it will magically create controls to edit/add/delete and move around the data. This is the result if DataGridView-mode was selected: And if Details was selected on the table: In code behind it also magically add some code to load the data to the adapter when the form loads and some save/validating code: Private Sub AccountBindingNavigatorSaveItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AccountBindingNavigatorSaveItem.Click Me.Validate() Me.AccountBindingSource.EndEdit() Me.AccountTableAdapter.Update(Me.MyDBDataSet.Account) End Sub Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 'TODO: This line of code loads data into the 'MyDBDataSet.Account' table. You can move, or remove it, as needed. Me.AccountTableAdapter.Fill(Me.MyDBDataSet.Account) End Sub
{ "pile_set_name": "StackExchange" }
Q: Jasmine + Angular module constants I have one Angular application,where I have defined constants for application. var module=angular.module('abc'); module.constant('constants',{ INTERNAL_VALUE:1 }); in my controller I have written below lines if(someService.getInternalValue() === constants.INTERNAL_VALUE){ $scope.showDropdown=true; someservice.somefunction().then(function(data){ $scope.dropDownData=data; }); }else{ $scope.showDropdown=false; } I have written jasmine test case for if condition but it always went to else condition. it('should show dropdown on user persmission',inject(function($controller){ spyOn(someServiceMock,'getInternalValue').andCallFake(function(){ return 1; }); expect(someServiceMock.getInternalValue()).toBe(1); // passed expect(constants.INTERNAL_VALUE).toBe(1);// passed expect(scope.showDropdown).toBe(true); // here it should be true but I am getting "Expected false to be true." error })); When I have done some RnD then I came to know that it's happening because of constants. I think constants are not injected properly Can anyone had faced this issue? Please share your thoughts on this. A: The problem is, your spyOn method is get called after the controller's if statement would be executed. So you need to put spyOn call before that execution. Move the spyOn execution from it block to beforeEach block.
{ "pile_set_name": "StackExchange" }
Q: Python modules confusion I feel a bit confused with how python modules work when I started looking at PyMySQL repository, see here: https://github.com/PyMySQL/PyMySQL?files=1 1) Why is there no pymysql.py file because it is imported like: import pymysql? Isnt it required to have such a file? 2) I cannot find the method connect, used like: pymysql.connect(...), anywhere. Is it possible to rename exported methods somehow? A: There's a directory pymysql there. A directory can also be imported as a module*, with the advantage that it can contain submodules. Classically, there's a __init__.py file in the directory that controls what's in the top-level pymysql.* namespace. So, the connect method you're missing will either be defined directly in pymysql/__init__.py, or defined in one of its siblings in that directory, and then imported from there by pymysql/__init__.py. *Strictly speaking, a directory that you import like a module is really called a "package". I like to avoid that term—it's potentially confusing because the term is overloaded: what you install with pip is also called a "package" in sense 2, and that might actually contain multiple "packages" in sense 1. See What is __init__.py for? and the official docs
{ "pile_set_name": "StackExchange" }
Q: Python: use generators to print 2d array I am new in python and I wanted to create a 2D array and print that one later. self.values = [[0 for k in range(8)] for i in range(8)] I've overwritten the __str__(self) method: def __str__(self): s = (x.__str__() + "\n" for x in self.values).__str__() return s def __repr__(self): return self.__str__() The question is about the line, where i create the variable s. I've tried a few things: s = (x.__str__() + "\n" for x in self.values).__str__() s = str((x + "\n" for x in self.values)) s = list((x.__str__() + "\n" for x in self.values)) In each case, I understand why it does not work but I can't find a way how this could work. I am very happy if someone could show a way to use generators to create the string. Greetings, Finn A: You're obtaining a generator that will create a list that looks somewhat like ["1\n", "2\n"]. You probably want to join that list: ''.join(s) As join allows you to specify the joining string, you can leave out the + "\n" from the generator as well and do: return '\n'.join(str(x) for x in self.values) See also https://docs.python.org/3.7/library/stdtypes.html?highlight=join#str.join
{ "pile_set_name": "StackExchange" }
Q: Save multiple models in loopback I'm doing research on loopback and was wondering if it's possible to save to multiple models from one request. Say.. an Post has many Tags with many Images. A user form would have the following: Post Title Post Description Tag Names (A multi field. E.g.: ['Sci-Fi', 'Fiction', 'BestSeller'] Image File (Hoping to process the file uploaded to AWS, maybe with skipper-s3?) How would I be able to persist on multiple models like this? Is this something you do with a hook? A: You can create RemoteMethods in a Model, which can define parameters, so in your example you could create something like this in your Post model: // remote method, defined below Post.SaveFull = function(title, description, tags, imageUrl, cb) { var models = Post.app.Models; // provides access to your other models, like 'Tags' Post.create({"title": title, "description": description}, function(createdPost) { foreach(tag in tags) { // do something with models.Tags } // do something with the image // callback at the end cb(null, {}); // whatever you want to return }) } Post.remoteMethod( 'SaveFull', { accepts: [ {arg: 'title', type: 'string'}, {arg: 'description', type: 'string'}, {arg: 'tags', type: 'object'}, {arg: 'imageUrl', type: 'string'} ], returns: {arg: 'Post', type: 'object'} } );
{ "pile_set_name": "StackExchange" }
Q: How to create procedurally generated surface bubbles on a liquid I am trying to procedurally generated surface bubbles on coffee. I know that you can use a UV map to do this, but I'd like to have more control. There is a nice demo of doing this with animation is 3ds Max, but I haven't worked out a way to do it in Blender. http://www.3dtotal.com/tutorial/1878-creating-and-animating-bubbles-3ds-max-misc-by-alvaro-moreira-particle-flow-frost I have tried using metaballs, but without much success. Here is the look I'd like simulate. A: The new microdisplacment feature can help with that. Here is a simple node setup as a proof of concept: After duplicating this effect a couple of time you can obtain that:
{ "pile_set_name": "StackExchange" }
Q: Adjusting brand logo for different devices in Bootstrap 3 I have the following code in my setup. The logo appears normal on my desktop, but on my phone I see two logos: 1 normally as I want it (top right) and another in the top-middle. <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> <span class="sr-only">Toggle navigation</span> <a href="http://example"><img class="logo" src="<?php echo base_url();?>resources/example.png"></a> </button> <a class="navbar-brand" href="http://example.com"><img src="<?php echo base_url();?>resources//example.png"></a> </div> A: That's because you have the same image duplicated showing for when you're on a mobile device. This code :- <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> <span class="sr-only">Toggle navigation</span> <a href="http://example"><img class="logo" src="<?php echo base_url();?>resources/example.png"></a> </button> Is for the icon that shows to open the menu on a navbar when on a mobile device. It's usually a burger icon (http://cdn.css-tricks.com/wp-content/uploads/2012/10/threelines.png). If you change the markup above to this :- <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> Then it will go back to the normal burger icon. Unless you're wanting your logo to be the menu button? If so, you'll need to make a media query in CSS to not show the other logo when on a mobile device. But I wouldn't suggest this, as people wouldn't know that clicking the logo on a mobile device will actually show a navigation menu.. Hope this helps.
{ "pile_set_name": "StackExchange" }
Q: Symfony Validator for Alphanumeric I am trying to only allow alphanumeric fields for a first name using: patientFirstName: - NotBlank: ~ - Regex: pattern: "/[^a-z_\-0-9]/i" htmlPattern: "^[a-zA-Z\-0-9]+$" message: Name must be alphanumeric However it is still allowing characters like "&&&". Is my regex wrong? A: Symfony 3 If you do not want to use regex, you can use @Assert\Type for validator alphanumeric You can see it in the symfony doc here @Assert\Type(type="alnum") A: You are missing ^, $ and + (just like your html pattern): /^[a-z\-0-9]+$/i If you do not add them, the regex will match any string if it contains at least one alphanumeric character.
{ "pile_set_name": "StackExchange" }
Q: Convert .txt to .csv in shell I have a text file: ifile.txt 1 4 22.0 3.3 2.3 2 2 34.1 5.4 2.3 3 2 33.0 34.0 2.3 4 12 3.0 43.0 4.4 I would like to convert it to a csv file: ofile.txt ID,No,A,B,C 1,4,22.0,3.3,2.3 2,2,34.1,5.4,2.3 3,2,33.0,34.0,2.3 4,12,3.0,43.0,4.4 I was trying with this, but not getting the result. (echo "ID,No,A,B,C" ; cat ifile.txt) | sed 's/<space>/<comma>/g' > ofile.csv A: Only sed and nothing else sed 's/ \+/,/g' ifile.txt > ofile.csv cat ofile.csv 1,4,22.0,3.3,2.3 2,2,34.1,5.4,2.3 3,2,33.0,34.0,2.3 4,12,3.0,43.0,4.4 A: awk may be a bit of an overkill here. IMHO, using tr for straight-forward substitutions like this is much simpler: $ cat ifile.txt | tr -s '[:blank:]' ',' > ofile.txt A: here is the awk version awk 'BEGIN{print "ID,No,A,B,C"}{print $1","$2","$3","$4","$5}' ifile.txt output: ID,No,A,B,C 1,4,22.0,3.3,2.3 2,2,34.1,5.4,2.3 3,2,33.0,34.0,2.3 4,12,3.0,43.0,4.4
{ "pile_set_name": "StackExchange" }
Q: How to get vertex connected (there is a path) to 3 vertices I'm trying to build a graph to store temporal change of users friends. In the graph below I want to get all followers, who follow both V1 and V2 (intersection) for a particular date (d1), that is vertex v3 as it's connected both to v1 and v2 for d1 I tried to start the query from v2<-follows-t2<-follows<-x->follows->t1-follows->v1, but I don't know how to connect the d1 node as this splits the path on t2. g.V(v2_id).inE('follows').otherV().as_('t2').inE('follows').otherV().as_('v3').outE('follows').otherV().as_('t1').outE('follows').otherV().hasId(v1_id).select('v3') Could you please give me a hint or gremlin trick how I specify that t2 and t1 should be linked by d1 Ids of d1,v1 and v2 are known so I could also start from d1 I guess A: If v1, v2 and d1 are vertices (not just ids): g.V(v1, v2).as("a").in("follows"). filter(out("of_day").is(d1)).in("follows"). group().by().by(select("a").fold()).unfold(). and(select(values).unfold().is(v1), select(values).unfold().is(v2)). select(keys) However, if v1, v2 and d1 are just ids, it's not much different: g.V(v1, v2).as("a").in("follows"). filter(out("of_day").hasId(d1)).in("follows"). group().by().by(select("a").fold()).unfold(). and(select(values).unfold().hasId(v1), select(values).unfold().hasId(v2)). select(keys) The queries above are good if there can be more than 2 inputs. If there are always only 2 inputs, then the following query should be more efficient: g.V(v1).in("follows"). filter(out("of_day").is(d1)). in("follows"). filter(out("follows").filter(out("of_day").is(d1)). out("follows").is(v2))
{ "pile_set_name": "StackExchange" }
Q: How to set configuration options for particular sub blogs? Is it possible to set configuration options such as DEBUG mode only for specific sub blogs in a wordpress multisite installation? If so, how? A: Hi @Raj Sekharan: If I understand your question lets say you have three (3) subdomains on your multisite and you only want to debug the first? http://foo.example.com http://bar.example.com http://baz.example.com If yes then it's a simply matter of adding the following to your /wp-config.php file: if ($_SERVER['HTTP_HOST']=='foo.example.com') define('WP_DEBUG', true); else define('WP_DEBUG', false); Or if you are a fan of terse coding you can just do it like this: define('WP_DEBUG', $_SERVER['HTTP_HOST']=='foo.example.com');
{ "pile_set_name": "StackExchange" }
Q: When to fetch/send data in an Android application I am currently creating an Android application and I have the following questions: We have a server which provides data for the app in form of a REST-JSON-API. The App is following the MVVM architecture. Now my question is: When should we fetch data from that server? We could fetch all data at once when the user reaches the first data related screen or we could make mulitple fetch calls over the lifespan of the application. Also when we are posting user-generated data to the server, should we gather all the data first and then make one post request or make multiple requests by sending as soon as the partial data is ready? What's your opinion on this issue and can you provide me with any guidelines on this topic? A: You'll hate my answer, but here it is - it depends on the use case. While syncing with the server, you generally, want to achieve two things: have the latest data state at all paries as soon as possible (server, client) have the smallest number of requests and transferred data To achieve this, you must familiarize yourself with your business requirements, i.e.: how often your data changes? do you need to support offline mode? what data is crucial for correct usage? will users be happier with old data but served immediately or it's crucial to show only fresh data? who depends on user-generated content and what is thair tolerance time for fresh data? For example, if your app needs to support offline mode and there are some actions that are relying on some data available, you'll probably need to fetch all that data at soon as possible. For other apps, that do not have those kinds of sensibility - it's an overkill and bad usage of resources. So, the decision of when to sync data is a business decision more than a technical one. If I were you, I would require those answers from the product owner, and only after that, you can start thinking about technical implementation. Very often, in the fear of looking bad or not skilfull enough, we programmers avoid asking crucial questions from our business teams and instead search for those answers in design patterns, practices, etc. But patterns are useful only after we know the business case.
{ "pile_set_name": "StackExchange" }
Q: laravel 5.4 Request::session() should not be called statically I am using Laravel 5.4, I rewrite the validator() method of RegisterController out of the box,as follow: <?php namespace App\Http\Controllers\Auth; use Illuminate\Http\Request; class RegisterController extends Controller { protected function validator(array $data) { $validationCode = Request::session()->get('validation_code', ''); return Validator::make($data, [ 'name' => 'required|max:255', 'role' => 'required|in:1,2', 'email' => 'required|email|max:255|unique:users', 'password' => 'required|min:6|confirmed', 'validation_code' => 'required|in:' . $validationCode ]); } } There is an error: Non-static method Illuminate\Http\Request::session() should not be called statically Why is it? A: Change this: $validationCode = Request::session()->get('validation_code', ''); to this: $validationCode = session()->get('validation_code', ''); //or $validationCode = request()->session()->get('validation_code', ''); //or $validationCode = Illuminate\Support\Facades\Request::session()->get('validation_code', ''); //or $validationCode = \Request::session()->get('validation_code', ''); Illuminate\Support\Facades\Request and Illuminate\Http\Request are two different class, the first is the facade the second the actual request class. My advice is to use the helper function request() you will have less confusion.
{ "pile_set_name": "StackExchange" }
Q: Extract day of the week from column in dataframe and put in another column # Give day of the week def DOW(df): DOW = pd.Series(datetime.datetime.strptime(df['indx'],'%Y%m%d').strftime('%A')) df = df.join(DOW) return df I am calling this function from another script as where d is my dataframe which I pass to function DOW d = TA.DOW(d) It throws the error . what can be solution for same DOW=pd.Series(datetime.datetime.strptime(df['indx'],'%Y%m%d').strftime('%A')) TypeError: must be string, not Series A: I think you can first convert column indx to_datetime and then use dt.strftime as mentioned EdChum: print df indx Value 0 20020101 3.00 1 20020102 3.50 2 20020103 3.30 3 20100101 4.96 4 20100102 4.98 df['new'] = pd.to_datetime(df['indx'], format='%Y%m%d').dt.strftime('%A') print df indx Value new 0 20020101 3.00 Tuesday 1 20020102 3.50 Wednesday 2 20020103 3.30 Thursday 3 20100101 4.96 Friday 4 20100102 4.98 Saturday
{ "pile_set_name": "StackExchange" }
Q: Regex Replace all found occurrences if the word not matches with the given prefix How can I replace text value without matching given prefix of text?? For Example: test hello world... I know hello world, this seems hello world.. then our replace value is "HI" the text will be.. test hello world... I know HI, this seems HI.. A: (?<!test\s)\bhello world\b This assumes that you're interested in test when it proceeds directly.
{ "pile_set_name": "StackExchange" }
Q: What's the point of :promptfind after all Not sure if it's an appropriate question. But I just can't help wondering, why would any Vim user find it necessary to invoke a GUI search prompt instead of search using / or ?, why would the designer of gvim, MacVim etc. want to add this feature. Or is it because they're just quite some inherent feature of a GUI app anyways? A: :promptfind and related commands are useful for the easy mode (evim), which according to :help easy sets Vim up to work like most click-and-type editors. As Notepad has such a find dialog, and users coming from such editors expect it / initially feel better with it, Vim has it, too. I personally wouldn't recommend this way for switching to Vim, though.
{ "pile_set_name": "StackExchange" }
Q: Oracle function to PostgreSQL I'm try to convert my Oracle function which contains SUBSTR() to PostgreSQL. Is there an equivalent function in PSQL? Thanks. I manage to find a Oracle Instr() conversion to PostgreSQL. A: You can use a code from Postgres documentation mentioned by michel-sim. Other possibility is Orafce extension - https://github.com/orafce/orafce or http://postgres.cz/wiki/Oracle_functionality_%28en%29 that is available for RedHat or Debian as binary package too.
{ "pile_set_name": "StackExchange" }
Q: javascript starnage issue , return undefined if block statements are used function ok(){ return { home : "OK" }; } when i code like this the function will return undefined but if i just shift the { it starts working function ok(){ return { home : "OK" }; } Is this somekind of auto adding ';' at the end of line ? A: Javascript engines insert semicolons at certain newline positions. So, your first code is really this: return; { home : "OK" }; And it returns nothing.
{ "pile_set_name": "StackExchange" }
Q: Java to C# Conversion I need to convert several Java classes to C#, but I have faced few problems. In Java I have following class hierarchy: public abstract class AbstractObject { public String getId() { return id; } } public class ConcreteObject extends AbstractObject { public void setId(String id) { this.id= id; } } There are implementation of AbstractObject which do not need to have setId() defined, so I cannot move it up in the hierarchy. How to convert this to C# using properties? Is that possible? A: When you supply only the get portion of a property in .Net, you are explicitly telling the compiler that this property is read-only. It's a bigger deal than just not providing a set. This is evident in the vb version of the property syntax, where you must also explicitly declare the property is ReadOnly. What you might be able to do is provide both a getter and a setter, but throw a NotImplementedException in the abstract setter, decorate it with the appropriate attributes and document so that no one uses it unless the setter has been property overridden. Otherwise, you're probably better off keeping these as methods anyway, to avoid a disconnect between Java and .Net versions of the code. A: I would suggest using method calls as you've already outlined to make sure that the usage of the class is clear to the caller. If you're set on implementing it using properties, then you could do the following (some documentation for the new keyword can be found here). public abstract class AbstractObject { protected string id; public string Id { get { return id; } } } public class ConcreteObject : AbstractObject { public new string Id { get { return base.Id; } set { id = value; } } }
{ "pile_set_name": "StackExchange" }
Q: Find the Integrating Factor of $xdy-3ydx=\frac{x^4}{y}dy$ This is integrating factor by inspection, $xdy-3ydx=\frac{x^4}{y}dy$ I've been trying to look for the Integrating factor for this problem but I can't still get one right. I think I really need to use the $3ydx$ in the problem since it has the $dx$ but i can't remove the $-3$ any ideas how? A: Hint As Mattos commented, considering the terms of the equation written as $$xy'-3y=\frac{x^4}{y}y'$$ a (may be) good idea would to start defining $y=x^3z$ which, after simplifications, leads to $$\frac{x (z-1) z'}{z}=3$$ which is now separable and easy to integrate.
{ "pile_set_name": "StackExchange" }
Q: How can I remove the duplicate using statement? I have a bunch of methods that do the following: using(var cn = new Connection()) { //custom code } Is there a way I can still use the using, but just call my custom code? A: What about creating a new method encapsulating your using-block and putting an action-delegate in? static void Main(string[] args) { doCustomCode(() => { Console.WriteLine("customCode #1"); }); doCustomCode(() => { Console.WriteLine("customCode #2"); }); } private static void doCustomCode(Action action) { using (var con = new Connection()) { action(); } } In case you need somethig more specific than a simple action, just modifiy the according parameter.
{ "pile_set_name": "StackExchange" }
Q: Create a new JSON after manipulating json values in angular6 Below is my JSON [ { "Key": "doc/1996-78/ERROR-doc-20200103.xlsx" } }, { "Key": "doc/1996-78/SUCCESS-doc-20200103.xlsx" }, { "Key": "doc/1996-78/PENDING-doc-20200103.xlsx" } ] First i want to split key value by backslash and after that will split the [2] json value by hyphen and then will check in string that if there is SUCCESS/PENDING/ERROR word found in the newly spitted JSON. If any word is present would like to add new status field and add Done/Processing/Failure respective values in newly created JSON. this is a dynamic json so without manipulating it i can't get status value This is what i would like to achive in my new JSON [ { "Key": "doc/1996-78/ERROR-doc-20200103.xlsx", "status":"Failure" } }, { "Key": "doc/1996-78/SUCCESS-doc-20200103.xlsx", "Status":"Done" }, { "Key": "doc/1996-78/PENDING-doc-20200103.xlsx", "Status":"Processing" } ] As i'm new to this kindly let me know how to achieve this A: You can use includes function and if true then add string. Try my code: let myJson = [ { "Key": "doc/1996-78/ERROR-doc-20200103.xlsx" }, { "Key": "doc/1996-78/SUCCESS-doc-20200103.xlsx" }, { "Key": "doc/1996-78/PENDING-doc-20200103.xlsx" }, { "Key": "doc/1996-78/WRONG-doc-20200103.xlsx" } ]; myJson = myJson.map(obj => ({ ...obj, "Status": obj.Key.includes("ERROR") ? 'Failure' : obj.Key.includes('SUCCESS') ? 'Done' : obj.Key.includes('PENDING') ? 'Processing' : false })) console.log(myJson)
{ "pile_set_name": "StackExchange" }
Q: Comma separated values In An IN statement (SQL) I have a table with a column of comma separated values, i want to take them as different values and place inside The In clause of another select statement. i've tried with cross apply but didn't get it working properly the table (T1) looks like : Empcode Eid Unitcodes 007645 164 UNT111$UNT112$UNT113$ 000645 162 UNT100$UNT102$UNT20$UNT97$UNT98$UNT99$UNT136$ 002585 163 UNT25$UNT39$ 003059 180 UNT76$ 000559 165 UNT109$UNT114$UNT166$UNT27$UNT60$UNT103$UNT58$ 003049 175 UNT106$UNT54$UNT86$UNT87$UNT130$UNT131$UNT132$ 003049 177 UNT51$UNT56$UNT91$UNT92$ and i need a query something like : select * from T2 where empcode='abcd' unitcode in ('UNT111','UNT112','UNT113') //only that particular emps Unitcodes from the table T1 A: You can do It in following: QUERY SELECT * FROM #test2 WHERE ID IN ( SELECT LTRIM(RTRIM(m.n.value('.[1]','varchar(8000)'))) AS Unitcodes FROM ( SELECT CAST('<XMLRoot><RowData>' + REPLACE(Unitcodes,'$','</RowData><RowData>') + '</RowData></XMLRoot>' AS XML) AS x FROM #test )t CROSS APPLY x.nodes('/XMLRoot/RowData')m(n) ) SAMPLE DATA CREATE TABLE #test ( Empcode INT, Eid INT, Unitcodes NVARCHAR(MAX) ) INSERT INTO #test VALUES (000559, 165, 'UNT109$UNT114$UNT166$UNT27$UNT60$UNT103$UNT58$'), (003049, 175, 'UNT106$UNT54$UNT86$UNT87$UNT130$UNT131$UNT132$') CREATE TABLE #test2 ( ID NVARCHAR(MAX) ) INSERT INTO #test2 VALUES ('UNT54'),('UNT130'),('UNT999') OUTPUT ID UNT54 UNT130
{ "pile_set_name": "StackExchange" }
Q: The opposite of paper being a dead-tree In this question, John Y refers to a printed version of a book as "dead-tree book". I found that amuzing and started to wonder what the opposite of such term would be. Of course, the popular term would be "electronic book". However, I'd like to retain the style of the original wording. A: How about :- "No-tree-dead book"
{ "pile_set_name": "StackExchange" }
Q: detect mouse hover on overlapping + transparent images I'm building a little game where the user has buy items to furnish his house. I have a lot of items/images; so I decided to use, for each of them, a "matte" (an image) that would define the hoverable zone, rather than drawing a map area for each image. Example : here's the displayed couch, and its matte. I "convert" the matte into a canvas element, and will check later if the hovered pixel is transparent to detect if the item is hovered. The second thing is that a lot of items are overlapping, so I also need to check which layer is on top. I have mousemove event (jQuery) on the house element; bound with the function getObjectsUnderMouse(). Basically, this is how getObjectsUnderMouse() works : Get the mouse coordinates Get the active (displayed) items in the house Filter those items to keep only the ones where the mouse hits the canvas boundaries, knowing the item position and width/height) Filter those items to keep only the ones where the mouse is NOT on a transparent pixel (canvas) Filter those items to keep only the one on the top (z-index) Give that item a mouseon class I was quite happy with my code, which was quite a challenge but works perfectly on Chrome. The problem I have is that it is slower elsewhere (not a so big deal), but; above all, seems to crash on ipad; and I need my game to run on ipad... :/ Does anyone knows why or have a better solution for this ? Here's a demo of the game, and here's the javascript file where you can have a look at getObjectsUnderMouse(). Any advice is welcome ! A: Although a matte canvas contains the information you need to hit-test, keeping a full sized canvas for each matte is expensive in terms of memory. Keeping a canvas for each matte is likely using more resources than your iPad can handle. Here's a way to greatly reduce your memory usage: First, crop any extra transparent space out of each of your objects. For example, your couch is 600x400=240000 pixels, but cropping away the empty space shrinks the image to 612x163=99756 pixels. That's a savings of 58% over the original image size. Less pixels means less memory for a matte. Instead of keeping a full-sized canvas for each object, instead keep an array for each object which only contains the opacity of each pixel in that image. An array value of 1 indicates that pixel is opaque (and is part of the object). An array value of 0 indicates that pixel is transparent (no part of the object is at this pixel). Then hit-test against the pixel array instead of hit-testing against a matte canvas. If you test the arrays in z-index order, you can even tell which object is on top of another object. Here's example code and a Demo: var canvas=document.getElementById("canvas"); var ctx=canvas.getContext("2d"); var cw=canvas.width; var ch=canvas.height; var $canvas=$("#canvas"); var canvasOffset=$canvas.offset(); var offsetX=canvasOffset.left; var offsetY=canvasOffset.top; // display which object the mouse is over var $result=$('#result'); // create an array of target objects var targets=[]; targets.push({ name:'couch', x:25, y:50, hitArray:[], url:'https://dl.dropboxusercontent.com/u/139992952/multple/couch.png' }); targets.push({ name:'lamp', x:50, y:30, hitArray:[], url:'https://dl.dropboxusercontent.com/u/139992952/multple/lamp.png' }); var imgCount=targets.length; // load the image associated with each target object for(var i=0;i<targets.length;i++){ var t=targets[i]; t.image=new Image(); t.image.crossOrigin='anonymous'; t.image.index=i; t.image.onload=start; t.image.src=t.url; } // this is called when each image is fully loaded function start(){ // return if all target images are not loaded if(--imgCount>0){return;} // make hit arrays for all targets for(var i=0;i<targets.length;i++){ var t=targets[i]; t.hitArray=makeHitArray(t.image); } // resize the canvas back to its original size canvas.width=cw; canvas.height=ch; // draw all targets on the canvas for(var i=0;i<targets.length;i++){ var t=targets[i]; t.width=t.image.width; t.height=t.image.height; ctx.drawImage(t.image,t.x,t.y); } // listen for events $("#canvas").mousemove(function(e){handleMouseMove(e);}); } // Draw a target image on a canvas // Get the imageData of that canvas // Make an array containing the opacity of each pixel on the canvas // ( 0==pixel is not part of the object, 1==pixel is part of the object) function makeHitArray(img){ var a=[]; canvas.width=img.width; canvas.height=img.height; ctx.drawImage(img,0,0); var data=ctx.getImageData(0,0,canvas.width,canvas.height).data; for(var i=0;i<data.length;i+=4){ // if this pixel is mostly opaque push 1 else push 0 a.push(data[i+3]>250?1:0); } return(a); } function handleMouseMove(e){ // tell the browser we're handling this event e.preventDefault(); e.stopPropagation(); // get the mouse position mouseX=parseInt(e.clientX-offsetX); mouseY=parseInt(e.clientY-offsetY); // Test the mouse position against each object's pixel array // Report hitting the topmost object if 2+ objects overlap var hit='Not hovering'; for(var i=0;i<targets.length;i++){ var t=targets[i]; var imgX=mouseX-t.x; var imgY=mouseY-t.y; if(imgX<=t.width && imgY<=t.height){ var hitArrayIndex=imgY*t.width+imgX; if(hitArrayIndex<t.hitArray.length-1){ if(t.hitArray[hitArrayIndex]>0){ hit='Hovering over '+t.name; } } } } $result.text(hit); } body{ background-color: ivory; padding:10px; } #canvas{border:1px solid red;} <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <h4 id='result'>Move mouse over objects.</h4> <canvas id="canvas" width=450 height=250></canvas>
{ "pile_set_name": "StackExchange" }
Q: Touch Down Event, Change the image button I know there already are many similar questions and answers here, I've done searching some and I think I should ask this as a new question as I still can't find the right answer for me. So, I write a simple card game, and I got 90% of my knowledge from the book "Beginning Android Games 2nd edition" by Mario Zechner, I wonder if some of you have read it. I follow the guide during writing my game, I even use the framework he provides in the book (Mr.Nom game). I've asked in his forum, but no response, the forum is not too active anyway. The book provide framework where there are method to draw Pixmap, draw line, etc.. all directly from code, so I never touch the layout, I don't use XML either. The book uses model similar to MVC (model view controller), separating the world and the game. The presentation and the manipulation layerd. It separates each UI according the game state: Ready, paused, running, gameOver. Now I am stuck at some code as I want to change my button image. I provide 2 image (Unpressed and Pressed), at first in so called (RunningUI) part, I draw Unpressed image. and simply when user touch the button (touch down only) I want to change the image to pressed image. And return back to unpressed image again after the touch is released. private void drawRunningUI() { Graphics g = game.getGraphics(); g.drawPixmap(Assets.buttonUnpressed, 70, 200); } The updateRunning code is here: private void updateRunning(List<TouchEvent> touchEvents, float deltaTime) { Graphics g = game.getGraphics(); int len = touchEvents.size(); for(int i = 0; i < len; i++) { TouchEvent event = touchEvents.get(i); if (event.type == TouchEvent.TOUCH_UP) { if (event.x < 64 && event.y < 64) { if (Settings.soundEnabled) Assets.click.play(1); state = GameState.Paused; return; } } if (event.type == TouchEvent.TOUCH_DOWN) { if (event.x >= 120 && event.x <= 180 && event.y >= 250 && event.y <= 380) { Assets.click.play(1); g.drawPixmap(Assets.buttonPressed, 70, 200); <-- nothing happened } } } world.update(deltaTime); } I modified "some here and there", but still I don't get the result I want. A: Although I don't know this framework and can only surmise how the canvas drawing is made, I suspect drawRunningUI() is called immediately after updateRunning() and "overwrites" the previous draw with Assets.buttonPressed (depends on how invalidation / redraw is handled). Anyway, you should only draw in one place, and it then gets a lot easier. In your event handling code you should update a UI state which you would then use to draw the UI. Something like this: private void updateRunning(List<TouchEvent> touchEvents, float deltaTime) { int len = touchEvents.size(); for(int i = 0; i < len; i++) { TouchEvent event = touchEvents.get(i); if(event.x < 64 && event.y < 64) { if(event.type == TouchEvent.TOUCH_UP) { // ... } else if (event.x >= 120 && event.x <= 180 && event.y >= 250 && event.y <= 380) { switch(event.type) { case TouchEvent.TOUCH_UP: uiState.updateButtonState(ButtonState.RELEASED); break; case TouchEvent.TOUCH_DOWN: Assets.click.play(1); uiState.updateButtonState(ButtonState.PRESSED); break; default: // nothing to do } } } world.update(deltaTime); // I suppose an invalidation has happened / a redraw will happen next } private void drawRunningUI() { Graphics g = game.getGraphics(); g.drawPixmap(uiState.getButtonState() == ButtonState.PRESSED ? Assets. buttonPressed : Assets.buttonUnpressed,70,200); } This won't be enough but should illustrate the idea.
{ "pile_set_name": "StackExchange" }
Q: I am Getting this error while creating a new component in Angular 2.! I have created the new component in angular 2 and I am getting this error "Individual declaration in merged declaration 'MyComponentComponent' must be all exported or all local." As I am new to angular 2 I am not able to figure out the error on code need help.! Thanks in advance ..! A: I think that you have several classes with the same name MyComponentComponent. When defining a component, you need to take a new name for its implementation class. @Component({ (...) }) export class Component1 { (...) } @Component({ (...) }) export class Component2 { (...) }
{ "pile_set_name": "StackExchange" }
Q: jquery autoResize textarea does not work when in jquery ui tab jquery autoResize textarea does NOT work when in jquery ui tab. jquery autoResize works outside of tab. See both examples in jsFiddle. Click the "Details" tab to see it not resize. http://jsfiddle.net/remy/6BwqE/25/ this is using the autoresize by James Padolsey http://james.padolsey.com Any ideas? A: This bug appears to be when the original element is not visible on the page and thus the clone function in the plugin fails to find the width. This can be resolved by the following steps: Change clone to be a function (remove wrapping parens and ()) Call the clone function in updateSize Trigger the updateSize event whenever a tab is shown or loads (up to you) I've made the modifications in this fiddle: http://jsfiddle.net/6BwqE/29/ I inlined the modified source for the autoResize plugin and added a show event to the tabs call.
{ "pile_set_name": "StackExchange" }
Q: Preferences activity deprecated I am doing an app with preferences but I have used a method that is deprecated and it says : "This function is not relevant for a modern fragment-based PreferenceActivity". My code is this: public class Settings extends PreferenceActivity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preferences); } } How can I update this to not deprecated function. Thank you very much. A: The new way is to do the Preferences in an Fragment instead of an Activity. This is espacially true for large screens and tablets. Fragments can be shown separate or next to each other over an Activity according to screen size. Use them like this: public static class YourPreferenceFragment extends PreferenceFragment { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Load the preferences from an XML resource addPreferencesFromResource(R.xml.preferences); } } and instead of calling the PreferenceActivity you make a call to the Fragment in your Activity: YourPreferenceFragment prefFragment = new YourPreferenceFragment(); prefFragment.show(getFragmentManager(), "someFragmentId");
{ "pile_set_name": "StackExchange" }
Q: VHDL 2008 > generic package in an entity: error expecting BASICID or EXTENDEDID When trying to declare an entity with a formal generic package (ieee.fixed_generic_pkg): library ieee; context ieee.ieee_std_context; entity myent is generic ( package myfpkg is new ieee.fixed_generic_pkg generic map (<>) ); end entity; I get the following error: Syntax error at or near "package", expecting BASICID or EXTENDEDID I have also tried: library ieee; context ieee.ieee_std_context; use ieee.fixed_generic_pkg; entity myent is generic ( package myfpkg is new ieee.fixed_generic_pkg generic map (<>) ); end entity; that doesn't work neither. However, if I declare any dummy instance of the package, it works without any error: library ieee; context ieee.ieee_std_context; package fpkg is new ieee.fixed_generic_pkg; -- library ieee; context ieee.ieee_std_context; entity myent is generic ( package myfpkg is new ieee.fixed_generic_pkg generic map (<>) ); end entity; What is the proper way of declaring an entity with a formal generic package, without having to previously instantiate a package of the same type? EDIT The tool I'm using is HDL Designer 2015.1b. I think that generic packages are supported. Indeed, the following example throws no error: library slfnlib; use slfnlib.gen_consts; use slfnlib.gen_wb_ctypes; package gen_ctypes is generic ( package cs is new slfnlib.gen_consts generic map (<>) ); package wb is new slfnlib.gen_wb_ctypes generic map ( g_mo => cs.g_mo, g_bas => cs.g_bas ); end package; EDIT2 While working with several generic packages (declarations, instantiations, use...), I realized that full projects are correctly compiled. I also got the same error several times, when analizing only parts of them. Then, I concluded that I can not analyze any generic package/entity on its own with DesignChecker. However, there is an easy workaround, which is just to use those components as we would in any practical design. That should be done anyway, in order to either simulate and synthetize the design. The key message is not bother with what the tools provide, until the body of the code actually makes sense as a practical design. A: You code looks to have a similar structure to the example in section 6.5.7.2 of the LRM ("Generic map aspects") except your top-level is an entity whereas in their example it is a package. Your original code compiled fine on the two tools I tried, so it looks to me like there is an issue in whatever tool you are using. I suggest you take it up with the tool vendor.
{ "pile_set_name": "StackExchange" }
Q: how to show z belongs to a set of Complex Numbers? I have been given the equation, show that $$z\bar z + 3(z-\bar z) = 13-12i$$ How would i go about finding $z\in \Bbb C$? I thought to go along the route of: $$z\bar z = \mathrm{Re}(z)^2+\mathrm{Im}(z)^2$$ and $$z-\bar z = 2\mathrm{Im}(z)$$ But I like to picture where to go but i cannot see where to go to show that the equation $= 13-12i$. Do i have to assume that $z = 13-12i$? I cant put my finger on where to go. Help would be much appreciated. sorry that my html isnt to good. A: The equation actually contains two equations, one for real part and the other for imaginary part. Let $z=x+yi$, then $$x^2+y^2+6yi=13-12i\quad\Leftrightarrow\quad \left\{ \begin{align} &x^2+y^2=13\\ &6yi=-12i \end{align} \right.$$
{ "pile_set_name": "StackExchange" }
Q: Apply a function to a time series Hey I am trying to apply a two different functions to a time series. The first function states the problem and the second function uses optim to solve it. I already tried to put both functions into one to apply this one single function to a time series. Now the big problem is I can not return the computed values. R tells me: * Error in return(V_A, Vola_A, DD, PD) : multi-argument returns are not permitted * I thought of removing the line return(V_A, Vola_A, DD, PD) But if I do this, a value I do not want (I do not even know what exactly it is) is printed out. Here is my code: data <- read.zoo(data) cca <- function(V_LCL,Vola_LCL,Barriere,rf,HZ) { cca_min <- function(x) { V_A <- x[1] Vola_A <- x[2] d1 <- (log(V_A/Barriere)+(rf+Vola_A^2/2)*HZ)/(Vola_A*sqrt(HZ)) d2 <- d1-Vola_A*sqrt(HZ) G <- V_A*pnorm(d1)-Barriere*exp(-rf*HZ)*pnorm(d2)-V_LCL H <- pnorm(d1)*Vola_A*V_A-Vola_LCL*V_LCL return(G^2+H^2) #Summe der Residuen. } cca_fin <- optim(c(V_A = V_LCL, Vola_A = Vola_LCL),cca_min) V_A <- cca_fin$par[1] Vola_A <- cca_fin$par[2] d1 <- (log(V_A/Barriere)+(rf+Vola_A^2/2)*HZ)/(Vola_A*sqrt(HZ)) d2 <- d1-Vola_A*sqrt(HZ) DD <- d2 PD <- pnorm(-d2) } solution <- apply(data, MARGIN = 1, FUN=function(data) cca(V_LCL=data[["V_LCL"]], Vola_LCL=data[["Vola_LCL"]], Barriere=data[["Barriere"]], rf=data[["rf"]], HZ=1)) I expect to get a data frame with 5 different columns. The date and my 4 different returns as mentioned before. For "rebuilding" the problem by yourself: #dput(head(data,10)) structure(c(75500410877, 77601206594, 79186519481, 80974008790, 82537645824, 83864068176, 85170542638, 85919899689, 86511152529, 86661504323, 0.079017183, 0.07855107, 0.077269899, 0.0712223, 0.069432901, 0.069656866, 0.069367016, 0.070503068, 0.071102523, 0.073219234, 9.2e+10, 87939600000, 84480400000, 80973200000, 7.74e+10, 7.45e+10, 70886400000, 67668720000, 64408640000, 61210800000, 0.028605, 0.030294737, 0.033022727, 0.033166667, 0.033309524, 0.033631818, 0.03641, 0.038721739, 0.038452381, 0.041755), .Dim = c(10L, 4L), .Dimnames = list(NULL, c("V_LCL", "Vola_LCL", "Barriere", "rf")), index = structure(c(12784, 12815, 12843, 12874, 12904, 12935, 12965, 12996, 13027, 13057), class = "Date"), class = "zoo") What do I have to change/add to my code? A: If we use the return with list (if the lengths are different) or a data.frame it would return return(data.frame(V_A, Vola_A, DD, PD)) do.call(rbind, apply(data, MARGIN = 1, FUN=function(data) cca(V_LCL=data[["V_LCL"]], Vola_LCL=data[["Vola_LCL"]], Barriere=data[["Barriere"]], rf=data[["rf"]], HZ=1))) # V_A Vola_A DD PD #2005-01-01 83050451962 0.68779085 -0.45110142 6.740418e-01 #2005-02-01 85361327254 0.64400360 -0.32116690 6.259580e-01 #2005-03-01 87105171426 0.60232917 -0.19554222 5.775158e-01 #2005-04-01 89071409714 0.54911211 -0.04056589 5.161790e-01 #2005-05-01 90791410452 0.48899014 0.14996570 4.403958e-01 #2005-06-01 92250475072 0.42087446 0.37724425 3.529960e-01 #2005-07-01 93687596965 0.06307322 4.96737159 3.393323e-07 #2005-08-01 94511889722 0.06415389 5.77931393 3.750293e-09 #2005-09-01 95162267830 0.06458672 6.60665865 1.965455e-11 #2005-10-01 95327654820 0.06656895 7.24865868 2.104595e-13 <
{ "pile_set_name": "StackExchange" }
Q: Java threads counter "issue"? I was trying impact of thread priority and when println in run method stays in comment both threads end in the same time and I don't understand this behavior, can you explain ? Thank you. Main.class public class Main { public static void main(String[] args) { Test t1 = new Test("Thread #1"); Test t2 = new Test("Thread #2"); t1.thread.setPriority(10); t2.thread.setPriority(1); t1.thread.start(); t2.thread.start(); try { t1.thread.join(); t2.thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(t1.thread.getName() + ": " + t1.count); System.out.println(t2.thread.getName() + ": " + t2.count); System.out.println("End of main thread."); } } Test.class public class Test implements Runnable{ public Thread thread; static boolean stop = false; int count = 0; public Test(String name){ thread = new Thread(this, name); } @Override public void run(){ for(int i = 0; i < 10000000 && stop == false; i++){ count = i; //System.out.println(count + " " + thread.getName()); } stop = true; System.out.println("End of " + thread.getName()); } } without println with println End of Thread #1 End of Thread #1 End of Thread #2 End of Thread #2 Thread #1: 9999999 Thread #1: 9999999 Thread #2: 9999999 Thread #2: 3265646 End of main thread. End of main thread. A: Your two threads access a shared mutable variable without proper synchronization. In this case, there is no guaranty about when (or whether at all) a thread will learn about a change made by another thread. In your case, the change made by one thread is not noticed by the other at all. Note that while for a primitive data type like boolean, not reading the up to date value is the worst thing that can happen, for non-primitive data types, even worse problems, i.e. inconsistent results could occur. Inserting a print statement has the side effect of synchronizing the threads, because the PrintStream perform an internal synchronization. Since there is no guaranty that System.out will contain such a synchronizing print stream implementation, this is an implementation specific side-effect. If you change the declaration of stop to static volatile boolean stop = false; the threads will re-read the value from the shared heap in each iteration, reacting immediately on the change, at the cost of reduced overall performance. Note that there are still no guarantees that this code works as you expect, as there is no guaranty about neither, that the thread priority has any effect nor that threads run in parallel at all. Thread scheduling is implementation and environment dependent behavior. E.g. you might find out that not the thread with the highest priority finishes its loop first, but just the thread that happened to be started first. A: To clarify: the only purpose of thread/process "priority," in any language environment on any operating system, is to suggest to the OS "which of these two 'ought to be, I think, run first'," if both of them happen to be instantaneously "runnable" and a choice must be made to run only one of them. (In my experience, the best example of this in-practice is the Unix/Linux nice command, which voluntarily reduces the execution-priority of a command by a noticeable amount.) CPU-intensive workloads which perform little I/O can actually benefit from being given a reduced priority. As other answerers have already stressed, it is impossible to predict "what will actually happen," and priority can never be used to alter this premise. You must explicitly use appropriate synchronization-primitives to assure that your code executes properly in all situations.
{ "pile_set_name": "StackExchange" }
Q: Intercept FIleSytemCall for Deletion Is there a way to detect deletion of a file before windows performs the deletion? I found FileSystemWatcher class but the event is raised only after the delete action is performed but I want to trap the delete action once the user/process chooses to delete it. You can monitor the file system table but looking for a better approach. Thanks for your help. A: I think the simpliest way is to use a hook to get notified (and eventually to stop) the process. It can't be done in .NET so you have to DllImport a lot of structures and few functions to P/Invoke. Let's start your job with the NtSetFileInformation (undocumented) function. It's the function called by anything else when a file need to be deleted (with the FileDispositionInformation structure). Now the problem is how to hook that function (good luck, it's not easy). A good choice can be to use Microsoft Detours. Take a look to this article for an example. Its problem is that it's not free. An alternative solution (with a reasonable price and with a .NET interface) is Deviare but I never tried even their free version so I don't know how much it's good. If someone else knows a good interception tool...
{ "pile_set_name": "StackExchange" }
Q: How can I stitch Minecraft worlds together? I visit a Minecraft survival multiplayer server. When monsters were added to SMP, the server archived the map and started afresh. When 1.8 is released, the server operator plants to do the same again. I'd like to merge the old maps into locations the new map, at distant locations. Does a tool exist to stitch together entire maps like that? A: My 1.8 plan is to allow players to select limited above ground areas that they would like to keep and then move those by hand to a fresh 1.8 map using mcedit. In addition I'll set up a portal between worlds to allow them to move their other items like rails, torches, chests, etc by hand themselves if they want to. I don't know of any "automated" stitching tools. Most people I've heard either do what I'm going to do, or just start with a fresh map and let their users move their own buildings. edit There is now a stiching tool. http://www.minecraftforum.net/topic/629884-a-tool-for-merging-171819-maps-mcmerge-v04/ A: As somebody with a lot of time and energy invested in Bigshell and the other maps you're referring to, I can confirm that MCEdit is exactly what you'll want. It's trivial to load the existing maps, select all of the terrain on which actual construction has occurred, and then export it to a file. Once you've got files for each of the maps you want to incorporate, it's probably best to just start a new map in Creative mode and fly way out away from the spawn. You might want to survey a pretty big cross section of areas so you can find terrain that nobody's going to mind getting supplanted by the old content. While Kort Pleco states above that MCEdit requires the area to already be explored, the version I was using had some tools for filling in ungenerated sections, so it shouldn't be too hard to take a map that has some holes in it and import the files from above.
{ "pile_set_name": "StackExchange" }
Q: How to check if specific set of ID's exists? I have a source table (piece of it): +--------------------+ | E M P L O Y E E | +--------------------+ | ID | EQUIPMENT | +--------------------+ | 1 | tv,car,phone | | 2 | car,phone | | 3 | tv,phone | +----+---------------+ After normalization process I ended with two new tables: +----------------+ | DICT_EQUIPMENT | +----------------+ | ID | EQUIPMENT | +----------------+ | 1 | tv | | 2 | car | | 3 | phone | +----+-----------+ +---------------------+ | SET_EQUIPMENT | +----+--------+-------+ | ID | SET_ID | EQ_ID | +----+--------+-------+ | 1 | 1 | 1 | | 2 | 1 | 2 | | 3 | 1 | 3 | | 4 | 2 | 2 | | 5 | 2 | 3 | | 6 | 3 | 1 | | 7 | 3 | 3 | +----+--------+-------+ (the piece/part) +-----------------+ | E M P L O Y E E | +-----------------+ | ID | EQ_SET_ID | +-----------------+ | 1 | 1 | | 2 | 2 | | 3 | 3 | +----+------------+ And now when I want to find correct SET_ID I can write something like this: SELECT SET_ID FROM SET_EQUIPMENT S1, SET_EQUIPMENT S2, SET_EQUIPMENT S3 WHERE S1.SET_ID = S2.SET_ID AND S2.SET_ID = S3.SET_ID AND S1.EQ_ID = 1 AND S2.EQ_ID = 2 AND S3.EQ_ID = 3; Maybe any ideas for optimize this query? how find the correct set? A: First, you should use explicit join syntax for the method you are using: SELECT S1.SET_ID FROM SET_EQUIPMENT S1 JOIN SET_EQUIPMENT S2 ON S1.SET_ID = S2.SET_ID JOIN SET_EQUIPMENT S3 ON S2.SET_ID = S3.SET_ID WHERE S1.EQ_ID = 1 AND S2.EQ_ID = 2 AND S3.EQ_ID = 3; Commas in a from clause are quite outdated. (And, this fixes a syntax error in your query.) An alternative method is to use group by with a having clause: SELECT S.SET_ID FROM SET_EQUIPMENT S GROUP BY S.SET_ID HAVING SUM(CASE WHEN S.EQ_ID = 1 THEN 1 ELSE 0 END) > 0 AND SUM(CASE WHEN S.EQ_ID = 2 THEN 1 ELSE 0 END) > 0 AND SUM(CASE WHEN S.EQ_ID = 3 THEN 1 ELSE 0 END) > 0; Which method works better depends on a number of factors -- for instance, the database engine you are using, the size of the tables, the indexes on the tables. You have to test which method works better on your system.
{ "pile_set_name": "StackExchange" }
Q: Template (.tpp) file include guards When writing templated classes, I like to move the implementation into a different file (myclass.tpp) and include it at the bottom of the main header (myclass.hpp). My Question is: do I need include guards in the .tpp file or is it sufficient to have them in the .hpp file? Example code: myclass.hpp #ifndef MYCLASS_HPP #define MYCLASS_HPP template<typename T> class MyClass { public: T foo(T obj); }; //include template implemetation #include "myclass.tpp" #endif myclass.tpp #ifndef MYCLASS_TPP //needed? #define MYCLASS_TPP //needed? template<typename T> T MyClass<T>::foo(T obj) { return obj; } #endif //needed? A: Do I need include guards in the .tpp file or is it sufficient to have them in the .hpp file? Include guards are never needed: they're just terribly useful, cheap, non-disruptive and expected. So Yes, you should protect both files with header guards: Terribly useful: they allow you to declare a dependency from multiple files without keeping track of which files have already be included. Cheap: this is just some precompilation tokens. Non-disruptive: they fit well with most use-cases of #include (I've had a colleague who didn't know how to write macros so he #included implementation files *facepalm*). Expected: developers know what they are and barely notice them; on the contrary a header file missing include guards wakes us up and adds to the global wtf/line counter. I take the opportunity to highlight the comment from StoryTeller: I'd go a step further and add a descriptive #error directive if the hpp guard is not defined. Just to offer a little protection from people including the tpp first. Which will translate to: #ifndef MYCLASS_TPP #define MYCLASS_TPP #ifndef MYCLASS_HPP #error __FILE__ should only be included from myclass.hpp. #endif // MYCLASS_HPP template<typename T> T MyClass<T>::foo(T obj) { return obj; } #endif // MYCLASS_TPP Notice: if a translation unit first #include <myclass.hpp> and then #include <myclass.tpp>, no error is fired and everything is fine. A: Just use pragma once in all headers file. The compiler will ensure your file will be included only once. The compiler may only fail to recognize in very unreasonable condition: someone structure its include directories using hard-link. Who does this? If someone cannot find a unique name for its file, why would he be more skilled to find a unique name for each include guard for all the header files? On the other hand, include guard may be broken because the name of the macro will not be that unique, because of a copy/paste, or a header file created by first copying an other, etc... How are chosen the unique macro name: <project name>_<filename>? How could it be more unique than a uniqueness based on the entire root directory structure? So in the end, one should consider when choosing between include guard or pragma once, the cost of the job that is necessary to ensure uniqueness: 1 - For pragma once you only have to ensure that the directory structured of your system is not messed-out thanks to hard links. 2 - For include guard for each file on your system you should ensure that the macro name is unique. I mean as a manager, evaluating the cost of this job and the failure risk does let only one option. Include guard are used only when no evaluation is performed: it is a non decision.
{ "pile_set_name": "StackExchange" }
Q: Extract only Hour from Epochtime in scala I am having a dataframe with one of its column as epochtime. I want to extract only hour from it and display it as a separate column. Below is the sample dataframe: +----------+-------------+ | NUM_ID| STIME| +----------+-------------+ |xxxxxxxx01|1571634285000| |xxxxxxxx01|1571634299000| |xxxxxxxx01|1571634311000| |xxxxxxxx01|1571634316000| |xxxxxxxx02|1571634318000| |xxxxxxxx02|1571398176000| |xxxxxxxx02|1571627596000| Below is the expected output. +----------+-------------+-----+ | NUM_ID| STIME| HOUR| +----------+-------------+-----+ |xxxxxxxx01|1571634285000| 10 | |xxxxxxxx01|1571634299000| 10 | |xxxxxxxx01|1571634311000| 10 | |xxxxxxxx01|1571634316000| 10 | |xxxxxxxx02|1571634318000| 10 | |xxxxxxxx02|1571398176000| 16 | |xxxxxxxx02|1571627596000| 08 | I have tried val test = test1DF.withColumn("TIME", extract HOUR(from_unixtime($"STIME"/1000))) which throws exception at <console>:46: error: not found: value extract Tried as below to obtain date format and even it is not working. val test = test1DF.withColumn("TIME", to_timestamp(from_unixtime(col("STIME"))) The datatype of STIME in dataframe is Long. Any leads to extract hour from epochtime in Long datatype? A: Extracting the hours from a timestamp is as simple as using the hour() function: import org.apache.spark.sql.functions._ val df_with_hour = df.withColumn("TIME", hour(from_unixtime($"STIME" / 1000))) df_with_hour.show() // +-------------+----+ // | STIME|TIME| // +-------------+----+ // |1571634285000| 5| // |1571398176000| 11| // |1571627596000| 3| // +-------------+----+ (Note: I'm in a different timezone)
{ "pile_set_name": "StackExchange" }
Q: relating two MySQL tables with followers Good afternoon, I'm not very expert in mysql. but I would like to relate my table followers to show. Here is an example of what I need to do. thank you very much table number1 id | user | example -------------------------- 1 | john | tall 2 | dave | fat 3 | maria | pretty 4 | example | love 4 | andres | hope table number2 followers id | id_user | user_table1 -------------------------- 1 | fran | red 2 | love | dave 3 | maria | dave 4 | maria | dave 5 | maria | dave selet * from number1 where user = 'dave' result: 2 | dave | fat but I would like to relate the table number2 and number2. I need this result: 1 | dave | fat 2 | maria | pretty 3 | example | love A: I'm not quite sure the relation you need actually but based on your example. I think you need all field which related to 'dave'. Try this : select distinct a.id, a.user, a.example from number1 a inner join number2 b on a.user = b.user_table1 or a.user = b.id_user or a.example = b.id_user where b.user_table1 = 'dave' order by a.id Example : http://sqlfiddle.com/#!9/9f2f79/16
{ "pile_set_name": "StackExchange" }
Q: malloc alternative for memory allocation as a stack I am looking for a malloc alternative for c that will only ever be used as a stack. Something more like alloca but not limited in space by the stack size. It is for coding a math algorithm. I will work with large amounts of memory (possibly hundreds of megabytes in use in the middle of the algorithm) memory is accessed in a stack-like order. What I mean is that the next memory to be freed is always the memory that was most recently allocated. would like to be able to run an a variety of systems (Windows and Unix-like) as an extra, something that can be used with threading, where the stack-like allocate and free order applies just to individual threads. (ie ideally each thread has its own "pool" for memory allocation) My question is, is there anything like this, or is this something that would be easy to implement? A: As you already found out, as long as it works with malloc you should use it and only come back when you need to squeeze out the last bit of performance. An idea fit that case: You could use a list of blocks, that you allocate when needed. Using a list makes it possible to eventually swap out data in case you hit the virtual memory limit. struct block { size_t size; void * memory; struct block * next; }; struct stacklike { struct block * top; void * last_alloc; }; void * allocate (struct stacklike * a, size_t s) { // add null check for top if (a->top->size - (a->next_alloc - a->top->memory) < s + sizeof(size_t)) { // not enough memory left in top block, allocate new one struct block * nb = malloc(sizeof(*nb)); nb->next = a->top; a->top = nb; nb->memory = malloc(/* some size large enough to hold multiple data entities */); // also set nb size to that size a->next_alloc = nb->memory; } void * place = a->next_alloc; a->next_alloc += s; *((size_t *) a->next_alloc) = s; // store size to be able to free a->next_alloc += sizeof (size_t); return place; } I hope this shows the general idea, for an actual implementation there's much more to consider. To swap out stuff you change that to a doubly linked list an keep track of the total allocated bytes. If you hit a limit, write the end to some file.
{ "pile_set_name": "StackExchange" }
Q: Python initializing a memoizing decorator with settings I have a memoizer decorator class in a library, as such: class memoizer(object): def __init__(self, f): "some code here" def __call__(self, *args, **kwargs): "some code here" When I use it for functions in the library, I use @memoizer. However, I'd like to have the client (ie the programmer using the library) initialize the memoization class from outside the library with some arguments so that it holds for all uses of the decorator used in the client program. Particularly, this particular memoization class saves the results to a file, and I want the client to be able to specify how much memory the files can take. Is this possible? A: You can achieve this using decorator factory: class DecoratorFactory(object): def __init__(self, value): self._value = value def decorator(self, function): def wrapper(*args, **kwargs): print(self._value) return function(*args, **kwargs) return wrapper factory = DecoratorFactory("shared between all decorators") @factory.decorator def dummy1(): print("dummy1") @factory.decorator def dummy2(): print("dummy2") # prints: # shared between all decorators # dummy1 dummy1() # prints: # shared between all decorators # dummy2 dummy2() If you don't like factories you can create global variables within some module and set them before usage of our decorators (not nice solution, IMO factory is more clean).
{ "pile_set_name": "StackExchange" }
Q: tidyverse: row wise calculations by group I am trying to do an inventory calculation in R which requires a row wise calculation for each Mat-Plant combination. Here's a test data set - df <- structure(list(Mat = c("A", "A", "A", "A", "A", "A", "B", "B" ), Plant = c("P1", "P1", "P1", "P2", "P2", "P2", "P1", "P1"), Day = c(1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L), UU = c(0L, 10L, 0L, 0L, 0L, 120L, 10L, 0L), CumDailyFcst = c(11L, 22L, 33L, 0L, 5L, 10L, 20L, 50L)), .Names = c("Mat", "Plant", "Day", "UU", "CumDailyFcst"), class = "data.frame", row.names = c(NA, -8L)) Mat Plant Day UU CumDailyFcst 1 A P1 1 0 11 2 A P1 2 10 22 3 A P1 3 0 33 4 A P2 1 0 0 5 A P2 2 0 5 6 A P2 3 120 10 7 B P1 1 10 20 8 B P1 2 0 50 I need a new field "EffectiveFcst" such that when Day = 1 then EffectiveFcst = CumDailyFcst and for following days - Here's the desired output - Mat Plant Day UU CumDailyFcst EffectiveFcst 1 A P1 1 0 11 11 2 A P1 2 10 22 22 3 A P1 3 0 33 23 4 A P2 1 0 0 0 5 A P2 2 0 5 5 6 A P2 3 120 10 10 7 B P1 1 10 20 20 8 B P1 2 0 50 40 I am currently using a for loop but the actual table is >300K rows so hoping to do this with tidyverse for more elegant and faster approach. Tried the following but didn't work out - group_by(df, Mat, Plant) %>% mutate(EffectiveFcst = ifelse(row_number()==1, CumDailyFcst, 0)) %>% mutate(EffectiveFcst = ifelse(row_number() > 1, CumDailyFcst - lag(CumDailyFcst, default = 0) + max(lag(EffectiveFcst, default = 0) - lag(UU, default = 0), 0), EffectiveFcst)) %>% print(n = nrow(.)) A: We can use accumulate from purrr library(tidyverse) df %>% group_by(Mat, Plant) %>% mutate(EffectiveFcst = accumulate(CumDailyFcst - lag(UU, default = 0), ~ .y , .init = first(CumDailyFcst))[-1] ) # A tibble: 8 x 6 # Groups: Mat, Plant [3] # Mat Plant Day UU CumDailyFcst EffectiveFcst # <chr> <chr> <int> <int> <int> <dbl> #1 A P1 1 0 11 11 #2 A P1 2 10 22 22 #3 A P1 3 0 33 23 #4 A P2 1 0 0 0 #5 A P2 2 0 5 5 #6 A P2 3 120 10 10 #7 B P1 1 10 20 20 #8 B P1 2 0 50 40
{ "pile_set_name": "StackExchange" }
Q: String.Format doesn't work as expected Maybe its my machine, but this doesn't make any sense. String.Format doesn't work. These two should technically equal, but do not. What's missing? I'm using ASP.NET 3.5 on Windows 7. string.Format("{0};{1};{2};{3};{4};{5};{7};{8};{9}" , "711.01" , "711.01" , "711.01" , "136.74" , "136.74" , "136.74" , "136.74" , "711.01" , "711.01" , "711.02 br "); //and string.Join(";" , new[]{"711.01" , "711.01" , "711.01" , "136.74" , "136.74" , "136.74" , "136.74" , "711.01" , "711.01" , "711.02"}); A: You are missing {6} in the Format example. "{0};{1};{2};{3};{4};{5};{7};{8};{9}" should be "{0};{1};{2};{3};{4};{5};{6};{7};{8};{9}" A: As pointed out by Chris you have an extra br. You're also missing {6} from your string.format: string.Format("{0};{1};{2};{3};{4};{5};{6};{7};{8};{9}" , "711.01" , "711.01" , "711.01" , "136.74" , "136.74" , "136.74" , "136.74" , "711.01" , "711.01" , "711.02");
{ "pile_set_name": "StackExchange" }