source
sequence
text
stringlengths
99
98.5k
[ "stackoverflow", "0054553180.txt" ]
Q: using pip search inside a python script in a short format, I'm preparing a python script to search all required dependencies in a private pypi repo if all dependencies exist in the repo, the script tops, if not it builds them and pushes them to the pypi repo I have seen some examples using: search_command = pip.commands.search.SearchCommand() options, _ = search_command.parse_args([name, "--index", publish_pypi_simple_url]) pypi_hits = search_command.search(name, options) hits = pip.commands.search.transform_hits(pypi_hits) However when running this code i get AttributeError: module 'pip' has no attribute 'commands' Does anyone have a good solution for performing pip searches in a private pypi repository with a python script? Thank you all in advance EDIT: My problem was related to badly installed python environments. A: Works for me. -->python2 -c "import pip; print(pip.commands); print(pip.commands.search)" <module 'pip.commands' from '/usr/lib/python2.7/site-packages/pip/commands/__init__.pyc'> <module 'pip.commands.search' from '/usr/lib/python2.7/site-packages/pip/commands/search.pyc'> -->python3 -c "import pip; print(pip.commands); print(pip.commands.search)" <module 'pip.commands' from '/usr/lib/python3.6/site-packages/pip/commands/__init__.py'> <module 'pip.commands.search' from '/usr/lib/python3.6/site-packages/pip/commands/search.py'>
[ "math.stackexchange", "0000446543.txt" ]
Q: Help for evaluating complicated integral $\int \frac 1 {x^n-x} dx$ I have this complicated integral to evaluate : $$\int \dfrac 1 {x^n-x} dx$$ I'm struggling to evaluate this. My attempt : $$\int \dfrac1x \cdot \dfrac 1 {x^{n-1}-1} dx$$ Now, I try to apply integration by parts. For that, I use : $V=\large\dfrac1x$ and $U=\large\dfrac 1 {x^{n-1}-1}$ But, that doesnt take me anywhere. It just gives me an even more complicated expression to evaluate.. Help would be appreciated.. Thank you.. A: Hint : Let I=$\large\int \dfrac 1 {x^n-x} dx$ I=$\large\int \dfrac 1{x} \cdot \dfrac 1 {x^{n-1}-1} dx$ I=$\large\int \dfrac {x^{n-2}}{x^{n-1}} \cdot \dfrac 1 {x^{n-1}-1} dx$ let $\large x^{n-1}=t$ $\implies dt=\big(n-1)x^{n-2}\ dx$ so, I=$\large \dfrac{1}{n-1}\cdot \int \dfrac {dt}{t\cdot (t-1)} $ use partial fractions now.. You're done!! A: $$\int\dfrac{1}{x^n-x}\mathrm{d}x=\int\dfrac{1}{x^n\left(1-\dfrac{1}{x^{n-1}}\right)}\mathrm{d}x$$ Now subs. $\dfrac{1}{x^{n-1}}=t\implies \mathrm{d}t=-\dfrac{(n-1)}{x^n}\mathrm{d}x$ Hence your integral becomes $$\dfrac{1}{(n-1)}\int\dfrac{\mathrm{d}t}{t-1}$$
[ "stackoverflow", "0033949013.txt" ]
Q: CSS overflow: hidden cuts shadow This is how it looks like now: When I disable overflow: hidden; shadow is normally all around, but when it's on - it's cut on the left and on the top. I'm not sure why it's only cutting those two sides, but still it looks not nice as for now. How to get rid of that? Code: .toolong { width: 80%; overflow: hidden; white-space:nowrap; text-overflow: ellipsis; } .shadow { text-shadow: 2px 2px 2px black, -2px -2px 2px black, 2px -2px 2px black, -2px 2px 2px black, 4px 4px 4px black, -4px -4px 4px black, 4px -4px 4px black, -4px 4px 4px black; font-weight: bold; } <div class="col-sm-12"> <h2 class="pull-right"><span class="label label-warning">1</span></h2> <h3 class="pull-left shadow toolong"> Piotrek z Bagien <br> <span><h4 class="gray shadow">Pinta</h4></span> <span><h6 class="gray shadow">India Pale Ale (Poland)</h6></span> </h3> </div> A: I would recommend adding padding to the top and left: JS Fiddle .toolong { width: 80%; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; padding-left: 5px; padding-top: 5px; } And if you need, you can re-align them back in place using negative margins: JS Fiddle .toolong { width: 80%; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; padding-left: 5px; padding-top: 5px; margin-left: -5px; margin-top: -5px; }
[ "stackoverflow", "0015569795.txt" ]
Q: Why is it possible to change chars in chars array, and impossible with char *? If I declare an array of chars (char str[]) I am able to change any of the characters inside. However, if I declare of that array like this - char* str="abcd"; its impossible to change any char inside. why is that? shouldn't them both be the same thing? A: When you declare an array of characters char myarr[5] = "abcd"; It's your array. The abcd letters are copied inside your local array and you're free to do with it whatever you want. A string literal in c++ (a string in "") is of type const char[N] . You can store a pointer to it const char* p = "abcd" Now, because p is const, you can't modify your string literal, which is good. Unfortunately, due to historical reasons, there exists an implicit conversion from a string literal to char* char * p = "abcd" In this case you can unfortunately modify the string literal, but doing so has undefined behavior. Luckily, this conversion is deprecated. Note that this is a unique issue with string literals, because it's the only type of literals that is an lvalue. All other literals are rvalues so there's no notion of modifying them. A: char* reserves space for the string in Read Only Memory so you can't alter it. Whereas char str[] is on Stack. Variables of type char* behave like const and hence you can't alter it.
[ "stackoverflow", "0062322619.txt" ]
Q: violin_plot() with continuous axis for grouping variable? The grouping variable for creating a geom_violin() plot in ggplot2 is expected to be discrete for obvious reasons. However my discrete values are numbers, and I would like to show them on a continuous scale so that I can overlay a continuous function of those numbers on top of the violins. Toy example: library(tidyverse) df <- tibble(x = sample(c(1,2,5), size = 1000, replace = T), y = rnorm(1000, mean = x)) ggplot(df) + geom_violin(aes(x=factor(x), y=y)) This works as you'd imagine: violins with their x axis values (equally spaced) labelled 1, 2, and 5, with their means at y=1,2,5 respectively. I want to overlay a continuous function such as y=x, passing through the means. Is that possible? Adding + scale_x_continuous() predictably gives Error: Discrete value supplied to continuous scale. A solution would presumably spread the violins horizontally by the numeric x values, i.e. three times the spacing between 2 and 5 as between 1 and 2, but that is not the only thing I'm trying to achieve - overlaying a continuous function is the key issue. If this isn't possible, alternative visualisation suggestions are welcome. I know I could replace violins with a simple scatter plot to give a rough sense of density as a function of y for a given x. A: Try this. As you already guessed, spreading the violins by numeric values is the key to the solution. To this end I expand the df to include all x values in the interval min(x) to max(x) and use scale_x_discrete(drop = FALSE) so that all values are displayed. Note: Thanks @ChrisW for the more general example of my approach. library(tidyverse) set.seed(42) df <- tibble(x = sample(c(1,2,5), size = 1000, replace = T), y = rnorm(1000, mean = x^2)) # y = x^2 # add missing x values x.range <- seq(from=min(df$x), to=max(df$x)) df <- df %>% right_join(tibble(x = x.range)) #> Joining, by = "x" # Whatever the desired continuous function is: df.fit <- tibble(x = x.range, y=x^2) %>% mutate(x = factor(x)) ggplot() + geom_violin(data=df, aes(x = factor(x, levels = 1:5), y=y)) + geom_line(data=df.fit, aes(x, y, group=1), color = "red") + scale_x_discrete(drop = FALSE) #> Warning: Removed 2 rows containing non-finite values (stat_ydensity). Created on 2020-06-11 by the reprex package (v0.3.0)
[ "stackoverflow", "0016044470.txt" ]
Q: How to render Html page in jsp Greeting,I want to render the whole html page in jsp and do some operation like replace the text according to code before run on server.Is it possible.Actually I am new in java Programming.In .net ,I render the html from xml file like this <appSettings> <add key="CreateUser" value="~/App_Data/CreatingUserhtm.htm"/> </appSettings> how can i render html page in jsp? A: This all depends on the amount of content that is "dynamic", and what your original question means. JSP Reading XML content to Render I would say you have the option to use XSL and do it all in the client that will also reduce the overhead on your server. You can use XSL to convert XML to HTML client side. Otherwise you could also use XSL within JAVA and transform the XML. See: http://www.java2s.com/Code/Java/JSP/JSPXMLandXSLTtransform.htm XML data sent from Servlet to JSP If you want to set variables from a servlet and read them in a JSP (utilizing MVC pattern e.g.), you could use one of the following references: Use Session Scope, e.g. request.getSession().setAttribute("key","value"); See: How to pass variable from a servlet to a jsp page? Use HTTP request variables, see: Pass variables from servlet to jsp
[ "apple.stackexchange", "0000066884.txt" ]
Q: How can I hide **some** birthdays in iOS Calendar? I have entered the birthday for several of my Contacts, and these birthdays show up in Calendar. I know that I can enable or disable all birthdays by selecting or deslecting "Birthdays" from Show Calendars in the top corner of the Calendar app. But I only want to see some of my contact's birthdays in the Calendar; for example, personal contacts but not ex-coworkers. How can I prevent the display of certain birthdays? A: You could edit out the birthdate information from those contacts you do not want to see in the Birthdays calendar. Another way to accomplish this would be by manually adding the birthdays you do want to see to a new or existing calendar and then disable the Birthdays subscription. A: As a compromise, you can disable the notification for that person's birthday. In calendar, double click on the birthday even and then change the alert to none. You will then be prompted if you want to change this event or all future events. Select all future events and you will no longer receive notifications for that birthday. It will however remain in your birthday calendar, but you will no longer be pestered with reminders (which is what I came her looking for before figuring out I could disable the reminder)
[ "stackoverflow", "0049810668.txt" ]
Q: Add POST data when doing a TEMPORARY_REDIRECT from another POST im developing a site that include a purchase screen. I will use a service similar to PAYPAL. I just need to send POST data to this service and the service will take care from that. The thing is, there are some fields I want to hide. So inputs type hidden are not an option. So I added a simple form with just one data, productId and then redirect the POST with the added data. Now the problem, that data is being sent as URL parameters(I can see those values in the URL in the browser). I want those values (in the example, userId and reference) as POST data. How could I achieve this? The code: @RequestMapping(value = "/doPurchase", method = RequestMethod.POST) public ModelAndView doPurchase(Principal principal, HttpServletRequest request, @RequestParam(value = "productId", required = true) String productId, RedirectAttributes attributes) { // Product product = productRepository.findByProductCode(productId); // // DO STUFF... // ModelAndView modelAndView = new ModelAndView("redirect:PAYMENT_SERVICE_URL"); attributes.addAttribute("UserId", "USER_ID"); attributes.addAttribute("Reference", "REF_ID"); // // ETC ETC // request.setAttribute(View.RESPONSE_STATUS_ATTRIBUTE, HttpStatus.TEMPORARY_REDIRECT); return modelAndView; } A: It is impossible to redirect to do a POST request by 301/302. 307 can repeat the POST request, but you can not modify it. Reference: https://softwareengineering.stackexchange.com/questions/99894/why-doesnt-http-have-post-redirect https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/307 https://tools.ietf.org/html/rfc7231#section-6.4.7 Some bypass methods: Make your PAYMENT_SERVICE_URL accept both GET and POST requests. Make a intermediate page accept the redirected GET request, and generate a HTML POST form to PAYMENT_SERVICE_URL, and auto submit the form by JavaScript. If you are using SpringFramework, consider to use Flash Attributes: https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html#mvc-flash-attributes If you really want to hide some parameters in a general way, you can store the values in a database table and pass the id of the row to your redirected page by GET request, and then load the parameters from the database table by id. Or, you can encrypt/decrypt the parameters.
[ "japanese.stackexchange", "0000061632.txt" ]
Q: Can "suru" be also added to japanese verbs? I thought that "suru" was used with english verbs to create japanese verbs (ie ドライブする) or with japanese nouns to create japanese verbs (ie denwa suru 電話する) Can "suru" be also added to japanese verbs? If so, what's the purpose of adding "suru" to a word that is already a verb. For example, 運転, according to Google translator (which I dont know if it works properly) both 運転 and 運転する means to drive. Is this so? If so is there any nuance in both? A: 運転, by itself, is a noun, just like most of these 2-kanji words. The construction is thus the same as with 電話する, you add する to the noun to turn it into a verb. NEVER use Google translate as a dictionary. Instead, use a dictionary, such as https://jisho.org/search/%E9%81%8B%E8%BB%A2 Although, I must add that Google translate translates this correctly for me, i.e. into "operation" or "driving".
[ "stackoverflow", "0043062453.txt" ]
Q: Manipulate or check what data is available in cache in firebase using Javascript? Is there any way to manipulate cache data available while offline mode in firebase using javascript ? or is there anyway to know that what data is available in cache on offline mode in firebase using javascript? A: There is no public API to specifically manipulate the Firebase Database client's cache. But any write operation will automatically apply to the cached data (as well as to the server-side database when your connection is restored). There is no public API to know what data is stored in the Firebase Database client's cache.
[ "stackoverflow", "0039461012.txt" ]
Q: Making async WebApi wrapper over existing code We are exposing our current logic/business layer using WebAPI. As per my understanding, if we want to keep our self safe from thread starvation for the requests, we should make Async WebAPI controller, so a large number of concurrent request can make up. I do understand that as the underlying service/business layer is synchronous, so there will be no performance gain. We are just aiming for a large number of concurrent requests to pass through. Below is the code that i am using: public async Task<IHttpActionResult> Get() { var result = await Task.Run(() => Service.GetAllCompanies()); //existing business layer return Ok(result); } Wrapping underlying layer in a Task, is this good to proceed with and achieve the goal. A: My understanding is that if your await-ed methods' implementations aren't async, then you are not really accomplishing what you think you are. If you have CPU-bound service methods, you're just releasing a thread from the request-handling pool and then spinning up a new one (from the same pool, mind you) when you Task.Run(); So you incur some overhead from that switch, but the ASP.NET thread pool is still doing the work, so you haven't achieved what you want. If you service methods can be converted to be pure (or mostly pure) async code, then you would stand to benefit from working bottom up. Reference: https://msdn.microsoft.com/en-us/magazine/dn802603.aspx
[ "stackoverflow", "0020517318.txt" ]
Q: Rails4 scope with parameters I somehow cannot find any place in the rails documentation about how to put some params into a named scope, f.e. something like this scope :by_id, -> { where :id = id } A: scope :by_id, ->(id) {where (:id => id)} this should work
[ "stackoverflow", "0023941126.txt" ]
Q: Regular expression MatchCollection returns 1 instead of expected 3 I have a long string in C# where it's formatted such as \\server\value I've been using a regular expression pattern of "(?<='\\\\).*(?=\\)" to extract the server from the string. However there's a use case where multiple '\server\value' strings could be chained together like so '\\serverA\value1' + '\\serverB\value2' + '\\serverC\value3' I'm trying to use the MatchCollection to extract all the server name using the pattern (?<=.\\\\).*(>=\\) the period in the first grouping construct to account for the ' character. I would expect the result to return 3 occurences but it only returns 1. What's wrong with my pattern? string expression = "'\\\\serverA\\value1' + '\\\\serverB\\value2' + '\\\\serverC\\value3'"; string pattern = @"(?<=\\\\).*(?=\\)"; MatchCollection matches; matches = Regex.Matches(expression, pattern); A: If I got, I're getting result like this serverA\value1' + '\\serverB\value2' + '\\serverC And you want to get these matches: serverA serverB serverC You can use lazy quantification: (?<=\\\\).*?(?=\\)
[ "stackoverflow", "0006645555.txt" ]
Q: android post issue, why I receive "No route to host" Anybody can help me? When calling HttpResponse response = client.execute(request); It throws an IOException, which shows "No route to host". HttpClient client = new DefaultHttpClient(); HttpPost request = new HttpPost(urlstr.toString()); List<NameValuePair> postParams = new ArrayList<NameValuePair>(); postParams.add(new BasicNameValuePair("Login_User_Name", namestr)); postParams.add(new BasicNameValuePair("Login_User_Password", passwordstr)); UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParams, HTTP.UTF_8); request.setEntity(formEntity); HttpResponse response = client.execute(request); my web soucecode is below <div class="S-Login" id="S-Login"> <div class="h" JNetDriftBar="title"> <span> </span> </div> <div class="lt" Lge="Login_User_Name"></div> <div class="ln"> <div class="N-Ipt"> <div class="Nir"></div> <div class="Nil"></div> <div class="Nic"> <input type="text" id="Login_User_Name" JNetDriftBar=":focus" value="" maxlength="40" /> </div> </div> </div> <div class="lt" Lge="Login_User_Password"></div> <div class="ln"> <div class="N-Ipt"> <div class="Nir"></div> <div class="Nil"></div> <div class="Nic"> <input type="password" id="Login_User_Password" value="" maxlength="40" /> </div> </div> </div> <div class="lt" Lge="Login_Language"></div> <div class="ln" style="text-align:left;"> <div class="N-Select"> <div class="N-Ipt"> <div class="Nir"></div> <div class="Nil"></div> <div class="Nic"> <input type="text" readonly="readonly" id="Login_Language" value="" /> </div> </div> <div class="NOpt Nc Lg" id="Login-allLanCot"> </div> </div> </div> <div class="lt"></div> <div class="ln"> <a href="javascript:;" hidefocus="true" class="N-Btn-1" onmousedown="$$.md(this,'N-Btn-1dw',event);" onmouseup="$$.mu(this,'N-Btn-1dw',event);" Lge="Login_Enter" onclick="Entry.submit();"></a> </div> </div> A: Either the domain name in the URL is invalid (does not exist), you have no network connection, or your DNS server is incorrectly set. Verify that you can browse to the URL in the Android browser. EDIT: also, make sure you have the INTERNET permission. Add <uses-permission android:name="android.permission.INTERNET" /> to your AndroidManifest.xml.
[ "puzzling.stackexchange", "0000062111.txt" ]
Q: Who am I?- I lived towards the end of the age of enlightenment I was able show the deconstruction of the intellectual pretension of the Enlightenment. Everyone was under the assumption that reason and science are the only routes to reality and truth. I perceived the idea that we must go deeper into the mind and how it constructs the universe. Most of the Enlightenment had already written and debated their philosophies by the time I was born. I would help label this period. A: I think you are almost certainly Immanuel Kant but I am inclined to agree with ABcDexter that this is more trivia question than puzzle; one bit of evidence for that is that there really isn't much to say about why that's the answer beyond "Well, the description there does somewhat resemble what he did". Though I will mention, in connection with the last sentence, that the German word Aufklärung generally used for the period is found in the title of one of his works, which may be partially responsible for its use. I'm not going to close it myself, not least because there isn't any very clear PSE policy on this sort of question; readers wondering whether or not to vote for closure may wish to have a look at this Meta question where the matter is discussed; there are two answers, both with quite positive scores, advocating different approaches.
[ "stackoverflow", "0026603974.txt" ]
Q: How to count elements from list if specific key present in list using scala? I have following list structure - "disks" : [ { "name" : "A", "memberNo" :1 }, { "name" : "B", "memberNo" :2 }, { "name" : "C", "memberNo" :3 }, { "name" : "D", } ] I have many elements in list and want to check for 'memberNo', if it exists I want count of from list elements. e.g. here count will be 3 How do I check if key exists and get count of elements from list using scala?? A: First create class to represent your input data case class Disk (name : String, memberNo : String) Next load data from repository (or other datasource) val disks: List[Disk] = ... And finally count disks.count(d => Option(d.memberNo).isDefined)
[ "stackoverflow", "0047994225.txt" ]
Q: Using lapply to subset a single data frame into a list of data frames in R Happy holidays everyone! This website has been particularly helpful for me with past programming needs so I am hoping you can help me out here as well as I'm a bit stuck :) Context Currently, I have a data frame that is full of soccer matches called wc_match_data. Here is what it looks like: type_id tourn_id day month year team_A score_A score_B team_B win loss f wc_1934 27 5 1934 Germany 5 2 Belgium Germany Belgium I wasn't able to fit the data for the final column, draw, but basically the draw column is TRUE if the match is a draw, if not, it is FALSE. In the case of a draw, the win and loss columns are just filled by DRAW. The type_id is either f or q depending on if the match was a World Cup qualifier or a World Cup finals match. The tourn_id refers to the tournament the match was for, whether it was a qualifier or finals. What I Want To Do I'm basically trying to create a new list of data frames for each World Cup year (1930, 1934, 1950, 1954, etc.). The first column of each of these new data frames should be ONLY the countries that played in that World Cup tournament (so it changes in every tournament). Here is what I'm doing # Create tournament vector (20 total) wc_years <- levels(wc_match_data$tourn_id) # Create empty list wc_dataframes <- list() # Filter wc_dataframes <- lapply(wc_years, function(year) data.frame(subset(wc_match_data, tourn_id == year)) This isn't working for me. It does create a list of 20 elements, but when I look at it in my environemnt, everything is pretty unrecognizable, and the tourn_id column for each of the 20 data frames says that it has 20 levels, which is obviously not what I want. It should just be one. I'm pretty lost, can anyone point me in the right direction? I'd be happy to send you my data if that makes things easier. One final note As you can tell, I haven't even bothered with getting the unique countries into the lapply function yet. I know that this code: unique(c(as.character(unique(wc_match_data$team_A)), as.character(unique(wc_match_data$team_B)))) Will return the unique list of countries for ALL World Cups, but I would need these for each individual World Cup, and I can't really figure out how to do that. Thank you so much in advance for the help, and happy holidays! I hope that this question can help people in the future :) A: Are you looking for split function? Basically you will use the year asyour splitting factor in your case. Let me show an example of using this function: set.seed(1) dat=data.frame(matrix(rnorm(10*5),10,5)) split(dat,rep(1:5,each=2)) $`1` X1 X2 X3 X4 X5 1 -0.6264538 1.5117812 0.9189774 1.3586796 -0.1645236 2 0.1836433 0.3898432 0.7821363 -0.1027877 -0.2533617 $`2` X1 X2 X3 X4 X5 3 -0.8356286 -0.6212406 0.07456498 0.38767161 0.6969634 4 1.5952808 -2.2146999 -1.98935170 -0.05380504 0.5566632 $`3` X1 X2 X3 X4 X5 5 0.3295078 1.12493092 0.61982575 -1.3770596 -0.6887557 6 -0.8204684 -0.04493361 -0.05612874 -0.4149946 -0.7074952 $`4` X1 X2 X3 X4 X5 7 0.4874291 -0.01619026 -0.1557955 -0.3942900 0.3645820 8 0.7383247 0.94383621 -1.4707524 -0.0593134 0.7685329 $`5` X1 X2 X3 X4 X5 9 0.5757814 0.8212212 -0.4781501 1.1000254 -0.1123462 10 -0.3053884 0.5939013 0.4179416 0.7631757 0.8811077
[ "stackoverflow", "0007175156.txt" ]
Q: How to make Cocoa understand that my iPhone app isn't in English? I work on an iPhone app that is purely in Swedish and it will never be localized to any other languages. All the strings in the app is in Swedish, so we don't even have Localizable.strings. The problem is that the strings generated by Cocoa (such as Done and Edit) are in English. I've tried setting Localization native development region in the Info.plist to Swedish, but that changed nothing. It shouldn't be harder than that to tell Cocoa that my app is in Swedish, but obviously it is. I've also tried a bunch of other stuff without any luck. So what do I need to do to make Cocoa localize its strings to Swedish? A: The strings generated by Cocoa (such as Done and Edit) are in English because your iPhone language settings are set to English (in Settings -> General -> International -> Language ). If you set the language settings to Swedish you should see the texts in Swedish. This is how the iPhone works by default, if you want to change the texts of some buttons to force them to Swedish you will have to create an outlet of them and change the text manually. For example like this UIBarButtonItem (with a default text Done (in english)): UIBarButtonItem *doneButton = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(doneContact)] autorelease]; doneButton.title =@"Whatever"; self.navigationItem.rightBarButtonItem = doneButton; I hope that this may help you...
[ "stackoverflow", "0004468703.txt" ]
Q: PHP / Prado property 'treatment' I'm learning Prado php framework for a while now, and I've been wondering about one feature, if it's from PHP or somehow implemented in Prado. Namely, classes used in Prado can utilize properties (fields) that aren't declared in the class itself, but 'defined' by set and get methods. Here's an example: class myClass extends somePradoClass { public function myPradoMethod() { $MyVariable = 22; echo $MyOtherVariable; // this one is read only (only get method defined) } public function getMyVariable() { return 0; } public function setMyVariable($value) { $this->isFieldFromParentClass = $value; } public function getMyOtherVariable() { return $this->isOtherFieldFromParentClass; } } Now, somehow it is perfectly fine to use $MyVariable and $MyOtherVariable throughout the class, as if they were declared as class properties. So, question again: is this a PHP or Prado feature? Thx A: This is neither a PHP feature nor a Prado feature. I don't know Prado, but PHP has not such feature, so Prado can't have it either ;) What you are looking for however, are things such as this: $this->myUndefinedMember = $something Your example uses local variables, these cannot be set and read from automagically. This will invoke the magic __set method, if defined that is. Prado could (I don't know if it does) define this method for a certain superclass that you usually use and then dynamically check whether a setter method has been defined for that variable name. The signature is as follows: public function __set($name, $value) The maigc method __get($name) works analogously. If you do not set it as public, you will only be able to use this property-like feature from within the class( or subclasses). As a reference, see here on PHP5's feature or overloading properties and methods. Update A sample implementation could look like this: class MyMagicSuperClass{ public function __get($name){ $getter_name = 'get'.ucwords($name); if(method_exists($this, $getter_name){ return $this->$getter_name(); } //error handling } public function __set($name, $value){ $setter_name = 'get'.ucwords($name); if(method_exists($this, $setter_name){ return $this->$setter_name($value); } //error handling } }
[ "gamedev.stackexchange", "0000128018.txt" ]
Q: Copy velocity of one object to other object I have a script to pick up items with a VR controller. I connect the object to the VR controller through a FixedJoint on a rigidbody attachPoint. When I drop an item through destroying the Joint however it plummets straight down to the ground, no force from the controller is transferred to the released object. Thus I can't throw the object. I tried it using the AddForce() method. attachPoint's velocity is the controller's as it is a child of the controller. Relevant code below. Can someone help me with transferring the velocity of the controller at the time of release to the object just released? Thanks! public class PickupCarryRelease : MonoBehaviour { public Rigidbody attachPoint; FixedJoint joint; GameObject obj; Collider grabbedObjColl; void Update() { Release(); } void Release() { var device = SteamVR_Controller.Input((int)trackedObj.index); if (canGrab && joint != null && device.GetTouch(SteamVR_Controller.ButtonMask.Trigger)) { var obj = joint.gameObject; var rb = obj.GetComponent<Rigidbody>(); grabbedObjColl.isTrigger = false; rb.detectCollisions = true; //Transfer velocity Destroy(joint); rb.AddForce(attachPoint.velocity, ForceMode.Impulse); StartCoroutine(GrabDelay()); } } } A: I will post this answer since this question was resolved by me in the comments above. In order to get the velocity of the VR controller, you need to use: var device = SteamVR_Controller.Input((int)trackedObj.index); device.velocity;
[ "stackoverflow", "0061414802.txt" ]
Q: How to manually add legend I have data that looks like the follow: test1 <- tibble(Freq=c(79,170,126), Seconds=1:3, Task = "Task1") Which I plot it the following way: ggplot(test1, aes(x=Seconds, y=Freq)) + geom_histogram(stat="identity", fill="red", alpha=0.5, width=1, color="black")+ ylim(0,180) + labs(title="Task 1", x="Number of Seconds Inside Island", y = "Count") But the graph produced have no legend. Ideally I would like a legend with the header "Task" and the red box named "Task 1". How do I manually add a legend to a graph like this with the data produced above? The other solutions I have found are for different kinds of datasets it seems, or at least I have failed to make them work. Any help is much appreciated. A: You should explicitly provide a column in aes if you want it on the legend. In this example, you just put a constant column test1$col <- "Task 1" ggplot(test1, aes(x=Seconds, y=Freq, fill=col)) + geom_histogram(stat="identity", alpha=0.5, width=1, color="black")+ ylim(0,180) + labs(title="Task 1", x="Number of Seconds Inside Island", y = "Count", fill = "Task")
[ "serverfault", "0000725152.txt" ]
Q: Connect two remote offices I would like to connect my company's office with another remote office that is owned by us. Our office is in Europe and the new one is in the states . I'm an experienced sys admin However I've never done such thing before , therefore I'd like to get some better understanding at what I'm looking at and if it's not somethings I think I can handle, I'll get a contractor to do it for us but I'd still want to know what should be done even if a contractor will do it. It has to be an fitted enterprise solution as the company is quite large. The two things I'd like to know are: 1)Networking - what's the best way to establish a site to site connectivity?( MPLS, vpn...something else? ) and recommended products. 2) How do I connect our two active directories together ? The new office doesn't have anything currently so I thought about spinning up an AD instance once the site2site is done , and setup the new AD as a domain controller in an existing domain? And the DNS should be setup as secondary - right ? Is that the right approach? Is there something else to be taken care of? ( other than dns/dhcp of course ). Thanks a lot for the kind help!! A: 1) unless you have tons of money and very high performance requirements, a site-to-site IPSec VPN is what the doctor ordered. I use pfsense for this purpose, but there are many options. 2) yes, add a new domain controller to your existing domain. Don't forget to create a new site (specifying the subnets correctly for each site), so that your AD clients can more easily locate their closest DC.
[ "tex.stackexchange", "0000406555.txt" ]
Q: The "to connector" does not work when using the the "algorithms" package bundle Suppose that one has the following pseudo code, written in LaTeX using the package algorithms: \documentclass[]{article} \usepackage{algorithm}% http://ctan.org/pkg/algorithms \usepackage{algpseudocode}% http://ctan.org/pkg/algorithmicx \begin{document} \begin{algorithm}[t] \caption{Euclid example}\label{euclid} \begin{algorithmic}[1] \Procedure{Euclid}{$a,b$}\Comment{The g.c.d. of a and b} \State $r\gets a\bmod b$ and foobar\label{foobar} \For{$i \gets 1$ to $n$} \While{$r\not=0$}\Comment{We have the answer if r is 0} \State $a\gets b$ \State $b\gets r$ \State $r\gets a\bmod b$ \EndWhile\label{euclidendwhile} \EndFor \State \textbf{return} $b$\Comment{The gcd is b} \EndProcedure \end{algorithmic} \end{algorithm} \end{document} Written like that, it does work. However, when I try changing the like \For{$i \gets 1$ to $n$} to \For{$i \gets 1$ \To $n$} or \For{$i \gets 1$ \TO $n$} it then does not compile, with the error "Undefined control sequence". Still, according to the package's documentation, it should work (see page 5 of the official documentation at http://ctan.math.utah.edu/ctan/tex-archive/macros/latex/contrib/algorithms/algorithms.pdf). What am I doing wrong? How else could I get the to connector in a for-loop, so that the to appears in bold and in the same font as loop and do? A: algpseudocode is part of algorithmicx and it does not provide \To or \TO. It's algorithmic (from the algorithms bundle) that provides \To. Define your own \To: \documentclass{article} \usepackage{algorithm,algpseudocode} \algnewcommand{\To}{{\normalfont\bfseries to }} \begin{document} \begin{algorithm}[t] \caption{Euclid example}\label{euclid} \begin{algorithmic}[1] \Procedure{Euclid}{$a,b$}\Comment{The g.c.d.\ of $a$ and $b$} \State $r\gets a \bmod b$ and foobar \For{$i \gets 1$ \To $n$} \While{$r \neq 0$}\Comment{We have the answer if $r$ is $0$} \State $a \gets b$ \State $b \gets r$ \State $r \gets a \bmod b$ \EndWhile \EndFor \State \textbf{return} $b$\Comment{The g.c.d.\ is $b$} \EndProcedure \end{algorithmic} \end{algorithm} \end{document}
[ "stackoverflow", "0027621844.txt" ]
Q: how to make a variable of two variables Before your read this, my first account was blocked because i asked bad questions.. So please dont vote negative but say what i am doing wrong Sooo I have this script: var img1 = new Image() img1.src="image1.jpg" var img2 = new Image() img2.src="image2.jpg" var img3 = new Image() img3.src="image3.jpg" function Canvas() { var ctx = document.getElementById('slider').getContext('2d'); var pic=1 function slider() { this.draw = function() { if(pic<4){pic++} else{ pic=1 } var img = "img"+pic ctx.drawImage(img,0,0,ctx.canvas.width,ctx.canvas.height) } } var slider = new slider(); function draw() { ctx.clearRect(0,0,ctx.canvas.width,ctx.canvas.height); ctx.save(); //draw slider.draw(); //draw ctx.restore(); } var animateInterval = setInterval(draw,100) } window.addEventListener('load', function(event) { Canvas(); }); I am trying to draw the image 1 or 2 or 3 on my canvas. But I also have the var pic wich has the number. So i tried ctx.drawimage(img+pic,0,0) or var img = "img"+pic and draw it then. But it doesnt work for me. I hope you accept my question and can answer it, THNX A: Use an array instead var img = []; /* you should use a for loop here */ for (var i = 0; i < 3; i++) { img[i] = new Image(); img[i].src = "image" + (i+1) ".jpg"; } and later you refer the right image with img[pic]. Be only sure to use an index between 0 and img.length - 1
[ "softwareengineering.stackexchange", "0000008789.txt" ]
Q: CMP Entity Beans as a "naive" ORM solution I was browsing through this talk about "Historically Bad Ideas" over the history of Computer Science, and found an interesting presentation about the rise & fall of the Java Enterprise initiatives. Slide #16 grabbed my attention by suggesting that Container Managed Persistence is a "naïve ORM solution". Of course, I assume the presenter made a live in-depth analysis of the problem, which is missing in the slide. So I was left intrigued by that statement. Is CMP Entity Beans just a heavy piece of naive engineering? Aside any bias from the author(s) of the presentation, what would constitute a more adequate ORM solution in the domain of languages like Java or C#? I'm not asking for specific tools or frameworks, but better approaches. A: In general a good ORM solution should be easy to use and understand. It should promote the use of good design patterns (DAOs, DTOs, lazy loading, services, transaction boundaries, ease of configuration etc). It should be non-invasive - that is, it should not force you to extend special classes or implement special interfaces. The EJB specifications fell over a lot in the early days leading to the mass migration away to the likes of Spring and Hibernate. EJB1 failed to adequately define CMP fields on the bean, EJB2 sort of implied that they should be abstract accessors rather than actual fields, which was just odd, and it wasn't until EJB3 that something close to what everyone actually wanted was created. By then it was too late, everyone believed EJB sucked and it took the JPA and JTA JCRs to put things right again. EJB1 and 2 generally forced the developer to put all their persistence configuration in a bunch of XML files well away from the actual code that was using it. This lead to lots of confusion and buggy code. Other ORM frameworks learned from this and decided to use annotations instead. Big win for them. EJB1 and 2 had very limited support for different kinds of relationships and how they could be implemented in the underlying relational database. All kinds of special interfaces had to be adhered to and the resulting code was hard to fathom. Anyway, all that is in the past and we can look forward to a bright future with the likes of Hibernate implementing JPA and JTA. All very harmonious.
[ "electronics.stackexchange", "0000483366.txt" ]
Q: Driving car electrical vacuum pump I am trying to drive an electrical vacuum pump from a car directly from 12 VDC. Earlier, I succeeded with a different pump just by connecting them to DC power, the other pump (different brand) used around 10 A at 13.8 V. But now I got a new pump (different manufacturer) which does not rotate when I plug the power. It just moves small steps each time I connect it. It might be an AC pump, which seems strange to me for using it in a car. Can someone help me understand how to drive it? I attach the image of the circuit inside after opening the cap in the electric side, next to the two leads. The model of the pump is 59220-J5000. It looks exactly like this.. The resistance between the leads is about 0.2 ohm. A: Jasen provided the correct answer in the comments: the original power supply could not provide the initial current to start the motor. After switching to a more powerful (108 A, 30 V) power supply, the pump started properly.
[ "stackoverflow", "0030488180.txt" ]
Q: Change classes with jquery I'm new to jQuery and I got a problem related to adding and removing classes to an element with a certain ID. This is what I want to do (and also it works just fine, but I want to know the jQuery-solution): $('#blub').click(function() { document.getElementById('myelement').classList.toggle("myclass"); }); This is what I did: $('#blub').click(function() { $('#myelement').toggleClass('myclass'); }); It's a fairly stupid question, probably, but I just can't find the mistake. edit: I have added a snippet, as the syntax itself seems to be alright. Thanks your help so far :) $('document').ready(function() { $('#blub').click(function() { $('#myelement').toggleClass('myclass'); }); }); #myelement { fill: red; } .myclass { fill: blue; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button id="blub" style="border:none; background: none; width:300px; height:100px;"> <svg width="100%" height="100%"> <rect id="myelement" class="myclass" width="300" height="100" /> </svg> </button> A: There are two issues here: One is css, the id selector overrides the styles. Solution: #myelement { fill: red; } #myelement.myclass { fill: blue; } There is issue with jquery itself while dealing with svg elements jQuery SVG, why can't I addClass? Solution: $('#blub').click(function() { $('#myelement')[0].classList.toggle('myclass') });
[ "stackoverflow", "0025035967.txt" ]
Q: node.js express jsonp return typeof don't know why but my Express app is returning something weird with res.jsonp, something llike this: /**/ typeof jsonp1406719695757 === 'function' && jsonp1406719695757({"published":true,"can_add_to_cart":true,"updated_at":"2014-01-[...snip...] instead only this: jsonp1406719695757({"published":true,"can_add_to_cart":true,"updated_at":"2014-01-[...snip...] I can't understand why. Any ideas? A: If you look at the code for res.jsonp(), you'll find comments explaining the extra content at the beginning: // the /**/ is a specific security mitigation for "Rosetta Flash JSONP abuse" // the typeof check is just to reduce client error noise body = '/**/ typeof ' + callback + ' === \'function\' && ' + callback + '(' + body + ');';
[ "stackoverflow", "0008631475.txt" ]
Q: Edit where a pointer points within a function I have a pointer to a struct object in C++. node *d=head; I want to pass that pointer into a function by reference and edit where it points. I can pass it but it doesn't change where the initial pointer points but only the local pointer in the function. The arguments of the function must be a pointer right? And after how do I change it to show to a different object of the same struct? A: You have two basic choices: Pass by pointer or pass by reference. Passing by pointer requires using a pointer to a pointer: void modify_pointer(node **p) { *p = new_value; } modify_pointer(&d); Passing by reference uses &: void modify_pointer(node *&p) { p = new_value; } modify_pointer(d); If you pass the pointer as just node *d, then modifying d within the function will only modify the local copy, as you observed. A: Pass it by reference: void foo(node*& headptr) { // change it headptr = new node("bla"); // beware of memory leaks :) }
[ "stackoverflow", "0009226730.txt" ]
Q: Wix installer finding registry key that does not exist I'm creating an installer for one of our products. The installer was done with WISE earlier but we wanted to change this to wix with this release. It's important that our users uninstall the old version of the product before installing the new version and thus I need to check for a key in the registry that was created by the old installer (the key is removed when the old version is uninstalled). I have a conditional check in the wxs like so: <!-- Check if older version of Product has been installed. Must be removed by user--> <!-- The key below is set by the old installer. If it exists, the old version is there.--> <Property Id="OLDKEY"> <RegistrySearch Id="OldRegKey" Root="HKLM" Key="SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Company Product för Product" Name="DisplayName" Type="raw"></RegistrySearch> </Property> <Condition Message="You need to uninstall the old version of Product before installing this one."> OLDKEY </Condition> You'll notice a Swedish character in there. I suspect this might be the cause of some problems. This is how I configured since I had to handle Swedish characters: <Product Id="*" Name="$(var.Manufacturer) $(var.ApplicationName)" Language="1033" Version="!(bind.FileVersion.Product.exe)" Manufacturer="$(var.Manufacturer) AB" UpgradeCode="[GUID]" Codepage="1252" > Notice the 1252 codepage. When I install and have the old version on the machine, I find the key in the registry and the installer will show me the message. If I remove the old version I can see the registry key disappear but the installer will still show me the message and exit. I have tried rebooting (you never know) to no avail. I'm running out of ideas... any thoughts? A: Turns out the registry search returns 1 if key is not found. So I changed OLDKEY To <![CDATA[OLDKEY <> 1]]> And it was fixed.
[ "stackoverflow", "0016382625.txt" ]
Q: Can I debug bluecove library? I see that Bluecove is open source, but there aren't any .pro files in sources. How can I open sources in eclipse and debug? A: In Eclipse you can right-click on project, and there is Java Build Path, there you have your dependencies. Each dependency can be unfolded and there is "Source attachment", you can attach your source files there and then debug it.
[ "stackoverflow", "0005835528.txt" ]
Q: Constant based on variable? I'm making a small game in XNA at the moment. And I want to base the size of an array on my screen's resolution. I did it like this: public const int intBoardheight = (GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Height -150) / 10 ; public const int intBoardwidth = (GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Width - 200) / 10; public bool[,] GameBoard = new bool[intBoardheight,intBoardwidth]; public bool[,] GameBoardUpdate = new bool[intBoardheight, intBoardwidth]; public int[,] GameBoardInt = new int[intBoardheight, intBoardwidth]; But this gives me the error "The expression being assigned to 'Game_Of_Life_2.Game1.intBoardheight' must be constant". So, how do I base a constant on a variable? Thanks in advance! Simon. EDIT: Thanks guys! Worked very well! A: You can't. Make it a public static readonly int
[ "stackoverflow", "0042920885.txt" ]
Q: MySQL add column if not exist error How do I add a column if not exist in MySQL? I have tried this, but it doesn't work anymore in the latest MySQL: IF NOT EXISTS( SELECT NULL FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = 'tablename' AND table_schema = 'db_name' AND column_name = 'columnname') THEN ALTER TABLE `TableName` ADD `ColumnName` int(1) NOT NULL default '0'; END IF; The error: [Err] 1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'IF NOT EXISTS ( SELECT NULL FROM INFORMATION_SCHEMA.COLUMNS WHERE ' at line 1 A: Sole reason you get that error cause you are trying to run it individually whereas that IF block has to be executed inside a procedure block like below create procedure usp_addcol as begin IF NOT EXISTS( SELECT NULL FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = 'tablename' AND table_schema = 'db_name' AND column_name = 'columnname') THEN ALTER TABLE `TableName` ADD `ColumnName` int(1) NOT NULL default '0'; END IF; end; Now you can just call the procedure.
[ "stackoverflow", "0053109388.txt" ]
Q: QML: Setting "source" property for image causes it to disappear What I'm trying to do is update the source of an image with QML in PyQt5. When I use element.setProperty("source", "./testImage.png") to change the image I get the following error message. QML Image: Protocol "" is unknown Any idea on how to fix this? I've looked at other ways to interact with QML elements and if possible I'd like to stick with changing the image through Python code rather then through just QML. main.py from PyQt5.QtWidgets import * from PyQt5.QtQml import * from PyQt5.QtCore import * from PyQt5.QtQuick import * from PyQt5 import * import sys import resource_rc class MainWindow(QQmlApplicationEngine): def __init__(self): super().__init__() self.load("main.qml") self.rootContext().setContextProperty("MainWindow", self) self.window = self.rootObjects()[0] self.cardLeft = self.window.findChild(QObject, "cardLeft") @pyqtSlot() def changeImage(self): self.cardLeft.setProperty("source", "./images/3_of_clubs.png") if __name__ == '__main__': app = QApplication(sys.argv) window = MainWindow() sys.exit(app.exec_()) main.qml import QtQml 2.11 import QtQuick 2.3 import QtQuick.Controls 2.1 import QtQuick.Window 2.2 import QtQuick.Controls.Material 2.1 import QtQuick.Layouts 1.11 ApplicationWindow{ id: screen width: 720 height: 490 visible: true Material.theme: Material.Dark Item { id: cards width: parent.width height: parent.height - toolBar.height anchors { top: parent.top; bottom: toolBar.top; bottomMargin: 10 } RowLayout { anchors.fill: parent spacing: 20 Image { objectName: "cardLeft" id: cardLeft Layout.fillWidth: true Layout.maximumHeight: 250 Layout.minimumHeight: parent.height Layout.margins: 20 source: "./testImage.png" fillMode: Image.PreserveAspectFit } } } Button { Layout.alignment: Qt.AlignHCenter Layout.fillWidth: true Layout.fillHeight: true Layout.maximumHeight: 100 Layout.maximumWidth: 300 Layout.margins: 20 text: qsTr("Change Image") highlighted: true Material.accent: Material.color(Material.LightGreen) onClicked: MainWindow.changeImage() } } A: You have to pass a QUrl for it you must use QUrl::fromLocalFile(): import os import sys from PyQt5 import QtCore, QtGui, QtQml # import resource_rc dir_path = os.path.dirname(os.path.realpath(__file__)) class MainWindow(QtQml.QQmlApplicationEngine): def __init__(self): super().__init__() self.load(QtCore.QUrl.fromLocalFile(os.path.join(dir_path, "main.qml"))) self.rootContext().setContextProperty("MainWindow", self) if self.rootObjects(): self.window = self.rootObjects()[0] self.cardLeft = self.window.findChild(QtCore.QObject, "cardLeft") @QtCore.pyqtSlot() def changeImage(self): if self.cardLeft: url = QtCore.QUrl.fromLocalFile(os.path.join(dir_path, "images/3_of_clubs.png")) self.cardLeft.setProperty("source", url) if __name__ == '__main__': app = QtGui.QGuiApplication(sys.argv) window = MainWindow() sys.exit(app.exec_())
[ "stackoverflow", "0025374055.txt" ]
Q: Asm volatile ("int $0x3") call restarts the machine I am studying kernel development. To test my interrupt handler I need to run asm volatile ("idt $0x3") command. Whenever this command is called in my main.c, machine always restarts. I even tried to remove the interrupt handler. Nothing changed. What should I do? gdt assembly: [extern _start] lgdt [gdt_descriptor] jmp CODE_SEG:initgdt initgdt: mov ax, DATA_SEG mov ds, ax mov es, ax mov fs, ax mov gs, ax mov ss, ax mov ebp, 0x90000 mov esp, ebp call _start ;main.c function jmp $ gdt_star: gdt_null: dd 0x0 dd 0x0 gdt_code: dw 0xffff dw 0x0010 db 0x00 db 10011011b db 01001111b db 0x00 gdt_data: dw 0xffff dw 0x0020 db 0x00 db 10010010b db 01001111b db 0x0 gdt_end: gdt_descriptor: dw gdt_end - gdt_star - 1 dd gdt_star CODE_SEG equ gdt_code - gdt_star DATA_SEG equ gdt_data - gdt_star descriptor_tables.c: extern void idt_flush(uint32_t); extern void isr0(); extern void isr1(); .... extern void isr31(); static void init_idt() { idt_ptr.limit = sizeof(idt_entry_t) * 256 -1; idt_ptr.base = (uint32_t)&idt_entries; memset((uint8_t*)&idt_entries, 0, sizeof(idt_entry_t)*256); idt_set_gate(0, (uint32_t)isr0, 0x08, 0x8E); idt_set_gate(1, (uint32_t)isr1, 0x08, 0x8E); .... idt_set_gate(31, (uint32_t)isr31, 0x08, 0x8E); idt_flush((uint32_t)&idt_ptr); } static void idt_set_gate(uint8_t num, uint32_t base, uint16_t sel, uint8_t flags) { idt_entries[num].base_lo = base & 0xFFFF; idt_entries[num].base_hi = (base >> 16) & 0xFFFF; idt_entries[num].sel = sel; idt_entries[num].always0 = 0; idt_entries[num].flags = flags } interrupt.asm: %macro ISR_NOERRCODE 1 [GLOBAL _isr%1] _isr%1: cli push byte 0 push byte %1 jmp isr_common_stub %endmacro %macro ISR_ERRCODE 1 [GLOBAL _isr%1] _isr%1: cli push byte %1 jmp isr_common_stub %endmacro ISR_NOERRCODE 0 ISR_NOERRCODE 1 .... ISR_NOERRCODE 31 [EXTERN _isr_handler] isr_common_stub: pusha mov ax, ds push eax mov ax, 0x10 mov ds, ax mov es, ax mov fs, ax mov gs, ax call _isr_handler pop eax mov ds, ax mov es, ax mov fs, ax mov gs, ax popa add esp, 8 sti iret isr.c: void isr_handler(registers_t regs) { uint8_t str[12] = "\ninterrupt:"; str[11] = 0; puts(str, FALSE); itoa(str, 10, regs.int_no); puts(str, FALSE); str[0] = '\n'; str[1] = 0; puts(str, TRUE); } kernel_entry.asm: .... [global _idt_flush] _idt_flush: mov eax, [esp+4] lidt [eax] ret A: I converted the descriptor_tables.c C code to Assembly code and used following macro: %macro IDT_ENTRY 1 dw _isr%1 dw 0x08 db 0x0 db 0x8E dw 0x0000 %endmacro Now, it works. But I am not sure why it did not accept the C code. Moreover, following macro did not work either: %macro IDT_ENTRY 1 dw (_isr%1 - $$) & 0xFFFF dw 0x08 db 0x0 db 0x8E dw ((_isr%1 - $$) >> 16) & 0xFFFF %endmacro Again, I am not sure why the second macro is not working.
[ "serverfault", "0000065484.txt" ]
Q: How can I replace all instances of a specified string in a text file with another string? I have a file a.txt. I would like to replace all instances of "1.6" with "1.5" in that file, overwriting the original file. A: Using the command line : sed -i .bak -e 's/1\.5/1.6/g' /path/to/file This command replace in the file, the orginal file is saved as /path/to/file.bak A: You can use sed for that: sed 's/1\.5/1\.6/g' /path/to/file | tee output also if you are inside an editor like vim, you can do that : vim /path/to/file :%s/1\.5/1\.6/g In emacs : emacs /path/to/file M-x replace-string
[ "serverfault", "0000591543.txt" ]
Q: Structuring an OU to properly model an Organizational Hierarchy I'm experimenting with using OUs in my network's Active Directory and group policy. However, I'm having a little trouble figuring out the right way to structure my OUs so that I can have individual departments, but also have a higher level management users gain all rights of the departments lower on the organization's hierarchy. Let's say I have 4 organizational units Sales Marketing Accounting Executive Each department has their own drive mapping, which I set up through individual group policies within the department OUs. However, the one exception to this structure is the Executive department. These are the leaders of the company, so I would like users in this OU to get access to ALL of the drive mappings, not just a single drive. However, since an OU can only have one parent, I don't know how I could set this up so that the Executive OU can inherit the drive mapping policies from all departments. One thought would be have individual policies for each drive mapping, and then simply link the drive mapping policies to each department I wanted to have access. In this case, the Executive OU would have 4 links, one for each drive mapping. While this makes sense to a certain extent, it doesn't sound like the most maintainable solution. Everytime a department was added, or if additional policies were granted to an existing department, I would need to duplicate this link in the Executive OU as well. The other thought I had would be to simply use Security Groups as the objects in each OU, and assign departmental users to the security group instead of the OU (e.g DOMAIN\Marketing). However, this does not appear to work the way I expect. Group policies only seem to be applied to a user once they have been added to the appropriate OU, and it does not matter what Security Group they are in. The only other solution I can think of is to simply move the department policies out of OUs and instead rely on Security Filtering to apply the policies to different Groups. However, this does not seem to be the way that most examples and tutorials handle managing their policy objects, instead favoring these departmental OUs like I've listed above. What is the proper way for me to structure my Group Policy objects to accomplish what I am after? A: The proper way of handling this is using a single group policy for drive maps across your organization, with the usage of Group Policy Preferences. You can then set up targeting rules on each drive map according to your own security scheme. I'd probably avoid using OU's as the targeting rule, since you would need security groups no matter what.
[ "stackoverflow", "0059297239.txt" ]
Q: C control reaches end of non void function #include <cs50.h> #include <stdio.h> int get_proper_int(string prompt); int main(void) { int i = get_proper_int("Height:"); printf("%i\n",i); } int get_proper_int(string prompt) { int n; do { n = get_int("%s",prompt); } while (n<1||n>8); { for (int j = 0; j < n; j++) { printf("#\n"); } } } Not sure what I'm doing wrong here. The do..while loop works when I return n; at end of loop...and for loop works on its own too... A: You declare get_proper_int to return a value of type int, but there's no return statement anywhere in the function. Add it to the end of the function: int get_proper_int(string prompt) { int n; do { n = get_int("%s",prompt); } while (n<1||n>8); { for (int j = 0; j < n; j++) { printf("#\n"); } } return n; }
[ "stackoverflow", "0048390562.txt" ]
Q: Counting Search Comparisons C++ This program searches for a user entered word in a dictionary text file and outputs what line it is on. I need to count the number of comparisons made to find the word in both a linear and binary search. Right now it says there were zero comparisons made. Any ideas on where or how to implement these counters would be much appreciated. string linearSearch(const vector<string> &L, string k); string binarySearch(const vector<string> &L, string k, int a = 0, int b = -1); int count1 = 0; int count2 = 0; int main() { ifstream inFile; inFile.open("dictionary.txt"); vector < string > words; string line; while (getline(inFile, line)) { words.push_back(line); } inFile.close(); string userWord; cout << "Search for a word: " << endl; cin >> userWord; if (words.empty()) { return -1; } cout << "Using binary search, the word " << userWord << " is in slot " << binarySearch(words, userWord) << ". There were " << count2 << " comparisons made." << endl; cout << "Using linear search, the word " << userWord << " is in slot " << linearSearch(words, userWord) << ". There were " << count1 << " comparisons made." << endl; return 0; } string linearSearch(const vector<string> &L, string k) { for (int i = 0; i < L.size(); ++i) { count1++; if (L[i] == k) { count1++; return to_string(i); } } return to_string(-1); } string binarySearch(const vector<string> &L, string k, int a, int b) { ++count2; if (b == -1) { b = L.size(); } int n = b - a; if (n == 0) { return to_string(-1); //? } int mid = (a + b) / 2; if (L[mid] == k) { ++count2; return to_string(mid); } else if (L[mid] > k) { ++count2; return binarySearch(L, k, a, mid); } else { count2 += 2; return binarySearch(L, k, mid + 1, b); } return to_string(-1); } A: Uh oh, this looks like undefined behavior caused by Sequence Points (see this question for more information). To quote the answer in that question, the order of evaluation of operands of individual operators and subexpressions of individual expressions, and the order in which side effects take place, is unspecified. You're trying to perform a set and a get on the same variable (one of the count's) in the same sequence point. Which will happen first (the set or the get) is undefined. Split your cout's into two and everything should be solved. cout << "Using binary search, the word "<< userWord << " is in slot " << binarySearch(words,userWord) << "."; cout << "There were " << count2 << " comparisons made." << endl; cout << "Using linear search, the word "<< userWord << " is in slot " << linearSearch(words,userWord) << "."; cout << "There were " << count1 << " comparisons made." << endl;
[ "stackoverflow", "0033909839.txt" ]
Q: Create a PDF by passing HTML content to a method Create a PDF by passing HTML content to a method. I want to do this is c#. Is there a utility I can use? A: Try wkhtmtopdf. It is the best tool I have found so far. For .NET, you may use this small library to easily invoke wkhtmtopdf command line utility. links: http://wkhtmltopdf.org/ https://github.com/codaxy/wkhtmltopdf
[ "stackoverflow", "0019888270.txt" ]
Q: Drawing an absolute line in a window in C# I have an application on windows with multiline text field on it. I need a way to draw lines on that text field, so you could see both, the letters typed and those lines. I need to do this with C#, but I can use .dll's written in C++. I've heard something about subclassing where I could overtake render function from a window and adjust something to it, how do I do that with C#? Or maybe there are simplier ways than that? Please share. A: In .NET Framework, you may use WPF and write user control with Canvas and TextBox overlaying - and then make such operations with Dependency Properties tracking
[ "stackoverflow", "0006139968.txt" ]
Q: Best data store solution for small mathematical data but fast and with aggregate functions I'm looking for a data storage solution for a project with these requirements: The application creates dynamically a containter/table in the store. For a small period of time (two weeks for example) that table/container gets a huge amount of inserts in parallel. Last read have to be immediately available. The data inserted is very small, 4 to 6 numeric columns. Small query/filtering support is required, but no joins or cross queries. Is needed to execute some aggregate functions like "Count", "Sum", "Max", "Min" and "Avg". Basically, I need something like Windows Azure Table Storage but with aggregate functions. What would you recommend? A: RavenDB supports all you mentioned and more. Its scales very well, and supports aggregate functions via Map/Reduce queries and Linq queries. It also can run in-memory. A: MongoDB is also a good choice. It supports group (aggregate) queries on single-node installation. If you need to scale you can create sharded cluster and use map/reduce for aggregation needs - but Mongo map/reduce performance isn't top level when comapring to other solutions. If you need big performance in map/reduce you can take look at Hadoop
[ "cogsci.stackexchange", "0000012619.txt" ]
Q: Is the brain inherently social? The concept of the "social brain" is thrown around a lot, but it's not entirely clear to me what it means. To me, it could mean a few different things: Modularity: We have some sort of modular, hardwired network that supports social behavior and cognition Domain-General Processes: The benefits of human sociality through evolution have promoted certain psychological processes that are useful for human interaction, but these processes are not specific to sociality (i.e., they're domain-general) Domain-General and Specific: Somewhere in the middle of (1) and (2). Prepared Learning: Akin to (2), we are not born "social," but we are born with a set of more basic tools that prepare us to learn to be social I have superficial familiarity with the area of social cognition and the brain structures (TPJ, DMN, mirror neurons) and chemicals that support it (oxytocin). Based on these literatures, my assumption is that social cognition is supported by domain-general processes that have been co-opted for social use--but we don't have "social" modules or chemicals. Any thoughts? :) A: The "social brain" concept likely originated with Robin Dunbar's Social Brain Hypothesis, proposed in 1998. However, Dunbar was not suggesting that the brain has dedicated "social modules". Rather, the hypothesis was that the evolutionary driving force behind intelligence (increased brain size and capacity) was social - most prominently the need to track relationships in communities of up to 150 people (henceforth known as Dunbar's number). However, I'll focus my answer on the question as asked. Plasticity: If the criteria for "inherently" social requires some "module" of the brain that has no value outside of a social context, then it is difficult to argue that the brain is "inherently" anything because the brain is so plastic (contrast this view with nativism). For example, say we argue that the brain is "inherently" visual as there is a fairly distinct visual cortex dedicated to this function. However, in blind people and others, this area can be co-opted for auditory, tactile, and spatial processing, so there is nothing "inherently" visual about it. Perhaps we should focus on a "lower level" part of the visual processing system, such as the LGN, that really is only ever used for visual processing. Language: It is difficult (though not impossible) to imagine evolutionary value for language and speech production outside a social context, and this function does appear to have domain-specific modularity in the brain.                                               For example, Broca's area is considered the "motor speech cortex", and appears to be dedicated to speech production. But like most areas of the brain, the boundaries of this region are not well defined, and on closer inspection, neither is its function - although just about all functions attributed to Broca's area are social. While language processing has for a long time been associated with Broca's and Wernicke's areas on the left side of the brain, language processing can spread out as far as the right hemisphere, and some individuals with lesions in these regions can retain largely unaffected language capabilities. Relating: The FFA, in the fusiform gyrus, is another potentially social part of the brain, critical for face recognition - a lesion in this region leads to prosopagnosia (face blindness). This function is distinct from the system for recognizing inanimate objects, such that other visual agnosias may not affect facial recognition ability. This function is already developed in infancy, and is a strong candidate for domain-specificity. However, once again, this region of the brain may have other functions, and facial recognition can be subsumed (although less efficiently) by other regions.                                                                       Fusiform face area                                                                  Both autism and Asperger's provide another hint at the social nature of the human brain. Though their etiology is not well understood, it is considered biological, suggesting a disruption of some inherent social mechanism of the brain. However, since ASD affects other cognitive functions as well, it is again not clear that a distinctly social element of the brain is involved. Learning: Both social reward and social pain have been shown to largely recycle the non-social reward and punishment systems, suggesting that there may be nothing inherent in the brain to support learning by social motivation. However, as pointed out in the question, Theory-of-Mind capabilities may have some modular support in the brain, though no domain-specific mechanisms have been implicated. Noam Chomsky famously argued that language acquisition in humans happens far too quickly to be accounted for by simple learning - that is, our brain must be somehow predisposed for language acquisition. How this happens is still not well understood, but the same logic is applicable to many other aspects of our social capabilities: We are simply too well honed at social functions such as language, relationships, modelling, and other social behaviours to be accounted for by learning / culture alone.
[ "stackoverflow", "0031867317.txt" ]
Q: Remove values in array equal to subsequent arguments I want this function to work and produce the array [1,1], why doesn't it work? function destroyer(arr) { return arr.reduce(function(a,b){ if (arguments.slice(1).every(function(arg){ return arg !== b; })) a.push(b); return a; }, []); } destroyer([1, 2, 3, 1, 2, 3], 2, 3); A: I suggest function destroyer(arr) { return [].slice.call(arguments, 1).reduce(function(arr, num) { return arr.filter(function(item) { return num !== item; }); }, arr); } Or, in ES6, function destroyer(arr, ...unwanted) { return unwanted.reduce((arr,num) => arr.filter(item => num !== item), arr); }
[ "stackoverflow", "0025115369.txt" ]
Q: How to display inline errors in the editor On the scrollbar, the yellow areas designate warnings in the code. When hovering them, we get a nice preview of the code along with message labels at the end of the line, as seen in the screenshot below: I find this really nice and would like to display them all the time directly in the code editor. I looked up a bit and didn't find any option for that. Is it possible? If yes, how? A: It is not possible. It works like that only in Code Lense mode which allows you to preview small chunk of another part of your file together with errors/warnings/etc. But if you want to see a list of all errors for this file/folder/whole project -- use Code | Inspect Code....
[ "stackoverflow", "0056498227.txt" ]
Q: How to highlight QScintilla using ANTLR4? I'm trying to learn ANTLR4 and I'm already having some issues with my first experiment. The goal here is to learn how to use ANTLR to syntax highlight a QScintilla component. To practice a little bit I've decided I'd like to learn how to properly highlight *.ini files. First things first, in order to run the mcve you'll need: Download antlr4 and make sure it works, read the instructions on the main site Install python antlr runtime, just do: pip install antlr4-python3-runtime Generate the lexer/parser of ini.g4: grammar ini; start : section (option)*; section : '[' STRING ']'; option : STRING '=' STRING; COMMENT : ';' ~[\r\n]*; STRING : [a-zA-Z0-9]+; WS : [ \t\n\r]+; by running antlr ini.g4 -Dlanguage=Python3 -o ini Finally, save main.py: import textwrap from PyQt5.Qt import * from PyQt5.Qsci import QsciScintilla, QsciLexerCustom from antlr4 import * from ini.iniLexer import iniLexer from ini.iniParser import iniParser class QsciIniLexer(QsciLexerCustom): def __init__(self, parent=None): super().__init__(parent=parent) lst = [ {'bold': False, 'foreground': '#f92472', 'italic': False}, # 0 - deeppink {'bold': False, 'foreground': '#e7db74', 'italic': False}, # 1 - khaki (yellowish) {'bold': False, 'foreground': '#74705d', 'italic': False}, # 2 - dimgray {'bold': False, 'foreground': '#f8f8f2', 'italic': False}, # 3 - whitesmoke ] style = { "T__0": lst[3], "T__1": lst[3], "T__2": lst[3], "COMMENT": lst[2], "STRING": lst[0], "WS": lst[3], } for token in iniLexer.ruleNames: token_style = style[token] foreground = token_style.get("foreground", None) background = token_style.get("background", None) bold = token_style.get("bold", None) italic = token_style.get("italic", None) underline = token_style.get("underline", None) index = getattr(iniLexer, token) if foreground: self.setColor(QColor(foreground), index) if background: self.setPaper(QColor(background), index) def defaultPaper(self, style): return QColor("#272822") def language(self): return self.lexer.grammarFileName def styleText(self, start, end): view = self.editor() code = view.text() lexer = iniLexer(InputStream(code)) stream = CommonTokenStream(lexer) parser = iniParser(stream) tree = parser.start() print('parsing'.center(80, '-')) print(tree.toStringTree(recog=parser)) lexer.reset() self.startStyling(0) print('lexing'.center(80, '-')) while True: t = lexer.nextToken() print(lexer.ruleNames[t.type-1], repr(t.text)) if t.type != -1: len_value = len(t.text) self.setStyling(len_value, t.type) else: break def description(self, style_nr): return str(style_nr) if __name__ == '__main__': app = QApplication([]) v = QsciScintilla() lexer = QsciIniLexer(v) v.setLexer(lexer) v.setText(textwrap.dedent("""\ ; Comment outside [section s1] ; Comment inside a = 1 b = 2 [section s2] c = 3 ; Comment right side d = e """)) v.show() app.exec_() and run it, if everything went well you should get this outcome: Here's my questions: As you can see, the outcome of the demo is far away from being usable, you definitely don't want that, it's really disturbing. Instead, you'd like to get a similar behaviour than all IDEs out there. Unfortunately I don't know how to achieve that, how would you modify the snippet providing such a behaviour? Right now I'm trying to mimick a similar highlighting than the below snapshot: you can see on that screenshot the highlighting is different on variable assignments (variable=deeppink and values=yellowish) but I don't know how to achieve that, I've tried using this slightly modified grammar: grammar ini; start : section (option)*; section : '[' STRING ']'; option : VARIABLE '=' VALUE; COMMENT : ';' ~[\r\n]*; VARIABLE : [a-zA-Z0-9]+; VALUE : [a-zA-Z0-9]+; WS : [ \t\n\r]+; and then changing the styles to: style = { "T__0": lst[3], "T__1": lst[3], "T__2": lst[3], "COMMENT": lst[2], "VARIABLE": lst[0], "VALUE": lst[1], "WS": lst[3], } but if you look at the lexing output you'll see there won't be distinction between VARIABLE and VALUES because order precedence in the ANTLR grammar. So my question is, how would you modify the grammar/snippet to achieve such visual appearance? A: The problem is that the lexer needs to be context sensitive: everything on the left hand side of the = needs to be a variable, and to the right of it a value. You can do this by using ANTLR's lexical modes. You start off by classifying successive non-spaces as being a variable, and when encountering a =, you move into your value-mode. When inside the value-mode, you pop out of this mode whenever you encounter a line break. Note that lexical modes only work in a lexer grammar, not the combined grammar you now have. Also, for syntax highlighting, you probably only need the lexer. Here's a quick demo of how this could work (stick it in a file called IniLexer.g4): lexer grammar IniLexer; SECTION : '[' ~[\]]+ ']' ; COMMENT : ';' ~[\r\n]* ; ASSIGN : '=' -> pushMode(VALUE_MODE) ; KEY : ~[ \t\r\n]+ ; SPACES : [ \t\r\n]+ -> skip ; UNRECOGNIZED : . ; mode VALUE_MODE; VALUE_MODE_SPACES : [ \t]+ -> skip ; VALUE : ~[ \t\r\n]+ ; VALUE_MODE_COMMENT : ';' ~[\r\n]* -> type(COMMENT) ; VALUE_MODE_NL : [\r\n]+ -> skip, popMode ; If you now run the following script: source = """ ; Comment outside [section s1] ; Comment inside a = 1 b = 2 [section s2] c = 3 ; Comment right side d = e """ lexer = IniLexer(InputStream(source)) stream = CommonTokenStream(lexer) stream.fill() for token in stream.tokens[:-1]: print("{0:<25} '{1}'".format(IniLexer.symbolicNames[token.type], token.text)) you will see the following output: COMMENT '; Comment outside' SECTION '[section s1]' COMMENT '; Comment inside' KEY 'a' ASSIGN '=' VALUE '1' KEY 'b' ASSIGN '=' VALUE '2' SECTION '[section s2]' KEY 'c' ASSIGN '=' VALUE '3' COMMENT '; Comment right side' KEY 'd' ASSIGN '=' VALUE 'e' And an accompanying parser grammar could look like this: parser grammar IniParser; options { tokenVocab=IniLexer; } sections : section* EOF ; section : COMMENT | SECTION section_atom* ; section_atom : COMMENT | KEY ASSIGN VALUE ; which would parse your example input in the following parse tree:
[ "stackoverflow", "0028878565.txt" ]
Q: JQuery and geolocation not sending any data Good day, I am trying to create a script that loads my Browser Geolocation and following sends it to a file that saves it. The problem is. The data does not get send. And an even bigger problem is that I have tried many things but I am quite clueless. I added several alerts but the alerts do not show up. What should the script do? Run once every five seconds and requesting your GeoLocation. When you click accept on your phone and accept for all from this source you will have an active GPS alike tracking. The code : <script type="text/javascript"> function success(position) { ///SaveActiveGeoLocation(); } function error(msg) { var s = document.querySelector('#status'); s.innerHTML = typeof msg == 'string' ? msg : "failed"; s.className = 'fail'; // console.log(arguments); } if(navigator.geolocation){ navigator.geolocation.getCurrentPosition(success, error); } else{ error('not supported'); } function SaveGeoLocation(){ var Lat = position.coords.latitude; var Lon = position.coords.longitude; var Accuracy = position.coords.accuracy; ///######## SENDING THE INFORMATION BY AJAX $.ajax({ type : "POST", /// **** SEND TYPE url : "savegeo.php", /// **** TARGET FILE TO FETCH THE DATA data : { 'Lat' : Lat, 'Lon' : Lon, 'GeoAccuracy' : Accuracy }, ///######## IN CASE OF SUCCESS success:function(response){ if( response == "ok" ){ alert('SEND!'); } else{ alert( "Response = " + response ); } } } ); } $(document).ready(function() { $.ajaxSetup({ cache: false }); // This part addresses an IE bug. without it, IE will only load the first number and will never refresh setInterval(function() { ///alert('HOI!'); SaveGeoLocation(); }, 5000); // the "10000" here refers to the time to refresh the div. it is in milliseconds. /// **** DEFAULT LOADING ///SaveGeoLocation(); }); </script> The file that saves the send POST data : <?php include('function.geolocation.class.php'); $geo = new GeoLocation(); $Lat = $_POST['Lat']; $Lon = $_POST['Lon']; $GeoAccuracy = $_POST['GeoAccuracy']; $IP = $geo->GetIP(); $file = 'location.txt'; $address = $geo->getAddress($Lat, $Lon); $contents = $Lat.'|'.$Lon.'|'.$IP.'|'.$GeoAccuracy.'|'.date('Y-m-d H:i:s').'|'.$address.PHP_EOL; $handle = fopen($file, 'a'); fwrite($handle, $contents); fclose($handle); echo 'ok'; ?> A: One problem I can see is the variable position does not exists in the context of the SaveGeoLocation method function success(position) { //SaveActiveGeoLocation(); window.position = position; } function SaveGeoLocation() { if (!window.position) { return; } //your stuff } There is no need to call SaveGeoLocation using interval, you can call SaveGeoLocation from the success callback like function success(position) { SaveActiveGeoLocation(position); } function SaveGeoLocation(position) { //your stuff } If you want to save the location continuously $(document).ready(function () { $.ajaxSetup({ cache: false }); function saveLocation() { navigator.geolocation.getCurrentPosition(success, error); } function success(position) { var Lat = position.coords.latitude; var Lon = position.coords.longitude; var Accuracy = position.coords.accuracy; ///######## SENDING THE INFORMATION BY AJAX $.ajax({ type: "POST", /// **** SEND TYPE url: "savegeo.php", /// **** TARGET FILE TO FETCH THE DATA data: { 'Lat': Lat, 'Lon': Lon, 'GeoAccuracy': Accuracy }, ///######## IN CASE OF SUCCESS success: function (response) {} }).done(function (response) { if (response == "ok") { alert('SEND!'); } else { alert("Response = " + response); } }).always(function () { setTimeout(saveLocation, 5000) }); } function error(msg) { var s = document.querySelector('#status'); s.innerHTML = typeof msg == 'string' ? msg : "failed"; s.className = 'fail'; } if (navigator.geolocation) { saveLocation(); } else { error('not supported'); } });
[ "es.stackoverflow", "0000341614.txt" ]
Q: Deferencia entre $this->$algo y $this->algo en PHP Estoy pasando un desarrollo en php nativo a php orientado a objetos, pero en este momento tengo varias dudas, algunas las logro resolver por mi cuenta pero tras no. Llegado a una parte del codigo y buscando un poco en la web me tope con esto $this->algo $this->$algo me gustaria saber cual es la diferencia entre estas dos y cual es su uso. si bien $this->algo accedo a la info de la propiedad "algo", con $this->$algo que es lo que haria. Desde ya gracias. A: En el primer caso $this->algo quiere decir que estás accediendo a la propiedad algo de la clase. En el segundo caso $this->$algo quiere decir que estás accediendo a la propiedad que tenga la variable $algo, si la clase no tiene la propiedad te arrojará un error. Dada la clase Car, en el primer echo vemos como accedemos normalmente a la propiedad de la clase. En el segundo echo vemos como utilizamos el contenido de una variable para acceder a esa propiedad. Se podría considerar como "dinámico" el ultimo caso, ya que es una forma de acceder a una propiedad de la clase mediante un string <?php class Car{ public $brand = 'suzuki'; public $model = 'swift'; } $car = new Car(); $brand = 'model'; echo $car->brand; echo $car->$brand; Si reemplazamos el contenido de la variable $brand se traduce en $car->model, ya que el contenido de $brand en realidad es model, el nombre de la variable es para demostrar que en realidad no tiene relación alguna con la propiedad de la clase.
[ "stackoverflow", "0003847880.txt" ]
Q: Using main and delta indexes in sphinx Im switching fulltext searching on my site to sphinx. Im going to be using SphinxSE to perform the searches. I created 2 indexes, as specified in the manual: http://www.sphinxsearch.com/docs/manual-0.9.9.html#live-updates It seems to work, and index different stuff in its own index, but Im somewhat confused about how I should handle the index updating, merging, and rebuilding. The way I understand is I cron it to run "indexer delta --rotate" every 5 mins or so, which would add new submissions to the index. Then once a day, I would merge the delta index into the main index by running "indexer main delta --rotate". then once a month or so, I'll run "indexer --all" to rebuild all indexes. Am I doing this right, or am I missing something? A: Sounds pretty much like the setup I did for a customer. And no, the search won't stop working during updates. From the Sphinx docs: --rotate is used for rotating indexes. Unless you have the situation where you can take the search function offline without troubling users, you will almost certainly need to keep search running whilst indexing new documents. --rotate creates a second index, parallel to the first (in the same place, simply including .new in the filenames). Once complete, indexer notifies searchd via sending the SIGHUP signal, and searchd will attempt to rename the indexes (renaming the existing ones to include .old and renaming the .new to replace them), and then start serving from the newer files. Depending on the setting of seamless_rotate, there may be a slight delay in being able to search the newer indexes. A: --rotate would just build index in tmp (need space disk) and switch + restart searchd when it's done. about delta, you need to use pre-query to compute the "limit" max(id) the main indexes id below the limit, and delta is up to this limit. if you have a timestamp (indexed if possible) you can use it main -> where timefile < today() delta -> where timefile >= today()
[ "math.stackexchange", "0003410394.txt" ]
Q: Question about machine epsilon I am studying over my notes, and there is something I don't understand about $e_m$. We represent the floating point numbers as $1.d_1d_2...d_t \times \beta^e$. Now, my professor defines $\epsilon_m$ as the smallest $x$ such that $fl(1+x) > 1$. But then she writes $$\epsilon_m = \beta^{1-t} \hspace{1cm} \text{ (for "chopping")}$$ and $$e_m = \dfrac 12 \beta^{1-t} \hspace{1cm} \text{ (for rounding)}$$ However, I think these should be $\beta^{-t}$ and $\dfrac 12 \beta^{-t}$, respectively. The number $1$, and the next number right after, are $$1.00 \cdots 00 \times \beta^0$$ and $$1.00 \cdots 01 \times \beta^0$$ where the $1$ is in the $t^{th}$ decimal place. Therefore their difference is $\beta^{-t}$ so if $x = \beta^{-t}$, then $1+x$ is itself a floating point number, so $fl(1+x) = 1+x>1$. Am I wrong, or are the notes wrong? Thank you very much. A: Unfortunately, you didn't introduce the variables' meanings but I assume, $\beta$ should be the base of the floating point number (which is typically 2). I think, $t$ is used by your teacher/professor to denote the number of precision bits in the bit string representation of the floating point format. The precision bits are defined to also include the sign bit [one more bit, see below] (besides the fraction/significand bits) which is subtracted away with the -1 in the exponent of the machine epsilon: $\beta^{-(t-1)}$. If you refer to Wikipedia it will give you the same formula. EDIT: as conditionalMethod pointed out, $t$ is the number of bits including the first implicit 1-bit before the decimal point which is not stored in the floating point format (this bit also counts as precision bit since it also constitutes the represented value). The length of $t$ is not due to the sign bit. I'd like to add that the 1st one bit is implicit if the floating point number is said to be "normalized". If the biased exponent field has its minimum value of all bits zero, the floating point number is said to be "denormalized". Denormalized floating point numbers store the first 1-bit explicitly in the significand bit field behind the decimal point (hence starts with an implicit 0-bit) to represent even smaller numbers than it would be possible with an implicit 1-bit in front. However, the $t$ as is used for the machine epsilon seems to me to be defined for normalized numbers. When we had floating point numbers in the lecture (which was not hold in English language) I didn't hear of the machine epsilon. So at least according to the formula, the machine epsilon apparently applies to normalized numbers specificly.
[ "sharepoint.stackexchange", "0000272195.txt" ]
Q: Permission settings to make a "comment box" style list for users, using only default permission levels I'm a new SharePoint SCA/developer in a large organization with very locked-down access to a SharePoint Server 2016 site collection. In general, from an admin point of view, we aim to keep permissions as out-of-the-box as possible for ease of support later. I have a site administrator who is requesting custom permission levels for their site in order to create a "comment box" style feature that will allow users to add items to a list, but not modify or delete the items they have added. The users should otherwise only have Read access to the rest of the site. Is there a way to do this using the Default Permission Levels Microsoft lays out? If no, my thinking is to create a new permission level with a descriptive name like "One-Way Contribute" to act as a red flag for future support needs, and then just duplicate the default Contribute permission level while removing "Edit Items" and "Delete Items" from it. I would love to avoid this and stick with the defaults if possible. A: You can create your own custom permission level and assign it to the user. Go to Site Actions > Site Permissions > Permissions Level > Add a Permission Level Select Add Items,View Items ,View Versions and leave the rest of permission levels checked as it is by default. Determine if a custom SharePoint Group needs to be created or not. If you are planning to give this permission to many users , you can create a SharePoint group and add users in that group. Give read permission to that group at a site level. Go to the library > Click on the tab named Library on the ribbon. > Permissions for this Library > Stop Inheriting Permissions Go to grant permissions > select the user or SharePoint group that you need to give permission to. Scroll down way to the bottom of the page and you will find your newly created permission level appear there. Select that permission level and save the form. Now it should work. Test it
[ "stackoverflow", "0027315297.txt" ]
Q: Accessing inner class method from causes nullpointerexception I am trying to add database in my app.I wrote this class: public class DatabaseHandler extends SQLiteOpenHelper { private static final int DATABASE_VERSION = 1; private static final String DATABASE_NAME = "testDb"; private static final String TABLE_KISILER = "loginCre"; private static final String KEY_ID = "id"; private static final String KEY_NAME = "username"; private static final String KEY_PASS = "password"; public DatabaseHandler(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } // Database Oluşturma işlemi. @Override public void onCreate(SQLiteDatabase db) { String CREATE_KISILER_TABLE = "CREATE TABLE " + TABLE_KISILER + "(" + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " VARCHAR(50)," + KEY_PASS + " VARCHAR(50)" + ")"; db.execSQL(CREATE_KISILER_TABLE); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS " + TABLE_KISILER); onCreate(db); } //CRUD // Yeni Kayıt Eklemek. public void addLoginInfo(String username,String password) { /* SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(KEY_NAME, username); // Kisi Adı Getir values.put(KEY_PASS, password); // Kisi Soyadı Getir // Ekleme işlemi... db.insert(TABLE_KISILER, null, values); db.close(); // Açık olan database i kapat. */ } } I want to access addLoginInfo method from main activity then I used this lines in onCreate private DatabaseHandler _db; _db.addLoginInfo("test", "test"); But I app is crashing.There is the logcat: 12-05 11:24:55.802: E/AndroidRuntime(2841): FATAL EXCEPTION: main 12-05 11:24:55.802: E/AndroidRuntime(2841): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.impact.xxx/com.impact.xxx.MainActivity}: java.lang.NullPointerException 12-05 11:24:55.802: E/AndroidRuntime(2841): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211) 12-05 11:24:55.802: E/AndroidRuntime(2841): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261) 12-05 11:24:55.802: E/AndroidRuntime(2841): at android.app.ActivityThread.access$600(ActivityThread.java:141) 12-05 11:24:55.802: E/AndroidRuntime(2841): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256) 12-05 11:24:55.802: E/AndroidRuntime(2841): at android.os.Handler.dispatchMessage(Handler.java:99) 12-05 11:24:55.802: E/AndroidRuntime(2841): at android.os.Looper.loop(Looper.java:137) 12-05 11:24:55.802: E/AndroidRuntime(2841): at android.app.ActivityThread.main(ActivityThread.java:5103) 12-05 11:24:55.802: E/AndroidRuntime(2841): at java.lang.reflect.Method.invokeNative(Native Method) 12-05 11:24:55.802: E/AndroidRuntime(2841): at java.lang.reflect.Method.invoke(Method.java:525) 12-05 11:24:55.802: E/AndroidRuntime(2841): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737) 12-05 11:24:55.802: E/AndroidRuntime(2841): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 12-05 11:24:55.802: E/AndroidRuntime(2841): at dalvik.system.NativeStart.main(Native Method) 12-05 11:24:55.802: E/AndroidRuntime(2841): Caused by: java.lang.NullPointerException 12-05 11:24:55.802: E/AndroidRuntime(2841): at com.impact.xxx.MainActivity.onCreate(MainActivity.java:164) 12-05 11:24:55.802: E/AndroidRuntime(2841): at android.app.Activity.performCreate(Activity.java:5133) 12-05 11:24:55.802: E/AndroidRuntime(2841): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087) 12-05 11:24:55.802: E/AndroidRuntime(2841): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175) 12-05 11:24:55.802: E/AndroidRuntime(2841): ... 11 more Why I am getting nullPointerException ? A: you are not initializing _db object.try this : private DatabaseHandler _db = new DatabaseHandler(this); _db.addLoginInfo("test", "test");
[ "stackoverflow", "0013890103.txt" ]
Q: Can't locate images with UIImagePickerController I'm trying to use a UIIMagePickerController to select images in my iPad app. When I run the simulator, the popup says: "No Photos. You can sync photos and videos onto your iPad using iTunes.". What does that mean? I'm running the app in the simulator, how can I tell UIIMagePickerController where to find the images? Can I use images from my Resources group? THanks in advance A: The simulator has its own camera roll, but by default it doesnt have any images in it. You cant just tell the simulator to look at a certain folder in your macs file system so you need to add images to the simulators camera roll the simplest way to do this is to: (repeat for as many images as you want) open the simulator open safari drag an image onto safaris page (so it opens the image) long press on the image and then select save to camera roll
[ "stackoverflow", "0057776825.txt" ]
Q: Casting rows to arrays in PostgreSQL I need to query a table as in SELECT * FROM table_schema.table_name only each row needs to be a TEXT[] with array values corresponding to column values casted to TEXT coming in the same order as in SELECT * so assuming the table has columns a, b and c I need the result to look like SELECT ARRAY[a::TEXT, b::TEXT, c::TEXT] FROM table_schema.table_name only it shouldn't explicitly list columns by name. Ideally it should look like SELECT as_text_array(a) FROM table_schema.table_name AS a The best I came up with looks ugly and relies on "hstore" extension WITH columnz AS ( -- get ordered column name array SELECT array_agg(attname::TEXT ORDER BY attnum) AS column_name_array FROM pg_attribute WHERE attrelid = 'table_schema.table_name'::regclass AND attnum > 0 AND NOT attisdropped ) SELECT hstore(a)->(SELECT column_name_array FROM columnz) FROM table_schema.table_name AS a I am having a feeling there must be a simpler way to achieve that UPDATE 1 Another query that achieves the same result but arguably as ugly and inefficient as the first one is inspired by the answer by @bspates. It may be even less efficient but doesn't rely on extensions SELECT r.text_array FROM table_schema.table_name AS a INNER JOIN LATERAL ( -- parse ROW::TEXT presentation of a row SELECT array_agg(COALESCE(replace(val[1], '""', '"'), NULLIF(val[2], ''))) AS text_array FROM regexp_matches(a::text, -- parse double-quoted and simple values separated by commas '(?<=\A\(|,) (?: "( (?:[^"]|"")* )" | ([^,"]*) ) (?=,|\)\Z)', 'xg') AS t(val) ) AS r ON TRUE It is still far from ideal UPDATE 2 I tested all 3 options existing at the moment Using JSON. It doesn't rely on any extensions, it is short to write, easy to understand and the speed is ok. Using hstore. This alternative is the fastest (>10 times faster than JSON approach on a 100K dataset) but requires an extension. hstore in general is very handy extension to have through. Using regex to parse TEXT presentation of a ROW. This option is really slow. A: A somewhat ugly hack is to convert the row to a JSON value, then unnest the values and aggregate it back to an array: select array(select (json_each_text(to_json(t))).value) as row_value from some_table t Which is to some extent the same as your hstore hack. If the order of the columns is important, then using json and with ordinality can be used to keep that: select array(select val from json_each_text(to_json(t)) with ordinality as t(k,val,idx) order by idx) from the_table t
[ "stackoverflow", "0014103827.txt" ]
Q: Defining the elements of a list of list as new variables in common lisp I have a list of lists as follows in Common Lisp of the form ((1 2) (3 4) (5 6)) and which is the value of the variable list, and I want to have three new variables whose values are the elements of the list. For instance: list-1 (1 2) list-2 (3 4) list-3 (5 6) Is there any function which does this operation? A: Use setq, first (or nth and elt) to set: (setq list-1 (first list) list-2 (second list) list-3 (third list)) Or destructuring-bind to bind: (destructuring-bind (list-1 list-2 list-3) list ...) Again, destructuring-bind binds the variables instead of assigning them (i.e., it is like let, not like setq).
[ "fitness.stackexchange", "0000017825.txt" ]
Q: Adding Whey Protein to fitness goal Some background - Its been around 8 months since I have been exercising regularly, I am 178 cm tall, used to weigh 52.4 Kg when I had started, I have increased to 57.8 till date. Though I was advised about whey protein all along in the beginning I ignored it thinking it was a supplement, it affects kidneys, I can consume that much protein in chicken and fish etc. Now at this point, I think the gains have not been as much as I had anticipated, mainly because of not reaching the daily protein intake on some days as I don't eat meat daily. So is it a good idea to consider taking whey protein? How much, which brand? Or just keep on going as it is and reach my goal of 64? Also, once I decide to stop taking it, will it affect my weight? A: Whey protein is used to gain muscle mass fast. Its a supplement and has very little side effects. The Brand is important because some people see more improvement with diffirent brands(needs to be verified). But ON is the leading provider by far, having the most reputation among bodybuilders. How much: There is no universal answer to this particular question since everybody's protein needs vary. Protein requirements vary depending on an individual's age, gender, weight, medical conditions and the nature of the workout one does. When: The best results can be seen when Whey protein is consumed in the morning, after a workout. If you exercise regularly, it may be best to consume a Whey protein shake immediately following a workout. A report published by the National Strength and Conditioning Association recommends consuming at least 15g of protein after each workout. Your body is highly sensitive to insulin after exercise and shuttles carbohydrates and proteins into muscle cells instead of fat cells. This sensitivity declines post-workout until ~2 hours at which point it reaches baseline.
[ "stackoverflow", "0012436186.txt" ]
Q: How to start .exe file contained in my project in c#? Possible Duplicate: Embedding an external executable inside a C# program I create project "MyProj" and add to resource program "This.exe"... How could I start "this.exe" in "MyProj.exe"? Thanks for any ideas. A: Once you added the .exe to your project, got to the properties window then change the Build action to Content and Copy to output directory to Always Copy or Copy if newer To run the Application use : Process.Start("This.exe");
[ "stackoverflow", "0024090593.txt" ]
Q: Tips for reducing battery drain for android services? I wrote an app recently and, well I'm quite disappointed about how much battery the service consumes. I go to make a call yesterday to find my battery is at 9%; I check the android system statics for the battery and find that my app is responsible for 60% of the battery drainage My question is, what can one do to reduce the battery usage on an app that runs and then sleeps for 60 seconds? The service is reading from a SQLite database; I could cache the data, but would that really account for that much battery usage? What are some standard ways to reduce battery drainage in a service? A: You should look into using AlarmManager to schedule your app or service to be called when necessary. This has a big advantage over your current wake lock method, because even a partial wake lock will keep the CPU running. An AlarmManager alarm can wake the phone even from CPU sleep. Basically, get rid of your existing wake lock and schedule an AlarmManager alarm—which can repeat once a minute, if that's what you need—to wake up the device, if necessary, and send you a message. The AlarmManager itself will take out a wake lock while calling an onReceive() method to notify you of the alarm, and relinquish it when onReceive() finishes, letting the phone go back into deep sleep if it wants to. Note that this means that if you want to do extended work—e.g. firing something off on a background thread—you'll probably want to take your own wake lock out in onReceive() and relinquish it when your work is done, otherwise the phone may go to sleep while you're in the middle of the work. This is all pretty well-explained in the AlarmManager docs, but the best explanation I've seen is in Mark Murphy's The Busy Coder's Guide to Android Development; he also provides a library for exactly this pattern on Github. Definitely worth a look.
[ "stackoverflow", "0024776117.txt" ]
Q: How to create Django custom query? I have a model named UserInfo with the following fields: id, name, number I want to create a custom search page. This will have the following elements: Search Box, Search Button Text field to match NAME Text field to match NUMBER How it should work: Let's say I input 'John' as the name and '1234' as the number in the respective text boxes and click search. The result should show me the entries which has 'John' as the name and '1234' as the number. The query is something like the following I guess: UserInfo.objects.filter(name='John').filter(number='1234') I have made this kind of queries in PHP before, but that doesn't work in Django. I want to know what code can I use to associate multiple FILTERS in a query so that if there is data input in both name and number text boxes I get a query like the above but if I search for name only then the query becomes: UserInfo.object.filter(name='John') instead of UserInfo.object.filter(name='John').filter(number='') There should be an easy solution for this, I dunno. Very confused. :-/ A: Filter methods are chainable, immutable :) def search_user(name=None, number=None): # Uncomment the following lines to return NO records when no input. # if not name and not number: # return UserInfo.objects.none() qs = UserInfo.objects.all() if name: qs = qs.filter(name=name) if number: qs = qs.filter(number=number) return qs This example would return all records if no input. (Note that QS are lazy, and all() would not retrieve all records unless accessed later on.)
[ "stackoverflow", "0009628859.txt" ]
Q: The point of ValueConversionAttribute class? What is the point of this attribute? After adding it I still need to make a cast on value object. [ValueConversion(sourceType: typeof(double), targetType: typeof(string))] public class SpeedConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { var speed = (double)value; Is it only for code readability? Because when I change a binding's path to a String in xaml, Visual Studio doesn't give a warning about incorrect type and exception is thrown only when casting, so it doesn't mean a thing even in early error catching while compiling. I also can change a cast to string and no warning is thrown despite it conflicting with this Attribute. A: You can potentially use the ValueConversionAttribute to determine what types are involved in the converters, and use that information usefully. Look at Piping Value Converters in WPF as an excellent example for the use of ValueConversionAttribute. The example shows how multiple converter classes can be chained, and ValueConversion can be used to pass type info to next converter in line. [ValueConversion( typeof( string ), typeof( ProcessingState ) )] public class IntegerStringToProcessingStateConverter : IValueConverter { object IValueConverter.Convert( object value, Type targetType, object parameter, CultureInfo culture ) { int state; bool numeric = Int32.TryParse( value as string, out state ); Debug.Assert( numeric, "value should be a String which contains a number" ); Debug.Assert( targetType.IsAssignableFrom( typeof( ProcessingState ) ), "targetType should be ProcessingState" ); switch( state ) { case -1: return ProcessingState.Complete; case 0: return ProcessingState.Pending; case +1: return ProcessingState.Active; } return ProcessingState.Unknown; } object IValueConverter.ConvertBack( object value, Type targetType, object parameter, CultureInfo culture ) { throw new NotSupportedException( "ConvertBack not supported." ); } } // ************************************************************* [ValueConversion( typeof( ProcessingState ), typeof( Color ) )] public class ProcessingStateToColorConverter : IValueConverter { object IValueConverter.Convert( object value, Type targetType, object parameter, CultureInfo culture ) { Debug.Assert(value is ProcessingState, "value should be a ProcessingState"); Debug.Assert( targetType == typeof( Color ), "targetType should be Color" ); switch( (ProcessingState)value ) { case ProcessingState.Pending: return Colors.Red; case ProcessingState.Complete: return Colors.Gold; case ProcessingState.Active: return Colors.Green; } return Colors.Transparent; } object IValueConverter.ConvertBack( object value, Type targetType, object parameter, CultureInfo culture ) { throw new NotSupportedException( "ConvertBack not supported." ); } } object IValueConverter.Convert( object value, Type targetType, object parameter, CultureInfo culture ) { object output = value; for( int i = 0; i < this.Converters.Count; ++i ) { IValueConverter converter = this.Converters[i]; Type currentTargetType = this.GetTargetType( i, targetType, true ); output = converter.Convert( output, currentTargetType, parameter, culture ); // If the converter returns 'DoNothing' // then the binding operation should terminate. if( output == Binding.DoNothing ) break; } return output; } //***********Usage in XAML************* <!-- Converts the Status attribute text to a Color --> <local:ValueConverterGroup x:Key="statusForegroundGroup"> <local:IntegerStringToProcessingStateConverter /> <local:ProcessingStateToColorConverter /> </local:ValueConverterGroup> A: It is just an annotation. MSDN: When implementing the IValueConverter interface, it is a good practice to decorate the implementation with a ValueConversionAttribute attribute to indicate to development tools the data types involved in the conversion I do not know what the "development tools" would do with that information...
[ "stackoverflow", "0025834125.txt" ]
Q: How to include a new .java file in my Android app project? I'm sorry, I'm a newbie, and I think that's simple, but I'm discovering the coding with Eclipse so I have this simple question : How to include a new .java file in my Android project ? My words are perhaps inapropriates, and to be more clear, I'm creating an Android application, and I want to include a .java file (located in projectname/src/) Actually I have an unique file, MainActivity.java, and my application start fine. I want to include a timer in my application, so I created a new Timer.java file in same folder, but when I start my app, it contain only data from this MainActivity.java file, nothing about my Timer.jar file. So how I must declare the new file in my project ? A: you simply add it by right clicking on your src folder you need to declare it on your AndroidManifest.xml file <activity android:name=".Timer" android:label="@string/title_timer" > </activity>
[ "stackoverflow", "0020094436.txt" ]
Q: Is there a way to link ASP.NET Web Forms aspx files transparently? (using the file system or some other way) We have a legacy ASP.NET 2.0 Webforms Web Site that we need to extend. It is poorly designed, and the architecture forces many files to be duplicated. Whenever we add new functionality we are forced to physically copy our pages+code behind for "Weekly" versions of our products to other folders for our "Daily" products. For obvious reasons, this makes updates very annoying, since we need remember to update 2 copies of each file. Although the Weekly and Daily versions can differ, this rarely happens, so they usually have to be identical and exactly in syc. Is there a way to create links/shortcuts in Windows or Visual Studio, so that we only need to create pages for our "weekly" products, and if a page is requested from the corresponding "daily" product, ASP.NET would transparently serve the "weekly" page, unless we physically subsitute a modified "daily" page? Bonus points if we can fool VS 2012 as well. Clarification 1: We have folders like /Products/ProductAMonthly/Price.aspx and /Products/ProductADaily/Price.aspx The products are set up in a config file, and a framework does the routing. Unfortunately, the config file forces each product into a separate folder on the server, so we can't get the config file to reuse pages. We have also refactored into base classes, and could perhaps refactor some more, but this doesn't get rid of the need for identical pages to exist in the folders defined in the config file. A: I eventually used a Windows feature called Symbolic Links (or Junctions). ASP.NET/IIS seems to serve these up without problems. We have a batch file that uses mklink to create these on each developer's machines. We also added the junctioned files to our source control's ignore file. It seems to work well.
[ "stackoverflow", "0047540926.txt" ]
Q: Get the largest connected component of segmentation image I have a segmentation image of CT scan (only 1 and 0 values). I use the function "label" from skimage.measure to get a ndarray of the connected component. Now I need to get only the largest connected component from the "label" output (ndarray). Do you have any idea how can I do it? My code looks like this: from skimage.measure import label def getLargestCC(segmentation): labels = label(segmentation) // now I need to get only the largest connected component and return it return largestCC Thanks a lot! A: The answer of Gilly is interesting but wrong if the background (label=0) is larger than CC researched. The Alaleh Rz solution deals with the background but is very slow. Adapting the solution proposed by Gilly and removing the background problem: import numpy as np from skimage.measure import label def getLargestCC(segmentation): labels = label(segmentation) assert( labels.max() != 0 ) # assume at least 1 CC largestCC = labels == np.argmax(np.bincount(labels.flat)[1:])+1 return largestCC A: I am not sure what you want as the output, a mask? import numpy as np from skimage.measure import label def getLargestCC(segmentation): labels = label(segmentation) largestCC = labels == np.argmax(np.bincount(labels.flat)) return largestCC Numpy's bincount will count for each label the number of occurrences, and argmax will tell you which of these was the largest. A: The OP's input segmentation data is binary where the background is 0. So, we can use Vincent Agnus' np.bincount approach but simplify the background rejection logic by using np.bincount's weights argument. Set weights=segmentation.flat to zero out the background sum. import numpy as np from skimage.measure import label def getLargestCC(segmentation): labels = label(segmentation) largestCC = labels == np.argmax(np.bincount(labels.flat, weights=segmentation.flat)) return largestCC
[ "stackoverflow", "0029877314.txt" ]
Q: Cloud Foundry with Spring Boot I am getting the following error when I am trying to push the Spring Boot application: C:\WORKSPACES>cf push spr_boot_first Creating app spr_boot_first in org k.agwl.org / space development_space_one as [email protected]... OK Using route spr-boot-first.cfapps.io Binding spr-boot-first.cfapps.io to spr_boot_first... OK Uploading spr_boot_first... FAILED Error uploading application. read C:\WORKSPACES\.metadata\.lock: The process cannot access the file because another process has locked a portion of the file. A: It looks like you are not using the Cloud foundry plugin from eclipse,but are doing the push from the command line. Close eclipse and try the push from the command line again. Or install the tooling from the marketplace: https://marketplace.eclipse.org/content/cloud-foundry-integration-eclipse
[ "stackoverflow", "0007534973.txt" ]
Q: Sort a PHP array by another array order and date Was wondering if there is a way to sort (usort or equiv) an array based on key order of another array and date. I know how to do basic date sorting with usort, but was wondering if you could do both in one shot. $cats = array(1,6,3,4,7,2); $prods = array( array('cat'=>1,'date'=>'1/3/2011'), array('cat'=>2,'date'=>'1/6/2011'), array('cat'=>3,'date'=>'2/3/2011') ); I want $prods sorted by the category order of $cats and date order of $prods A: Pay attention to your low accept rate, as it can deter people from taking the time to answer your questions. Remember to mark valid answers as accepted or otherwise post a comment to them explaining why they aren't valid. This solution works fine in php 5.3+, if you are trapped in an older version you can easily replace DateTime objects with calls to strptime. Products with a category that has no position specified are pushed to the end of the list (see product with cat == 42 in the example). $cats = array(1,6,3,4,7,2); // added a few products to test the date sorting $prods = array( array('cat'=>1,'date'=>'3/3/2011'), array('cat'=>1,'date'=>'2/3/2011'), array('cat'=>1,'date'=>'1/3/2011'), array('cat'=>42,'date'=>'2/3/2011'), array('cat'=>2,'date'=>'1/3/2011'), array('cat'=>2,'date'=>'2/3/2011'), array('cat'=>2,'date'=>'1/6/2011'), array('cat'=>3,'date'=>'2/3/2011') ); // need an index of category_id => position wanted in the sort $r_cats = array_flip($cats); // if the category of a product is not found in the requested sort, we will use 0, and product with category id 0 will be sent to the end of the sort $r_cats[0] = count($r_cats); // this one is needed for DateTime, put whatever your timezone is (not important for the use we do of it, but required to avoid a warning) date_default_timezone_set('Europe/Paris'); usort($prods, function($a, $b) use($r_cats) { $cat_a = isset($r_cats[$a['cat']]) ? $r_cats[$a['cat']] : $r_cats[0]; $cat_b = isset($r_cats[$b['cat']]) ? $r_cats[$b['cat']] : $r_cats[0]; if ($cat_a < $cat_b) { return -1; } elseif ($cat_a > $cat_b) { return 1; } $date_a = DateTime::createFromFormat('j/n/Y', $a['date']); $date_b = DateTime::createFromFormat('j/n/Y', $b['date']); if ($date_a < $date_b) { return -1; } elseif ($date_a > $date_b) { return 1; } return 0; }); var_dump($prods); The results are as follow: array(8) { [0]=> array(2) { ["cat"]=> int(1) ["date"]=> string(8) "1/3/2011" } [1]=> array(2) { ["cat"]=> int(1) ["date"]=> string(8) "2/3/2011" } [2]=> array(2) { ["cat"]=> int(1) ["date"]=> string(8) "3/3/2011" } [3]=> array(2) { ["cat"]=> int(3) ["date"]=> string(8) "2/3/2011" } [4]=> array(2) { ["cat"]=> int(2) ["date"]=> string(8) "1/3/2011" } [5]=> array(2) { ["cat"]=> int(2) ["date"]=> string(8) "2/3/2011" } [6]=> array(2) { ["cat"]=> int(2) ["date"]=> string(8) "1/6/2011" } [7]=> array(2) { ["cat"]=> int(42) ["date"]=> string(8) "2/3/2011" } }
[ "stackoverflow", "0058942143.txt" ]
Q: JAVA Swing: Can't add text area to a Border Layout MainFrame.java import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JTextArea; public class MainFrame extends JFrame{ private JTextArea textArea; private JButton btn; private TextPanel textPanel; public MainFrame() { super("My First JAVA Swing Window"); setLayout(new BorderLayout()); textArea = new JTextArea(); btn = new JButton("Click Me"); textPanel = new TextPanel(); btn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { textArea.append("Button has been clicked!\n"); //textPanel.appendText("Button has been clicked!\n"); } }); add(textArea, BorderLayout.CENTER); add(btn, BorderLayout.SOUTH); setSize(600,500); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); } } My goal is to add a text (Button has been clicked!) to the text area if I click the button. I managed to do it but I tried to seperate the text area in a different class, and if I seperate it, it doesnt work anymore.. What I see is it dont even add the text area to the border layout... This is how I try to seperate and thats the part thats not working: MainFrame.java import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JTextArea; public class MainFrame extends JFrame{ //private JTextArea textArea; private JButton btn; private TextPanel textPanel; public MainFrame() { super("My First JAVA Swing Window"); setLayout(new BorderLayout()); //textArea = new JTextArea(); btn = new JButton("Click Me"); textPanel = new TextPanel(); btn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { //textArea.append("Button has been clicked!\n"); textPanel.appendText("Button has been clicked!\n"); } }); //add(textArea, BorderLayout.CENTER); add(btn, BorderLayout.SOUTH); setSize(600,500); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); } } TextPanel.java import java.awt.BorderLayout; import javax.swing.JPanel; import javax.swing.JTextArea; public class TextPanel extends JPanel{ private JTextArea textArea; public TextPanel() { textArea = new JTextArea(); setLayout(new BorderLayout()); add(textArea, BorderLayout.CENTER); } public void appendText(String text) { textArea.append(text); } } And of course there is a Main class which runs the MainFrame... A: The problem is that you called add(textArea, BorderLayout.CENTER); in your MainFrame.java before the refactoring. The add method there adds the textArea to the layout of the JFrame. But afterwards you don't add the TextPanel to the JFrame, but only to a local BorderLayout of the JPanel your extending of. That BorderLayout isn't added anywhere. It should work, if you still call add(textPanel, BorderLayout.CENTER);
[ "salesforce.stackexchange", "0000166094.txt" ]
Q: HTTP Mock Response class has 0 coverage I have created a mock response to gain coverage for a hhtp request, as per the following documentation: https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_restful_http_testing_httpcalloutmock.htm Here is my class: public class SASProposalGenerationClass { private final Opportunity oppty; @AuraEnabled public static String getUIThemeDescription() { String theme = UserInfo.getUiThemeDisplayed(); return theme; } public SASProposalGenerationClass(ApexPages.StandardController stdController){ this.oppty = (Opportunity)stdController.getRecord(); } @AuraEnabled public static Opportunity getParentOpportunity(String opportunityId){ if(opportunityId == null){ return null; } Opportunity o = [SELECT Id, Name, Owner.Name, Owner.Email, Vertical_Group__c, Billing_Entity__r.Name, Billing_Entity__r.Client_Account__c, Billing_Entity__r.Client_Account__r.Name, Billing_Entity__c, Billing_Entity__r.ABN__c, Billing_Entity__r.ACN__c, Campaign_Start_Date__c, Campaign_End_Date__c, Account.Name, Billing_Entity__r.Legal_Entity__c, Billing_Entity__r.REA_ID__c, Billing_Entity__r.CID__c, Owner.SAS_ID__c, Owner.SAS_Ad_Trafficker__c, Owner.SAS_Ad_Trafficker__r.SAS_ID__c FROM Opportunity WHERE Id =:opportunityId]; return o; } @AuraEnabled public static String getSASProposalId(String opportunityId, String reqBody) { // Instantiate a new http object Http h = new Http(); // Instantiate a new HTTP request, specify the method (GET) as well as the endpoint HttpRequest req = new HttpRequest(); String url = 'http://sf-to-sas-sandbox.au.cloudhub.io/opportunities/' + opportunityId; req.setEndpoint(url); req.setMethod('POST'); req.setBody(reqBody); req.setHeader('Content-Type', 'application/json'); // Send the request, and return a response HttpResponse res = h.send(req); System.debug('response:--> ' + res.getBody()); String responseString = String.valueOf(res.getBody()); return responseString; } } and my test class: @isTest public class SASProposalGenerationClass_Test { static testMethod void testSASProposalGeneration() { //Need an agency Account Account agency = DataFactory.generateSingleAccount(); INSERT agency; //Need a contact Contact contact = DataFactory.generateSingleContact(); contact.AccountId = agency.Id; INSERT contact; //Need an advertiser account Account advertiser = DataFactory.generateSingleAccount(); INSERT advertiser; //Need a billing Entity SAGE_Billing_Details__c BE = DataFactory.generateSingleBillingEntity(); BE.Billing_Account__c = agency.id; BE.Client_Account__c = advertiser.Id; BE.Contact__c = contact.Id; INSERT BE; //Need an opportunuty Opportunity op = DataFactory.generateSingleOpportunity(); op.Billing_Entity__c = BE.Id; op.AccountId = advertiser.Id; //set opportunity record type to Media Opportunity List<RecordType> rtList = new List<RecordType>([SELECT ID FROM RecordType WHERE Name = 'Media Opportunity' AND SObjectType = 'Opportunity' LIMIT 1]); op.RecordTypeId = rtList[0].Id; INSERT op; Test.startTest(); //Aura Component environment test String currentTheme = SASProposalGenerationClass.getUIThemeDescription(); //get all opportunity details Opportunity currentOp = SASProposalGenerationClass.getParentOpportunity(op.Id); //set test mock http callout Test.setMock(HttpCalloutMock.class, new SASProposalGenerationClass_MockResponse()); String res = SASProposalGenerationClass.getSASProposalId(op.Id, '{test:test}'); //VF page test environment ApexPages.currentPage().getParameters().put('id',op.Id); ApexPages.StandardController stdOpp = new ApexPages.StandardController(op); SASProposalGenerationClass objSASProposalGenerationClass = new SASProposalGenerationClass(stdOpp); Test.stopTest(); } } and finally my mock response: @isTest global class SASProposalGenerationClass_MockResponse implements HttpCalloutMock { // Implement this interface method global HTTPResponse respond(HTTPRequest req) { // Optionally, only send a mock response for a specific endpoint // and method. //System.assertEquals('http://sf-to-sas-sandbox.au.cloudhub.io/opportunities/' + opportunityId, req.getEndpoint()); System.assertEquals('POST', req.getMethod()); // Create a fake response HttpResponse res = new HttpResponse(); res.setHeader('Content-Type', 'application/json'); res.setBody('{"proposalId":"001827262524"}'); res.setStatusCode(200); return res; } } Via the test class the SASProposalGenerationClass has 95% coverage, however the Mock HTTP Response is being given 0% coverage, bringing down my org average. Is there a way to resolve this issue? Considering the main class is getting coverage on the callout I can assume that the mock is being run, however it is showing 0% coverage which is confusing me? A: Your Mock is annotated with isTest and thus does not count in overall coverage There is a small bug when creating classes in that if from an IDE you don't specify it is a test class and thus isTest is not present on insert it will mess up you coverage. Simply delete the mock class and recreate it ensuring the isTest annotation is present on creation.
[ "stackoverflow", "0019086817.txt" ]
Q: Regex issue with infix expression in Java I'm trying to create a Java program that is able to follow the order of operations when infix expressions are entered. To simplify input I've decided it would be best to split the entire String by using a regex expression. I've been able to split everything except the 6 3 into their own String values in the splitLine array. My SSCCE attempt at this is as follows: String line = "6 + 5 + 6 3 + 18"; String regex = "(?<=[-+*/()])|(?=[-+*/()])"; //Not spitting 6 3 correctly String[] splitLine = line.split(regex); for (int i=0; i<splitLine.length; i++) { System.out.println(splitLine[i]); } Output: 6 + 5 + 6 3 //Error here + 18 Expected Output: 6 + 5 + 6 //Notice 3 //these + 18 I've tried and tried to modify my regex expression and have been unsuccessful. Could anyone tell me why my regex expression isn't splitting the 6 and the 3 into their own Strings in the splitLine array? Edit: Just wanted to point out that I am doing this for fun, it is not for any sort of school work, etc. I just wanted to see if I could write a program to perform simple infix expressions. I do agree that there are better ways to do this and if the expression were to become more complicated I would run into some issue. But unfortunately this is how my book recommended I approach this step. Thanks again for all of the quick comments and answers! A: try this : (?<=[-+*/()])|(?=[-+*/()]|\\s{2,}) you can try adding a space in the regex, this will also split when there is 2 or more space as in this case 6 and 3 is separated by space, 6 3 will also be separated. this regex will spit the string if more than 2 space is matched. You can change the minimum number of space as \s{min,} in the regex
[ "stackoverflow", "0033716933.txt" ]
Q: Maintain normal text font after paragraph pre format I have the following code which I'm trying to test on how to use pre format on my site. After including the pre , the font changes and the lines does not break to fit on the 200px division . I want to maintain the default font size, style and family. NB: I don't want to use overflow method . I would like to have an output like this "Sometimes it is very hard to code but by circumstance you find yourself struggling to fit in the game . Awesome feelings come and disappear. Niggas say this game is for the patient hearts. You nigga is this true?? Nigga love style keep in touch with us at any given time" plus the default text font <html> <head> <title>Test</title> <style> { pre{ font-family: monospace; text-wrap: unrestricted; } } </style> </head> <body> <div style='width:200px;'> <pre>Sometimes it is very hard to code but by circumstance you find yourself struggling to fit in the game .Awesome feelings come and disappear.Niggas say this game is for the patient hesrts .. You nigga is this true?? Nigga love style keep in touch with us at any given time</pre> </body> </html> please help me solve this problem A: Remove the <pre> element and just add the style to the CSS as follows: <div style='width:200px; white-space: pre-wrap;'> Your text here </div> A: Would this solution fit your need? <div style="white-space: pre-wrap;">content</div> I've seen that here link
[ "ru.stackoverflow", "0001014394.txt" ]
Q: Расположение css картинки в шапке сайта Есть картинка нарисованная при помощи css + html css robot_logo{ position: fixed; margin-top: 0px; float: left; } .a{ position: absolute; background:#C0C0C0; width: 200px; height: 90px; left: 130px; top: 130px; } .b { position: absolute; background:#C0C0C0; width: 160px; height: 155px; left: 150px; top: 110px; } html <div class="robot_logo"> <div class="a"></div> <div class="b"></div> </div> Пытаюсь разместить его в шапке сайта таким образом html <header> <div class="container"> <div class="heading clearfix"> <div class="robot_logo"> <div class="a"></div> <div class="b"></div> </div> <img class="logo" src="img/logotip.png"></img> <nav> <ul class="menu"> <li><a href="#partfolio">qwerty</a></li> <li><a href="">qwert</a></li> <li><a href="">qwer</a></li> <li><a href="">qwe</a></li> </ul></nav> </div> <div class="titles"> <div class="titles__first"> qwertyqwertyqwertys2634871268756197856923852386598326 </div> <h1 class="gradient-text"> qwerty1qwerty1qwerty1 </h1> </div> <a class="button" href="">qwerty111</a> </div> </header> css div { box-sizing: border-box; } body { font-family: Arial, sans-serif; padding: 0; margin:0; } .clearfix:after { content: ''; display: table; width: 100%; clear: both; } header { background: url(../img/4.jpg) 100% 100% no-repeat; background-size: cover; } .heading { background-color: #fff; box-shadow: 0 0 10px rgba(0,0,0,0.5); } .container{ width: 60%; margin: 0 auto; } .logo { margin-top: 41px; float: left; } /*меню*/ nav{ float: right; margin-top: 50px; } .menu{ padding: 0; margin: 0; display: block; } .menu li{ float: left; display: block; margin-right: 41px; } .menu li a{ color: #000; text-decoration: none; /*убрать подчеркивания*/ text-transform: uppercase; font-size: 14px; } .titles{ word-wrap:break-word; color: #fff; } .titles__first { font-size: 40px; text-transform: uppercase; text-align: center; margin-top: 180px; color: #fff; } h1 { font-size: 75px; color: #fff; text-transform: uppercase; text-align: center; margin: 15px; } .button { background: #fed136; color: #484543; display: block; width: 240px; padding: 20px 0; margin: 0 auto; text-decoration: none; text-align: center; text-transform: uppercase; font-weight: bold; font-size: 18px; margin-top: 50px; margin-bottom: 100px; } Пытаюсь сделать что бы этот рисунок был вместо logotip.png но вместо этого оно выезжает за границы блока heading A: добавь .robot-logo {top: 0; left: 0;}
[ "stackoverflow", "0036840527.txt" ]
Q: Latency of short loop I'm trying to understand why some simple loops run at the speeds they do First case: L1: add rax, rcx # (1) add rcx, 1 # (2) cmp rcx, 4096 # (3) jl L1 And according to IACA, throughput is 1 cycle and bottleneck are ports 1,0,5. I don't understand why it is 1 cylce. After all we have a two loop-carried dependencies: (1) -> (1) ( Latancy is 1) (2) -> (2), (2) -> (1), (2) -> (3) (Latency is 1 + 1 + 1). And this latancy is loop-carried so it should make slower our iteration. Throughput Analysis Report -------------------------- Block Throughput: 1.00 Cycles Throughput Bottleneck: Port0, Port1, Port5 Port Binding In Cycles Per Iteration: ------------------------------------------------------------------------- | Port | 0 - DV | 1 | 2 - D | 3 - D | 4 | 5 | ------------------------------------------------------------------------- | Cycles | 1.0 0.0 | 1.0 | 0.0 0.0 | 0.0 0.0 | 0.0 | 1.0 | ------------------------------------------------------------------------- | Num Of | Ports pressure in cycles | | | Uops | 0 - DV | 1 | 2 - D | 3 - D | 4 | 5 | | --------------------------------------------------------------------- | 1 | 1.0 | | | | | | CP | add rax, rcx | 1 | | 1.0 | | | | | CP | add rcx, 0x1 | 1 | | | | | | 1.0 | CP | cmp rcx, 0x1000 | 0F | | | | | | | | jl 0xfffffffffffffff2 Total Num Of Uops: 3 Second Case: L1: add rax, rcx add rcx, 1 add rbx, rcx cmp rcx, 4096 jl L1 Block Throughput: 1.65 Cycles Throughput Bottleneck: InterIteration Port Binding In Cycles Per Iteration: ------------------------------------------------------------------------- | Port | 0 - DV | 1 | 2 - D | 3 - D | 4 | 5 | ------------------------------------------------------------------------- | Cycles | 1.4 0.0 | 1.4 | 0.0 0.0 | 0.0 0.0 | 0.0 | 1.3 | | Num Of | Ports pressure in cycles | | | Uops | 0 - DV | 1 | 2 - D | 3 - D | 4 | 5 | | --------------------------------------------------------------------- | 1 | 0.6 | 0.3 | | | | | | add rax, rcx | 1 | 0.3 | 0.6 | | | | | CP | add rcx, 0x1 | 1 | 0.3 | 0.3 | | | | 0.3 | CP | add rbx, rcx | 1 | | | | | | 1.0 | CP | cmp rcx, 0x1000 | 0F | | | | | | | | jl 0xffffffffffffffef The more I don't understand why throughput is 1.65. A: In the first loop, there are two dep chains, one for rax and one for rcx. add rax, rcx # depends on rax and rcx from the previous iteration, produces rax for the next iteration add rcx, 1 # latency = 1 The 2-cycle latency dep chain of add rcx,1 -> add rax, rcx spans 2 iterations (so it already has time to happen) and it's not even loop-carried anyway (because rax doesn't feed back into the add rcx,1). In any given iteration, only the previous iteration's results are needed to produce this iteration's results. There are no loop-carried dependencies within an iteration, only between iterations. Like I explained in answer to your question a couple days ago, the cmp/jcc is not part of the loop-carried dep chain. cmp is only part of a dep chain if a cmov or setcc reads the flag output it generates. Control dependencies are predicted, not waited for like data dependencies. In practice, on my E6600 (first-gen Core2, I don't have a SnB available at the moment): ; Linux initializes most registers to zero on process startup, and I'm lazy so I depended on this for this one-off test. In real code, I'd xor-zero ecx global _start _start: L1: add eax, ecx ; (1) add ecx, 1 ; (2) cmp ecx, 0x80000000 ; (3) jb L1 ; can fuse with cmp on Core2 (in 32bit mode) mov eax, 1 int 0x80 I ported it to 32bit since Core2 can only macro-fuse in 32bit mode, and used a jb since Core2 can only macro-fuse unsigned branch conditions. I used a large loop counter so I didn't need another loop outside this. (IDK why you picked a tiny loop count like 4096. Are you sure you weren't measuring extra overhead from something else outside your short loop?) $ yasm -Worphan-labels -gdwarf2 -felf tinyloop.asm && ld -m elf_i386 -o tinyloop tinyloop.o $ perf stat -e task-clock,cycles,instructions,branches ./tinyloop Performance counter stats for './tinyloop': 897.994122 task-clock (msec) # 0.993 CPUs utilized 2,152,571,449 cycles # 2.397 GHz 8,591,925,034 instructions # 3.99 insns per cycle 2,147,844,593 branches # 2391.825 M/sec 0.904020721 seconds time elapsed So it runs at 3.99 insns per cycle, which means ~one iteration per cycle. I'd be surprised if your Ivybridge runs that exact code only about half as fast. Update: per discussion in chat, yes, it appears IVB really does only get 2.14 IPC. (one iteration per 1.87c). Changing the add rax, rcx to add rax, rbx or something to remove the dependency on the loop counter from the previous iteration brings the throughput up to 3.8 IPC (one iteration per 1.05c). I don't understand why this happens. With a similar loop that doesn't depend on macro-fusion, (add / inc ecx / jnz) I also get one iteration per 1c. (2.99 insns per cycle). However, having a 4th insn in the loop that also reads ecx makes it massively slower. Core2 can issue 4 uops per clock, even though (like SnB/IvB) it only has three ALU ports. (A lot of code include memory uops, so this does make sense.) add eax, ecx ; changing this to add eax,ebx helps when there are 4 non-fusing insns in the loop ; add edx, ecx ; slows us down to 1.34 IPC, or one iter per 3c ; add edx, ebx ; only slows us to 2.28 IPC, or one iter per 1.75c ; with neither: 3 IPC, or one iter per 1c inc ecx jnz L1 # loops 2^32 times, doesn't macro-fuse on Core2 I expected to still run at 3 IPC, or one iter per 4/3 = 1.333c. However, pre-SnB CPUs have many more bottlenecks, like ROB-read and register-read bottlenecks. SnB's switch to a physical register file eliminated those slowdowns. In your 2nd loop, IDK why it doesn't run at one iteration per 1.333c. The insn updating rbx can't run until after the other instructions from that iteration, but that's what out-of-order execution is for. Are you sure it's as slow as one iteration per 1.85 cycles? You measured with perf for a high enough count to get meaningful data? (rdtsc cycle counting isn't accurate unless you disable turbo and frequency scaling, but perf counters still count actual core cycles). I wouldn't expect it to be much different from L1: add rax, rcx add rbx, rcx # before/after inc rcx shouldn't matter because of out-of-order execution add rcx, 1 cmp rcx, 4096 jl L1
[ "stackoverflow", "0047676723.txt" ]
Q: Parameterized includes In a few C programs (for example in gecko) I've noticed an idiom whereby a program will temporarily define a macro, then include a file which uses that macro, then undefine the macro. Here's a trivial example: speak.c: #define SPEAK(phrase) (printf("When I speak I say %s\n", (phrase))) #include "dog.h" #undef SPEAK dog.h: SPEAK("woof"); Which expands to: (printf("When I speak I say %s\n", ("woof"))) I gather this might be a useful technique to generalize included code by being able to specify behavior at the expansion site. Does this pattern have a name, or has it been written about previously? A: This is a variant of what are often called X macros. Further reading The New C: X Macros (Dr Dobbs)
[ "stackoverflow", "0008963408.txt" ]
Q: Change CSV Delimiter with sed I've got a CSV file that looks like: 1,3,"3,5",4,"5,5" Now I want to change all the "," not within quotes to ";" with sed, so it looks like this: 1;3;"3,5";5;"5,5" But I can't find a pattern that works. A: You could try something like this: echo '1,3,"3,5",4,"5,5"' | sed -r 's|("[^"]*),([^"]*")|\1\x1\2|g;s|,|;|g;s|\x1|,|g' which replaces all commas within quotes with \x1 char, then replaces all commas left with semicolons, and then replaces \x1 chars back to commas. This might work, given the file is correctly formed, there're initially no \x1 chars in it and there're no situations where there is a double quote inside double quotes, like "a\"b".
[ "stackoverflow", "0023640376.txt" ]
Q: MySQL Nested Select and IFNULL Syntax Error need help on a MySQL query, can't seem to figure out how to correctly write this statement. I am trying to nest a select in an insert statment and ifnull is also used. INSERT INTO vo (vo_id, agreement_id, serial_no, vo_date, vo_status) VALUES (NULL, '3', (SELECT IFNULL(max(serial_no),1) FROM vo WHERE agreement_id = '3'), CURDATE(), 'Open') Any help is appreciated! Thank you! EDIT: Error i got in mysql is : #1093 - You can't specify target table 'vo' for update in FROM clause A: You can get rid of this error by wrapping your subquery in another subquery without WHERE clause : INSERT INTO vo (vo_id, agreement_id, serial_no, vo_date, vo_status) VALUES (NULL, '3', (SELECT x.* FROM (SELECT IFNULL(max(serial_no),1) FROM vo WHERE agreement_id = '3' ) x), CURDATE(), 'Open')
[ "stackoverflow", "0057529681.txt" ]
Q: Why is empty unordered_map.find not returning end()? I am trying to test if a entry in a unordered_map already exists with a given key. I am using the find() function to return a iterator. The problem is that whether the unordered_map is empty (or not) it returns a 'empty' object when there is no entry with the given key, like this - it = (<Error reading characters of string.>, -842150451) I have tried creating an empty project solution and putting in a minimal example. It still returns the same 'empty' object for find(). I have even tried changing the type of key from std::string to int with the same results. #include <unordered_map> int main(int argc, char* argv[]) { std::string key = "test"; std::unordered_map<std::string, int> myMap; myMap["abc"] = 5; std::unordered_map<std::string, int>::iterator it = myMap.find(key); } I am expecting find() to return 'end' when there is no entry with the given key, but the output is some sort of 'empty' object. A: Just compare the iterator to the end of your list, e.g. if (it == myMap.end()) { std::cout << "didn't find" << std::endl; } else { std::cout << "found " << it->second << std::endl; }
[ "stackoverflow", "0012871790.txt" ]
Q: jquery: .attr() fails for child element I'm going crazy staring at this. I need to change the attribute of an element, something which I have done many times before. But it fails. Now I can't even get jquery to show me the attribute that it has. Does it have to do with what is returned by find()? var c = new_photo_div.find('[class = photo]')[0]; alert(c); alert(new_photo_div.attr('class')); alert(c.attr('class')); The first alert correctly identifies the element: Object HTMLImageElement The second alert correctly gives me the class of new_photo_div. The third alert fails. No alert. I think it should say: photo A: you are using new_photo_div.find('[class = photo]')[0] Dom element not jquery object . try this $(c).attr('class');
[ "sharepoint.stackexchange", "0000192004.txt" ]
Q: CAML Query of List's Lookup Field I have a child form and I want to get the total of the child forms to update the parent with the sum total. I am struggling with the CAML query to get the total back. The below returns zero records at present because (i suspect) the query isn't quite right. var query = '<Query><Where><Eq><FieldRef Name="Engagement" /><Value Type="Lookup">'; query += ParentEngagementID + ";#" + ParentEngagementText + "</Value></Eq></Where></Query>"; console.log("Query is " + query); //Checked in chrome this is: Query is <Query><Where><Eq><FieldRef Name="Engagement"></FieldRef><Value Type="Lookup">106;#ABC Ltd - 31/03/2016 - Year End</Value></Eq></Where></Query> var viewFields = '<ViewFields><FieldRef Name="Budget_x0020_hours" /><FieldRef Name="Actual_x0020_hours" />'; viewFields += '</ViewFields>'; var NewBudgetTotal = 0.00; var NewActualTotal = 0.00; $().SPServices({ operation: "GetListItems", async: false, listName: "Work tracker - Products", webURL: "/sites/UKIAsuDataAnalytics", CAMLViewFields: viewFields, CAMLQuery: query, completefunc: function (xData, Status) { console.log("---------------------"); console.log(status); console.log(xData.responseText); console.log("---------------------"); $(xData.responseXML).SPFilterNode('z:row').each(function() { console.log('Processing list of returned CAML items'); if($(this).attr("ows_Budget_x0020_hours")) { NewBudgetTotal += Number(parseFloat($(this).attr("ows_Budget_x0020_hours").split(";#")[0],2).toFixed(2)); } if($(this).attr("ows_Actual_x0020_hours")) { NewActualTotal += Number(parseFloat($(this).attr("ows_Actual_x0020_hours").split(";#")[0],2).toFixed(2)); } }); } }); If I comment out the query the XML responses coming back are like the below, and you can see the Engagement field should match: "<z:row ows_Budget_x0020_hours='3.00000000000000' ows_Actual_x0020_hours='0' ows_MetaInfo='80;#' ows__ModerationStatus='0' ows__Level='1' ows_ID='80' ows_UniqueId='80;#{E91295D7-EF93-4F11-B486-E00F6A6AB7DF}' ows_owshiddenversion='16' ows_FSObjType='80;#0' ows_Created='2016-07-13 10:17:15' ows_PermMask='0x7fffffffffffffff' ows_Modified='2016-08-26 18:58:30' ows_Engagement='106;#ABC Ltd - 31/03/2016 - Year End' ows_FileRef='80;#sites/MySite/Lists/Work Tracker Tools/80_.000' />" I have tried all sorts of changes to the query for the content of "Engagement" but nothing helps. Any thoughts? (Please don't blame me on design here - I am trying to patch up some Sharepoint "work" done by a colleague. I am certainly not the best person to do the patchup, as much as they weren't the person do to the work.) A: Lookup columns should be queried differently By Value <Query> <Where> <Eq> <FieldRef Name='Engagement' /> <Value Type='Lookup'>" + ParentEngagementText + "</Value> </Eq> </Where> </Query> By Id <Query> <Where> <Eq> <FieldRef Name='Engagement' LookupId='TRUE' /> <Value Type='Lookup'>" + ParentEngagementID + "</Value> </Eq> </Where> </Query>
[ "stackoverflow", "0006290440.txt" ]
Q: C# | Regex Dotall and Result Match To the point, how i can enable dotall flags on C# Regex ? And i have this regex. string reg = "<table>.*</table>"; And for example, i regexed this html text <table id="table1"> <table id="table2"> </table> </table> Where does my regex stop the match ? The first </table> or the second </table> Thanks guys.. :) A: Regular expressions are greedy by default, gobbling up as much as possible. Therefore, it'll stop at the second table. You can change this by applying the question mark modifier. <table>.*?</table> That said, you'll need to make sure that your regex is set up to cover multiple lines of text.
[ "webapps.stackexchange", "0000023827.txt" ]
Q: How to add Picasa web album service to Apps account I just created a Google Apps account (domain name) but only the core services like Gmail, Docs, Calendar, and Sites are activated. However, Photos (Picasa web album) is missing and I don't know how to add it as a service. A: Head over to https://www.google.com/a/cpanel/yourdomain/SelectServices & add from there.
[ "stackoverflow", "0032341240.txt" ]
Q: Bin java time stamp by hour/half hour based on date I have a hashmap, which has keys as date_site, example Key: 2015-08-24_Demo-Site, Value:08:30, and then keys which are in sorted order by time. I want the values binned by time interval within an hour as one report and half hour as another. For example, Key: 2015-08-24_cimp, Value:16:13, 16:20, 16:34, 18:49, 18:57, 22:33 Should be a datapoint in the hour report as: [2015-08-24, "cimp", 16-17, 3], [2015-08-24, "cimp", 18-19, 2], [2015-08-24, "cimp", 21-22, 1] I attempted to make a calendar date time and then checking if the instance is after that, but I am sort of stuck and was wondering if there was an easier way to bin from the hashmap. I am calling the function while iterating over keys, values in my hashmap: for (Map.Entry<String, String> entry : daySiteMap.entrySet()) { System.out.println("Key: " + entry.getKey() + ", Value:" + entry.getValue()); compareTime(entry.getValue()); } private static ArrayList<String> compareTimeHour(String time) { String[] times = time.split(","); ArrayList<String> datas = new ArrayList<String>(); if(times.length == 1){ Integer hour = Integer.parseInt(times[0].split(":")[0].trim()); Integer hour1 = hour+1; datas.add(hour.toString() + "-" + hour1.toString()); datas.add("1"); } else{ for (int i = 0; i < times.length; i++) { Calendar check = Calendar.getInstance(); check.set(Calendar.HOUR_OF_DAY, Integer.parseInt(times[i].split(":")[0].trim())); check.set(Calendar.MINUTE, Integer.parseInt(times[i].split(":")[1].trim())); boolean checking = true; Integer startHour = 1; Integer startMin = 0; while(checking){ Calendar cal = Calendar.getInstance(); cal.set(Calendar.HOUR_OF_DAY, startHour); cal.set(Calendar.MINUTE, startMin); checking = Calendar.getInstance().before(check); startHour+=1; startMin+=30; } } } return datas; } A: The following is an example of how to do something like that: SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Map<Date, String> activityMap = new TreeMap<Date, String>(); activityMap.put(fmt.parse("2015-04-01 09:00:00"), "Show up at work"); activityMap.put(fmt.parse("2015-04-01 09:05:00"), "Get coffee"); activityMap.put(fmt.parse("2015-04-01 09:15:00"), "Read the news"); activityMap.put(fmt.parse("2015-04-01 10:02:00"), "Smoke break"); activityMap.put(fmt.parse("2015-04-01 10:38:00"), "Watercooler break"); activityMap.put(fmt.parse("2015-04-01 11:45:00"), "Lunch break"); Map<Date, List<String>> dateHourMap = new TreeMap<Date, List<String>>(); Calendar cal = Calendar.getInstance(); for (Map.Entry<Date, String> activity : activityMap.entrySet()) { cal.setTime(activity.getKey()); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH); int day = cal.get(Calendar.DAY_OF_MONTH); int hour = cal.get(Calendar.HOUR_OF_DAY); int minute = cal.get(Calendar.MINUTE); int second = cal.get(Calendar.SECOND); cal.clear(); cal.set(year, month, day, hour, 0); Date dateHour = cal.getTime(); List<String> list = dateHourMap.get(dateHour); if (list == null) dateHourMap.put(dateHour, list = new ArrayList<String>()); list.add(String.format("%02d:%02d %s", minute, second, activity.getValue())); } fmt = new SimpleDateFormat("yyyy-MM-dd HH"); for (Map.Entry<Date, List<String>> entry : dateHourMap.entrySet()) System.out.println(fmt.format(entry.getKey()) + ": " + entry.getValue()); Output 2015-04-01 09: [00:00 Show up at work, 05:00 Get coffee, 15:00 Read the news] 2015-04-01 10: [02:00 Smoke break, 38:00 Watercooler break] 2015-04-01 11: [45:00 Lunch break]
[ "stackoverflow", "0047050245.txt" ]
Q: Hide modal by ID when there are more modals I have a page with several modals and I open them by unique ID, like this: %a{"data-toggle" => "modal", href: "#modal-123", role: "button"} %a{"data-toggle" => "modal", href: "#modal-456", role: "button"} This works fine, but the problem is closing a specific modal. By default this is done by this: .modal.fade{:style => "display: none;", :tabindex => "-1", id: "modal-123"} .modal-dialog .modal-content .modal-header .modal-body .modal-footer %button.btn.btn-default{"data-dismiss" => "modal", :type => "button"} Close But this doesn't work because it doesn't know which of the modals to close. How can I make it close the modal with the specific ID? A: Remove the data-dismiss attribute. then add $('.btn.btn-default').click(function(){ $(this).modal('hide'); });
[ "magento.stackexchange", "0000269687.txt" ]
Q: Magento 2 - Get URL data by request path I have gathered URLs from sitemap.xml now I need category ID against category URL and Product ID against product URL. I want to do it by getting URL data from url_rewrite table In Magento 1.9 we use this code to get data by request path Mage::getModel('core/url_rewrite')->loadByRequestPath("abcPath"); How can we do it in Magento 2? A: After some digging in magento core code I finally got solution. I have used this code to get url_rewrite data by url key /* Find url data by request path */ $filterData = [ UrlRewrite::REQUEST_PATH => $path ]; $rewrite = $this->urlFinder->findOneByData($filterData); $type = $rewrite->getEntityType(); $entityId = $rewrite->getEntityId(); $targetPath = $rewrite->getTargetPath(); Hope it will help others too.
[ "stackoverflow", "0033311893.txt" ]
Q: Securing Jersey 2 Rest API I'm building a webcrawler (similar to http://diffbot.com | SAAS) with Jersey 2. Other developers should be able to use this API (make a request -> get a JSON response) in a secure way. Here is the flow: A users goes to the applications website (register/login). After the login/registration he should see a panel with API_KEY and API_SECRET. He can now use this API_SECRET to access the API and therefore the crawler. Is Ouath suitable for that? Are there better/simpler solutions? A: I assume you want to offer your users the possibility to register applications that can use your API. I would say for your use case you don't necessarily need OAuth. A simple authentication method like basic authentication (with SSL) would also be sufficient. As wikipedia put it: [OAuth] specifies a process for resource owners to authorize third-party access to their server resources without sharing their credentials. What you could use OAuth for: To give your users access to your resources (your API), but you want to let them use an existing account for that (say for example their Github account). This way a user does not need an account with your site, but he can authorize his application against your API using Github's authorization facilities. If you don't mind spending a few hours on learning a bit about OAuth, it will offer you more flexibility.
[ "math.stackexchange", "0001378362.txt" ]
Q: Pigeonhole principle 3 I need help on this question, I'm lost and really don't know how to proceed: Use the pigeonhole principle to prove that in a round-robin chess tournament (with 18 participants) there will be at least two players with the same number of draws? A: The argument below is a parity argument. Let us suppose that each player makes a tick mark in her notebook for every drawn game she is involved in. Note that a drawn game results in $2$ tick marks, so the total number of tick marks is even. Each player makes $0$ to $17$ tick marks. If all the players have different numbers of draws, then the total number of tick marks is $0+1+2+\cdots+17$, which is $153$. This is impossible, since $153$ is odd. A: My original answer was wrong. Please see the other answers.
[ "stackoverflow", "0034570164.txt" ]
Q: Represent List as a String with Double-Quotes Instead of Single-Quotes for JSON Input: mylist = ["a", "b"] I have to output: '["a", "b"]' But using str(mylist) or '{}'.format(mylist) on the list gets me: "['a', 'b']" This is for a JSON API, and JSON doesn't accept '. Looking around, this is indeed stated that here it doesn't work with format for containers. Is there still a solution? I'm now using .replace("'", '"') but that really seems silly. A: Are you trying to output JSON? In that case you should use json.dumps: import json json.dumps(mylist) This outputs: '["a", "b"]'.
[ "stackoverflow", "0008797367.txt" ]
Q: why does IE need for me to click twice I have this jQuery $('.billing_info').click(function(e){ e.preventDefault(); if(($('.shipping_selection').length) > 0){ if ($('.shipping_selection:checked').length == 0){ $('.hide_error').show(); $("html, body").animate({ scrollTop: $(".hide_error").offset().top }, "slow"); $(".hide_error").effect("highlight", {}, 4000); return false; }else{ $('.billing_info').unbind("click"); $('.billing_info').click(); } }else{ $('.billing_info').unbind("click"); $('.billing_info').click(); } }); which works awesome in all browsers except in IE. I'm using IE8 and the user needs to click the button twice for the button to accept the click event even if there is one radio button $('.shipping_selection') clicked A: Perhaps a bit of refactoring would help. Only prevent default when you need to, otherwise let the function pass through to the default submit event. $('.billing_info').click(function(e){ if(($('.shipping_selection').length) > 0 && $('.shipping_selection:checked').length == 0){ e.preventDefault(); $('.hide_error').show(); $("html, body").animate({ scrollTop: $(".hide_error").offset().top }, "slow"); $(".hide_error").effect("highlight", {}, 4000); return false; } });
[ "stackoverflow", "0006605313.txt" ]
Q: smoothing of auto-correlated time series data with ggplot2 Is there a way to incorporate smoothing function for an auto-correlated time series in ggplot2? I have time series data that is auto-correlated for which I currently use a manual process to determine 95% CI for the fitted spline. Usage and Date are in a data frame AB. The main components of the model I use are as follows: d<-AB$Date a<-AB$Usage o<-order(d) d<-d[o] a<-a[o] id<-ts(1:length(d)) a1<-ts(a) a2<-lag(a1-1) tg<-ts.union(a1,id,a2) mg<-lm(a1~a2+bs(id,df=df1), data=tg) From this model I obtain fitted means and standard errors of the fit which are used to work out the 95% CI for the fitted spline. I have seen examples of the lm method in ggplot2 with a term to specify the model formula. Is this kind of time series model achievable when the time series is auto-correlated? Thanks. A: The CI will be biased if you use the simple formula in ggplot2 for adding any model fit if there is dependence in the residuals. If I were doing this, I would fit whatever model I wanted outside of gpplot2. Then predict from that model over a grid evenly spaced points in the range of the covariates. Compute confidence intervals for those predictions and combine these and the fitted values and the data into a single data frame. From there you can use geom_line() and geom_ribbon() for the fitted model and confidence interval respectively. This allows you to compute proper confidence intervals that account for the lack of independence in the residuals. One issue I foresee is that you have a model that includes two covariates, whereas ggplot() would normally consider the relationship between a response and a single covariate. For example, if you are plotting a1 vs id in ggplot but the model is for a2 + bs(id) then you'd need to account a2 in some manner first, say be predicting for a range of values in id but keep a2 fixed at some reasonable value, say the sample mean.
[ "stackoverflow", "0006848689.txt" ]
Q: Sql Server CLR Functions While writing a CLR function Sql Server can we use namespaces ? namespace SomeName1.SomeName2 { public static class SomeClass { [SqlFunction] public static SqlString SomeMethod(SqlString input) { // .... } } } If so, then how do we call this function from SqlServer. In other words how do we call CLR functions from SQL Server with namespaces? A: Yes, you absolutely can: CREATE FUNCTION SomeMethod(@input VarChar(200)) RETURNS VarChar(200) WITH EXECUTE AS CALLER AS EXTERNAL NAME [SomeName1.SomeName2].[SomeName1.SomeName2.SomeClass.SomeMethod] Where [SomeName1.SomeName2] in the first part is the assembly as named in SQL Server, and the rest ([SomeName1.SomeName2.SomeClass.SomeMethod]) is the fully qualified function name, including the namespace. Incidentally, if you deploy from Visual Studio it handles a lot of this for you.
[ "stackoverflow", "0015043532.txt" ]
Q: "message": "java.lang.NullPointerException" when trying to insert entity via api-explorer I`m new in appEngine and i trying simple things that are necessary for my project: I create simple JDO class of Image: @PersistenceCapable(identityType = IdentityType.APPLICATION) public class Image { @PrimaryKey @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY) private Key key; @Persistent private Blob image; @Persistent private String type; @Persistent private String description; public Key getKey() { return key; } public void setKey(Key key) { this.key = key; } public Blob getImage() { return image; } public void setImage(URL url) throws IOException { try { BufferedReader reader = new BufferedReader(new InputStreamReader( url.openStream())); String line; StringBuffer stbf = new StringBuffer(); while ((line = reader.readLine()) != null) { stbf.append(line); } image = new Blob(stbf.toString().getBytes()); reader.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } End-Points where succesfully created and deplyoed to AppEngine. When i trying to insert simple object to datastore via google-api-explorer https://developers.google.com/apis-explorer/?base=https://my-application.appspot.com/_ah/api#s/, with just link to image and Key with id and appID paraemeters, i recieve the following error: 503 Service Unavailable - Show headers - { "error": { "errors": [ { "domain": "global", "reason": "backendError", "message": "java.lang.NullPointerException" } ], "code": 503, "message": "java.lang.NullPointerException" } } When i changing key to by from type Long, query executed properly and i see new entity in datastore. Additional to that, in Documentation said that "If the encoded key field is null, the field is populated with a system-generated key when the object is saved". But seems that it`s not accept it without key? Can anybody help me with this issue? A: Have a look at the generated method containsImage: The standard generated code doesn't check if getKey() returns null. You'll need to include something like: if (image.getKey() == null) { return false; } before it does a getObjectById.
[ "stackoverflow", "0059904938.txt" ]
Q: How do I make a nested for loop in R that multiples X & X? So I'm trying to do a nested for loop that will multiple 1:100 with 1:100 (10,000 possible combinations). So 1*1, 1*2 ... 1* 100. Once it reaches 100, I want it to repeat, so 2*1, 2*2, 2*100. Of note: I need to be doing this using for loops table<-matrix(ncol=3, nrow=100*100) for (i in 1:100) { for (z in 1:100){ answer<-i*z table[i,] <- c(i,z,answer) } } Here's my code above. It seems like an easy fix, but I'm missing something.. A: We can use outer out <- outer(1:100, 1:100) It can be converted to a 3-column data.frame with melt library(reshape2) out2 <- melt(out) In the for loop, we need for (i in 1:100) { for (z in 1:100){ answer<-i*z table[i, z] <- answer } } table[i, z] <- answer where table <- matrix(nrow = 100, ncol = 100) Checking the output all.equal(out, table) #[1] TRUE If we need the 'i', 'z' out2 <- transform(expand.grid(i = 1:100, z = 1:100), answer = i * z) Or with crossing library(tidyr) library(dplyr) crossing(i = 1:100, z = 1:100) %>% mutate(answer = i * z) # A tibble: 10,000 x 3 # i z answer # <int> <int> <int> # 1 1 1 1 # 2 1 2 2 # 3 1 3 3 # 4 1 4 4 # 5 1 5 5 # 6 1 6 6 # 7 1 7 7 # 8 1 8 8 # 9 1 9 9 #10 1 10 10 # … with 9,990 more rows Or in a forloop table1 <- c() for(i in 1:100) { for(z in 1:100){ table1 <- rbind(table1, c(i, z, i * z)) } }
[ "stackoverflow", "0013526027.txt" ]
Q: mysql, php calculate mean per month with multiple userid's This is driving me crazy, I cant seam to manage this without massive amount of code, this is my sql table: userid date orderValue 2 2012-01-01 2000 1 2012-01-01 3000 1 2012-01-01 5000 1 2012-01-02 5000 2 2012-01-02 8000 2 2012-01-02 8000 For each month I need to get the mean value per user from the first date ever intill the current month. The output I'am looking for is something along the line of $orderArray[$month][$userid]['mean'] I don't relay need the code, jut need to get my mind out the current thoughts that man stuck on. How would you go about solving this? A: Something along the lines of: SELECT `userid`, DATE_FORMAT(`date`, '%Y%m') AS `month`, AVG(`orderValue`) AS `mean` FROM `orderTable` GROUP BY `userid`, `month` Note that I'm using DATE_FORMAT instead of MONTH. If you don't do this, January 2012 and January 2013 would effectively be merged, which I guess is not what you want. You'll have to create the desired result array yourself in PHP by iterating over the SQL result set and putting each mean value in the appropriate place.
[ "stackoverflow", "0061668584.txt" ]
Q: How do you always refresh html Audio My web application is based on generating and playing an audio file. Unfortunately, despite the audio file itself being updated (I know this because when I download it it's correct), the audio that is played on the website is a cached, old version. Even hard refreshing multiple times doesn't get past the cache. How can I reload the audio source. <audio controls> <source src="/static/output.wav"> </audio> A: Even hard refreshing multiple times doesn't get past the cache. ... Unfortunately, despite the audio file itself being updated (I know this because when I download it it's correct) Those aren't the same HTTP request. When you use the <audio> element, it will make ranged requests. Something, somewhere along the way, is caching it. In any case, all you need to do is set the appropriate Cache-Control header on the HTTP response. Something like this will do: Cache-Control: no-store (Of course, you will actually need to flush your browser's cache, and any server-side caches before you'll see this take effect.) See also: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control
[ "serverfault", "0000322247.txt" ]
Q: Should I use ubuntu 11.04 or 11.10 on ec2 for a rails front-end server? I have been digging around for an answer to this question and have come up with a handful of benchmarks and a whole lot of promotional material but it's not clear to me what to choose. If I am setting up a new rails 3.1 front-end server, what version of ubuntu (11.04 or 11.10) should I choose? A: Here are some of the considerations that go into this decision for me (not specific to rails): Neither of these is an LTS release, so both reach their end of life for support 18 months after release. 11.10 was just released this month. 11.04 is already 6 months into its release, so reaches end of life in one year. 11.10 will have newer versions of the various software packages and applications. This can be great for getting the latest features in new projects. 11.04 has been around for half a year, so is less likely to have undiscovered bugs. If I'm launching a project that needs to have less risk in the immediate future, I'll generally avoid a new release until it's aged a month or two. 11.10 may get problems addressed more quickly than older releases as it's the most recent. It might also get better support on EC2 if that's where you're thinking of running.
[ "stackoverflow", "0008241463.txt" ]
Q: how to next detailView like in Mail-App i want to jump in my detailview through the rows of my tableview. passing the data from the tableview to detailview works fine. passing the indexpath.row working fine, too. in the detailview i can change the indexpath of the row and by returning to the tableview the changed row is selected right. And my problem is that i cant view the data of new selected row in the detailview. i hope you understand what i am trying to do :) for example like in the mail app: i want to push the "next" button and get the associated data . Next function: - (IBAction)nextRow:(id) sender { NSLog(@"nextBtn"); TableRotateViewController *parent = (TableRotateViewController *)self.parentViewController; NSIndexPath *actualIndexPath = detailselectedRow; NSIndexPath * newIndexPath = [NSIndexPath indexPathForRow:actualIndexPath.row+1 inSection:actualIndexPath.section]; if([parent.view.subviews objectAtIndex:0]) { UIView * subview = (UIView *) [parent.view.subviews objectAtIndex:0]; UITableView *tView = (UITableView *) subview; [tView selectRowAtIndexPath:newIndexPath animated:YES scrollPosition:UITableViewScrollPositionMiddle]; [tView.delegate tableView:tView didSelectRowAtIndexPath:newIndexPath]; } } Here is my sample application for better understanding what i have done jet: http://www.file-upload.net/download-3896312/TableRotate.zip.html A: Would you like to show new detail information when click left or right button in detail Page , right? In the Parent View Class (TableView Layout), you should create NSMutableArray that contain some specific object (ex. "MailDetailObject" that containg data1 , data2 ,data 3 ,... as you wish) and you could keep each MailDetailObject contain each detail information and put them together to NSMutableArray in Parent View Class and now , when you didselectRowAtIndexPath in tableView , send this NSMutableArray and your current index on tableView to DetailView (Don't forget to create this property in DetailView for refer object that send from parentView) In the detailView , (IBAction)nextRow Method , if you click next you can refer to the next index and lookup in NSMutableArray that have sent from your parentView and get the next index information to display hope it helps you
[ "stackoverflow", "0028369390.txt" ]
Q: swift is slow at updating view after a REST POST request I'm sending some POST request to my sever with swift, the usual: let request = NSMutableURLRequest(URL: url) request.HTTPMethod = "POST" request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding) let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in if error != nil { println("error=\(error)") return } let responseString = NSString(data: data, encoding: NSUTF8StringEncoding) println(responseString) //this is fast label.text = "\(responseString)" // this is very slow } task.resume() This works well, I get the data and all. Now there are 2 things that behave very differently and I can't figure out why. The line: println(responseString) print the data instantly as expected, however, the line label.text = "\(responseString)" takes about 10 seconds to update the label's text. Any ideas why? has DrawRect got anything to do with this? A: Try doing it on the main thread like this: dispatch_async(dispatch_get_main_queue(), { () -> Void in label.text = "\(responseString)" })
[ "photo.stackexchange", "0000007574.txt" ]
Q: Where can I sell digital photos online without advance commissions or fees? I am looking for an online place to sell my photos. My requirements are slightly different to normal. Don't pay anything upfront. Only pay commission when a sale falls through. No filtering of images so if my images are rubbish I should still be able to have them for display to sell. Don't sell prints, only electronic format of high resolution images. Basically I don't want to pay any fees unless I am making a sale/profit ;) A: If your volume is low enough, you could just handle everything yourself. Post low-resolution images on your website and let users contact you directly specifying which ones they want. You could accept Paypal, which has much lower fees than many photo-selling websites I have seen. A: Have you considered a solution like Instaproofs? They don't have a setup fee, you can set your own prices, you can upload whatever you want to (it's designed as a professional photography proofing site), and they charge a commission only when a sale is actually made... The commission is kinda steep- 15% of the total order amount (although it is on a sliding scale, so if you hope to sell big-dollar amounts, the commission will end up being less). Sounds like it might be exactly what you're looking for. A: I'm pretty sure that Lulu.com will do what you are asking of them. It's not a particularly well know site for selling digitial prints, but it will do the job.
[ "stackoverflow", "0049300428.txt" ]
Q: Multiples Conditions Sum SQL I am aiming to produce code that generates an independent total check. As per the below table: column1 Column2 Column3 value independent total check A B C 10 Null A B E 11 Null A B total 21 21 x y z 10 Null x y p 20 Null x y total 30 30 I am trying to employ a conditional sum, but with no success! What I have at the moment is: IF OBJECT_ID('tempdb..#Temp') IS NOT NULL DROP Table #Temp select t2.Column1, t2.Column2, t2.Column3,t2.value, independanttotal = case when t2.Column1 ='A' and t2.Column2= 'B'and t2.T_subdesk = 'Total' then sum(t2.value) when t2.Column1 ='x' and t2.Column2= 'y'and t2.T_subdesk = 'Total' then sum(t2.value) end into #Temp from #Temp_A t2 group by t2.Column1,t2.Column2,t2.Column3,t2.value but this is clearly incorrect, although it produces the correct result actually I am just reproducing the total value. Do I need some kind of nested sum? Do I need to separate out this into different table? this is really frustrating me thanks for your help in advance! A: You seem to want: select t.*, sum(case when column3 <> 'total' then value end) over (partition by column1, column2) as independent_total from #temp t; This puts the computation on all rows. I don't think that is a problem, but you can use a case expression outside the sum() if that is really an issue. If you only want this on the "total" row, you can do: select t.*, (case when column3 = 'total' then sum(case when column3 <> 'total' then value end) over (partition by column1, column2) end) as independent_total from #temp t; Or, you slightly simplify the logic: select t.*, (case when column3 = 'total' then sum(value) over (partition by column1, column2) - value end) as independent_total from #temp t; This gets the total sum for the two columns and then subtracts the value on the 'total' row.
[ "stackoverflow", "0011085526.txt" ]
Q: Calculating a camera's position and orientation in opencv So imagine that there is a camera looking at your computer screen. What I am trying to do is determine how much that camera is rotated, how far away it is from the screen, and where it is relative to the screen's center. In short the rotation and translation matrices. I'm using opencv to do this, and followed their camera calibration example to do this task with a checkerboard pattern and a frame from a webcam. I would like to do with any generic images, namely a screen cap and a frame from a webcam. I've tried using the feature detection algorithms to get a list of keypoints from both images and then match those keypoints with a BFMatcher, but have run into problems. Specifically SIFT does not match keypoints correctly, and SURF does not find keypoints correctly on a scaled image. Is there an easier solution to this problem? I feel that this would be a common thing that people have done, but have not found much discussion of it online. Thanks!! A: Finding natural planar markers is a common task in computer vision but in your case you have a screen which varies depending on what you are visualizing on the screen, it can be your desktop, your browser, a movie,... So you cannot apply usual methods for marker detection, you should try shape recognition. An idea is trying a particle filter on a rectangular template of the same dimensions (through different scales) of your screen frame, applying first edge detection. The particle filter will fit the template to the area of the frame. After doing this, you will know the position. For orientation you will need to calculate homography, and you need 4 points in the "marker" for this, so you can apply Direct Linear Transform (cv::findHomography() does this for you). So your four points can be the four corners. This is just an idea, good luck!
[ "english.stackexchange", "0000463681.txt" ]
Q: We're square/even/quits in formal speech What are the differences between: be square, be even and be quits? Are they acceptable to use in formal speech? If they not, what should I use instead? A: If you are even with someone, you do not owe them anything, such as money or a favor: You don't owe me. I don't owe you. We're even. (informal) If two people are quits, they are on even terms, especially because a debt or score has been settled: I think we're just about quits now, don't you? (informal) If two people are square, one of them has paid off a debt to the other and neither now owes or is owed any money: I paid you back, so we're square. (informal according to the Cambridge Dictionary) Since all the three adjectives are informal, I suggest using "debt-free", for example (the word is not formal though; I'd say it's neutral): The company's virtually debt-free status gives it the flexibility to consider larger deals. The family business is healthy and completely debt-free. "Debt-free" can be used to talk about not only companies but also people: Whether we’re there yet or not, many of us hope to be debt-free and continue living that way.
[ "stackoverflow", "0027018767.txt" ]
Q: Navigation drawer lag The navigation drawer lags every time I open a new activity. I looked on Google for a solution and I found out that I can solve it by delaying the new activity with a Handler. I experimented a little bit but got nowhere. Some code pieces from MainActivity.java: public void SelectItem(int possition) { Fragment fragment = null; Bundle args = new Bundle(); switch (possition) { case 2: fragment = new FragmentZero(); break; case 3: fragment = new FragmentOne(); break; case 4: fragment = new FragmentTwo(); break; case 5: fragment = new FragmentThree(); break; case 7: fragment = new FragmentTwo(); break; case 8: fragment = new FragmentZero(); break; case 9: fragment = new FragmentOne(); break; case 10: fragment = new FragmentTwo(); break; case 11: fragment = new FragmentZero(); break; case 12: fragment = new FragmentOne(); break; case 14: fragment = new FragmentZero(); break; case 15: fragment = new FragmentOne(); break; case 16: fragment = new FragmentTwo(); break; default: break; } fragment.setArguments(args); FragmentManager frgManager = getFragmentManager(); frgManager.beginTransaction().replace(R.id.content_frame, fragment) .commit(); mDrawerList.setItemChecked(possition, true); setTitle(dataList.get(possition).getItemName()); mDrawerLayout.closeDrawer(mDrawerList); } and private class DrawerItemClickListener implements ListView.OnItemClickListener { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (dataList.get(position).getTitle() == null) { SelectItem(position); } } } A: In your activity create a handler and initialize it in your on create method private Handler mHandler; mHandler = new Handler(); then change your drawer item click listener to this. private class DrawerItemClickListener implements ListView.OnItemClickListener { @Override public void onItemClick(AdapterView<?> parent, View view, final int position, long id) { if (dataList.get(position).getTitle() == null) { mHandler.postDelayed(new Runnable() { @Override public void run() { SelectItem(position);; } }, 250); } mDrawerList.setItemChecked(possition, true); mDrawerLayout.closeDrawer(mDrawerList); } } and change SelectItem method to this public void SelectItem(int possition) { Fragment fragment = null; Bundle args = new Bundle(); switch (possition) { case 2: fragment = new FragmentZero(); break; case 3: fragment = new FragmentOne(); break; case 4: fragment = new FragmentTwo(); break; case 5: fragment = new FragmentThree(); break; case 7: fragment = new FragmentTwo(); break; case 8: fragment = new FragmentZero(); break; case 9: fragment = new FragmentOne(); break; case 10: fragment = new FragmentTwo(); break; case 11: fragment = new FragmentZero(); break; case 12: fragment = new FragmentOne(); break; case 14: fragment = new FragmentZero(); break; case 15: fragment = new FragmentOne(); break; case 16: fragment = new FragmentTwo(); break; default: break; } fragment.setArguments(args); FragmentManager frgManager = getFragmentManager(); frgManager.beginTransaction().replace(R.id.content_frame, fragment) .commit(); setTitle(dataList.get(possition).getItemName()); }