source
sequence
text
stringlengths
99
98.5k
[ "stackoverflow", "0036894358.txt" ]
Q: What is a good way to extract dominant colors from image without the shadow? Is it possible to extract the 'true' color of building façade from a photo/ a set of similar photos and removing the distraction of shadow? Currently, I'm using K-means clustering to get the dominant colors, however, it extracts darker colors (if the building is red, then the 1st color would be dark red) as there are lots of shadow areas in real photos. Any suggestions are greatly appreciated! Thanks in advance! A: You could simply ignore the shadow areas by only evaluating areas of a certain brightness. I suggest you make yourself familiar with the HSI/HSL/HSV colour models https://en.wikipedia.org/wiki/HSL_and_HSV Understanding this should help to solve the problem on your own.
[ "stackoverflow", "0006091944.txt" ]
Q: Why does printing an object fail with a "no match for 'operator<<'" error? I have created a dynamic memory as s_points, which has the type PointList. PointList is vector of integer values. I have appended to s_points by getting some values from another list of data. Now I want to visualise my s_points to check whether it is updated or not, but I have an error: no match for 'operator<<' in 'std::cout << (&z)->__gnu_cxx:: __normal_iterator<_Iterator, _Container>::operator* [with _Iterator = Number*, _Container = std::vector<Number, std::allocator<Number> >]()' Here is my code: MyPoints::iterator point; PointList *s_points = new PointList; for (point=my_points.begin();point!=my_points.end();point++){ s_points->push_back(point->Attribute(NumberTag)); } PointList::iterator z; for(z=s_points->begin();z!=s_points->end();z++){cout<<*z<<" ";} Please help me understand this error. A: The error speaks for itself. You don't have operator<<() defined for Number.
[ "stackoverflow", "0039550732.txt" ]
Q: Is there a way to have conditional markdown chunk execution in Rmarkdown? I am an instructor looking to make a homework assignment and homework solution guide from the same Rmarkdown file by changing a document parameter I created called soln. When soln=FALSE the assignment document is generated, and when soln=TRUE the homework solution guide is generated. I can control R code chunk execution using the document parameter, but I would also like conditional inclusion of markdown text. My current workaround is ugly: --- title: "Homework" output: word_document params: soln: TRUE --- Fit the linear regression model $Y \sim X$ with the following data. Interpret the coefficient estimates. ```{r promptchunk, include = TRUE, echo = TRUE} # R code I want to show in the question prompt goes here # This executes in both assignment and solution versions set.seed(123) X <- c(1, 1, 0, 0) Y <- rnorm(4) ``` ```{r, include = params$soln, echo = FALSE, results = "asis"} cat(" **ANSWER** ") ``` ```{r, echo = params$soln, include = params$soln, eval = params$soln} # R code corresponding to the solution fit1 <- lm(Y ~ X) summary(fit1) ``` ```{r, include = params$soln, echo = FALSE, eval = params$soln, results = "asis"} cat(" The interpretation of the intercept is.... Our estimate $\\hat{\\beta}_0$ is ",coef(fit1)[1],". The estimated X coefficient $\\hat{\\beta}_1$ is ",coef(fit1)[2]," This can be interpreted as.... You can imagine that for more difficult questions, this section could be quite long. ") ``` What I would like to do is to replace the chunks containing cat functions with something more elegant and readable for the person writing the solutions guide. My current approach works enough for me, but it is not something that I could ask my co-instructors to use because it is so unpleasant to write the solutions inside of the cat function. (As a LaTeX user, it is also annoying to need double slashes for everything inside the math commands.) Is there another way to do this? A: Instead of using cat to print the solution from within an R code chunk, you could write the solution as you usually would in rmarkdown (i.e., with the usual combination of text, latex, and R code chunks), and use the parameter soln to comment out that section when you don't want to include the solution in the final document. In the sample rmarkdown document below, if the parameter soln is FALSE, then the line r if(!params$soln) {"\\begin{comment}"} inserts \begin{comment} to comment out the solution (with matching code at the end to insert \end{comment}). I've also indented everything with two tabs, so that the question numbers are formatted with a hanging-indent. (If you like this format, you don't have to type the double-tab for each new paragraph or chunk. If you do this for one line, then each subsequent time you press the Enter key, the new line will automatically be formatted with the double-tab. Or, just type in all your text and code for a given question, then when you're done, highlight all of it and type tab twice.) --- title: "Homework" output: word_document header-includes: - \usepackage{comment} params: soln: TRUE --- 1. Fit the linear regression model $Y \sim X$ with the following data. Interpret the coefficient estimates. ```{r promptchunk, echo = TRUE} set.seed(123) X <- c(1, 1, 0, 0) Y <- rnorm(4) ``` `r if(!params$soln) {"\\begin{comment}"}` **Solution:** Run the following R code to fit the linear regression model: ```{r, include = params$soln, echo = TRUE, results = "asis"} fit1 = lm(Y ~ X) ``` To see a summary of the regression results, run the following code and review the output: ```{r, include = params$soln, echo=TRUE} summary(fit1) ``` The interpretation of the intercept is.... Our estimate $\hat{\beta}_0$ is `r round(coef(fit1)[1], 2)`. The estimated X coefficient $\hat{\beta}_1$ is `r round(coef(fit1)[2], 2)`. This can be interpreted as.... `r if(!params$soln) {"\\end{comment}"}` Also, instead of knitting the file above interactively, you can render both versions by running the render function in a separate R script. For example, assuming the file above is called hw.Rmd, open a separate R script file and run the following: for (i in c(TRUE, FALSE)) { rmarkdown::render("hw.Rmd", params = list(soln = i), output_file=ifelse(i, "Solutions.doc", "Homework.doc")) } Below is what Solutions.doc looks like. Homework.doc is similar, except everything from the bold word Solution: onward is excluded:
[ "stackoverflow", "0040152795.txt" ]
Q: How to get actual class type from Class method argument I am trying to get the instance or class name from the method argument as follows : public class Test { public void getData (Class<T> type){ // Class type of instance of "type" method argument. if(type instanceOf SomeClass) { //Do something } } } I have already tried reflation methods like getClass(), getSimpleClassName(), getName() etc. These all are returning class name as "Class" and instance as "class java.lang.Class". I need it to compare the instance with some class and do necessary operation. A: If the types should be exactly the same (equals for example String.class and String.class then you can use == or equals) public class Test { public void getData (Class<T> type){ // Class type of instance of "type" method argument. if(type.equals(SomeClass.class) { //Do something } } } ELse if the types are related by inheritance e.g CharSequence.class and String.class you can use assignableFrom public class Test { public void getData (Class<T> type){ // Class type of instance of "type" method argument. if(SomeClass.class.isAssignableFrom(type) { //Do something } } }
[ "stackoverflow", "0029465994.txt" ]
Q: Not able to get data in the dataFilter function I am trying to filter the json array received from the server. I'm able to receive the data properly in the success function however I get a "data is undefined error" within the filterdata block. [Uncaught TypeError: Cannot read property 'list' of undefined] $(function () { function log(message) { $("<div>").text(message).prependTo("#log"); $("#log").scrollTop(0); } $("#city").autocomplete({ source: function (request, response) { $.ajax({ url: "http://api.openweathermap.org/data/2.5/find?mode=json&type=like", dataType: "jsonp", data: { q: request.term }, dataFilter: function (data, type) { console.log(data); alert(data.list.length); alert(data.list[0].name + ', ' + data.list[0].sys.country); jsonObj = []; for (i = 0; i < data.list.length; i++) { item = {} item["city"] = data.list[0].name; item["country"] = data.list[0].sys.country; jsonObj.push(item); } return jsonObj; }, success: function (data) { //alert(data.list.length); response(data); } }); }, minLength: 3, select: function (event, ui) { log(ui.item ? "Selected: " + ui.item.label : "Nothing selected, input was " + this.value); }, open: function () { $(this).removeClass("ui-corner-all").addClass("ui-corner-top"); }, close: function () { $(this).removeClass("ui-corner-top").addClass("ui-corner-all"); } }); }); A: As dataFilter is a function to be used to handle the raw response data of XMLHttpRequest. Since you are using JSONP request, which is not an XHR request so there is no XHR object and no raw data, which makes the behavior of dataFilter in your case perfectly valid. You should check the response in success callback instead.
[ "stackoverflow", "0018363500.txt" ]
Q: How do I run tests without exporting all the symbols I have (at least) one package where my main program lives. I have another package for running tests. I :use the package of the main program in the defpackage form of the test package but that only imports the exported symbols. So I can't test all of functions, only the ones I have explicitly exported (the public API). How to I solve this issue? A: You can always refer to internal (un-exported) symbols with a double-colon qualifier: (package-name::function-name) You can also import a symbol into your test package (regardless of whether it's been exported from the main package) with import. For instance: (import 'package-name::function-name) (fboundp 'function-name) ;; => t Here's the CLHS entry on import. Also, if you haven't read it, I recommend the Programming in the Large: Packages and Symbols chapter from Practical Common Lisp. It doesn't directly address your question, but I mention it because I've found it very helpful regrading packages and symbols in general.
[ "stackoverflow", "0056937493.txt" ]
Q: Call a karate feature, which include another call inside I am trying to call a feature file, which is also calling another one inside. The feature I am calling is in another directory. Therefore, when I execute the scenario it is looking in the wrong place. Here is an example: -scenarios --directoryA ---feature1 ---feature2 --directoryB ---feature3 Feature: feature2 Scenario: scenario2 * url testUrl * def testCall = call read('feature1.feature') Given request { test: 'test' } When method post Then status 201 Feature: feature3 Scenario: scenario3 * url testUrl * def testCall = call read('classpath:scenarios/directoryA/feature2.feature') Given request { test: 'test' } When method post Then status 201 The error I get after feature 3 is executed: feature2.feature:9 - javascript evaluation failed: read('feature1.feature'), java.io.FileNotFoundException: /Users/svetoslavlazarov/project/src/test/java/scenarios/directoryB/feature1.feature (No such file or directory) The problem here is that call for feature1 is in wrong directory. It should look at directoryA, instead of directoryB. However, if I execute the scenario2 standalone, it is fine. Can you help me with this? Thanks. A: Try this: * def testCall = call read('this:feature1.feature')
[ "stackoverflow", "0008336858.txt" ]
Q: How to combine two strings together in PHP? I don't actually know how to describe what I wanted but I'll show you: For example: $data1 = "the color is"; $data2 = "red"; What should I do (or process) so $result is the combination of $data1 and $data2? Desired result: $result = "the color is red"; A: $result = $data1 . $data2; This is called string concatenation. Your example lacks a space though, so for that specifically, you would need: $result = $data1 . ' ' . $data2; A: There are several ways to concatenate two strings together. Use the concatenation operator . (and .=) In PHP . is the concatenation operator which returns the concatenation of its right and left arguments $data1 = "the color is"; $data2 = "red"; $result = $data1 . ' ' . $data2; If you want to append a string to another string you would use the .= operator: $data1 = "the color is "; $data1 .= "red" Complex (curly) syntax / double quotes strings In PHP variables contained in double quoted strings are interpolated (i.e. their values are "swapped out" for the variable). This means you can place the variables in place of the strings and just put a space in between them. The curly braces make it clear where the variables are. $result = "{$data1} {$data2}"; Note: this will also work without the braces in your case: $result = "$data1 $data2"; You can also concatenate array values inside a string : $arr1 = ['val' => 'This is a']; $arr2 = ['val' => 'test']; $variable = "{$arr1['val']} {$arr2['val']}"; Use sprintf() or printf() sprintf() allows us to format strings using powerful formatting options. It is overkill for such simple concatenation but it handy when you have a complex string and/or want to do some formatting of the data as well. $result = sprintf("%s %s", $data1, $data2); printf() does the same thing but will immediately display the output. printf("%s %s", $data1, $data2); // same as $result = sprintf("%s %s", $data1, $data2); echo $result; Heredoc Heredocs can also be used to combine variables into a string. $result= <<<EOT $data1 $data2 EOT; Use a , with echo() This only works when echoing out content and not assigning to a variable. But you can use a comma to separate a list of expressions for PHP to echo out and use a string with one blank space as one of those expressions: echo $data1, ' ', $data2; A: No one mentioned this but there is other possibility. I'm using it for huge sql queries. You can use .= operator :) $string = "the color is "; $string .= "red"; echo $string; // gives: the color is red
[ "stackoverflow", "0060611441.txt" ]
Q: disabled button after timer expired I am using <button> not <input type="button"> , I think there is big difference for that right? I just want that if the countdown is Expired the <button> will disable too, I don't know if my logic is correct for disabling the button but my countdown works like a charm I have this script inside of my html <button class="main-btn main-btn-2" id="invite"> <a href="{% url 'add' %}?parent_ID={{ me.id }}" rel="nofollow">Invite Now</a></button> {% for timer in countdown %} <script> var countDownDate = new Date("{{timer.enddate}}").getTime(); var x = setInterval(function() { var now = new Date() var distance = countDownDate - now; var days = Math.floor(distance / (1000 * 60 * 60 * 24)); var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)); var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60)); var seconds = Math.floor((distance % (1000 * 60)) / 1000); document.getElementById("demo").innerHTML = days + "d " + hours + "h " + minutes + "m " + seconds + "s "; if (distance < 0) { clearInterval(x); document.getElementById("demo").innerHTML = "EXPIRED"; document.getElementById("invite").disabled = true; // this is my logic if the timer expired the button will disabled } }, 1000); </script> {% endfor %} A: try this <a href="{% url 'add' %}?parent_ID={{ me.id }}" style="color:white;" rel="nofollow" ><input type="button" id="invite" value="Invite Now!" class="main-btn main-btn-2"></a> {% for n in ako %} <script> var countDownDate = new Date("{{n.enddate}}").getTime(); var x = setInterval(function() { var now = new Date() var distance = countDownDate - now; var days = Math.floor(distance / (1000 * 60 * 60 * 24)); var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)); var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60)); var seconds = Math.floor((distance % (1000 * 60)) / 1000); document.getElementById("demo").innerHTML = days + "d " + hours + "h " + minutes + "m " + seconds + "s "; if (distance < 0) { clearInterval(x); document.getElementById("demo").innerHTML = "EXPIRED"; document.getElementById("invite").disabled = true; } }, 1000); </script> {% endfor %}
[ "math.stackexchange", "0002946973.txt" ]
Q: What type of functions have an average rate of change thats the same as the derivative? I assume this applies to linear functions (y=mx+c), but are there other functions that fit this description? A: You are looking for differentiable function that satisfies $$\frac{f(x)-f(x_{0})}{x-x_{0}}=f^{\prime}(x_{0})=\lim_{x\rightarrow x_{0}}\frac{f(x)-f(x_{0})}{x-x_{0}}\qquad (1)$$ for every $x_{0}$. As user247327 commented, only linear functions satisfy (1) because, unlike nonlinear functions, they have the linear representation $f(x)=f(x_{0})+(x-x_{0})f^{\prime}((x_{0})$ at every point $x_{0}$. Intuitively, linear functions are the only functions with the property that the slope of the tangent at every point equals the slope of every secant (chord) passing through that point.
[ "stackoverflow", "0054028210.txt" ]
Q: MS-ACCESS Filter Subform with Button I am trying to do something I imagine is very trivial. I was able to do this using a ComboBox, but have switched to using SubForms, due to the ease of conditional formatting. Form = Expiring SubForm = CORE2 Fields = [Core], [Active] Button = CoreSearch Option Compare Database Private Sub CoreSearch_Click() Dim Task As String Me.Refresh Task = "SELECT * FROM CORE2.Expiring WHERE DateDiff('m', [Core RS], Date()) > 36 And [Active] = True" DoCmd.ApplyFilter Task End Sub I keep getting The action of method is invalid because the form or report isn't bound to a table or query. Is this because I am not specifying where to apply the filter? A: I can't find any example that uses the FilterName argument, they all use the WHERE Condition argument. ApplyFilter acts on whatever form the code is behind. Assuming button is on form CORE2. DoCmd.ApplyFilter , "DateDiff('m', [Core RS], Date()) > 36 And [Active] = True" Alternatively: Me.Filter = "DateDiff('m', [Core RS], Date()) > 36 And [Active] = True" Me.FilterOn = True Suggest naming subform/subreport container control different from the object it holds, such as ctrCore. If button is on main form and you want to apply filter to subform: Me.ctrCore.Form.Filter = "DateDiff('m', [Core RS], Date()) > 36 And [Active] = True" Me.ctrCore.Form.FilterOn = True
[ "stackoverflow", "0052666193.txt" ]
Q: ViewController Pushing Swift From One VC to Another VC And Returning back Consider two view controller Controller1 and Controller2, I have created a form of many UITextField in controller 1, in that when a user clicks a particular UITextField it moves to Controller2 and he selects the data there. After selecting the data in Controller2 it automatically moves to Controller1, while returning from controller2 to controller1 other UITextfield data got cleared and only the selected data from controller2 is found. I need all the data to be found in the UITextfield after selecting. Here is the code for returning from Controller2 to Controller1 if(Constants.SelectedComplexName != nil) { let storyBoard: UIStoryboard = UIStoryboard(name: "NewUserLogin", bundle: nil) let newViewController = storyBoard.instantiateViewController(withIdentifier: "NewUser") as! NewUserRegistrationViewController self.present(newViewController, animated: true, completion: nil) } A: To pass messages you need to implement Delegate. protocol SecondViewControllerDelegate: NSObjectProtocol { func didUpdateData(controller: SecondViewController, data: YourDataModel) } //This is your Data Model and suppose it contain 'name', 'email', 'phoneNumber' class YourDataModel: NSObject { var name: String? // var phoneNumber: String? var email: String? } class FirstViewController: UIViewController, SecondViewControllerDelegate { var data: YourDataModel? var nameTextField: UITextField? var phoneNumberTextField: UITextField? var emailTextField: UITextField? override func viewDidLoad() { super.viewDidLoad() callWebApi() } func callWebApi() { //After Success Fully Getting Data From Api //Set this data to your global object and then call setDataToTextField() //self.data = apiResponseData self.setDataToTextField() } func setDataToTextField() { self.nameTextField?.text = data?.name self.phoneNumberTextField?.text = data?.phoneNumber self.emailTextField?.text = data?.email } func openNextScreen() { let vc2 = SecondViewController()//Or initialize it from storyboard.instantiate method vc2.delegate = self//tell second vc to call didUpdateData of this class. self.navigationController?.pushViewController(vc2, animated: true) } //This didUpdateData method will call automatically from second view controller when the data is change func didUpdateData(controller: SecondViewController, data: YourDataModel) { } } class SecondViewController: UIViewController { var delegate: SecondViewControllerDelegate? func setThisData(d: YourDataModel) { self.navigationController?.popViewController(animated: true) //Right After Going Back tell your previous screen that data is updated. //To do this you need to call didUpdate method from the delegate object. if let del = self.delegate { del.didUpdateData(controller: self, data: d) } } }
[ "stackoverflow", "0037252164.txt" ]
Q: Why does Ckeditor show a removed tab in a dialog? I have removed the "Advanced"-tab of my Ckeditor table dialog but when I look at the properties of an existing table then the advanced tab is still there. In my config.js I have this config.removeDialogTabs = "image:advanced;table:advanced;link:advanced;link:target"; When I create a new table then the "Advanced"-tab doesn't show but when I edit an existing table it is there. I'm using version 4.5.6. Why is a removed tab shown? Here is a screen recording: A: The same dialog is actually defined twice with different names. The first one is called table and the other one is called tableProperties. So you need to add tableProperties:advanced as well: config.removeDialogTabs = "image:advanced;table:advanced;tableProperties:advanced;link:advanced;link:target";
[ "stackoverflow", "0001494522.txt" ]
Q: Sybase SQL Anywhere Database Management Tools What tools can I use to monitor performance, defragment, etc. a Sybase SQL Anywhere database? A: To defragment a SQL Anywhere database, you need to rebuild it. Look in the docs for the dbunload -an switch. As for performance monitoring, in version 11.x, the Sybase Central Performance Monitor was introduced. Full disclosure: I work for Sybase in SQL Anywhere engineering.
[ "stackoverflow", "0016835832.txt" ]
Q: Re Increment the Primary Column after deletion of the record in table in Sql? i want to do this one to my child table. check the primary key.It does not contains Identity Specification. when inserting data my table should be like this when i delete a record it should be shown below. how can i do this after deleting the record i want to update the next rows ....,and the result should like below how can i do this any ideas..., please this is important for me..., A: UPDATE dbo.table SET splr_Slno=splr_Slno-1 WHERE splr_Slno> @splr_Slno AND splr_Id= @Splr_Id
[ "stackoverflow", "0010047982.txt" ]
Q: Get Columns Returned from SQL Statement Is there a way to get the columns that a SQL query would return without actually executing a SQL statement? I looked into using set showplan_all on and using the OutputList field, but the results weren't quite what I wanted. I need to get the columns in the correct order and the correct column names (if they are aliased or not). I am using SQL Server 2008 R2. To clarify, here is an example of a query that could run: --log that the user has executed a query insert into execution_log_table (timestamp ,user_id ,report_id) values (CURRENT_TIMESTAMP ,1234 ,5678) select * from (select column1 ,column2 from another_table) tbl I would not want to insert anything into the first table when trying to get the columns returned. *Note: this is only a simple example, I have some SQL statements that are hundreds of lines of code that do multiple crud operations. I know that I could try to parse the lines of code manually, but my question was directed to a method using SQL servers parser to determine which columns would be returned in the final select statement. A: SET FMTONLY ON. It "returns" empty result sets, but shouldn't affect any actual tables: set fmtonly on go insert into execution_log_table ([timestamp] ,user_id ,report_id) values (CURRENT_TIMESTAMP ,1234 ,5678) select * from (select column1 ,column2 from another_table) tbl By the way, remember to turn it off before using the same connection for any other activity (using SET FMTONLY OFF in its own batch), otherwise you can confuse yourself for a while. (As I did when trying to create tables to test your batch of statements, forgetting that the CREATE TABLEs themselves would fail silently (with success messages) once FMTONLY was on). I've just noticed that this feature seems to be deprecated, and the replacement only allows you to retrieve information concerning the first result set. What use is that in the face of complex queries?
[ "stackoverflow", "0009943181.txt" ]
Q: JavaScript Find Specific URLs. Alright, I've been working on a userscript that redirects when a specific page is loaded. This is what I have so far: function blockThreadAccess() { var TopicLink = "http://www.ex.com/Forum/Post.aspx?ID="; var Topics = [ '57704768', '53496466', '65184688', '41182608', '54037954', '53952944', '8752587', '47171796', '59564382', '59564546', '2247451', '9772680', '5118578', '529641', '63028895', '22916333', '521121', '54646501', '36320226', '54337031' ]; for(var i = 0; i < Topics.length; i++) { if(window.location.href == TopicLink + Topics[i]) { // Execute Code } } } The function is called on the page load, but it doesn't seem execute the code. What it's supposed to do is check to see if the user is on that specific page, and if he is then execute the code. Say someone goes to this link - http://www.ex.com/Forum/Post.aspx?ID=54646501, it then redirects the use. I'm trying to make it efficient so I don't have to add a bunch of if statements. A: try converting both to lower case before comparing var loc = window.location.href.toLowerCase(); var topicLnk = TopicLink.toLowerCase(); for(var i = 0; i < Topics.length; i++) { if(topicLnk + Topics[i] == loc) { // Execute Code } }
[ "stackoverflow", "0041017565.txt" ]
Q: What is the difference between ReentrantLock vs stampedlock? Which one to prefer? What should be the use cases for choosing between ReentrantLock and StampedLock? For example, Which lock should be chosen if I have 10 Readers and 10 Writers? And which one to choose if i have 20 Readers and 1 writers? A: ReentrantLock is, as its name and javadocs say, reentrant. StampedLock is not. StampedLock is a low-level building block with some fragile behavior and complex interaction with the java memory model. Its use should be avoided unless you understand all its properties and have profiled code to determine that something is actually bottlenecked on locking.
[ "superuser", "0000462863.txt" ]
Q: sending mail from linux commad line Is it possible to send mail from linux terminal to any gmail account. If possible then what are the configuration are needed. I tried with mailx and sendmail but its not working. I also tried with mutt like this echo "test" | mutt -s this-is-my-subjest [email protected] but no use... I am using CentOS 6.2 A: I would advise to use sendEmail: sendEmail-1.56 by Brandon Zehm <[email protected]> Synopsis: sendEmail -f ADDRESS [options] Required: -f ADDRESS from (sender) email address * At least one recipient required via -t, -cc, or -bcc * Message body required via -m, STDIN, or -o message-file=FILE Common: -t ADDRESS [ADDR ...] to email address(es) -u SUBJECT message subject -m MESSAGE message body -s SERVER[:PORT] smtp mail relay, default is localhost:25 Optional: -a FILE [FILE ...] file attachment(s) -cc ADDRESS [ADDR ...] cc email address(es) -bcc ADDRESS [ADDR ...] bcc email address(es) -xu USERNAME username for SMTP authentication -xp PASSWORD password for SMTP authentication Paranormal: -b BINDADDR[:PORT] local host bind address -l LOGFILE log to the specified file -v verbosity, use multiple times for greater effect -q be quiet (i.e. no STDOUT output) -o NAME=VALUE advanced options, for details try: --help misc -o message-content-type=<auto|text|html> -o message-file=FILE -o message-format=raw -o message-header=HEADER -o message-charset=CHARSET -o reply-to=ADDRESS -o timeout=SECONDS -o username=USERNAME -o password=PASSWORD -o tls=<auto|yes|no> -o fqdn=FQDN Help: --help the helpful overview you're reading now --help addressing explain addressing and related options --help message explain message body input and related options --help networking explain -s, -b, etc --help output explain logging and other output options --help misc explain -o options, TLS, SMTP auth, and more It works very well for me. Remember to use TLS with gmail. You need to provide details of the server that will send the email with those options: -s SERVER[:PORT] smtp mail relay, default is localhost:25 -xu USERNAME username for SMTP authentication -xp PASSWORD password for SMTP authentication It's best for me as it allows to add attachments and can be easily placed in the scripts. Example usage: sendEmail -f [email protected] -t [email protected] -s test -m messageBody -s smtp.gmail.com -xu [email protected] -xp xxxxxpass -o tls=auto Aug 17 16:21:37 z sendEmail[22420]: Email was sent successfully! A: The mail terminal program should do the trick. It usually works "straight out of the box" to allow users/programs to send messages locally, inside the system. Type mail -s 'subject line' [email protected] and hit return. Then type your message and close/send using Ctl-D.
[ "math.stackexchange", "0001024105.txt" ]
Q: greatest common divisor proves I have two exercises for my mathematic study, and I really can't prove them: Let $a, b$ be in $\mathbb{Z}$. Prove: (a) If $\gcd(a, b) = \gcd(a, c) = 1$ , then $\gcd(a, bc) = 1$ (b) If $\gcd(a, b) = 1$, and $a\mid c$ and $b\mid c$ then $ab\mid c$ I'm trying for two days to prove these exercises, but I'm not able to do it. Thanks in advance! A: Hint: (a), suppose $\gcd(a,b)=\gcd(a,c)=1$. Suppose $\gcd(a,bc)=d\ne 1$. So there is a prime $p$ such that $p|d$. How can you use this to get a contradiction? (b) Have you heard of the theorem which says, if $a|c$ and $b|c$ then $lcm(a,b)|c$? You could use that very well. Or just go with the fundamental theorem of arithmetic. Edit You can also solve (b) using this Suppose $a|c$ and $b|c$ and $\gcd(a,b)=1$ Then, $aq=c$ and $b|aq$. And Since $\gcd(a,b)=1\ldots\ldots$?
[ "stackoverflow", "0055774196.txt" ]
Q: How to share a Google Cloud SQL instance between two projects using private IP? I have two projects in GCP, both are running App Engine Flexible environments with Node.js. One of the projects has an Cloud SQL instance attached, running with Private IPs. I want the App Engine in the other project to be able to use this Cloud SQL instance (PostgreSQL) as well, but it's not getting a connection. All instances are running in the same region I have peered both VPCs Service Networking API is activated in both projects Service account of the project that needs to be connected has "Cloud SQL Client" rights for the project that created the SQL instance From my understanding the Cloud SQL instance lives in its own VPC that is peered by automatically created peer connections and routes to the project from which it has been created. But there does not seem to be a way to create those routes and peers for another VPC in order to connect it, right? Or is there another possibility to connect both projects to the same Cloud SQL? A: As per the first point in the Network requirements in the docs: You can only access a Cloud SQL instance on its private IP addresses from a single VPC network. This means that you can only connect from the project that has the Cloud SQL network peered. This comes from the 6th restriction on the VPC peering docs: Only directly peered networks can communicate. Transitive peering is not supported. In other words, if VPC network N1 is peered with N2 and N3, but N2 and N3 are not directly connected, VPC network N2 cannot communicate with VPC network N3 over VPC Network Peering.
[ "stackoverflow", "0039746506.txt" ]
Q: c++ class difference between this and class:: My understanding is that if I have a class class MyClass { public: MyClass(); void SetVal( int ); private: int val_; } I can reference a member MyClass::SetVal( int val ) { val_ = val } MyClass::SetVal( int val ) { MyClass::val_ = val } MyClass::SetVal( int val ) { this->val_ = val } I like the idea of indicating that a variable is a class member. Is there any difference between the second and the third approach? EDIT: made SetVal( int ) public. Been sloppy in writing down the example. Thanks for pointing out A: (Presumably in real-life you'd mark SetVal public or protected.) There is absolutely no difference in your particular case, although I'd plump for val_ = val as it's the clearest. Note that this-> is a tautology. Note that you can use the MyClass::val_ notation to descriminate between class members that have been shadowed by base and child classes having a class member with that same name. A: There is actually a difference!... Its a name lookup thing This, MyClass::SetVal( int val ) { val_ = val } does an unqualified name lookup. where val_ is first searched in class scope first, if not found, name-lookup proceeds to search global namespace for val_. An example here This, MyClass::SetVal( int val ) { MyClass::val_ = val } does a qualified name lookup. where val_ it is strictly limited to class namespace. so if you do not have such member val_, it wouldn't go further searching global namespace. Another example here This, MyClass::SetVal( int val ) { this->val_ = val } is similar to the second. example here
[ "stackoverflow", "0000502059.txt" ]
Q: Passing pointers of arrays in C So I have some code that looks like this: int a[10]; a = arrayGen(a,9); and the arrayGen function looks like this: int* arrayGen(int arrAddr[], int maxNum) { int counter=0; while(arrAddr[counter] != '\0') { arrAddr[counter] = gen(maxNum); counter++; } return arrAddr; } Right now the compilier tells me "warning: passing argument 1 of ‘arrayGen’ makes integer from pointer without a cast" My thinking is that I pass 'a', a pointer to a[0], then since the array is already created I can just fill in values for a[n] until I a[n] == '\0'. I think my error is that arrayGen is written to take in an array, not a pointer to one. If that's true I'm not sure how to proceed, do I write values to addresses until the contents of one address is '\0'? A: The basic magic here is this identity in C: *(a+i) == a[i] Okay, now I'll make this be readable English. Here's the issue: An array name isn't an lvalue; it can't be assigned to. So the line you have with a = arrayGen(...) is the problem. See this example: int main() { int a[10]; a = arrayGen(a,9); return 0; } which gives the compilation error: gcc -o foo foo.c foo.c: In function 'main': foo.c:21: error: incompatible types in assignment Compilation exited abnormally with code 1 at Sun Feb 1 20:05:37 You need to have a pointer, which is an lvalue, to which to assign the results. This code, for example: int main() { int a[10]; int * ip; /* a = arrayGen(a,9); */ ip = a ; /* or &a[0] */ ip = arrayGen(ip,9); return 0; } compiles fine: gcc -o foo foo.c Compilation finished at Sun Feb 1 20:09:28 Note that because of the identity at top, you can treat ip as an array if you like, as in this code: int main() { int a[10]; int * ip; int ix ; /* a = arrayGen(a,9); */ ip = a ; /* or &a[0] */ ip = arrayGen(ip,9); for(ix=0; ix < 9; ix++) ip[ix] = 42 ; return 0; } Full example code Just for completeness here's my full example: int gen(int max){ return 42; } int* arrayGen(int arrAddr[], int maxNum) { int counter=0; while(arrAddr[counter] != '\0') { arrAddr[counter] = gen(maxNum); counter++; } return arrAddr; } int main() { int a[10]; int * ip; int ix ; /* a = arrayGen(a,9); */ ip = a ; /* or &a[0] */ ip = arrayGen(ip,9); for(ix=0; ix < 9; ix++) ip[ix] = 42 ; return 0; } A: Why even return arrAddr? Your passing a[10] by reference so the contents of the array will be modified. Unless you need another reference to the array then charlies suggestion is correct.
[ "electronics.stackexchange", "0000330288.txt" ]
Q: Wiring on-off switch with resistor to SoC Please note: although this question involves a Raspberry Pi (hereafter RPi), it is really a pure electronics question at heart! I am trying to connect my RPi 1 Model A to a breadboard with a single, simple on-off-on-off switch on it. The kicker here is that although I'm using an on-off-on-off switch, I really just want it to function like a normal (on-off) switch. That is: push it once, the circuit is closed and sending an input signal on to my RPi. Push it again, and the circuit open. Rinse and repeat. I was given this diagram to follow for wiring things up: I then subsequently inferred my own rendition of this, which more clearly shows the joining of the switch's left and right pins together (giving it the desired on-off behavior) as well as how to wire the 3.3V power on the RPi to the GPIO input pin: So to behin with if anything above looks incorrect or awry to you, please begin by correcting me! Assuming I'm on track, I'm now trying to actually wire this up in real life, between my RPi and my breadboard. Here's my best attempt: Nevermind the LED and resistors in the bottom right corner of the breadboard, they're leftover from another experiment and aren't connected to anything else. So at the top-left we have the 3.3V power source from the RPi connected to the top-most rail on the breadboard via a red jumper; then A smaller red jumper wire forwards the power onto a column that is then connected to a 10-kOhm resistor; more on this in a second On the left-side of the above photo we have the switch, here's a better look at the wiring/setup: Notice the small orange jumper connecting the left and right switch pins; I believe this is what accomplishes the on-off-on-off -> on-off behavior I'm looking for The same column that joins left and right pins (via orange jumper) is also connected to a red jumper which is also connected to the same 10-kOhm resistor we talked about up above Finally, the switch's middle pin is connected to the GND rail via a black jumper This brings us to the center of the beadboard, where that big fat 10-kOhm resistor is hanging out: The resistor is connecting the RPi's power to the switch (both pins at the same time) The resistor is also connecting back to the GPIO's input pin via gray jumper wire Finally, my question! Remember, at the end of the day, all I want to do is: Convert this on-off-on-off switch to a on-off switch When the user presses the switch (closing it), an appropriate signal is sent on to the GPIO input pin, which is then handled at the software layer So I ask: will my circuit accomplish the following behavior? Is it wired correctly (correct junctions of wires, correct usage of resistor, etc.)? Or will it "fry my pi"?! If anything is incorrect, what's the fix/solution? Update Several users have pointed out to me that my wiring around the switch is incorrect, here's a Fritzing diagram of what I think the solution is: Final update Wiring when I set the internal pin resistor at the software layer, and omit the breadboard resistor: A: Figure 1. Incorrect pull-up. Your pull-up resistor is connected to the wrong rail. It is pulling down. Your button just pulls it down better. simulate this circuit – Schematic created using CircuitLab Figure 2. (a) What you intended. (b) The way you wired it. (c) With internal pull-up enabled. The wire link on the right end of your resistor is wired to GND instead of V+. If you can program the GPIO with internal pull-up then omit the resistor. It is not required. In the present configuration it is competing with the pull-up and the input voltage can never rise above that set by the potential divider created by the pull-up and pull-down. Extreme clarification: Figure 2. The pull-up resistor jumper wire needs to be moved to terminate in position 2 - not position 1. From the comments: OK, so I will initialize my pin at the software layer via gpioController.provisionDigitalOutputPin(RaspiPin.GPIO_23, 'RunningLed', PinState.HIGH), which will cause the GPIO pin #23's internal resistor to "pull up" (PinState.HIGH), so that when someone pushes the switch (which in turn closes the circuit) the internal resistor will kick in, yes? That will work correctly but your description of the action is incorrect. simulate this circuit Figure 3. Internal pull-up with external pull-down switch. Once enabled the pull-up resistor will be in-circuit as though it is wired in place. It doesn't "kick-in" at any point but it will be effective under certain conditions. Fig. 3a: With SW1 open the pull-up, R1, connects the internal buffer to V+. The input is now "pulled-up" to Vcc. It will be read as "high" by your program. Fig. 3b: With SW2 closed the pull-up is still trying to pull but is overcome by the much, much lower resistance of the switch. The input voltage will drop to 0 V. The input will be read as "low" by your program. Note that earlier in the discussion you were going to have an external pull-down and an internal pull-up. This would not work as the voltage (with the switch open) would be neither fully high nor fully low and would probably be in an undefined state alternating between the two when read by your program.
[ "stackoverflow", "0014329837.txt" ]
Q: Integers and string in a prepared statement I have this in my try clause... It is working fine if I remove pst.setString(5, value5), also it works if I remove all the integer values, but I can't get it to work if all the integers and value5 is added... try { Class.forName("org.postgresql.Driver"); connection = DriverManager.getConnection(connectionURL, "username", "password"); String sql ="UPDATE table1 SET value1 = ?, value2 = ?, value3 = ?, value4 = ? value5 = ? WHERE value6 = ? "; PreparedStatement pst = connection.prepareStatement(sql); Integer value1A = Integer.parseInt(value1), value2A = Integer.parseInt(value2), value2A = Integer.parseInt(value3), value2A = Integer.parseInt(value4); pst.setInt(1, value1A); pst.setInt(2, value2A); pst.setInt(3, value3A); pst.setInt(4, value4A); pst.setString(5, value5); pst.setString(6, value6); int numRowsChanged = pst.executeUpdate(); pst.close(); } A: You're missing a comma in your SQL: String sql ="UPDATE table1 SET value1 = ?, value2 = ?, value3 = ?, value4 = ?, value5 = ? WHERE value6 = ? "; ^
[ "stackoverflow", "0007362782.txt" ]
Q: In terms of performance, what is the best method to show 1000 images on a page? I'm trying to show 1000 quite small images on a page (rather a lot indeed but out of my control). When loading them all at once, the performance obviously suffers drastically rendering 1000 images at once. I tried implementing applying the image src upon scroll (at numerous amounts - 250px scroll, 25 images load etc.), then tried loading the images on a timer. These methods did help to increase performance but what would be the most efficient way to do this? They seemed to still have an irritating amount of lag - I understand there is a fundamental problem with rendering that many images on one page, but is there a better solution? EDIT: Pagination of course would help but isn't an option here. Also, the images are pulled from an API so it's not convenient to make 1 large image / use sprites. A: If all the images are unique files then you are feeling the big hit from making multiple connections to retrieve them. You could create 1 "master" image of all the items and then create 1000 divs each with a different class or id then in css define background offsets for each. This method is often refered to as css sprites. http://css-tricks.com/158-css-sprites/ A: Couldn't you make an AJAX pagination, that dynamicly loads the images based on page number? For example, 25 images per page. On requesting the first page, you dynamicly load the next page and so on. That way, the user won't notice the delay.. That's all you can do to improve the performance even further! A: Since sprites/pagination weren't an option in this situation, I found the following the best solution: Adapting the 'load images on scroll' method, with some tweaks and cruically setting the parent element for each image (so there are 1000 elements, each with images) to display:none. With the parent elements defaulted to display:none & also making the first 25 display:block: var scrollPos = 0; var endEle = 0; $(window).scroll(function(){ scrollPos = $(window).scrollTop(); if ($(window).scrollTop() < scrollPos + 250) { //load 15 images. $('.myDiv img').slice(endEle,endEle+50).each(function(obj){ var self = $(this); var url = self.attr("role"); self.attr("src", url); self.parent().css("display","block"); }); endEle = endEle + 50; } }); This sets the next 50 elements to display:block and switches the <img role> into <src> (the image urls were put into role when the page is rendered) every time the user scrolls 250px.
[ "stackoverflow", "0034576312.txt" ]
Q: Send value from another form I have multiple forms that point to the same site where the datas are stored into a sql database. For each form the user has to fill out a textfield which is separated from the form. I don't understand how i could send for each form the same value from the separated textfield. <form name="user" action="http://hello.xy/login.php" method="GET"> <input type="text" value="User" name="provider" hidden> Name: <br/> <input type="text" value="" name="user_name"><br/> Email: <br/> <input type="text" value= "" name="user_email"><br/> <textarea hidden name="comment" value="value from the form comment"></textarea> <input type="submit" value="submit"> </form> <form name="google" action="http://hello.xy/login.php" method="GET"> <input type="text" value="Google" name="provider" hidden> <textarea hidden name="comment" value="value from the form comment"></textarea> <input type="image" src="images/logos/google.png" value="submit"> </form> <form name="twitter" action="http://hello.xy/login.php" method="GET"> <input type="text" value="Twitter" name="provider" hidden> <textarea hidden name="comment" value="value from the form comment"></textarea> <input type="image" src="images/logos/twitter.png" value="submit"> </form> <form name="facebook" action="http://hello.xy/login.php" method="GET"> <input type="text" value="Facebook" name="provider" hidden> <textarea hidden name="comment" value="value from the form comment"></textarea> <input type="image" src="images/logos/facebook.png" value="submit"> </form> Separated textfield, but on the same site: <form name="comment" > <textarea name="input" ></textarea> </form> I hope somebody can help me. Thanks, Misch A: You can't send data from two forms at the same time without JavaScript. The solution without JavaScript is to use one form: <form action="http://hello.xy/login.php" method="GET"> <textarea name="comment"></textarea> <label for="user_name">Name</label> <input type="text" name="user_name" id="user_name"> <label for="user_email">Email</label> <input type="text" name="user_email" id="user_email"> <button type="submit" name="provider" value="User">Submit</button> <input type="image" src="images/logos/google.png" name="provider" value="Google"> ... </form> Update Since you're using jQuery, use: <textarea name="comment" class="comment-visible"></textarea> And include this in each form: <input type="hidden" name="comment" class="comment-hidden"> jQuery: $(document).on('input', '.comment-visible', function(){ $('.comment-hidden').val( $(this).val() ); });
[ "stackoverflow", "0061004096.txt" ]
Q: Returning ListView from funciton makes Flutter Column blank Whenever I put this on my Column of widgets, the entire column gets blank. If I take this off, it works: Widget productsList(List<Product> products) { List<ListTile> p = products.map((product) => _product(product)).toList(); return new ListView(children: p); } ListTile _product(Product product) => ListTile( title: Text(product.name, style: TextStyle( fontWeight: FontWeight.w500, fontSize: 20, )), subtitle: Text(product.quantity.toString()), leading: Icon( Icons.shopping_basket, color: Colors.blue[500], ), ); Here's how I'm using it: @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("Pedido " + _order.orderNumber.toString()), ), body: Column( children: [ orderItem("Nome: ", _order.clientName), productsList(_order.products) ], )); } I can't see anything wrong. I'm returning a ListView as a Widget A: Add shrinkWrap to true in the productsList widget. ListView(children: p, shrinkWrap: true); Then wrap the productsList inside the Expanded widget and also add the property mainAxisSize to a minimum size in the Column widget.
[ "stackoverflow", "0013615381.txt" ]
Q: d3 add text to circle I am trying to add some text into circle. I have been following example from a mbostock tutorial, but wasn't able to get the right output. The code snippet is: var data; var code; d3.json("/json/trace.json", function(json) { data = json; console.log(data); // get code for visualization code = data["code"]; alert(code); var mainSVG = d3 .select("#viz") .append("svg") .attr("width", 900) .attr("height", 900); mainSVG .append("circle") .style("stroke", "gray") .style("fill", "white") .attr("r", 100) .attr("cx", 300) .attr("cy", 300); circle = mainSVG.selectAll("circle").data([code]); }); Any suggestions how to get this work? A: Here is an example showing some text in circles with data from a json file: http://bl.ocks.org/4474971. Which gives the following: The main idea behind this is to encapsulate the text and the circle in the same "div" as you would do in html to have the logo and the name of the company in the same div in a page header. The main code is: var width = 960, height = 500; var svg = d3.select("body").append("svg") .attr("width", width) .attr("height", height) d3.json("data.json", function(json) { /* Define the data for the circles */ var elem = svg.selectAll("g") .data(json.nodes) /*Create and place the "blocks" containing the circle and the text */ var elemEnter = elem.enter() .append("g") .attr("transform", function(d){return "translate("+d.x+",80)"}) /*Create the circle for each block */ var circle = elemEnter.append("circle") .attr("r", function(d){return d.r} ) .attr("stroke","black") .attr("fill", "white") /* Create the text for each block */ elemEnter.append("text") .attr("dx", function(d){return -20}) .text(function(d){return d.label}) }) and the json file is: {"nodes":[ {"x":80, "r":40, "label":"Node 1"}, {"x":200, "r":60, "label":"Node 2"}, {"x":380, "r":80, "label":"Node 3"} ]} The resulting html code shows the encapsulation you want: <svg width="960" height="500"> <g transform="translate(80,80)"> <circle r="40" stroke="black" fill="white"></circle> <text dx="-20">Node 1</text> </g> <g transform="translate(200,80)"> <circle r="60" stroke="black" fill="white"></circle> <text dx="-20">Node 2</text> </g> <g transform="translate(380,80)"> <circle r="80" stroke="black" fill="white"></circle> <text dx="-20">Node 3</text> </g> </svg> A: Extended the example above to fit the actual requirements, where circled is filled with solid background color, then with striped pattern & after that text node is placed on the center of the circle. var width = 960, height = 500, json = { "nodes": [{ "x": 100, "r": 20, "label": "Node 1", "color": "red" }, { "x": 200, "r": 25, "label": "Node 2", "color": "blue" }, { "x": 300, "r": 30, "label": "Node 3", "color": "green" }] }; var svg = d3.select("body").append("svg") .attr("width", width) .attr("height", height) svg.append("defs") .append("pattern") .attr({ "id": "stripes", "width": "8", "height": "8", "fill": "red", "patternUnits": "userSpaceOnUse", "patternTransform": "rotate(60)" }) .append("rect") .attr({ "width": "4", "height": "8", "transform": "translate(0,0)", "fill": "grey" }); function plotChart(json) { /* Define the data for the circles */ var elem = svg.selectAll("g myCircleText") .data(json.nodes) /*Create and place the "blocks" containing the circle and the text */ var elemEnter = elem.enter() .append("g") .attr("class", "node-group") .attr("transform", function(d) { return "translate(" + d.x + ",80)" }) /*Create the circle for each block */ var circleInner = elemEnter.append("circle") .attr("r", function(d) { return d.r }) .attr("stroke", function(d) { return d.color; }) .attr("fill", function(d) { return d.color; }); var circleOuter = elemEnter.append("circle") .attr("r", function(d) { return d.r }) .attr("stroke", function(d) { return d.color; }) .attr("fill", "url(#stripes)"); /* Create the text for each block */ elemEnter.append("text") .text(function(d) { return d.label }) .attr({ "text-anchor": "middle", "font-size": function(d) { return d.r / ((d.r * 10) / 100); }, "dy": function(d) { return d.r / ((d.r * 25) / 100); } }); }; plotChart(json); .node-group { fill: #ffffff; } <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script> Output: Below is the link to codepen also: See the Pen D3-Circle-Pattern-Text by Manish Kumar (@mkdudeja) on CodePen. Thanks, Manish Kumar A: Here's a way that I consider easier: The general idea is that you want to append a text element to a circle element then play around with its "dx" and "dy" attributes until you position the text at the point in the circle that you like. In my example, I used a negative number for the dx since I wanted to have text start towards the left of the centre. const nodes = [ {id: ABC, group: 1, level: 1}, {id:XYZ, group: 2, level: 1}, ] const nodeElems = svg.append('g') .selectAll('circle') .data(nodes) .enter().append('circle') .attr('r',radius) .attr('fill', getNodeColor) const textElems = svg.append('g') .selectAll('text') .data(nodes) .enter().append('text') .text(node => node.label) .attr('font-size',8)//font size .attr('dx', -10)//positions text towards the left of the center of the circle .attr('dy',4)
[ "stackoverflow", "0006495420.txt" ]
Q: Objective-C Copying a view So I've got a quick question here... I've got an instance of a view controller object, lets call it viewCon1, and it has several subview's placed on it each with unique properties. Lets call them sub1, sub2, and sub3. Now, I add each of these subviews programatically doing something to the extent of: //create the subviews TaskUIButton *sub1 = [[TaskUIButton alloc] init]; TaskUIButton *sub2 = [[TaskUIButton alloc] init]; TaskUIButton *sub3 = [[TaskUIButton alloc] init]; //add them to viewCon1 [viewCon1.view addSubView:sub1]; [viewCon1.view addSubView:sub2]; [viewCon1.view addSubView:sub3]; Now here is where I don't know how to proceed. I need to create another view controller object called viewCon2 and make it exactly like viewCon1 with identical (albiet separate) subviews attached to it. So for instance, lets say that viewCon1's sub1 had a title of "foo", I need viewCon2 to also have an identical subview with a title of "foo", etc. Is there any easy way to go about this? I'd appreciate any insight, thanks! A: Neither UIViewController nor UIView implements the NSCopying protocol, so duplicating such objects is more than a one-step process. The general idea is to create a new instance of the class in question and copy the original object's configuration. Since you already have code that configures the views for your view controller, the easiest thing will be to call that method again to create a second instance of the view controller. I realize that your code may not be set up to do that right now, so you may need to refactor to make that possible. Based on your comments above, it sounds like you may be storing some state in your view rather than letting the view reflect the data stored in your application. It may help to determine what information is determining the layout of your view and make sure that data is properly represented in your app's data model. If you can do that, you should be able to simply create a new view controller based on the same data and get an identical layout.
[ "stackoverflow", "0018675321.txt" ]
Q: Updating $scope values affects it's previous usage points Updating $scope values affects it's previous usage points. After addPhrase call I use sayPhrase to update $scope function PhrasesCtrl($scope) { $scope.trail = [0]; $scope.addPhrase = function() { $scope.phrases.push({ trail: $scope.trail }); } $scope.sayPhrase = function(id) { // id = 1 $scope.trail.push(id); } } Newly created Phrase have it's trail equal to [0], after sayPhrase call it becomes [0, 1] After $scope.trail.push(id); my new element updates it's trail value. How to keep used trail value away from changes? A: This is because JS objects (and arrays) are passed by reference only. When you push the trail into phrases, you are pushing the reference to the same array that is referenced by $scope.trail. The easiest solution is to break the reference on $scope.trail, by creating a new array: $scope.addPhrase = function() { $scope.phrases.push({ trail: $scope.trail }); $scope.trail = [0]; // I assume the `0` is on purpose } Now $scope.trail will start over every time addPhrase() is called. Alternatively, if you need to keep the current contents of trail, you should copy the array into a new one. Angular conveniently provides a method just for this: $scope.addPhrase = function() { $scope.phrases.push({ trail: angular.copy($scope.trail) }); }
[ "stackoverflow", "0025822343.txt" ]
Q: Laravel Cashier/Stripe not setting subscription_ends_at Laravel Cashier is not setting the subscription_ends_at field when i create a new subscription. I´ve been fiddling arround with this now a few days, and i think that at the very beginning it worked, but i had to pull the repository we´re working on again and lost the changes and i did install and configure everything again, now it won´t set that field. It sets, though, the trial_ends_at if i specify a trial period. It´s a yearly plan and we would like to inform our users of the renewal date. The user model: use Illuminate\Auth\UserInterface; use Illuminate\Auth\Reminders\RemindableInterface; use Laravel\Cashier\BillableTrait; use Laravel\Cashier\BillableInterface; class User extends Eloquent implements UserInterface, RemindableInterface, BillableInterface { use BillableTrait; /** * The database table used by the model. * * @var string */ protected $table = 'users'; protected $dates = ['trial_ends_at', 'subscription_ends_at']; The controller method for creating the subscription: public function postConfirmSubscription() { $user = Auth::user(); $user->subscription('premium')->create(Input::get('token.id')); } Thanks in advance for any help. A: Laravel Cashier will NOT set the subscription_ends_at field, unless that subscription is cancelled. It is designed to manage grace periods (user will have access until that date, once the subscription is cancelled), not to inform the user about their next payment date, or remaining active subscription time. As I originally thought too. You may have actually seen that field populated, when you were testing the cancel procedure. I'm affraid you'll have to set up an extra field for that, let's say "next_payment_at", and "manually" update it, either at controller or model level.
[ "tridion.stackexchange", "0000018660.txt" ]
Q: What is the purpose of Related Keyword? When I open a Keyword, there is Parent and Child Keywords, and also Related Keywords. What are they, what is the purpose of it, what is their behavior while publishing? A: Taken from docs.sdl.com : Related Keywords Select related Keywords to create non parent/child Keyword relationships such as see also links and related topics. For example, you can relate a Holiday Type Keyword to Sports Equipment Keyword. Meaning that you can link Keywords which aren't from the same Category but can be related somehow. Whilst publishing this is sent as Metadata and is updated in the Broker, so you use the CD API to get those related Keywords of a given Keyword object (for example to build some dynamic functionality, criteria, etc.) Of course you can get this in TOM.NET as well and include data from them in your publishing process, like creating links, etc.
[ "stackoverflow", "0058150657.txt" ]
Q: Is c sizeof() function dependent on the host computer? Is the sizeof() function dependent on the host computer. If you were to use sizeof(structure) and get a return of 4 bytes in a Linux computer will that result changes if you were to compile the program in a different operating system? Would cross compiling fix this issues? Say if you were expecting 4 bytes if you compile On a Linux and instead of moving it to a different operating system, you cross compiler it on your and than move it to the other operating system. Wouldn’t the package size be the same at that point? A: yes for sure the size of the structure can change depending on the operating system that's one of the main reasons to use sizeof() to make sure you get the same functionality on different operating systems.
[ "stackoverflow", "0011350518.txt" ]
Q: Get detailed field information for a pgsql resultset in php I have been trying to get the complete meta information for the fields in a result set from Postgresql in php (something like mysql_fetch_field(), which gives a lots of info about the field definition). While I am able to use the following functions to find some information: $name = pg_field_name($result, 1); $table = pg_field_table($result, 1); $type = pg_field_type($result, 1); I could not find a way to get more details about whether the field allow null values, contains blob data (by field definition), is a primary,unique key by definition etc. The mysql_fetch_field() gives all of this information somehow, which is very useful. I would really like some way to get that information from php directly, but if that is not possible, then maybe someone has created a routine that might be able to extract that info from a pgsql resultset somehow. PS: This looks promising, but the warning on the page is not a good sign: http://php.net/manual/en/pdostatement.getcolumnmeta.php Also, I am not using PDO at the moment, but if there is no solution, then a PDo specific answer will suffice too. A: You can find the metadata on you column with a query like this: select * from information_schema.columns where table_name = 'regions' and column_name = 'capital' This should provide all of the information found in mysql_fetch_field. I'm not a php coder, so perhaps someone knows of a function that wraps this query.
[ "stackoverflow", "0027826583.txt" ]
Q: What is the best way to add big amount of html elements using innerHTML idea? Not on Chrome, but on Firefox the browser just get freeze every time I make an ajax request. Here's the deal... The ajax request receive a huge html, where the length is more than 75,000. <div> ... <table> ... etc ... </table> ... </div> So I start to use replace to get something better: var html = data.replace(/\r?\n|\r/g, '').replace(/\s{2,}/g, ' ') Than I got 55,000 that is not enough. So I've been searching but until now I got nothing that can help. Here's what I tried: 1. asyncInnerHTML(html, function(fragment){ $(tab).get(0).appendChild(fragment); // myTarget should be an element node. }); 2. var node = document.createTextNode(html); $(tab).get(0).innerHTML = node; 3. $(tab).get(0).innerHTML = html; 4. $(tab).append(html); 5. $(tab).html(html); The only thing that was fast what the second one, where the javascript add the nodeContent, of course that was not what I want, because I need the HTML rendered and not the html in text/string form. I hope that someone could help me. Anyway, thanks. A: The Skype Toolbar for Firefox is an extension that detects phone numbers in web pages, and re-renders them as a clickable button that can be used to dial the number using the Skype desktop application. So, when the HTML is rendered, the skype extension try to find shit at my code making the browser stop work for a moment. Thanks for all help.
[ "stackoverflow", "0062921251.txt" ]
Q: Deleting images in Imgbb via API i'm using the imgbb API since it is very straghtforward to use and quite cheap. The problem is that the documentation is very poor and it does not explain how to delete an image through the API. I want to be able to delete the photo from my server in the case something happens (ex. if I delete a user). My server is written in node.js. pd. Also the response object I get after uploading an image is this one: { data: { id: 'c3VRs4x', title: 'client1-Bali', url_viewer: 'https://ibb.co/c3VRs4x', url: 'https://i.ibb.co/Pj0JVqt/client1-Bali.jpg', display_url: 'https://i.ibb.co/1QjB4Fb/client1-Bali.jpg', size: 60385, time: '1594835546', expiration: '0', image: { filename: 'client1-Bali.jpg', name: 'client1-Bali', mime: 'image/jpeg', extension: 'jpg', url: 'https://i.ibb.co/Pj0JVqt/client1-Bali.jpg' }, thumb: { filename: 'client1-Bali.jpg', name: 'client1-Bali', mime: 'image/jpeg', extension: 'jpg', url: 'https://i.ibb.co/c3VRs4x/client1-Bali.jpg' }, medium: { filename: 'client1-Bali.jpg', name: 'client1-Bali', mime: 'image/jpeg', extension: 'jpg', url: 'https://i.ibb.co/1QjB4Fb/client1-Bali.jpg' }, delete_url: 'https://ibb.co/c3VRs4x/b3072de2f5287a39f81c7dec3cd8a236' }, success: true, status: 200 } Edit: Here is the link to the imgbb API documentation: https://api.imgbb.com/ A: Imgbb does not allow you to delete images. I just tried going to the delete URL to delete the image and the image got deleted on that page but not on the other links in the JSON. If the functionality is not implemented on the site itself there is no use trying on the API. If they did have the functionality to entirely delete an image then you could have used web scraping to press the buttons.
[ "unix.stackexchange", "0000375044.txt" ]
Q: Send data to a command using an specific frequency I want to do a bash script that reads a file that each line contains a timestamp and a value, and send the line to another command with the same frequency as the data. For example, if I have these lines: 1499108150 26 1499108156 100 I would need to send the first line in a certain moment, and the second line 6 seconds after the previous one. I hope you can help me, thank you in advance! A: #!/usr/bin/bash previous=0 while read tstamp value do if [[ $previous -eq 0 ]] then echo sending "$value" else sleep $((tstamp - previous)) echo sending "$tstamp $value" fi previous=$tstamp done < input Put that into a script and make it executable.
[ "stackoverflow", "0012444904.txt" ]
Q: Log in with psql I am trying to run postgres from terminal. What am I missing? $psql perl: warning: Setting locale failed. perl: warning: Please check that your locale settings: LANGUAGE = (unset), LC_ALL = (unset), LC_CTYPE = "UTF-8", LANG = "en_GB.UTF-8" are supported and installed on your system. perl: warning: Falling back to the standard locale ("C"). psql: could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"? A: It looks like you're on a system with pg_wrapper like Ubuntu or Debian, and your locale settings are messed up. This isn't to do with PostgreSQL, it's a system configuration problem. Perl is just complaining about it. Run perl without arguments and you'll see the same complaint. Assuming you're on Ubuntu since you didn't say otherwise, see: Locale - Ubuntu Wiki How to select and generate locales on Ubuntu - UbuntuGeek
[ "stackoverflow", "0049605748.txt" ]
Q: How can we skip records in mongodb stitch? I can see the limit option in mongoDB Stitch docs but unable to find how can we skip records for pagination. A: You can use aggregate with pipeline. Something like that: exports = function(arg){ const mongodb = context.services.get("mongodb-atlas"); const coll = mongodb.db(<dbname>).collection(<collectionname>); const pipeline = [ { "$skip" : 1 }, { "$limit": 20 } ]; return coll .aggregate(pipeline) .toArray(); };
[ "stackoverflow", "0004368982.txt" ]
Q: Plotting a line on a grid layout, then addition veritcal axis SOLUTION AT BOTTOM OF THIS QUESTION I have this code: public void lineImproved(int x0, int y0, int x1, int y1, Color color) { int pix = color.getRGB(); int dx = x1 - x0; int dy = y1 - y0; raster.setPixel(pix, x0, y0); if (Math.abs(dx) > Math.abs(dy)) { // slope < 1 float m = (float) dy / (float) dx; // compute slope float b = y0 - m*x0; dx = (dx < 0) ? -1 : 1; while (x0 != x1) { x0 += dx; raster.setPixel(pix, x0, Math.round(m*x0 + b)); } } else if (dy != 0) { // slope >= 1 float m = (float) dx / (float) dy; // compute slope float b = x0 - m*y0; dy = (dy < 0) ? -1 : 1; while (y0 != y1) { y0 += dy; raster.setPixel(pix, Math.round(m*y0 + b), y0); } } } It currently plots a line and fills in the specific pixels that make up the line between the 2 points specified (i.e. [x0,y0] and [x1,y1]). I need it to include an h0 and h1 for the height of the 2 points. By doing so I hope to be able to obtain a height value on the vertical axis with every raster.setPixel function. UPDATE I have now the code how it should be for this task, but still only in 2D. I need to implement the suggested solution to the following code to verify it: internal static int DrawLine(Player theplayer, Byte drawBlock, int x0, int y0, int z0, int x1, int y1, int z1) { int blocks = 0; bool cannotUndo = false; int dx = x1 - x0; int dy = y1 - y0; int dz = z1 - z0; DrawOneBlock (theplayer, drawBlock, x0, y0, z0, ref blocks, ref cannotUndo); if (Math.Abs(dx) > Math.Abs(dy)) { // slope < 1 float m = (float)dy / (float)dx; // compute slope float b = y0 - m * x0; dx = (dx < 0) ? -1 : 1; while (x0 != x1) { x0 += dx; DrawOneBlock(theplayer, drawBlock, x0, Convert.ToInt32(Math.Round(m * x0 + b)), z0, ref blocks, ref cannotUndo); } } else { if (dy != 0) { // slope >= 1 float m = (float)dx / (float)dy; // compute slope float b = x0 - m * y0; dy = (dy < 0) ? -1 : 1; while (y0 != y1) { y0 += dy; DrawOneBlock(theplayer, drawBlock, Convert.ToInt32(Math.Round(m * y0 + b)), y0, z0, ref blocks, ref cannotUndo); } } } return blocks; } SOLUTION: internal static int DrawLine(Player theplayer, Byte drawBlock, int x0, int y0, int z0, int x1, int y1, int z1) { int blocks = 0; bool cannotUndo = false; bool detected = false; int dx = x1 - x0; int dy = y1 - y0; int dz = z1 - z0; DrawOneBlock (theplayer, drawBlock, x0, y0, z0, ref blocks, ref cannotUndo); //a>x,b>y,c>z if (Math.Abs(dx) > Math.Abs(dy) && Math.Abs(dx) > Math.Abs(dz) && detected == false) { // x distance is largest detected = true; float my = (float)dy / (float)dx; // compute y slope float mz = (float)dz / (float)dx; // compute z slope float by = y0 - my * x0; float bz = z0 - mz * x0; dx = (dx < 0) ? -1 : 1; while (x0 != x1) { x0 += dx; DrawOneBlock(theplayer, drawBlock, Convert.ToInt32(x0), Convert.ToInt32(Math.Round(my * x0 + by)), Convert.ToInt32(Math.Round(mz * x0 + bz)), ref blocks, ref cannotUndo); } } //a>y,b>z,c>x if (Math.Abs(dy) > Math.Abs(dz) && Math.Abs(dy) > Math.Abs(dx) && detected == false && detected == false) { // y distance is largest detected = true; float mz = (float)dz / (float)dy; // compute z slope float mx = (float)dx / (float)dy; // compute x slope float bz = z0 - mz * y0; float bx = x0 - mx * y0; dy = (dy < 0) ? -1 : 1; while (y0 != y1) { y0 += dy; DrawOneBlock(theplayer, drawBlock, Convert.ToInt32(Math.Round(mx * y0 + bx)), Convert.ToInt32(y0) , Convert.ToInt32(Math.Round(mz * y0 + bz)), ref blocks, ref cannotUndo); } } //a>z,b>x,c>y if (Math.Abs(dz) > Math.Abs(dx) && Math.Abs(dz) > Math.Abs(dy) && detected == false && detected == false) { // z distance is largest detected = true; float mx = (float)dx / (float)dz; // compute x slope float my = (float)dy / (float)dz; // compute y slope float bx = x0 - mx * z0; float by = y0 - my * z0; dz = (dz < 0) ? -1 : 1; while (z0 != z1) { z0 += dz; DrawOneBlock(theplayer, drawBlock, Convert.ToInt32(Math.Round(mx * z0 + bx)), Convert.ToInt32(Math.Round(my * z0 + by)), Convert.ToInt32(z0), ref blocks, ref cannotUndo); } } A: You will need to compare abs(dx), abs(dy), and abs(dz) and pick the biggest one. In each case use code like to what you have, computing both other coordinates similarly: if (Math.abs(dx) > Math.abs(dy) && Math.abs(dx) > Math.abs(dz)) { // x distance is largest float my = (float) dy / (float) dx; // compute y slope float mz = (float) dz / (float) dx; // compute z slope float by = y0 - my*x0; float bz = z0 - mz*x0; dx = (dx < 0) ? -1 : 1; while (x0 != x1) { x0 += dx; raster.setPixel(pix, x0, Math.round(my*x0 + by), Math.round(mz*x0 + bz)); }
[ "stackoverflow", "0013725529.txt" ]
Q: The textField is ignoring pattern for showing sum with currency I have a variable V{Total} where the pattern ###0.00 is not applied, what am I missing? <textField pattern="###0.00" isBlankWhenNull="false"> <reportElement uuid="ea9933c9-1863-474f-a6e2-65cfe3f07426" x="390" y="9" width="144" height="20" forecolor="#000000"/> <box> <pen lineColor="#999999"/> <topPen lineColor="#999999"/> <leftPen lineColor="#999999"/> <bottomPen lineWidth="0.5" lineColor="#999999"/> <rightPen lineColor="#999999"/> </box> <textElement> <font fontName="Verdana" isBold="true" isUnderline="false"/> </textElement> <textFieldExpression><![CDATA[$V{Total}+".- €"]]</textFieldExpression> </textField> A: You are trying to format a string: $V{Total}+".- €" will be a string, even if the the variable was decimal adding the .-€ will turn it into a string, thus meaning your formatting won't work What you need to do is format the value on its own and the add the trailing characters, try something like this: new DecimalFormat("###0.00").format($V{Total})+".- €" Full Solution: <textField isBlankWhenNull="false"> <reportElement uuid="ea9933c9-1863-474f-a6e2-65cfe3f07426" x="390" y="9" width="144" height="20" forecolor="#000000"/> <box> <pen lineColor="#999999"/> <topPen lineColor="#999999"/> <leftPen lineColor="#999999"/> <bottomPen lineWidth="0.5" lineColor="#999999"/> <rightPen lineColor="#999999"/> </box> <textElement> <font fontName="Verdana" isBold="true" isUnderline="false"/> </textElement> <textFieldExpression><![CDATA[new DecimalFormat("###0.00").format($V{Total})+".- €"]]></textFieldExpression> </textField>
[ "stackoverflow", "0009360206.txt" ]
Q: can you modify jQuery source for self and redistribution? I know jQuery is issued under GNU or MIT license. Can we modify the jQuery source code for self use and redistribution purpose according to these license terms? A: From the license: Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. tl;dr Yes you can.
[ "superuser", "0000879427.txt" ]
Q: What are the license(s) of the Linux man pages? What is the license on the Linux man pages? GPL, Public Domain, etc? The Wikipedia page about the man doesn't appear to have any info about the licensing status of the man pages. A: What is the license on the Linux man pages? GPL, Public Domain, etc? All submissions to man-pages must be licensed using a license that permits the page to be freely redistributed and modified. Include that license or a reference to it, in the source code of the man page. There are many such licenses, but in the interests of minimizing the number of licenses in man-pages, it is preferred that you use one of the following: The "verbatim" license (personal preference of the current maintainer, and seems also to have been the preference of the previous maintainer as well) The GNU General Public License (GPL) The BSD License man-pages does not include pages under the GNU Free Documentation License (GFDL). This is a purely pragmatic decision, made because the GFDL is problematic for Debian, one of the largest distributions. The rest of the above link includes examples of each of the three licence types mentioned. Source Licenses for man-pages It's all about the glibc network functions The GNU C Library, commonly known as glibc, is the GNU Project's implementation of the C standard library. The GNU C Library documentation licence can be found at http://www.gnu.org/software/libc/manual/html_mono/libc.html#Documentation-License. The GNC C library documentation can be found at http://www.gnu.org/software/libc/manual/html_mono/libc.html and is covered by the above mentioned licence. A: According to kernel.org, it must be licensed as freely available work: All submissions to man-pages must be licensed using a license that permits the page to be freely redistributed and modified. Include that license or a reference to it, in the source code of the man page. A: It depends on the specific manpage. For example, the manual pages for socket, send, and recv (in general anything in section 2) are part of the kernel and documented as part of the kernel documentation. While gethostbyname is a glibc function, it too is documented as part of the kernel.org manpages on my system. I suspect this is because the GNU people are not interested in manpages as a primary documentation format, and focus their efforts on Texinfo. In general, you should look at the specific manpage you are quoting to find its specific license. socket/send/recv have BSD licenses whereas the gethostbyname manual has the "verbatim" license. To find the specific license and the copyright owner, you need to look in the manpage source itself. From /usr/share/man/man3/gethostbyname.3.gz: .\" Copyright 1993 David Metcalfe (david@...) .\" .\" Permission is granted to make and distribute verbatim copies of this ...(goes on for four paragraphs, then lists references and change history) From /usr/share/man/man2/send.2.gz: .\" Copyright (c) 1983, 1991 The Regents of the University of California. .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions ...(rest of four-clause BSD license, then change history) You should, however, look at the source code comments for the work you are quoting/copying, rather than relying on claims that someone else makes about the manpages installed on their system. You should also note that if you are using the text of the manpage, you may have to add a copyright notice. From the verbatim license: .\" Formatted or processed versions of this manual, if unaccompanied by .\" the source, must acknowledge the copyright and authors of this work. The BSD license requires you to include the entire license, and may require you to include "This product includes software developed by the University of California, Berkeley and its contributors." in your advertising materials. In general you need to read and follow the license terms on each manpage you are using. You should talk to a lawyer if you are unsure of how to comply with the terms of the licenses. (And not all manpages have the same author - check each individual page for the copyright statement near the top.) You can view manpage source with zless /usr/share/man/man[section]/[file].[section].gz. Older distributions may have it under /usr/man instead of /usr/share/man, and may not have the files gzipped.
[ "stackoverflow", "0038484352.txt" ]
Q: template issue with class derived from const Given following code: class MyClass {}; template< class T > class Base {}; template< class T > class Derived : public Base< const T > {}; Base< const MyClass* >* MyFunc () { return new Derived< MyClass* >(); } clang gives: error: cannot initialize return object of type 'Base<const MyClass *> *' with an rvalue of type 'Derived<MyClass *> *' However, "Derived MyClass*" is derived from "Base const MyClass*", so I expected it to work. What did I get wrong ? A: This is because Derived<MyClass*> is derived from Base<MyClass* const>, not Base<const MyClass*>. The former means a const pointer to MyClass, the latter means a pointer to a const MyClass. You need to think about what you want to be const: the pointer or the pointee. If it's the pointer, then just change the return type to Base<MyClass* const>*. If it's the pointee, then you'll need to do some transformations on T in your definition for Derived. If you only expect T to be a pointer, then const std::remove_pointer_t<T>* will probably work for you, otherwise you'll need to do some partial specialization.
[ "stackoverflow", "0021030980.txt" ]
Q: removeEventListener() not removing function after added with addEventListener javascript I've added a mouseover function with addEventListener() and am trying to remove it on mouseout with removeEventListener() . Adding the function works fine but it's not being removed on mouseout. What is the problem with the code here ? How can it be amended to remove the function ? var elem = document.getElementById('a'); function highLight() { var p = document.getElementById('p'); var strong = p.getElementsByTagName('strong'); for(var i = 0; i < strong.length; i++) { strong[i].style.color = 'red'; } } elem.addEventListener('mouseover', highLight, false); elem.removeEventListener('mouseout', highLight, false); A: I'm guessing the point is to remove the red color, and not really remove the eventListener var elem = document.getElementById('a'); function highLight() { var p = document.getElementById('p'); var strong = p.getElementsByTagName('strong'); for (var i = 0; i < strong.length; i++) { strong[i].style.color = 'red'; } } function unhighLight() { var p = document.getElementById('p'); var strong = p.getElementsByTagName('strong'); for (var i = 0; i < strong.length; i++) { strong[i].style.color = 'black'; } } elem.addEventListener('mouseenter', highLight, false); elem.addEventListener('mouseleave', unhighLight, false); FIDDLE
[ "stackoverflow", "0044818541.txt" ]
Q: Reactjs Add dynamic component into other component I am trying to develop a webapp using reactjs and i have a issue. After more than 1 day of research, i don't understand how to do. I want to use a component which are the main layout of my page adding other component to display in it. In the component Base2, the child props contains another component. import React from 'react'; import PropTypes from 'prop-types'; import { Link, NavLink } from 'react-router-dom'; const Base2 = (child) => ( <div> <div className="top-bar"> <div className="top-bar-left"> <NavLink to="/">React App</NavLink> </div> <div className="top-bar-right"> <Link to="/login">Log in</Link> </div> </div> <child/> // HERE the dynamic component </div> ); export default Base2; The function calling it is : const TestBase = ({props}) => { return (<Base child={MyComponent}/>) }; Moreover MyComponent can be a class declare following 2 methods: import React from 'react'; import LoginForm from '../components/LoginForm.jsx'; class MyComponent extends React.Component{ constructor(props) { super(props); ... } render() { return ( <LoginForm onSubmit={this.processForm} onChange={this.changeUser} errors={this.state.errors} user={this.state.user} /> ); } } export default LoginPage; Second method : import React from 'react'; import { Card, CardTitle } from 'material-ui/Card'; const MyComponent = { render() { return (<Card className="container"> <CardTitle title="React Application" subtitle="Home page." /> </Card>); } }; export default MyComponent ; During my tests, only the second method works. The lack of "instance" (something like that i guess) from the second method might be the issue? How can I develop Base2 component to take these 2 types of component declaration? Thanks in advance for your help A: First pass the component like this: <Base child={<MyComponent/>}/> Then render it inside Base2 component by props.child, the way you wrote the Base2 component, child (just the argument name) will have the value of props not directly the component you are passing in props. Write it like this: const Base2 = (props) => ( <div> <div className="top-bar"> <div className="top-bar-left"> <NavLink to="/">React App</NavLink> </div> <div className="top-bar-right"> <Link to="/login">Log in</Link> </div> </div> {props.child} //here </div> );
[ "rpg.stackexchange", "0000172585.txt" ]
Q: For areas of effect, what is the difference between "each creature in blast" and "each creature in area"? What is the difference between "each creature in blast" and "each creature in area"? I noticed that the dragon breath power said "all creatures in area", and was curious what the difference was. A: It makes Dragon Breath forward-compatible. Most attack powers in 4e will use the more specific nomenclature of their Close or Area targeting type to describe their targets. A close blast that targets all creatures in the blast, or an area burst that targets all creatures in the burst. However, Dragon Breath is a racial power, and one of the more common uses for feats in 4E is to manipulate racial powers somehow. So, "all creatures in the area" is a generic targeting statement that applies no matter what shape or shapes your Dragon Breath takes. (It's a little confusing because Area is also a power type, but it should be read as shorthand for "area of effect", a generic term for the squares affected by a power.) If you can take feats to let you use your Dragon Breath as a Close burst 1 or an Area burst 2 within 10 or an Area wall 9 within 3, the targeting statement doesn't need to be updated as part of the feat. This is important because if the targeting statement stays the same, other feats can independently update the targeting statement - you could make your breath target all enemies in the area and gain an effect that helps all allies in the area. As a result, all of the feats that affect your Dragon Breath stack - you can, for example, cough out an area burst that only hurts enemies and helps your allies, and there isn't the possibility that you create contradictory rules text by doing so. (Some of these feats are in the Player's Handbook Races: Dragonborn mini-supplement - Bolstering Breath lets your breath help allies and harm enemies, Focused Breath lets you turn your breath into a close burst, and Hurl Breath lets you use it as an area burst. As far as I know there isn't one that lets you use it as an area wall.)
[ "stackoverflow", "0012713571.txt" ]
Q: Should only error messages be logged? I just started using NLog and logging in general, but I find myself possibly over abusing it. I am logging every single line of code, most of it is Info messages, but in my try catch scenarios or if something is null, I will log an error. What is the best thing to log? I am using this for a WPF solution that has 2 projects (1 is the UI and the other is a Class library) <?xml version="1.0" encoding="utf-8" ?> <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <!-- make sure to set 'Copy To Output Directory' option for this file --> <!-- go to http://nlog-project.org/wiki/Configuration_file for more information --> <targets> <target name="errorLog" xsi:type="File" fileName="${basedir}/error.txt" /> <target name="infoLog" xsi:type="File" fileName="${basedir}/info.txt" /> </targets> <rules> <logger name="*" level="Error" writeTo="errorLog" /> <logger name="*" level="Info" writeTo="infoLog" /> </rules> </nlog> A: NLog supports the concept of logging levels. It is a good idea to log anything that might be useful in tracking down why the program does what it does, using a level less than Error. Set the desired logging level to Error in NLog.config when you deploy your application. http://nlog-project.org/wiki/Log_Levels If a user experiences an unexpected problem, you can change the logging level to e.g. Info and get much more information about what is happening. Having said that, every single line of code is almost certainly overkill. You are cluttering your code with logging if you go to that extreme. Concentrate on places where things can go wrong in the application. My personal preference is to: Use Trace level to indicate the flow of code (entering a method, exiting a method) Use Info level to indicate progress / steps in key calculations Use Error level to indicate something unexpected that the application can recover from Use Fatal level to indicate that something really bad has happened and the app is about to shut down.
[ "stackoverflow", "0025457871.txt" ]
Q: Masonry callback in jQuery infinite scroll isn't working in Wordpress - and neither are infinite scroll plugins I've got a ton of problems surrounding the combination of Masonry and infinite scrolling in Wordpress, namely on this page. I gather getting Masonry to work with infinite scrolling requires a callback within the infinite scroll jQuery code - this seems to be well-established. However, I can only seem to get infinite scrolling working on my Wordpress site under very specific circumstances, and given those circumstances I'm not sure how to integrate Masonry. This code is borrowed from the Masonry.js website's infinite scroll demonstration and is in the footer right now: <script> $(function(){ var $container = $('.et_pb_blog_grid_wrapper'); $container.imagesLoaded(function(){ $container.masonry({ itemSelector: '.post', columnWidth: 100 }); }); $container.infinitescroll({ navSelector : '#nextposts', // selector for the paged navigation nextSelector : '#nextposts a', // selector for the NEXT link (to page 2) itemSelector : '.post', // selector for all items you'll retrieve loading: { finishedMsg: 'No more pages to load.', img: 'http://dearjackalope.com/juliaproblems/wp-content/themes/juliamariani/images/ajax-loader.gif' } }, // trigger Masonry as a callback function( newElements ) { // hide new items while they are loading var $newElems = $( newElements ).css({ opacity: 0 }); // ensure that images load before adding to masonry layout $newElems.imagesLoaded(function(){ // show elems now they're ready $newElems.animate({ opacity: 1 }); $container.masonry( 'appended', $newElems, true ); }); } ); }); </script> The problem is, even though it works in static HTML, on this page it doesn't have any effect and I have no idea why! What does work is this: <script> var infinite_scroll = { loading: { img: "<?php echo get_stylesheet_directory_uri(); ?>/images/ajax-loader.gif", msgText: "<?php _e( 'Loading the next set of posts...', 'custom' ); ?>", finishedMsg: "<?php _e( 'All posts loaded.', 'custom' ); ?>" }, "nextSelector":"#nextposts a", "navSelector":"#nextposts", "itemSelector":".post", "contentSelector":".et_pb_blog_grid_wrapper" }; jQuery( infinite_scroll.contentSelector ).infinitescroll( infinite_scroll ); </script> But I'm not sure how to add the Masonry callback to this - the way the variables are declared in the callback looks quite different from this (I know that the dollar sign is defined in jQuery and it appears in the callback but not in the original code - I'm not sure if this matters?), and I'm not sure exactly where in the function it needs to go. I've tried: <script> var infinite_scroll = { loading: { img: "<?php echo get_stylesheet_directory_uri(); ?>/images/ajax-loader.gif", msgText: "<?php _e( 'Loading the next set of posts...', 'custom' ); ?>", finishedMsg: "<?php _e( 'All posts loaded.', 'custom' ); ?>" }, "nextSelector":"#nextposts a", "navSelector":"#nextposts", "itemSelector":"article.post", "contentSelector":".et_pb_blog_grid_wrapper" }, // hide new items while they are loading var $newElems = jQuery(newElements).css({ opacity: 0 }); // ensure that images load before adding to masonry layout $newElems.imagesLoaded(function(){ // show elems now they're ready $newElems.animate({ opacity: 1 }); $container.masonry( 'appended', $newElems, true ); }); }; jQuery( infinite_scroll.contentSelector ).infinitescroll( infinite_scroll ); </script> and this, declaring a new function: <script> var infinite_scroll = { loading: { img: "<?php echo get_stylesheet_directory_uri(); ?>/images/ajax-loader.gif", msgText: "<?php _e( 'Loading the next set of posts...', 'custom' ); ?>", finishedMsg: "<?php _e( 'All posts loaded.', 'custom' ); ?>" }, "nextSelector":"#nextposts a", "navSelector":"#nextposts", "itemSelector":"article.post", "contentSelector":".et_pb_blog_grid_wrapper" }); }; jQuery( infinite_scroll.contentSelector ).infinitescroll( infinite_scroll ); function newElements() // hide new items while they are loading var $newElems = jQuery(newElements).css({ opacity: 0 }); // ensure that images load before adding to masonry layout $newElems.imagesLoaded(function(){ // show elems now they're ready $newElems.animate({ opacity: 1 }); $container.masonry( 'appended', $newElems, true ); </script> Neither of these work, so I'm not sure where I'm supposed to be putting the callback, or if there's something about the original code that means the callback won't work. I've spent about eight hours reading through Javascript tutorials and documentation and I'm not sure what to try next. :( There is a now-unsupported, but still seemingly widely-used, plugin called Infinite-Scroll which includes a checkbox for 'Masonry Mode', but when I tried installing it I got nothing - it didn't appear to load any code into the page at all, so that doesn't appear to be an option here. It's possibly worth noting that I also found the Jetpack infinite scroll feature loaded no code into the page whatsoever even after fully setting up the theme for it, so I seem to be limited to non-plugin code here. Is there something fundamentally wrong with my theme that's causing all these problems? My Javascript is beginner-level at best and I'm really struggling to know where to go from here - any help would be much appreciated. A: OK, so it looks like this whole issue stemmed from the fact that Wordpress doesn't understand $ as a jQuery variable since its default enqueued version of jQuery runs in no-conflict mode. Replacing all the '$' signs with 'jQuery' solves the problem, or you can wrap it in a function and map it to $ like this which is what I did - http://digwp.com/2011/09/using-instead-of-jquery-in-wordpress/ Not sure how I missed this, but if anyone else is having difficulty getting infinite scrolling working in Wordpress, it worked like a charm after hours of puzzling over why it wasn't working!
[ "stackoverflow", "0001576636.txt" ]
Q: XStream, CircularReferenceException Please consider this code. Is it using Circular Reference? If not why am I getting CircularReferenceException, while enabling NO_REFERENCE mode in XStream. Anyone, please clarify the thing. @XStreamAlias("BalanceEnquiry") public class BalanceEnquiry extends EAIRequest { @XStreamImplicit private List<BalanceEnquiry.Detail> details; public List<Detail> getDetails() { .... } public void setDetails(Detail... details) { .... } @XStreamAlias("details") public final class Detail { @XStreamAsAttribute private String item; private BalanceEnquiry.Detail.Request request; public String getItem() { .... } public void setItem(String item) { .... } public Request getRequest() { .... } public void setRequest(Request request) { .... } public final class Request { private String code; private String branch; public String getCode() { .... } public void setCode(String code) { .... } public String getBranch() { .... } public void setBranch(String branch) { .... } } } } A: I suspect it's because Detail is an inner class. As such, it has an implicit reference to the instance of the outer class (and hence forms a circular reference). See here for more details.
[ "askubuntu", "0000648823.txt" ]
Q: How to read ANSI encoded files in the right way? I have some files that Ubuntu can't read it ( ANSI encoding ) but Windows can read it well. When I open it in gedit or notepad++ it seems like this : Êã ÇáÊÍæíá áÜÜ How can I make Ubuntu read ANSI encoded files well? A: ANSI means more or less nothing --- the most probable candidate for your encoding is Windows-1252. You can convert the file with iconv -f WINDOWS-1252 -t utf8 < filein.txt > fileout.txt but remember, most encodings (read the linked article if you are not sure about what that mean) can't be reliably guessed, so you need to know the exact encoding to give sense to your data. From the comments it seems that you are most probably looking for some Arabic encoding --- in that case check WINDOWS-1256. The list of available encodings for iconv is on github, or you can find it with the command iconv --list Notice that just at the start of the list there are a bunch of "ANSI"-like encodings.
[ "dba.stackexchange", "0000116749.txt" ]
Q: Postgresql equivalent to sqlite pragma What would be the equivalent of the sqlite pragma below if I want to get the best performance out of postgresql. pragma synchronous = OFF; pragma journal_mode = OFF; pragma count_changes = OFF; pragma temp_store = MEMORY; A: Most of what these pragmas do for SQLite can be best accomplished by using an UNLOGGED table or a TEMPORARY table. This also makes it very obvious that these are ephemeral tables, that aren't crash or restart safe. It also highlights that there are very real tradeoffs for blazing speed versus data durability. Going off of the PRAGMA documentation for SQLite, I've attempted to translate them into equivalent PostgreSQL GUC variables. pragma synchronous = OFF; is roughly equvalent to setting synchronous_commit off. If you're using a TEMPORARY or UNLOGGED table, this setting will have no real effect because those types of tables aren't actually written into the WAL anyway. pragma journal_mode = OFF; shuts off the WAL, in PostgreSQL you can only do that with UNLOGGED or TEMPORARY tables. pragma temp_store = MEMORY; temporary tables in PostgreSQL can write to disk, but setting temp_buffers should let you keep more of the tables in memory for better performance. pragma count_changes = OFF; is deprecated in SQLite, and doesn't really make sense in PostgreSQL. Robert Haas has a great blog posting about Temporary and Unlogged Tables. Whatever you do, be sure to not put any of your tablespaces in RAM. The dangers are spelled out in the following two blog posts. PostgreSQL no tablespaces on ramdisks Cannot recover from the loss of a tablespace
[ "stackoverflow", "0027268450.txt" ]
Q: GNU make ifeq comparison not working I am trying to have a command executed depending on the current target from a list of targets (currently only one entry in that list) before another makefile is executed. i have this: $(LIBS): ifeq ($@,libname) my command here endif $(MAKE) -C ./lib/$@ the problem is, that the ifeq does not get executed even if the target name is correct. Using an $(info $@) shows exactly the libname but the expression is not evaluated as true. I thought maybe there is a problem with expansion of the automatic variable in a conditional so i tried using an eval like this: $(LIBS): $(eval CURRENT_LIB := $@) ifeq ($(CURRENT_LIB),libname) my command here endif $(MAKE) -C ./lib/$@ info shows that the variable now equals exactly the libname but the ifeq does not get excuted. When i enter something like ifeq (libname,libname) it works so the statement is working, but the comparison between variable and text does not evaluate to true even if the two are equal and it should work. GNU make version is 4.1 What am i missing here? Complete Makefile: CC := g++ CFLAGS := -v -std=c++0x -pthread -Wall -g -O3 OBJ := mycode.o OBJ += moreobjects.o #more objects in here LIBS = libname .PHONY: libs $(LIBS) SRC = $(OBJ:%.o=%.cpp) DEPFILE := .depend mytarget: libs $(OBJ) $(CC) $(CFLAGS) -o $@ $(OBJ) -include $(DEPFILE) %.o: %.cpp $(CC) $(CFLAGS) -c $< $(CC) -MM -std=c++11 $(SRC) > $(DEPFILE) libs: $(LIBS) $(LIBS): $(eval CURRENT_LIB := $@) ifeq ($(CURRENT_LIB),libname) ./lib/$(CURRENT_LIB)/configure endif $(MAKE) -C ./lib/$@ .PHONY: clean_all clean_all: clean $(foreach dir,$(LIBS),$(MAKE) clean -C ./lib/$(dir)) .PHONY: clean clean: rm -rf mytarget $(OBJ) $(DEPFILE) Thank You very much! A: What you are trying to do cannot work. From the documentation: Conditionals control what 'make' actually "sees" in the makefile, so they cannot be used to control recipes at the time of execution. The way I put it is that conditionals are evaluated at the time the Makefile is read. So make reads your Makefile, your conditional is false and it is removed.
[ "stackoverflow", "0030962746.txt" ]
Q: Unable to join 3 tables properly While understanding natural joins, I came across the query: Find the names of branches with customers who have an account in the bank and live in Harrison The relational algebra expression from the book as follows: Implementing the same with the query: select distinct a.branch_name from depositor d, account a, customer where d.account_number=a.account_number and customer.customer_city='Harrison'; I get spurious tuples as follows: +-------------+ | branch_name | +-------------+ | Perryridge | | Downtown | | Brighton | | Redwood | | Mianus | | Round Hill | +-------------+ 6 rows in set (0.00 sec) But the query must have returned only Brighton and Perryridge based on the schema as follows: mysql> select * from account; +----------------+-------------+---------+ | account_number | branch_name | balance | +----------------+-------------+---------+ | A101 | Downtown | 500 | | A102 | Perryridge | 400 | | A201 | Brighton | 900 | | A215 | Mianus | 700 | | A217 | Brighton | 750 | | A222 | Redwood | 700 | | A305 | Round Hill | 350 | +----------------+-------------+---------+ 7 rows in set (0.00 sec) mysql> select * from customer; +---------------+-----------------+---------------+ | customer_name | customer_street | customer_city | +---------------+-----------------+---------------+ | Adams | Spring | Pittsfield | | Brooks | Senator | Brooklyn | | Curry | North | Rye | | Glenn | Sand Hill | Woodside | | Green | Walnut | Stamford | | Hayes | Main | Harrison | | Johnson | Alma | Palo Alto | | Jones | Main | Harrison | | Lindsay | Park | Pittsfield | | Smith | North | Rye | | Turner | Putnam | Stamford | | Williams | Nassau | Princeton | +---------------+-----------------+---------------+ 12 rows in set (0.00 sec) mysql> select * from depositor; +---------------+----------------+ | customer_name | account_number | +---------------+----------------+ | Hayes | A102 | | Johnson | A101 | | Johnson | A201 | | Jones | A217 | | Lindsay | A222 | | Smith | A215 | | Turner | A305 | +---------------+----------------+ 7 rows in set (0.00 sec) Where am I making the mistake? A: You didnt make join for customer table, your query should be like this Select a.branch_name From depositor d Join account a on d.account_number=a.account_number Join customer as c on d.customer_name = c.customer_name Where c.customer_city='Harrison' I dont know how to join customer table to depositor maybe by name or if you have some key just replace it and you will get your result. How to make joins in where clause useful link
[ "stackoverflow", "0007543826.txt" ]
Q: How to remove a specific parameter from the URL in PHP? Example: $url = http://example.com/?arg=val&arg2=test&arv3=testing&arv2=val2 remove_url_arg($url, "arg2") echo($url); // http://example.com/?arg=val&arv3=testing The above remove_url_arg() function removes all occurrence of arg2 argument from the URL A: unset($_GET['arg2']); $query_string = http_build_query($_GET); if it's not on request but to parse whole url $parsed = parse_url($url); $qs_arr = parse_str($parsed['query'],1); unset($qs_arr['arg2']); $parsed['query'] = http_build_query($qs_arr); and then assemble the url back. or one-liner regexp
[ "stackoverflow", "0000601543.txt" ]
Q: Command line command to auto-kill a command after a certain amount of time I'd like to automatically kill a command after a certain amount of time. I have in mind an interface like this: % constrain 300 ./foo args Which would run "./foo" with "args" but automatically kill it if it's still running after 5 minutes. It might be useful to generalize the idea to other constraints, such as autokilling a process if it uses too much memory. Are there any existing tools that do that, or has anyone written such a thing? ADDED: Jonathan's solution is precisely what I had in mind and it works like a charm on linux, but I can't get it to work on Mac OSX. I got rid of the SIGRTMIN which lets it compile fine, but the signal just doesn't get sent to the child process. Anyone know how to make this work on Mac? [Added: Note that an update is available from Jonathan that works on Mac and elsewhere.] A: GNU Coreutils includes the timeout command, installed by default on many systems. https://www.gnu.org/software/coreutils/manual/html_node/timeout-invocation.html To watch free -m for one minute, then kill it by sending a TERM signal: timeout 1m watch free -m A: Maybe I'm not understanding the question, but this sounds doable directly, at least in bash: ( /path/to/slow command with options ) & sleep 5 ; kill $! This runs the first command, inside the parenthesis, for five seconds, and then kills it. The entire operation runs synchronously, i.e. you won't be able to use your shell while it is busy waiting for the slow command. If that is not what you wanted, it should be possible to add another &. The $! variable is a Bash builtin that contains the process ID of the most recently started subshell. It is important to not have the & inside the parenthesis, doing it that way loses the process ID. A: I've arrived rather late to this party, but I don't see my favorite trick listed in the answers. Under *NIX, an alarm(2) is inherited across an execve(2) and SIGALRM is fatal by default. So, you can often simply: $ doalarm () { perl -e 'alarm shift; exec @ARGV' "$@"; } # define a helper function $ doalarm 300 ./foo.sh args or install a trivial C wrapper to do that for you. Advantages Only one PID is involved, and the mechanism is simple. You won't kill the wrong process if, for example, ./foo.sh exited "too quickly" and its PID was re-used. You don't need several shell subprocesses working in concert, which can be done correctly but is rather race-prone. Disadvantages The time-constrained process cannot manipulate its alarm clock (e.g., alarm(2), ualarm(2), setitimer(2)), since this would likely clear the inherited alarm. Obviously, neither can it block or ignore SIGALRM, though the same can be said of SIGINT, SIGTERM, etc. for some other approaches. Some (very old, I think) systems implement sleep(2) in terms of alarm(2), and, even today, some programmers use alarm(2) as a crude internal timeout mechanism for I/O and other operations. In my experience, however, this technique is applicable to the vast majority of processes you want to time limit.
[ "stackoverflow", "0006785405.txt" ]
Q: SqLite in memory DB and NHibernate I have nhibernate working with an oracle db, and I am trying to use sqlite in memory db to test our query logic. I believe I have read, understood and confirmed every answer on the web concerning this problem, some of them a few times :) I am getting the SQLite error no such table: I also don't see any ddl commands on the SchemaExport call Here are the bits of my setup that I feel are relevant. This code is all from same method cfg = new Configuration() .SetProperty(Environment.ReleaseConnections, "on_close") .SetProperty(Environment.Dialect, typeof(SQLiteDialect).AssemblyQualifiedName) .SetProperty(Environment.ConnectionDriver, typeof(SQLite20Driver).AssemblyQualifiedName) .SetProperty(Environment.ConnectionString, "Data Source=:memory:;Version=3;New=True") .SetProperty(Environment.ProxyFactoryFactoryClass, typeof(ProxyFactoryFactory).AssemblyQualifiedName) .SetProperty(Environment.ShowSql, "true") .SetProperty(Environment.ConnectionProvider, typeof(NHibernate.Connection.DriverConnectionProvider).AssemblyQualifiedName); cfg.AddAssembly("MyAssembly"); _sessionFactory = cfg.BuildSessionFactory(); _session = _sessionFactory.OpenSession(); new SchemaExport(cfg).Execute(true, true, false, _session.Connection, Console.Out); <--don't see any ddl commands here var q = from c in _session.Query<ComponentGroup>() where !c.IsDiscontinued select c; var z = q.ToList(); //<--get error here My .hbm.xml : <?xml version="1.0" encoding="utf-8" ?> <hibernate-mapping assembly="myassmebly" namespace="myns" xmlns="urn:nhibernate-mapping-2.2"> <class name="ComponentGroup" table="TBL_COMPONENT_GROUP" lazy="true" > <id name="Id" column="N_COMPONENT_GROUP_ID" type="int"> <generator class="native" /> </id> <property name="AssemblyFacilityId" column="N_ASSEMBLY_FACILITY_ID" type="int" not-null="true" /> <property name="Name" column="C_COMPONENT_GROUP_NAME" type="string" not-null="true" /> <property name="IsDiscontinued" column="N_DISCONTINUED_FLAG" type="bool" not-null="true" /> </class> </hibernate-mapping> My POCO public class ComponentGroup { public virtual int Id { get; set; } public virtual int AssemblyFacilityId { get; set; } public virtual string Name { get; set; } public virtual bool IsDiscontinued { get; set; } } The innerexception InnerException: System.Data.SQLite.SQLiteException Message=SQLite error no such table: TBL_COMPONENT_GROUP Source=System.Data.SQLite ErrorCode=-2147467259 StackTrace: at System.Data.SQLite.SQLite3.Prepare(SQLiteConnection cnn, String strSql, SQLiteStatement previous, UInt32 timeoutMS, String& strRemain) at System.Data.SQLite.SQLiteCommand.BuildNextCommand() at System.Data.SQLite.SQLiteCommand.GetStatement(Int32 index) at System.Data.SQLite.SQLiteDataReader.NextResult() at System.Data.SQLite.SQLiteDataReader..ctor(SQLiteCommand cmd, CommandBehavior behave) at System.Data.SQLite.SQLiteCommand.ExecuteReader(CommandBehavior behavior) at System.Data.SQLite.SQLiteCommand.ExecuteDbDataReader(CommandBehavior behavior) at System.Data.Common.DbCommand.System.Data.IDbCommand.ExecuteReader() at NHibernate.AdoNet.AbstractBatcher.ExecuteReader(IDbCommand cmd) at NHibernate.Loader.Loader.GetResultSet(IDbCommand st, Boolean autoDiscoverTypes, Boolean callable, RowSelection selection, ISessionImplementor session) at NHibernate.Loader.Loader.DoQuery(ISessionImplementor session, QueryParameters queryParameters, Boolean returnProxies) at NHibernate.Loader.Loader.DoQueryAndInitializeNonLazyCollections(ISessionImplementor session, QueryParameters queryParameters, Boolean returnProxies) at NHibernate.Loader.Loader.DoList(ISessionImplementor session, QueryParameters queryParameters) I'm using NHibernate version 3.1.0.4, System.Date.SQLite version 2.0.50727 A: so the fix is to replace new SchemaExport(cfg).Execute(true, true, false, _session.Connection, Console.Out); with new SchemaExport(cfg).Execute(true, true, false, _session.Connection, null); Really not sure why, but I added code to insert rows into exported table, which worked as expected. I then put the Console.Out parm back in and got a "Cannot write to a closed TextWriter." error.
[ "stackoverflow", "0042956690.txt" ]
Q: Python periodically remove items from a list Say I have a long list with 1000 elements and I want to periodically delete groups of elements based off of two variables. So for my_list=[1,2,3,4...1000], and a=5, b=7, I would keep the first 5 elements, delete the next 7, and repeat until the end of the list. The list will then look like: my_list = [1,2,3,4,5,12,13,14,15,16...] I don't know a or b prior to using them, nor the length of the list, so I'm looking for a general solution. Thanks! A: Here's one way to do it using enumerate and taking the mod of the index on the sum of a and b. Filter out values whose mod is less than a: l = range(1, 30) a, b = 5, 7 r = [x for i, x in enumerate(l) if i%(a+b) < a] print(r) # [1, 2, 3, 4, 5, 13, 14, 15, 16, 17, 25, 26, 27, 28, 29] P.S. if you're deleting the next 7, 12 should not be included.
[ "stackoverflow", "0031055988.txt" ]
Q: Most effecient way to calculate this in swift (simple math) The question is related to calculating an increase in currency. Loop over this n times, and let's say you start with $50k and your multiplier is 2. Something like b * 2 + a This is the correct result: $50,000.00 $100,000.00 $250,000.00 $600,000.00 $1,450,000.00 $3,500,000.00 $8,450,000.00 $20,400,000.00 $49,250,000.00 So just to be clear, the question is about efficiency in swift, not simply how to calculate this. Are there any handy data structures that would make this faster? Basically I was just looping through how many years (n) adding 2 (200%) and incrementing a couple temp variables to keep track of the current and previous values. It feels like there has got to be a much better way of handling this. $50k base $50k * 2 + 0 (previous value) = $100k $100k * 2 + $50k = $250k $250k * 2 + $100k = $600k etc. Code: let baseAmount = 50000.0 let percentReturn = 200.0 let years = 10 // Calc decimal of percent. var out: Double = 0.0 var previous: Double = 0.0 let returnPercent = percentReturn * 0.01 // Create tmp array to store values. var tmpArray = [Double]() // Loop through years. for var index = 0; index < years; ++index { if index == 0 { out = baseAmount tmpArray.append(baseAmount) } else if index == 1 { out = (out * returnPercent) tmpArray.append(out) previous = baseAmount } else { let tmp = (tmpArray.last! * returnPercent) + previous previous = tmpArray.last! tmpArray.append(tmp) } } println(tmpArray) A: Here are some ideas for improving efficiency: Initialize your array to the appropriate size (it isn't dynamic; it is always the number of years) Remove special cases (year 0 and 1 calculations) from the for-loop Code: func calculate(baseAmount: Double, percentReturn: Double, years: Int) -> [Double] { // I prefer to return an empty array instead of nil // so that you don't have to check for nil later if years < 1 { return [Double]() } let percentReturnAsDecimal = percentReturn * 0.01 // You know the size of the array, no need to append var result = [Double](count: years, repeatedValue: 0.0) result[0] = baseAmount // No need to do this in the loop if years > 1 { result[1] = baseAmount * percentReturnAsDecimal } // Loop through years 2+ for year in 2 ..< years { let lastYear = result[year - 1] let yearBeforeLast = result[year - 2] result[year] = (lastYear * percentReturnAsDecimal) + yearBeforeLast } return result }
[ "gamedev.stackexchange", "0000044723.txt" ]
Q: Raycasting mouse coordinates to rotated object? I am trying to cast a ray from my mouse to a plane at a specified position with a known width and length and height. I know that you can use the NDC (Normalized Device Coordinates) to cast ray but I don't know how can I detect if the ray actually hit the plane and when it did. The plane is translated -100 on the Y and rotated 60 on the X then translated again -100. Can anyone please give me a good tutorial on this? For a complete noob! I am almost new to matrix and vector transformations. A: There's a list of different collision types (ray-plane included) that can be found here. One of the better sources of ray-plane intersection can be found here. With a c++ implementation: // intersect3D_SegmentPlane(): intersect a segment and a plane // Input: S = a segment, and Pn = a plane = {Point V0; Vector n;} // Output: *I0 = the intersect point (when it exists) // Return: 0 = disjoint (no intersection) // 1 = intersection in the unique point *I0 // 2 = the segment lies in the plane int intersect3D_SegmentPlane( Segment S, Plane Pn, Point* I ) { Vector u = S.P1 - S.P0; Vector w = S.P0 - Pn.V0; float D = dot(Pn.n, u); float N = -dot(Pn.n, w); if (fabs(D) < SMALL_NUM) { // segment is parallel to plane if (N == 0) // segment lies in plane return 2; else return 0; // no intersection } // they are not parallel // compute intersect param float sI = N / D; if (sI < 0 || sI > 1) return 0; // no intersection *I = S.P0 + sI * u; // compute segment intersect point return 1; }
[ "stackoverflow", "0011068806.txt" ]
Q: Is it possible to move the "box" of a checkbox? Currently when you make a checkbox, the "box" is to the left of the text. Is it possible to adjust the orientation for: 1: vertical (above): 2: vertical (below): 3: horizontal (to the right of the text): ? A: Input checkbox does not have connection to the text. Box on the left: <input type="checkbox" name="v[]" value="1"> 1 <input type="checkbox" name="v[]" value="2"> 2 <input type="checkbox" name="v[]" value="3"> 3 Box on the right: 1 <input type="checkbox" name="v[]" value="1"> 2 <input type="checkbox" name="v[]" value="2"> 3 <input type="checkbox" name="v[]" value="3"> If you are going to put it below or above, maybe you can create a table like: <table> <tr> <td>ONE</td> <td>II</td> <td>3</td> </tr> <tr> <td><input type="checkbox" name="v[]" value="1"></td> <td><input type="checkbox" name="v[]" value="2"></td> <td><input type="checkbox" name="v[]" value="3"></td> </tr> </table>
[ "stackoverflow", "0042513452.txt" ]
Q: Android libgdx IAP billing? I need to use this library: https://github.com/anjlab/android-inapp-billing-v3 and I have a libgdx AndroidLiveWallpaperService the probleme I don't know how to implement it, because it is for Activity and not for AndroidLiveWallpaperService. I have a LiveWallpaper class to that extends AndroidLiveWallpaperService, but I can't figure it out how to add onActivityresult to that. Is it any IAP billing lib for libgdx and live wallpapers? A: You can check gdx-pay, libGDX cross-platform API for InApp purchasing. It provide a cross-platform API for InApp purchasing. EDIT May be If you're not able to integrate LWP with gdx-pay, You can use https://github.com/anjlab/android-inapp-billing-v3
[ "stackoverflow", "0037222901.txt" ]
Q: Installation failed with message INSTALL_FAILED_CONFLICTING_PROVIDER I am getting "Installation failed with message INSTALL_FAILED_CONFLICTING_PROVIDER." while run the project in Android Studio. How to resolve this? My manifest.xml is: <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.mmsapp" > <uses-permission android:name="android.permission.SEND_SMS" /> <uses-permission android:name="android.permission.RECEIVE_SMS" /> <uses-permission android:name="android.permission.READ_SMS" /> <uses-permission android:name="android.permission.WRITE_SMS" /> <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" /> <uses-permission android:name="android.permission.RECEIVE_MMS" /> <uses-permission android:name="android.permission.READ_CONTACTS" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.CALL_PHONE" /> <uses-permission android:name="android.permission.VIBRATE" /> <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /> <uses-permission android:name="android.permission.CALL_PHONE" /> <uses-permission android:name="android.permission.READ_CONTACTS" /> <uses-permission android:name="android.permission.WRITE_CONTACTS" /> <uses-permission android:name="android.permission.RECEIVE_SMS" /> <uses-permission android:name="android.permission.RECEIVE_MMS" /> <uses-permission android:name="android.permission.SEND_SMS" /> <uses-permission android:name="android.permission.VIBRATE" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.READ_SMS" /> <uses-permission android:name="android.permission.WRITE_SMS" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" /> <uses-permission android:name="android.permission.READ_PHONE_STATE" /> <uses-permission android:name="android.permission.WAKE_LOCK" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.INSTALL_DRM" /> <uses-permission android:name="android.provider.Telephony.SMS_RECEIVED" /> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.WRITE_SETTINGS" /> <uses-feature android:name="android.hardware.camera" android:required="false"></uses-feature> <uses-feature android:glEsVersion="0x00020000" android:required="true" /> <application android:name=".Volley.AppController" android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme"> <activity android:name=".ui.SplashScreenActivity" android:screenOrientation="portrait"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".ui.tutorial.Demo1" android:screenOrientation="portrait" /> <activity android:name=".ui.tutorial.Demo2" android:screenOrientation="portrait" /> <activity android:name=".ui.tutorial.Demo3" android:screenOrientation="portrait" /> <activity android:name=".ui.tutorial.Demo5" android:screenOrientation="portrait" /> <activity android:name=".ui.tutorial.Demo4" android:screenOrientation="portrait" /> <activity android:name=".ui.Setup1" android:screenOrientation="portrait" android:theme="@android:style/Theme.NoTitleBar" android:windowSoftInputMode="adjustResize" /> <activity android:name=".ui.Setup2" android:screenOrientation="portrait" android:theme="@android:style/Theme.NoTitleBar" /> <activity android:name=".ui.Setup3" android:screenOrientation="portrait" /> <activity android:name=".ui.Setup4" android:screenOrientation="portrait" /> <activity android:name=".ui.MessageListActivity" android:theme="@style/AppTheme" /> <activity android:name=".ui.MessagingActivity" android:theme="@android:style/Theme.NoTitleBar" /> <activity android:name=".ui.SettingsActivity" android:screenOrientation="portrait" android:theme="@android:style/Theme.NoTitleBar" /> <activity android:name=".ui.StatisticsActivity" android:screenOrientation="portrait" android:theme="@android:style/Theme.NoTitleBar" /> <activity android:name=".ui.LoginActivity" android:screenOrientation="portrait" android:theme="@android:style/Theme.NoTitleBar" /> <activity android:name=".v2.ui.SignInActivity" android:screenOrientation="portrait" /> <activity android:name=".ui.SignInActivity" android:screenOrientation="portrait" /> <activity android:name=".ui.UpdatePasswordActivity" android:screenOrientation="portrait" android:theme="@android:style/Theme.NoTitleBar" /> <receiver android:name=".control.SmsReceiver"> <intent-filter> <action android:name="android.provider.Telephony.SMS_RECEIVED" /> </intent-filter> </receiver> <activity android:name=".mms.MainActivity" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.SEND" /> <action android:name="android.intent.action.SENDTO" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.BROWSABLE" /> <data android:scheme="sms" /> <data android:scheme="smsto" /> <data android:scheme="mms" /> <data android:scheme="mmsto" /> </intent-filter> <intent-filter> <category android:name="android.intent.category.DEFAULT" /> <data android:mimeType="text/plain" /> <data android:mimeType="image/*" /> <action android:name="android.intent.action.SEND" /> </intent-filter> </activity> <activity android:name="eu.janmuller.android.simplecropimage.CropImage" /> <service android:name="com.android.mms.transaction.TransactionService" /> <receiver android:name=".mms.SmsReceiver" android:permission="android.permission.BROADCAST_SMS"> <intent-filter> <action android:name="android.provider.Telephony.SMS_DELIVER" /> </intent-filter> </receiver> <receiver android:name=".mms.MmsReceiver" android:permission="android.permission.BROADCAST_WAP_PUSH"> <intent-filter> <action android:name="android.provider.Telephony.WAP_PUSH_DELIVER" /> <data android:mimeType="application/vnd.wap.mms-message" /> </intent-filter> </receiver> <service android:name=".mms.HeadlessSmsSendService" android:exported="true" android:permission="android.permission.SEND_RESPOND_VIA_MESSAGE"> <intent-filter> <action android:name="android.intent.action.RESPOND_VIA_MESSAGE" /> <category android:name="android.intent.category.DEFAULT" /> <data android:scheme="sms" /> <data android:scheme="smsto" /> <data android:scheme="mms" /> <data android:scheme="mmsto" /> </intent-filter> </service> <activity android:name=".mms.PermissionActivity" /> </application> </manifest> A: The fix is to make sure that defaultConfig.applicationId is defined in android section of the build.gradle file for each project using your library android { defaultConfig.applicationId = "com.company.appname"(Your application package name) } And other thing please uninstall Settings --> Application --> --> Uninstall
[ "math.stackexchange", "0002601460.txt" ]
Q: Every smooth curve is solution of a differential equation Let $\gamma:\Bbb{R}\rightarrow \Bbb{R}^n$ be a $C^1$-function with $\gamma(t)\neq 0\ \forall t\in \Bbb{R}$. Then I want to show that there exists a continous function $f:\Bbb{R}\rightarrow \text{End}(\Bbb{R}^n)$ such that $\dot{\gamma}(t)=f(t)\gamma(t).$ For $n=1$ one can simply choose $f(t):=\frac{\dot{\gamma}(t)}{\gamma(t)}$. But what can I do in higher dimensions? I tried to apply the implicit function theorem but to apply it one needs that $A(x,t):=\dot{\gamma}(t)-x\gamma(t)$ is $C^1$, but our hypothesis only yields that this function is continuous. Any help will be greatful appreciated. A: Notice that you can rephrase the problem as given continuous functions $\def\RR{\mathbb R}\alpha$, $\beta:\RR\to\RR^n$, with $\beta$ nowhere zero, there exists a continuous $A:\RR\to End(\RR^n)$ such that $\alpha(t)=A(t)(\beta(t))$ for all $t\in\RR$, as you can then take $\alpha=\gamma'$ and $\beta=\gamma$. This shows that the problem is not really about ODEs! To solve this for of the problem, we may take $\displaystyle A(t)(v)=\frac{\langle v,\beta(t)\rangle}{\langle\beta(t),\beta(t)\rangle}\alpha(t)$.
[ "physics.stackexchange", "0000362182.txt" ]
Q: Direction of Friction on two stacked boxes I have box 2 stacked on box 1. Box 1 is on a frictionless table and accelerated by a force. However, there is friction between box 1 and box 2. Now, I was told that this is the diagram for that problem: I thought that since m1 and m2 are moving to the right, then the frictional force between box 1 and 2 will be to the left, opposite to the direction of motion. Can someone confirm what is the actual direction of friction for the frictional force between box 1 and box 2? Also, is the action-reaction pair of forces between box 1 and box 2 the normal force of box 1 and the negative normal force of box 1? It is the same issue with another problem I saw online: In one of the free-body-diagrams, the friction seems to be going to the right (which makes sense since the movement is to the left), but in the lower free-body diagram the friction appears to be going to the right (in the same direction of movement). How is this possible? A: Consider Newton's Third Law; commonly stated "every action has an equal and opposite reaction". You should expect the surfaces to have friction in the opposite direction. Friction doesn't help one of them move, it resists the relative movement of both, causing forces in opposite directions. You can sense this yourself by taking two rough surfaces and trying to move them one with each hand. The friction will resist movement with both hands, not just one.
[ "stackoverflow", "0032417992.txt" ]
Q: Visual Studio Java debugger only supports starting the execution in a named class I am having problems setting up Java Compiler for Visual Studio and keep getting this error. I am using Visual Studio 2015 and the latest version of JDK. I downloaded the Java extension from here. What could be the cause, how do I solve this problem? Thank you for your time. A: This is the answer that nerdyguy64 said in a forum , This ONE work for ME ..... ".. I had this same problem but I figured it out. Do what it says, go into the Debug tab and then go down and click "'PROJECT_NAME_HERE' Properties" Then click the "Debug" tab on the side and then you will see "Start Class within project:" radio button. Make sure it is clicked and then in the text field along side it type in the class name that has you main method in it. Remember, if your main method is within a package you must type the package name then forward slash ("/") and then your class name (with the main method). For example: if you start a new console application, you should get a basic hello world console application. Since the basic console hello world application has the main method class in a package (called "pkg"), you have to put in the "Start Class within project" field: "pkg/Program"
[ "stackoverflow", "0000740555.txt" ]
Q: LockBits Performance Critical Code I have a method which needs to be as fast as it possibly can, it uses unsafe memory pointers and its my first foray into this type of coding so I know it can probably be faster. /// <summary> /// Copies bitmapdata from one bitmap to another at a specified point on the output bitmapdata /// </summary> /// <param name="sourcebtmpdata">The sourcebitmap must be smaller that the destbitmap</param> /// <param name="destbtmpdata"></param> /// <param name="point">The point on the destination bitmap to draw at</param> private static unsafe void CopyBitmapToDest(BitmapData sourcebtmpdata, BitmapData destbtmpdata, Point point) { // calculate total number of rows to draw. var totalRow = Math.Min( destbtmpdata.Height - point.Y, sourcebtmpdata.Height); //loop through each row on the source bitmap and get mem pointers //to the source bitmap and dest bitmap for (int i = 0; i < totalRow; i++) { int destRow = point.Y + i; //get the pointer to the start of the current pixel "row" on the output image byte* destRowPtr = (byte*)destbtmpdata.Scan0 + (destRow * destbtmpdata.Stride); //get the pointer to the start of the FIRST pixel row on the source image byte* srcRowPtr = (byte*)sourcebtmpdata.Scan0 + (i * sourcebtmpdata.Stride); int pointX = point.X; //the rowSize is pre-computed before the loop to improve performance int rowSize = Math.Min(destbtmpdata.Width - pointX, sourcebtmpdata.Width); //for each row each set each pixel for (int j = 0; j < rowSize; j++) { int firstBlueByte = ((pointX + j)*3); int srcByte = j *3; destRowPtr[(firstBlueByte)] = srcRowPtr[srcByte]; destRowPtr[(firstBlueByte) + 1] = srcRowPtr[srcByte + 1]; destRowPtr[(firstBlueByte) + 2] = srcRowPtr[srcByte + 2]; } } } So is there anything that can be done to make this faster? Ignore the todo for now, ill fix that later once I have some baseline performance measurements. UPDATE: Sorry, should have mentioned that the reason i'm using this instead of Graphics.DrawImage is because im implementing multi-threading and because of that I cant use DrawImage. UPDATE 2: I'm still not satisfied with the performance and i'm sure there's a few more ms that can be had. A: There was something fundamentally wrong with the code that I cant believe I didn't notice until now. byte* destRowPtr = (byte*)destbtmpdata.Scan0 + (destRow * destbtmpdata.Stride); This gets a pointer to the destination row but it does not get the column that it is copying to, that in the old code is done inside the rowSize loop. It now looks like: byte* destRowPtr = (byte*)destbtmpdata.Scan0 + (destRow * destbtmpdata.Stride) + pointX * 3; So now we have the correct pointer for the destination data. Now we can get rid of that for loop. Using suggestions from Vilx- and Rob the code now looks like: private static unsafe void CopyBitmapToDestSuperFast(BitmapData sourcebtmpdata, BitmapData destbtmpdata, Point point) { //calculate total number of rows to copy. //using ternary operator instead of Math.Min, few ms faster int totalRows = (destbtmpdata.Height - point.Y < sourcebtmpdata.Height) ? destbtmpdata.Height - point.Y : sourcebtmpdata.Height; //calculate the width of the image to draw, this cuts off the image //if it goes past the width of the destination image int rowWidth = (destbtmpdata.Width - point.X < sourcebtmpdata.Width) ? destbtmpdata.Width - point.X : sourcebtmpdata.Width; //loop through each row on the source bitmap and get mem pointers //to the source bitmap and dest bitmap for (int i = 0; i < totalRows; i++) { int destRow = point.Y + i; //get the pointer to the start of the current pixel "row" and column on the output image byte* destRowPtr = (byte*)destbtmpdata.Scan0 + (destRow * destbtmpdata.Stride) + point.X * 3; //get the pointer to the start of the FIRST pixel row on the source image byte* srcRowPtr = (byte*)sourcebtmpdata.Scan0 + (i * sourcebtmpdata.Stride); //RtlMoveMemory function CopyMemory(new IntPtr(destRowPtr), new IntPtr(srcRowPtr), (uint)rowWidth * 3); } } Copying a 500x500 image to a 5000x5000 image in a grid 50 times took: 00:00:07.9948993 secs. Now with the changes above it takes 00:00:01.8714263 secs. Much better.
[ "stackoverflow", "0059079838.txt" ]
Q: How to use nonlinear axes in Gnuplot? I saw some examples like this one: f(x) = log10(x) g(x) = 10**x set nonlinear x via f(x) inverse g(x) So this one is equivalent to just log-scaling the x. But I don’t get why we need to write the inverse function? And also I have this situation: For data in x>=0 range I need to scale x in a way that it shows in an almost-half plot; For data in -100<=x<0 I need to scale x in a way that it shows in a small part of plot; For data in x<-100 I need to scale x in a way as for data in x>=0. So let’s imagine we have an a4paper and gnuplot creates his plots on it. I want to have a plot result that will be drawn in an x scales like: If x>=0 1cm = 5 If -100<=x<0 1cm = 100 If x<-100 1cm = 5 (I don’t mean it’s important to me to have only this centimeters, it just says that I need a correlation between delta of two x values and real length between them.) I’m so sorry I can’t understand this mechanics of scaling. A: The forward function tells gnuplot where to draw user coordinate [x,y] on the page. Call that location [x',y']. Only the forward function is needed for this. But the interactive terminals echo back mouse position and allow you to click on the plot for various purposes. In order to know what a mouse click on [x',y'] means, the program has to convert it back to the original [x,y]. For that it needs the inverse function. For an example of using different scaling functions over different portions of the full plot, see the online demo nonlinear1.dem reproduced below # This example shows how a nonlinear axis definition can be used to # create a "broken axis". X coordinates 0-100 are at the left, # X coordinates 500-1000 are at the right, there is a small gap between them. # So long as no data points with (100 < x < 500) are plotted, this works as expected. # # f(x) maps x axis (discontinuous) to shadow axis coords (continuous linear range [0:1000]) # g(x) maps shadow axis coords to x axis readout # set title "A 'broken' x axis can be defined using 'set nonlinear x'" # Define the broken-axis mapping axis_gap = 25. f(x) = (x <= 100) ? x : (x < 500) ? NaN : (x - 400 + axis_gap) g(x) = (x <= 100) ? x : (x < 100 + axis_gap) ? NaN : (x + 400 - axis_gap) set xrange [15:600] noextend set nonlinear x via f(x) inverse g(x) set xtics 50. set xtics rotate by -90 nomirror set ytics nomirror set border 3 unset key # Creation of the broken axis marks (this should be automated) set arrow 500 from 100, graph 0 to 500, graph 0 nohead lt 500 lw 2 lc bgnd front set arrow 501 from 100, graph 0 length graph .01 angle 75 nohead lw 2 front set arrow 502 from 100, graph 0 length graph -.01 angle 75 nohead lw 2 front set arrow 503 from 500, graph 0 length graph .01 angle 75 nohead lw 2 front set arrow 504 from 500, graph 0 length graph -.01 angle 75 nohead lw 2 front plot 'silver.dat' with yerrorbars lw 2, '' with lines
[ "stackoverflow", "0002081546.txt" ]
Q: jCarouselLite - height? I am using the jCarouselLite jquery plugin to a simple rotate where an image+text is displayed on at a time, with a prev+next button. My problem is that jCarouselLite seems to be inserting a set height for all the elements. My need is that all my pictures are of the same height, but the amount of text can differ - currently jCarouselLite cuts of/hides the text where the are many lines. I want to be able to show all types of texts, no matter how many lines there is - any ideas? A: I know this is an old post, but this is how I sorted out the problem. It's applicable to version 1.0.1 of the carousellite.js code. The issue is the height for the container is set by the first element, rather than iterating through all of the items to find the largest. I adjusted the code accordingly as follows. First, add a new function to the script called max_height: function max_height(el) { // Adapted 25/09/2011 - Tony Bolton - Return height of the largest item.. var _height = 0; $.each(el,function() { var _compHeight = $(this).height(); if (_compHeight > _height) { _height = _compHeight; } }); return parseInt(_height); }; Now, look for the line of code where the list item height is set: li.css({ width: li.width(), height: li.height() }); Change it to the following: li.css({ width: li.width(), height: max_height(li) }); That should sort out the cropping issue. Incidentally this will only work if you initialise the carousel in the window.load event, otherwise the dom won't know how high the container is. A: I'd like to clarify Tony's excellent answer slightly. Not only should the li.css line be modified to use his new function, but that line should also be moved up in the code. This is the original code: var liSize = o.vertical ? height(li) : width(li); // Full li size(incl margin)-Used for animation var ulSize = liSize * itemLength; // size of full ul(total length, not just for the visible items) var divSize = liSize * v; // size of entire div(total length for just the visible items) li.css({width: li.width(), height: li.height()}); ul.css(sizeCss, ulSize+"px").css(animCss, -(curr*liSize)); This is the modified code: li.css({width: li.width(),height: max_height(li)}); var liSize = o.vertical ? height(li) : width(li); // Full li size(incl margin)-Used for animation var ulSize = liSize * itemLength; // size of full ul(total length, not just for the visible items) var divSize = liSize * v; // size of entire div(total length for just the visible items) ul.css(sizeCss, ulSize+"px").css(animCss, -(curr*liSize)); This ensures that the animation accommodates the new list item height.
[ "stackoverflow", "0041522280.txt" ]
Q: How to use regex in Yaml file for Logstash Translate filter? I am trying to use the Logstash Translate Filter to enrich network data that bro is generating and that I'm ingesting into my ELK stack. For example, here is how I was enriching data manually: translate { field => "id.orig_h" destination => "src_comp_name" dictionary => [ "192.168.1.1", "Home_Router", "192.168.1.150", "My_Laptop", "192.168.1.210", "My_Desktop" ] } While this works, it doesn't scale for what I am going to eventually need it for. So I'm trying to move my dictionary to a yaml file and use regex to match IP addresses to assign them tags. So I edited my translate function to: translate { field => "id.orig_h" destination => "src_comp_name" dictionary_path => '/etc/logstash/config/compNames.yaml' } Below is the contents of roughly what I want to do in the yaml file: '^192\.168\.1\.[1-2]$': "Home_Routers" '^192\.168\.1\.1[0-9]{2}$': "Home_Laptops" '^192\.168\.1\.2[0-9]{2}$': "Home_Desktops" This would cause 192.168.1.1/2 to be tagged as routers, anything in the .100-199 range to be tagged as Home_Laptops, and anything from .200-255 to be tagged as "Home_Desktops". I have tried multiple ways of using regex in the Yaml file, but I'm either getting errors like "LogStash::Filters::Translate: can't convert Array into Hash when loading dictionary file at /etc/logstash/config/compNames.yaml"* Or logstash is correctly starting but not tagging traffic that should be matching. Any guidance out there on how to implement regex matching in a yaml file for data enrichment via Logstash Translate Filter? A: Add this to the translate function: "exact" => true, "regex" => true
[ "unix.stackexchange", "0000131609.txt" ]
Q: Using cat to modify ~/.bash_profile seems to remove __git_ps1 compeltely I want my prompt to display the current git-branch when inside of a repo directory. e.g., [desktop repo(master)]$ In my terminal I can type: cat <<EOF >> ~/.bash_profile PS1='\[\e[0;32m\][\h \W\[\e[m\]$(__git_ps1 "(%s)")\[\e[0;32m\]]\$ \[\e[m\]' EOF But the resultant appended text in .bash_profile is: PS1='\[\e[0;32m\][\h \W\[\e[m\]\[\e[0;32m\]]$ \[\e[m\]' the __git_ps1 method is not present in the result. If I manually edit the .bash_profile with vim then source ~./bash_profile, the PS1 statement contains the __git_ps1 method and it works fine. This cat statement is part of a larger 'bootstrapping' script, but I've trimmed out all the irrelevant stuff. I have successfully implemented this on Ubuntu. I am trying to get it running on a CentOS VM. Thanks! A: Try cat << "EOF", this prevents expansion of the dollar function and the quotes.
[ "stackoverflow", "0038363640.txt" ]
Q: Why hash function on two different objects return same value? I used Spyder, run Python 2.7. Just found interesting things: hash(-1) and hash(-2) both return -2, is there a problem? I though hash function on different object should return different values. I read previous posts that -1 is reserved as an error in Python. hash('s') returns 1835142386, then hash(1835142386) returns the same value. Is this another problem? Thanks. A: -1 is not "reserved as an error" in Python. Not sure what that would even mean. There are a huge number of programs you couldn't write simply and clearly if you weren't allowed to use -1. "Is there a problem?" No. Hash functions do not need to return a different hash for every object. In fact, this is not possible, since there are many more possible objects than there are hashes. CPython's hash() has the nice property of returning its argument for non-negative numbers up to sys.maxint, which is why in your second question hash(hash('s')) == hash('s'), but that is an implementation detail. The fact that -1 and -2 have the same hash simply means that using those values as, for example, dictionary keys will result in a hash conflict. Hash conflicts are an expected situation and are automatically resolved by Python, and the second key added would simply go in the next available slot in the dictionary. Accessing the key that was inserted second would then be slightly slower than accessing the other one, but in most cases, not enough slower that you'd notice. It is possible to construct a huge number of unequal objects all with the same hash value, which would, when stored in a dictionary or a set, cause the performance of the container to deteriorate substantially because every object added would cause a hash collision, but it isn't something you will run into unless you go looking for it.
[ "stackoverflow", "0042425929.txt" ]
Q: EF database first code generation missing Key and data annotation For EF 6.1 and above, when I add/reverse engineer-Entity model model/code generation in VS15 & Sql-Server 2k16 Database my entities are missing both Id, and auto increment data-annotations. Saw this and this Question on SO, but no answers, just that its a bug, I am seeking an option to generate the PK Key, Auto Increment. Question: How can I ensure, that the Id key & Auto-increment options are added to the entities during the code generation? There are no data annotations except on the foreign keys! Can I also get EF to generate Composite keys? What I did: In the database, I added the Set primary key on the [Id] col as int, I also set Identity true, seed 1, auto increment 1 E.g. missing primary key //E.g. Reverse Eng. Generated code from ASP table public partial class AspNetUsers { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] public AspNetUsers() { this.AspNetUserClaims = new HashSet<AspNetUserClaims>(); this.AspNetUserLogins = new HashSet<AspNetUserLogins>(); this.AspNetRoles = new HashSet<AspNetRoles>(); } // Missing Primary Key public string Id { get; set; } public Nullable<int> IdNumber { get; set; } ... E.g. 2 Missing both Primary Key & Auto Increment public partial class AuditNetEvent { //Reverse Generated code missing Primary Key & Auto Increment public bigint Id { get; set; } public System.DateTime InsertedDate { get; set; } A: It seems that the tooling doesn't add annotations when the default conventions make them redundant. For an Id column the default is that it's PK and identity. I tried with a table not matching the conventions (deviating PK column name and no identity) and the annotations were added: [Key] [DatabaseGenerated(DatabaseGeneratedOption.None)] public int CstId { get; set; }
[ "mathematica.stackexchange", "0000043706.txt" ]
Q: intersection of two lines with a slope slider I am trying to build an IS/LM model with sliders for a few things including the slope of the IS curve. I am stuck getting the equilibrium ticks and dashed lines to properly follow the intersection of the two lines when the slope is changed. I have tried incorporating my variable i in as many ways as I can think of into the ticks and dashed lines, but continually come up short. I am a newbie at Mathematica and the code is confusing the hell out of me and making the basic math more confusing for me. Help! Manipulate[ Show[ Plot[Tooltip[s + .8 *q, "LM"], {q, 0, 150}, AxesOrigin -> {0, 0}, PlotStyle -> {Thick, Blue}, AxesLabel -> {"GDP", "Interest Rate"}, PlotRange -> {{0, 100}, {0, 100}}, PlotLabel -> IS LM, Ticks -> {{{0.77*d - (0.77*s), "GDP"}}, {{d - i*(0.77*d - (0.77*s)), "r"}}}, BaseStyle -> {FontWeight -> "Bold", FontSize -> 12}], Plot[Tooltip[d - i*q, "IS"], {q, 0, 200}, AxesOrigin -> {0, 0}, PlotStyle -> {Thick, Green}], Graphics[{Dashed, Line[{{0.77*d - (0.77*s), 0}, {0.77*d - (0.77*s), d - i (0.77*d - 0.5 (0.77*s))}}]}], Graphics[{Dashed, Line[{{0, d - i (0.77*d - (0.77*s))}, {0.77*d - (0.77*s), d - i (0.77*d - (0.77*s))}}]}]], {{d, 75, "Fiscal Policy"}, 50, 100, 2}, {{s, 0, "Monetary Policy"}, 0, 100, 2}, {{i, .5, "Interest Sensitivity"}, 0, 5, .1}] A: I am uncertain if this is what you are after. A static baseline plot (reference) starting position I guess could be added. If the aim is simpler this may be helpful: Manipulate[sol = q /. First@Solve[lm[s, q] == is[d, i, q], q]; ysol = lm[s, sol]; tcks = {{{sol, "GDP"}}, {{ysol, "r"}}}; lns = {{Dashed, Line[{{sol, 0}, {sol, ysol}}]}, {Dashed, Line[{{0, ysol}, {sol, ysol}}]}}; Plot[{lm[s, q], is[d, i, q]}, {q, 0, 200}, Ticks -> tcks, Epilog -> lns, PlotRange -> {0, 100}, PlotStyle -> {{Thick, Blue}, {Thick, Green}}], {{d, 75, "Fiscal Policy"}, 50, 100, 2}, {{s, 0, "Monetary Policy"}, 0, 100, 2}, {{i, .5, "Interest Sensitivity"}, 0, 5, .1}, Initialization :> (lm[x_, y_] := x + .8*y; is[x_, y_, z_] := x - y*z)] The tooltips and other style formatting can be adapted as desired.
[ "stackoverflow", "0059194557.txt" ]
Q: Why Bootstrap panel is not working in Blazor client? I compile below code to get a bootstrap panel but no success @page "/test" <h3>test</h3> <div class="panel panel-primary"> <div class="panel-heading">Panel with panel-primary class</div> <div class="panel-body">Panel Content</div> </div> @code { } the project setting is And bootstrap.main.cs is The wwwroot folder looks like this Index.html A: Blazor uses Bootstrap 4 and there .panel was replaced by .card So the basic version becomes this: <div class="card text-primary"> <div class="card-header">Panel with panel-primary class</div> <div class="card-body">Panel Content</div> </div>
[ "stackoverflow", "0042082614.txt" ]
Q: SQLite.swift pod: Swift Compiler Error in Xcode 8.3 beta 2 Project builds fine in Xcode 8.2.1, but in 8.3b2 the pod SQLite.swift produces >18 issues like: Swift Compiler Error Build a shadowed submodule 'Darwin.POSIX.basic' module.modulemap Errors appear to relate to redefinition of basic types such as _int8_t Is there a simple resolution/workaround? A: I was hoping to see this resolved in subsequent betas, but happy to note that this is no longer an issue. I'm not quite sure which of these items actually resolved it for me: Xcode Version 8.3 (8E162) - release version Using SQLite.swift (0.11.2) - I don't think this has changed Clean Build Folder (Cmd-Opt-Shift-K) This issue (suspiciously similar to this post) confirms that 0.11.3 of the pod tests against Xcode 8.3
[ "stackoverflow", "0047268266.txt" ]
Q: How to toggle in a nested list Im trying to be able to toggle these sub menus one at a time, im getting lost in nests and cant quite figure out how to target the correct list item, I found that i should be using find() instead of children() as it can go deeper in the nest but still no luck in getting it working. <ul> <li>Profile</li> <li>Edit</li> <li class="drop-nav"> <a href="#"> See your products</a> <ul> <li class="drop-nav"> <a href="#"> Mens </a> <ul> <li> <a href="#"> jumpers </a> </li> <li> <a href="#"> t shirts </a> </li> </ul> </li> <li class="drop-nav"> <a href="#">Womens</a> <ul> <li> <a href="#"> hoodies </a> </li> <li> <a href="#"> leggings </a> </li> </ul> </li> </ul> </li> </ul> $(".drop-nav").on("click", function(e){ e.preventDefault(); }); li ul{ display: none; } Any help would be much appreciated. Thanks A: You could use $(this).find('ul').eq(0) to get the ul, but I would delegate the changing of the display to the stylesheet, but use javascript to add a class where applicable. This will give you many more options for the design of your dropdown later. $(".drop-nav").on("click", function(e) { e.preventDefault() // don't allow the event to fire horizontally or vertically up the tree e.stopImmediatePropagation() // switch the active class that you can use to display the child $(this).toggleClass('active') }) /* don't target ll list items in you page, be more specific */ .drop-nav > ul { display: none; } .drop-nav.active > ul { display: block; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul> <li>Profile</li> <li>Edit</li> <li class="drop-nav"> <a href="#"> See your products</a> <ul> <li class="drop-nav"> <a href="#"> Mens </a> <ul> <li> <a href="#"> jumpers </a> </li> <li> <a href="#"> t shirts </a> </li> </ul> </li> <li class="drop-nav"> <a href="#">Womens</a> <ul> <li> <a href="#"> hoodies </a> </li> <li> <a href="#"> leggings </a> </li> </ul> </li> </ul> </li> </ul>
[ "stackoverflow", "0040631490.txt" ]
Q: Length of a 2-dimensional array / matrix So I would like to construct a program that receives the elements of two matrices and gives out the product of these two matrices. I experimented a little bit so far, created a matrix and used the "readInts"-manual. First, I would like to make sure that the program actually receives the elements typed in by the user, so I wanted to print out the first matrix as a whole (and then go further, of course). This is included in this code: int rows = readInt("Number of rows: "); int columns = readInt("Number of columns: "); int [][] m = new int[rows][columns]; int [] elements = readInts("Please type in the elements: "); for(int = 0; i < m.length; i++) { print(elements[i], 5); } Now, what I didn't understand yet is how I have to interpret "m.length". After a little bit of testing, I found out that it refers to the number of rows, so for example when I define 3 rows and type in the numbers 1, 2, 3, 4, 5, I receive only 1, 2, 3, so the program cuts off the rest. I guess he actually is supposed to refer to the number of columns, so I'd have to switch [rows] and [columns] when I define m, but that's counterintuitive since you always name the number of rows first. Plus, I don't know whether there would arise other problems with that sooner or later or not. So, is there another way to do this without switching [rows] and [columns] at the beginning? A: since you know the rows and columns you can do 2 for loops. int rows = readInt("rows"); int columns =readInt("columns"); int [][] m = new int[rows][columns]; for (int i = 0; i < rows; i++) { int n[]=readInts("enter 3 numbers:"); for (int k = 0; k < columns; k++) { m[i][k] = n[k]; } } There is no need to use the scanner like i did(isn't working properly here). yet this should give you the desired result if you read the strings right
[ "stackoverflow", "0063356984.txt" ]
Q: How to create a "method" in a telegram bot Hi there i'm tryng to create a bot to automate amazon search,and I wanted it to be very simple to use. I Wanted it to act like BotFather when you create a new bot: Ask for Bot name Input and get bot name Ask for bot tag Input and get bot tag Create bot I don't know where to start code done so far: keyboard= types.ReplyKeyboardMarkup(row_width=1) help_btn = types.KeyboardButton('Aiuto') min_price = types.KeyboardButton('Prezzominimo') max_price = types.KeyboardButton('Prezzomassimo') range_price = types.KeyboardButton('Range') keyboard.row(min_price) keyboard.row(max_price) keyboard.row(range_price) keyboard.row(help_btn) bot = telebot.AsyncTeleBot(TOKEN,'HTML') if bot_is_active: @bot.message_handler(commands=["start"]) def main_menu(message): bot.send_message(message.chat.id,"Benvenuto,questo bot ti permette di cercare articoli su Amazon",reply_markup=keyboard) pass @bot.message_handler(func=lambda message:True) def kb1_handler(message): if message.text == 'Aiuto': bot.send_message(message.chat.id,Help message) elif message.text == 'Range': bot.send_message(message.chat.id,"Cosa cerchi?") #range_set = True elif message.text == 'Prezzominimo': bot.send_message(message.chat.id,"Cosa cerchi?") min_set = True else: bot.send_message(message.chat.id,"Cosa cerchi?") #max_set = True pass if min_set: bot.send_message(message.chat.id,"trovato") pass docs:https://github.com/eternnoir/pyTelegramBotAPI A: I woud suggest checking out the library python-telegram-bot and their very informative wiki. The code samples include one for a conversation bot which sounds like what you're describing
[ "stackoverflow", "0002724327.txt" ]
Q: Render page as a picture I have question to Java or C# programmers. I want to render some pages in various browsers mainly Firefox and IE and save it as a picture. I have not any serious experience in Java/.Net. Is there any libs/tools for such tasks? I thought about some FF extensions for example but I don't know how to do it in IE. Is the in .Net some libs for dealing with it? Maybe some ActiveX? Any sugestions? A: http://www.vesic.org/english/blog/winforms/render-html-to-quality-jpeg/
[ "stackoverflow", "0023906826.txt" ]
Q: Excel Source failing the pre-execute phase and returned error code 0xC0207013, expecting parameters SELECT UCase(LTRIM(RTRIM(c.F2))) AS Name,c.F2 AS NameProperCase,c.F3 As Initials, c.F4 As CountryCode FROM `Country$` c I have the above query in an SSIS Excel Source as its SQL command. In the Excel Source Editor, i can successfully click preview and see the sample data returned by the query from the Excel file. I have configured my Excel Connection Manager that the First row DOES NOT have column headers. When i try to execute my package, it fails at this Excel source and the errors below are logged to my text Log file. The SQL command requires 3 parameters, but the parameter mapping only has 0 parameters. The SQL command requires 3 parameters, but the parameter mapping only has 0 parameters. The SQL command requires 3 parameters, but the parameter mapping only has 0 parameters. "Excel Source 2" (2303) failed the pre-execute phase and returned error code 0xC0207013. "Excel Source 2" (2303) failed the pre-execute phase and returned error code 0xC0207013. "Excel Source 2" (2303) failed the pre-execute phase and returned error code 0xC0207013. If i reconfigure the Excel Connection Manager that the First row HAS column names, and then replace the Excel source query with the one below, the package runs fine with out errors SELECT UCase(LTRIM(RTRIM(c.Name))) AS Name,c.Name AS NameProperCase,c.Initials, c.CountryCode FROM `Country$` c I don't have any parameters in the query but i am getting "The SQL command requires 3 parameters, but the parameter mapping only has 0 parameters." in the log file. The only difference between the failing and succeeding Excel sources is the setting that First row has column names (Success with out error), AND First row does NOT have column names (Fails with errors posted above) A: I haved faced the same issue, First i ran package by changing excel connection manager properties-> FirstRowHasColumn to False. I could preview the data, but only at run time, this error came. After few googling no answer. Then found out myself. Reason was i did not change excel connection string in config file or in properites. After changing connection string HDR to NO, it worked fine. HDR=NO Right click excel connection manager-> properties-> connection string locate the value HDR. if HDR=YES then change it to NO. Ensure the same thing is done in config file as well if you have one. Cheers!
[ "stackoverflow", "0062759640.txt" ]
Q: Runtime mapping of values to types I have no hope that what I'd like to achieve is possible in C++, but maybe I'm wrong since my previous question about bidirectional static mapping got an unlikely answer. I have a set of certain types, an enumeration with keys representing the types, and a template handle type that accepts mentioned types as template parameters. struct foo {}; struct bar {}; enum class types { foo, bar }; template<typename T> struct qux {}; I'd like to be able to map types::foo to foo at runtime. Most of the time foo would be used as the template parameter of qux, so mapping of types::foo to qux<foo> is fine too but I feel that if one is possible, then the other is too. I'm mentioning this because it's important to note that qux is a simple handle-like type that only consists of an index and is passed around by value and there are a lot of template functions that take qux<T> as a parameter. This makes polymorphism - a standard solution in such cases - not an obvious choice. Sometimes though I need to create a qux<T> while having only a variable holding a types value, so it has to be mapped to the proper type somehow. What I've been doing up until now is just switching each time I have to do this but I hit the point where there's too many switches to maintain. I don't see a better solution, so what I'm looking to do is create a single swich or other mechanism in the code that will take types value and return... something that will let me create a qux<T> with related type. Ultimately it'd work like this. template<typename T> void baz(qux<T> q) { /* ... */ } // Somewhere else... types t = get_type(); // Read type at runtime. baz(create_object(t)); // Calls adequate baz specialization based on what value t contains. I don't know how to implement the create_object function though. What I tried already: std::variant with careful use of emplace and index - quickly hit the problem of being unable to return different types from a single function; clever use of conversion operators - doesn't allow me to call a proper templated function taking qux<T> as a parameter since it's not decided which specialization should be called; external polymorphism - unable to return different types; modified template specialization loop proposed in this answer that looked for proper types value and returned mapped type - this failed due to being unable to return different types - or called a lambda with auto parameter - which also failed as it tried to specialize the lambda multiple times. A: std::visit is your friend here. Convert types to a certain std::variant/replace it with an alias to that type: // or std::type_identity template<typename T> struct proxy { using type = T }; template<typename T> constexpr inline proxy<T> proxy_v{}; using var_types = std::variant<proxy<foo>, proxy<bar>>; var_types mk_var_types(types t) { switch(t) { case types::foo: return proxy_v<foo>; case types::bar: return proxy_v<bar>; } } /write a custom std::visit-like for types (all three choices are equivalent, but replacing types is the shortest) template<typename F> decltype(auto) visit(F &&f, types t) { switch(t) { case types::foo: return std::forward<F>(f)(proxy_v<foo>); case types::bar: return std::forward<F>(f)(proxy_v<bar>); } } This can be used to implement a std::variant-of-quxs-returning create_object auto create_object(var_types t) { std::visit([](auto p) -> std::variant<qux<foo>, qux<bar>> { return qux<typename decltype(p)::type>{} };, t); } // or auto create_object(types t) { return create_object(mk_var_types(t)); } // or auto create_object(types t) { return visit([](auto p) -> std::variant<qux<foo>, qux<bar>> { return qux<typename decltype(p)::type>{}; }, t); } Which can be used to call baz types t; // or var_types t; std::visit([](auto &&q) { baz(std::forward<decltype(q)>(q)); }, create_object(t)); Of course, create_object isn't necessary in this case visit([](auto p) { baz(qux<typename decltype(p)::type>{}); }, /*mk_var_types(*/t/*)*/); Repeating foo and bar everywhere is itself a pain. This can be rectified: template<template<typename> typename F> using variant_with = std::variant<F<foo>, F<bar>>; using var_types = variant_with<proxy>; using a_qux = variant_with<qux>; a_qux create_object(a_type); // etc.
[ "stackoverflow", "0061361136.txt" ]
Q: Use multiple ID'S in DOM Javascript the main idea is to try to disable multiple checkboxes using multiple ID'S for example using documentGetElementById Each id belongs to a checkbox function main(){ var a = document.getElementById("actual").value; var b = document.getElementById("destination").value; if (a == "Jamaica" && b == "Paris"){ document.getElementById("A", "B", "C", "D").disabled = true; // occupied seats } } A: You have three options: 1.) Multiple calls document.getElementById("A").disabled = true; document.getElementById("B").disabled = true; // and so on... 2.) Loop over the IDs ["A", "B", "C", "D"].forEach(id => document.getElementById(id).disabled = true) 3.) You find a selector that matches all of them and use document.querySelectorAll. IDs have to be unique, so that won't suffice, but let's say all checkboxes on the page need to be disabled: document.querySelectorAll("input[type='checkbox']").forEach(elem => elem.disabled = true); For this option, you can alternatively use other CSS selectors that would select the desired checkboxes, like a class name.
[ "stackoverflow", "0028902256.txt" ]
Q: python - reference method of object defined in main In python 3.4.2 is there a way to call, from any class, a method of an object that was defined in main() ? I am not very skilled in OOP so perhaps my understanding is wrong? Is there a better way to accomplish this goal? Below is pseudo-code; the overall goal is, in PyQt, to be able to call a method of the main window object, from inside a method of an object of any arbitrary other class. class A(object): myVar=0 def __init__(self): pass def doit(): print(self.myVar) class B(object): def __init__(self): A.doit() # uses the class variable, should print '0' a1.doit() # uses the object variable, should print '1' def main(): a1=A() a1.myVar=1 b1=B() UPDATE: Thanks to KronoS for the response. After looking at that and some more trial and error, here's an example I came up with of calling a method of an ancestor object (even if the classes have no inheritance relationship): class A(object): def __init__(self): b1=B(self) def do_stuff(self): print("Stuff is done") class B(object): def __init__(self,parent): self.parent=parent # needed so children of this object can reference this object's parent c1=C(self) class C(object): def __init__(self,parent): parent.parent.do_stuff() # or actually make parent an object of this instance; # necessary if children of this object will reference this object's parent: #self.parent=parent #self.parent.parent.do_stuff() def main(): a1=A() if __name__ == '__main__': main() However I'm still fairly new to this, so, let me know if there's a better way, or, if there's some reason why this whole concept should be unnecessary or such. A: I've made some annotations to your current code. HOWEVER, the simple answer to your question is that you cannot reference another class without passing in an instance of that class: class A(object): myVar=0 def __init__(self): pass def doit(self): # <--- Missing 'self' here print("A.doit(): {}".format(self.myVar)) class B(object): def __init__(self, other): #A.doit() # This will not work. It's not a class function now that we've added 'self' print("B.__init__: {}".format(A.myVar)) other.doit() # other is the passed in object def main(): a1=A() a1.myVar=1 b1=B(a1) print("main: {}".format(A.myVar)) if __name__ == "__main__": main() # Out # B.__init__: 0 # A.doit(): 1 # main: 0
[ "stackoverflow", "0029408463.txt" ]
Q: Kendo validation in table cell show on top (z-index) my issue is that the validation message of kendo within a grid (inside a td) is hidden inside the grid. Is there anyway I can show it on top of everything? I tried with position:relative, z-index etc. but nothing worked. Screenshot of issue: and plunker: http://embed.plnkr.co/Wyf24V/preview Add a few entries, then add an empty string and save. the validation message will be hidden inside grid. A: For the record I solved it using the following code, every time a row is updated: var gridContent = grid.find('.k-grid-content'); if (gridContent.find('.k-widget.k-tooltip.k-tooltip-validation.k-invalid-msg').length > 0) { gridContent.css("overflow", "visible"); } else { gridContent.css("overflow", "auto"); }
[ "stackoverflow", "0050404040.txt" ]
Q: Displaying Elements of Multidimensional Array of Strings [Java] I am new in programming. Need to have your advise to shorten improve my code below. public class Exercise4 { public static void main(String[] args) { // TODO Auto-generated method stub String[][] info = {{"010","John","Male","21"}, {"011","Mary","Female","25"}, {"012","Joseph","Male","24"}, {"013","Peter","Male","22"}}; for(int i = 0; i < 4; i++) { for(int j = 0; j < 4; j++) { if(j == 0) { System.out.print("ID: "); } else if(j == 1) { System.out.print("Name: "); } else if(j == 2) { System.out.print("Gender: "); } else if(j == 3) { System.out.print("Age: "); } System.out.println(info[i][j]); } System.out.println(); } } } This will display the following output. Is there any way to improve/shorten my code? I think there's a way to shorten it but I just couldn't figure it out. Output: A: You can do something like this - List<String> headerList = Arrays.asList(new String[]{"ID","Name","Gender","Age"}); List<String[]> infoList = Arrays.asList(info); for(String[] s: infoList){ int count = 0; for(String header : headerList){ System.out.println(header+": "+s[count]); count++; } } Note: Headers length and rows length should be same.
[ "stackoverflow", "0048390673.txt" ]
Q: Can not discard all changes Xcode 2 and we are working on a shared Github Project. Sadly I uploaded the UserInterfaceState.xcuserstate file to Github. My Partner just uploaded a version of our App witch works fine but makes it impossible for me to make changes. When I try to commit and push it failed because "The local repository is out of date" which makes sense. So I discard all changes and try to pull. But pulling failes because I make changes in UserInterfaceState.xcuserstate right after I discard changes. So basically I need to remove UserInterfaceState.xcuserstate from my Github upload. I tried to delete the file on Github webend wich worked but doesn't solved the problem. Then I tried to do something with the .gitignore file. I generated one by using touch .gitignore but I sadly don't find the file and even when I don't know exactly what to do with it. A: If git is already tracking the file, adding it to the .gitignore won't do much - you'll need to remove it from being tracked first. Firstly, in Terminal, cd to your project directory and run git status. If there's any file aside from your UserInterfaceState.xcuserstate that's changed, you'll likely want to save a copy of that file before continuing. With Xcode closed, do a hard reset to roll back any changes that you might have made from your last pull/commit. (Note: this will erase anything you've been working on in that time, although from the text of your question it seems as though you're alright with this). git reset --hard HEAD From there, ensure git will no longer track your UserInterfaceState.xcuserstate file: git rm --cached <path>/<to>/UserInterfaceState.xcuserstate Then, commit and push the change to origin: git commit -m "Removed file that shouldn't be tracked" git push origin <branchname>
[ "stackoverflow", "0015683233.txt" ]
Q: Razor file name with a dash I need my page names to have a dash in the name. E.G our-vision I'm new to MVC & c# so I may be going about all this wrong. Here is my controller: public class HomeController : Controller { // // GET: /Home/ public ActionResult Index() { return View(); } // // GET: /our-vision/ public ActionResult ourVision() { return View(); } } And then in my views, I have Views/Home/ourVision.cshtml. When I compile and go to http://localhost/ourVision it works, but when I go to http://localhost/our-vision it does not. Here is my routing: routes.MapRoute( "Default", // Route name "{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults ); A: You'll need to do a few things in order to achieve that. First, to achieve our-Vision, you'll need to give your action method the ActionName attribute, like so: [ActionName("our-Vision")] public ActionResult ourVision() Next, you'll have to rename your ourVision.cshtml view to be our-Vision.cshtml Finally, whenever you're using Url.Action or ActionLink, you need to use our-Vision and not vision, like so: Url.Action("our-Vision", "Home");
[ "stackoverflow", "0044664041.txt" ]
Q: Programming Tic Tac Toe in Java with ImageIcons - winningCondition I need help because im a beginner in Java programming. I am programming Tic Tac Toe for University at the moment and i have some problems because i wanted to use some smileys instead of X's & O's. But i don't know how to compare them by Searching for Winners, so i used letters. But you can see the letters together with the Smileys in the playfield and i think this is not the best solution. Maybe some of you have better suggestions and reviews for my program. I copied the images devil.png and sun.png in my TicTacToe src folder. import java.awt.GridLayout; import java.awt.event.*; import javax.swing.*; public class Gui implements ActionListener { // Variables private static int[][] winCombos = new int[][] //Possible win combinations { {0, 1, 2}, {3, 4, 5}, {6, 7, 8}, //horizontal wins {0, 3, 6}, {1, 4, 7}, {2, 5, 8}, //vertical wins {0, 4, 8}, {2, 4, 6} //diagonal wins }; static JButton btn[] = new JButton[9]; private int count = 0; private int xscore = 0; private int oscore = 0; private String letter = ""; private boolean win = false; private ImageIcon devil; // devil= spieler X private ImageIcon sun; // sun = spieler O public Gui() { // Create Window JFrame jf = new JFrame(); jf.setSize(400, 400); jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jf.setLocationRelativeTo(null); jf.setResizable(false); jf.setTitle("Tic-Tac-Toe Playfield"); jf.setLayout(new GridLayout(3, 3)); devil = new ImageIcon(getClass().getResource("devil.png")); //X sun = new ImageIcon(getClass().getResource("sun.png")); //O // Add Buttons to the Window for (int i = 0; i < btn.length; i++) { btn[i] = new JButton(); btn[i].setVisible(true); btn[i].setFocusPainted(false); btn[i].addActionListener(this); jf.add(btn[i]); } jf.setVisible(true); } public void actionPerformed(ActionEvent a) { count++; //Who's turn is it if(count % 2 == 0) { letter = "O"; oscore++; } else { letter = "X"; xscore++; } //Change button to letter if(letter == "X") { JButton pressedButton = (JButton)a.getSource(); pressedButton.setIcon(devil); pressedButton.setEnabled(false); } else if(letter == "O") { JButton pressedButton = (JButton)a.getSource(); pressedButton.setIcon(sun); pressedButton.setEnabled(false); } //Search for Winner for(int i=0; i<=7; i++) { if(btn[winCombos[i][0]].getIcon() !=null && btn[winCombos[i][0]].getIcon().equals(btn[winCombos[i][1]].getIcon()) && btn[winCombos[i][1]].getIcon() !=null && btn[winCombos[i][1]].getIcon().equals(btn[winCombos[i][2]].getIcon()) ) { win = true; } } //Dialog at the end of the game if(win) { JOptionPane.showMessageDialog(null, letter + " wins the game"); System.exit(0); } else if(count == 9 && !win) { JOptionPane.showMessageDialog(null, "There is no winner."); System.exit(0); } }} A: MadProgrammers advice here Step back for a moment. You need to do is separate the logic from the presentation, this allows you to consistently model the logic and allow the presentation to present in whatever form it wants to. This is the basic functionality of the "model-view-controller" paradigm. With this, you model your data (the game and it's state) and then allow the view (the UI) to present it in what ever manager it wants to. This means the logic for determining when a player wins a game is determined by the model is definitely the right way to go and the how you should consider designing future projects. However I assume that you perhaps are yet to cover MVC and other design patterns in your course. The problem you are now getting will be NullPointerException in your loop as on the first click most of the buttons will have no icon assigned, so when you then try to call .equals() on that null object the exception occurs. So the simple fix is you will need to check for null icons before you can do the equality check. Edit Before you call the equals! if(btn[winCombinations[i][0]].getIcon() != null && btn[winCombinations[i][0]].getIcon().equals(.... You will also need to do this for btn[winCombinations[i][1]].getIcon() End Edit A more concise way might be to use the Objects.equals() method if you are able To explain more: When the Exception occurs, the method breaks - so it occurs in your for loop so then the code below that will not get executed. Try adding this below your loop: System.out.println("Reached here!"); And you will notice that it is only ever printed once all the buttons have been pressed. And to help you check more visually, you could add a try catch around your loop - note that this is not ideal operation - but will help you diagnose the problem more visually. try { // your win check loop } catch (Exception e) { e.printStackTrace(); JOptionPane.showMessageDialog(null, "Oh no!:\n" + e); }
[ "stackoverflow", "0013371359.txt" ]
Q: Weird 127.0.0.1 & localhost resolution when running Apache on Mac OS X with POW/Powify installed I could not figure out why http:// localhost would resolve and http:// 127.0.0.1 would not resolve, when i was running apache, made no sence. While when running POW both would resolve. I ve set up proper mapping in hosts file, and created VirtualHost entry in httpd-vhosts.conf file with defined ServerName that I have already mapped to 127.0.0.1. VirtualHost entry is for reverse proxy set up. Every time i would run localhost, VirtualHost entry would work, but anytime i would try to access 127.0.0.1 or mapped domain i would be out of luck. In my case due to project(s) set up http:// localhost is not sufficient to run dev enviroment and i need mapped entry in hosts file to function. I also use POW for my rails and sinatra apps. Had previously encountered POW issues, and to start and shutdown POW server I have installed gem Powify. Very convinient, I thought, and assumed when i run "powify server stop", that it would take care of things, which it did, for localhost resolution at least. So how to deal with this? I ended up uninstalling POW. So the simple solution for this issue, is to completely uninstall POW, apparently due to configuration POW sets up I ended up dealing with this problem. Due to lack of knowledge behind the scenes of what actually happens I would appreciate if some one could point out inner workings. I read up some of the articles on how to set up POW along side Apache, but would appreciate very much if someone could explain why exactly this behavior happens. A: Ended up being about powify not removing the firewall exception and just stopped pow instance to free up some memory and processing power. Still need to uninstall pow for firewall rule to be removed. So that you can use apache properly.
[ "askubuntu", "0000030988.txt" ]
Q: How do you set the title of the active gnome-terminal from the command line? Is there a way to set the gnome-terminal title from within the terminal itself without having to right click on the tab. Something like: active-terminal --title "Foo" There was a related question previously with an answer that almost lets you do this: How to change Gnome-Terminal title? but that doesn't set the gnome-terminal tab title only the window title. A: The following will set the terminal's title to "New terminal title": echo -en "\033]0;New terminal title\a" You will probably also have to change the environment variable PS1, first though, otherwise your changes won't show up because it will reset the title after each command. The default .bashrc that ships with Ubuntu contains the following line: PS1="\[\e]0;${debian_chroot:+($debian_chroot)}\u@\h: \w\a\]$PS1" ... the "\e]0;" code tells it to write everything up to the "\a" in both the title and icon-name properties. You need to remove that and set it to something like this (i.e. without the \e]0; code): PS1="${debian_chroot:+($debian_chroot)}\u@\h \w\a$ " Then any changes that you make with the above echo command will change the terminal title. If you're going to use this a lot, you can throw it into a function in your ~/.bashrc file: set_term_title(){ echo -en "\033]0;$1\a" } Then you can just set the title to "kittens" from the command line by doing: set_term_title kittens (You have to restart bash though after editing .bashrc, for your changes to take effect)
[ "stackoverflow", "0018665751.txt" ]
Q: Using Cookies in Laravel 4 How do you use cookies in Laravel 4? I'm sure it's simple and something just isn't clicking with me but I need a little help. As far as I can tell, you have to create a cookie like this: $cookie = Cookie::make('test-cookie', 'test data', 30); Then, aside from returning a custom response, how do you set it? What good is setting it with a custom response? When would I ever want to do this? What if I want to set a cookie and return a view? What good does return Response::make('some text')->withCookie('test-cookie') actually do me aside from showing me how to use withCookie()? Like I say, I'm probably just missing something here, but how would I use a cookie in a practical way... ...like somebody enters info, logs in, etc and I'd like to set a cookie and take them to a page made with a view? A: To return a cookie with a view, you should add your view to a Response object, and return the whole thing. For example: $view = View::make('categories.list')->with('categories', $categories); $cookie = Cookie::make('test-cookie', 'test data', 30); return Response::make($view)->withCookie($cookie); Yeah, it's a little bit more to write. The reasoning is that Views and a Response are two separate things. You can use Views to parse content and data for various uses, not necessarily for sending to the browser. That's what Response is for, and why if you want to set headers, cookies, or things of that nature, it is done via the Response object. A: This one is what I prefer to use: at any time, you can queue a cookie to be sent in the next request Cookie::queue('cookieName', 'cookieValue', $lifeTimeInMinutes); A: As described in the other answers, you can attach Cookies to Response/Views/Redirects simply enough. $cookie = Cookie::make('name', 'value', 60); $response = Response::make('Hello World'); return $response->withCookie($cookie); or $cookie = Cookie::make('name', 'value', 60); $view = View::make('categories.list'); return Response::make($view)->withCookie($cookie); or $cookie = Cookie::make('name', 'value', 60); return Redirect::route('home')->withCookie($cookie); But you don't need to attach your Cookie to your response. Using Cookie:queue(), in the same way you would use Cookie::make(), your cookie will be included with the response when it is sent. No extra withCookie() method is needed. Source: http://laravel.com/docs/requests#cookies
[ "travel.stackexchange", "0000040452.txt" ]
Q: Safety in Warsaw Poland Just want to be prepared, with no intention of judging or whatsoever, I have some questions about safety in Warsaw: Is it safe to stay in a dorm? I've read some reviews where the person get robbed when asleep, some strangers came in and searched jeans for keys and open the locker, look for cash and valuables. What time during the day is it safe for a female to walk alone? A: I've stayed in Warsaw for a week as a tourist last year and slept in many dorms in central/eastern Europe. Is it safe to stay in a dorm? First of all: check the reviews of the dorm you've selected (there are many websites to do that). It'll give you an idea of the "risk" encountered. Security may vary a lot depending on the location of the building. Warsaw is as safe as other European capitals. But I suggest you take several precautions so that you're not robbed of your valuables : Do not leave your belongings without surveillance Use locks For instance: before going to bed put all your belongings in your backpack. Lock it up, tie your bag up to the bed, hide it under the bed. Keep the key with you. This will protect you against thieves who are most of the time looking for easy targets. What time during the day is it safe for a female to walk alone? For sure, no problems in the city center during the day. A: Sleeping in dorms / hostels Relating dorms specifically in Warsaw I can't answer but I have stayed in all kind of dorms and never had any trouble. Of course you hear stories and strange things really happen. I remember a guy once, in the next room, whose belongings were stolen. This was classified as a safe hostel by the reviews. In the end it's up to you and your practices. You are in a shared space with unknown people. You should either carry or secure your most valuable belongings (ID, Passports, etc. included). In principle no one is going to steal a bag of dirty laundry but if you walk around showing your latest iWhatever, etc. someone might actually think it's worth it to break or take your bag/lock. In general the more valuable things you leave unattended/show off the biggest is the risk. Mitigation is up to you. Side note about hostels: Locks are not always safe. Some are very easy to break. In some hostels you are allowed to leave your most valued goods at the reception. Security in Warsaw I was there this year. It's a perfectly normal city. It felt very safe even at night. At least around the center where I spent most of the time. I was staying in the suburbs and even during the commute in public transport, by night, it seemed fine. Again, common sense is the most important thing here. Don't put yourself in strange places / situations and you should be safe. A: I live in Warsaw whole my life. I can't answer on question 1 because I've never slept in dorm in Warsaw :) With regard to question 2 I think it's safe city but it's worth to be watchful as there are pickpockets. At night you can see many drunk people who can behave loud, sometimes you can see some street fight but I was never afraid someone could beat me. I had one unpleasant situation at night, when some man forced me to give him my phone, telling that he has a knive. Given that I live here 28 years I think one bad situation is not much but I try to have my eyes at the back of my head, mainly at night.
[ "apple.stackexchange", "0000118265.txt" ]
Q: In Terminal, when the the “cd” command is called, libwww-perl's “head” command is also executed Currently, in Terminal, when I execute a cd command, it also executes LWP's head command. A copy of the Terminal output follows: laptop:bin user$ cd ~ Unknown option: n Usage: head [-options] <url>... -m <method> use method for the request (default is 'HEAD') -f make request even if head believes method is illegal -b <base> Use the specified URL as base -t <timeout> Set timeout value -i <time> Set the If-Modified-Since header on the request -c <conttype> use this content-type for POST, PUT, CHECKIN -a Use text mode for content I/O -p <proxyurl> use this as a proxy -P don't load proxy settings from environment -H <header> send this HTTP header (you can specify several) -u Display method and URL before any response -U Display request headers (implies -u) -s Display response status code -S Display response status chain -e Display response headers -d Do not display content -o <format> Process HTML content in various ways -v Show program version -h Print this message -x Extra debugging output laptop:bin user$ I've reviewed the ~/.bash_profile and ~/.bashrc but there are only three export statements and no alias or something like that. It's as follows: [[ -s "/Users/user/.rvm/scripts/rvm" ]] && source "/Users/user/.rvm/scripts/rvm" # This loads RVM into a shell session. ### Added by the Heroku Toolbelt export PATH="/Applications/XAMPP/xamppfiles/bin:/usr/local/heroku/bin:$PATH" export PATH=/Users/user/bin/Sencha/Cmd/3.1.2.342:$PATH export SENCHA_CMD_3_0_0="/Users/user/bin/Sencha/Cmd/3.1.2.342" export PATH=$PATH:/Applications/acquia-drupal/drush From reading, it seems that installing LWP might have overwritten the /usr/bin/head command, but I've checked and it's the OSX one. However, when I call head from Terminal, it invokes the LWP head command instead. Per patrix's request, here are the contents of ~/.rvm/scripts/rvm: http://pastebin.com/7rZVQAcy I'll keep out trying things, and I'll update the question with new information if relevant. Additional information: laptop:dir user$ alias cd -bash: alias: cd: not found laptop:dir user$ which cd /usr/bin/cd laptop:dir user$ which head /Applications/XAMPP/xamppfiles/bin/head The output of echo "$PS1"; echo "$PROMPT_COMMAND" is: \h:\W \u\$ update_terminal_cwd; The output of type -a update_terminal_cwd is: update_terminal_cwd is a function update_terminal_cwd () { local SEARCH=' '; local REPLACE='%20'; local PWD_URL="file://$HOSTNAME${PWD//$SEARCH/$REPLACE}"; printf '\e]7;%s\a' "$PWD_URL" } The output of type -a cd is: cd is a function cd () { if builtin cd "$@"; then __rvm_do_with_env_before; __rvm_project_rvmrc; __rvm_after_cd; __rvm_do_with_env_after; return 0; else return $?; fi } cd is a shell builtin cd is /usr/bin/cd A: I am going to assume you are using bash. So in that case when you just type cd it should be running the bash built-in. This is what has the problem. To confirm this try using the external version - at the command prompt type /usr/bin/cd and you should go to your home directory with no problems. Now let's check what the other cd might be up to. type -a cd should give us cd is a shell builtin cd is /usr/bin/cd which head should give us /usr/bin/head alias might give us a long list but nothing pointing towards an alias for cd The CD environment variables should have sane entries: CDARGS_NODUPS=1 CDARGS_SORT=0 CDPATH='.:~:~/bin:~/dev:/usr:/' The same with: PROMPT_COMMAND='history -a; history -n; printf "\e]1;${PWD}\a"' PS1='\[\033[34m\]\h:\W \u$\[\033[0m\] ' SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor If all that is OK then my money would be on cd being redefined by a builtin function that has gone pear shaped. At the command line set | less will allow you to page through a dump of all your shell variables, aliases and functions. If you type / you can search through the file for cd (notice the space) and see if that is happening. Once you have discovered that "someone" - in your case rvm - is defining a shell function called cd then you can either uninstall the culprit or find where it does the nasty work and change the name of the function to something like 'rcd' instead of 'cd'. As the shell function is listed first in the output of type the builtin cd is ignored except where it is getting called by the function (that's what the builtin cd in the function definition is doing - calling the builtin version). I'd almost guarantee that the function is defined in /Users/user/.rvm/scripts/rvm. I'd start by uninstalling rvm and then reinstall to see if that fixes it. Are you installing it using MacPorts or Homebrew?
[ "gaming.stackexchange", "0000181420.txt" ]
Q: Can underground pools have windows between them and basements? I've seen videos of people making pools on the second floor (and higher up) in houses, and put large windows in them so you could see your sims swimming from the other side of the window. I tried this but underground: building a basement bordering on a pool and putting a window in between them. But for some reason I am unable to put them next to one another: there stays a square in between them with a message from the game. Am I doing it wrong, or is it impossible to do in the first place? A: Yes this is possible but only with cheats that allow you to place things without restrictions. open the cheatconsole and type moveobjects on. Now you can place everything wherever you want without restrictions. Please be aware that cou can delete items that normally cannot be deleten or sold such as your trashcan or sims themself. You disable this cheat mode by restarting your game or typing moveobjects off in your cheat console. Have fun with your non-common placed windows.
[ "stackoverflow", "0033081090.txt" ]
Q: JavaScript - how to directly call a function from .js file without providing it's reference I would like to invoke function without providing the .js file name where this function is stored. In helpers.js file have function like this (it's not the only function in this file) : exports.clickOn = function (element) { browser.wait(EC.presenceOf(element), waitTimeout).then(function () { browser.wait(EC.visibilityOf(element), waitTimeout) }).then(function () { element.click(); }); }; var EC = protractor.ExpectedConditions; var waitTimeout = 10000; Function is called in spec.js file in following way: var InitPage = require('../pages/init_page.js'); var LogInToSystem = require('../helper.methods/test_with_system_authentication'); var Helpers = require('../helper.methods/helpers.js'); describe('Test -> my test', function () { var EC = protractor.ExpectedConditions; var waitTimeout = 10000; var helper = Helpers; beforeEach(function () { LogInToSystem.AsAdmin(); var initPage = new InitPage; helper.clickOn(initPage.usersButton); }); I would like to call clickOn function without helper. - just clickOn(initPage.usersButton); - in java I could just import static this exact method but js do not allows on it. Could anyone advise how ? A: Since this is protractor-specific, you can make a function available globally using global: onPrepare: function () { var helpers = require('../helper.methods/helpers.js'); global.clickOn = helpers.clickOn; // ... },
[ "stackoverflow", "0020398499.txt" ]
Q: Remove last argument from argument list of shell script (bash) This question concerns a bash script that is run in automator osx. I am using automator actions to get and filter a bunch of file references from the finder. Then I append to that list the name of the parent folder, also via an automator action. Automator then feeds these arguments to an action called "run shell script". I am not sure exactly how automator invokes the script but the argument list looks like this when echoed with: echo "$@" /Volumes/G-Raid/Online/WAV_TEST/Testbok 50/01/01000 43-001.wav /Volumes/G-Raid/Online/WAV_TEST/Testbok 50/02/02000 43-002.wav /Volumes/G-Raid/Online/WAV_TEST/Testbok 50/03/03000 43-003.wav /Volumes/G-Raid/Online/WAV_TEST/Testbok 50 In this case path to 3 files and a folder. In the shell script I launch an application called ripcheckc* with the args passed from automator minus the last argument(the folder) in the list. I use this to remove the last argument: _args=( "$@" ) unset _args[${#_args[@]}-1] And this is echo $_args: /Volumes/G-Raid/Online/WAV_TEST/Testbok 50/01/01000 43-001.wav /Volumes/G-Raid/Online/WAV_TEST/Testbok 50/02/02000 43-002.wav /Volumes/G-Raid/Online/WAV_TEST/Testbok 50/03/03000 43-003.wav Same as before but without the folder. Now, if I run ripcheckc with "$@" as argument it works (but fails later on because of that last path in the argument list) If I use ${_args[@]} the application will just abort silently. When I echo $@ and _args the output looks identical except for the last argument. My question is - what is the difference between $@ and $_args that make the first valid input and the second not? *The application is ripcheckc I hope my question makes sense. EDIT: Solved. A: I have used this bash one-liner before set -- "${@:1:$(($#-1))}" It sets the argument list to the current argument list, less the last argument. How it works: $# is the number of arguments $((...)) is an arithmetic expression, so $(($#-1)) is one less than the number of arguments. ${variable:position:count} is a substring expression: it extracts count characters from variable starting at position. In the special case where variable is @, which means the argument list, it extracts count arguments from the list beginning at position. Here, position is 1 for the first argument and count is one less than the number of arguments worked out previously. set -- arg1...argn sets the argument list to the given arguments So the end result is that the argument list is replaced with a new list, where the new list is the original list except for the last argument. A: Assuming that you already have an array, you can say: unset "array[${#array[@]}-1]" For example, if your script contains: array=( "$@" ) unset "array[${#array[@]}-1]" # Removes last element -- also see: help unset for i in "${array[@]}"; do echo "$i" done invoking it with: bash scriptname foo bar baz produces: foo bar A: You can also get all but the last argument with "${@:0:$#}" which, honestly, is a little sketchy, since it seems to be (ab)using the fact that arguments are numbered starting with 1, not 0. Update: This only works due to a bug (fixed in 4.1.2 at the latest) in handling $@. It works in version 3.2.
[ "stackoverflow", "0031328043.txt" ]
Q: Replace items in a list with unique items starting from 0 Let's say I have a list like this: Y=[1018, 1018, 1011, 1012, 1013, 1014, 1019, 1019, 1017] What's the most pythonic way to replace each number with the lowest unused integer (>=0), if the number has not been seen before the same integer that has been used to replace the number otherwise So that the list becomes: Y=[0, 0, 1, 2, 3, 4, 5, 5, 6] It's not important that first element is 0, but there must be a unique maximal matching (= assignment) between the two lists of numbers, i.e. also this is a good solution: Y=[3, 3, 4, 0, 2, 5, 6, 6, 1] EDIT: what I tried is a for loop using find, my solution is very ugly, I know there is better way to do it, it's not relevant how bad I did it :D A: The first idea that comes to mind is to convert the values to a set() and enumerate() them, store the pairs in a dict, and use a mapping list comprehension to create the new list: >>> Y=[1018, 1018, 1011, 1012, 1013, 1014, 1019, 1019, 1017] >>> mapping={v:k for k,v in enumerate(set(Y))} >>> Y1=[mapping[y] for y in Y] >>> Y1 [5, 5, 0, 1, 2, 3, 6, 6, 4] A: You can also use a defaultdict with itertools.count, eg: from collections import defaultdict from itertools import count dd = defaultdict(lambda c=count(): next(c)) Y=[1018, 1018, 1011, 1012, 1013, 1014, 1019, 1019, 1017] mapped = [dd[el] for el in Y] # [0, 0, 1, 2, 3, 4, 5, 5, 6] How this works is that a defaultdict will return the value for an existing key but where that key doesn't exist, it will assign the key to a default value - in this case that value is the next number in sequence.
[ "stackoverflow", "0039540175.txt" ]
Q: record not saving when before_save action is called Can't figure this out.. Not sure why the record isn't being saved.. the method is being called properly, and all the fields are present, and the logic is correct.. Here is my model code: class Mine < ActiveRecord::Base belongs_to :shop validates :merchant_id, presence: true validates :auth_token, presence: true before_save :assign_three_speed private def assign_three_speed if CreateFulfillmentService::NON_US_MARKETPLACES.include? (self.marketplace) self.three_speed = false else self.three_speed = true end end end Well this is super crazy.. I put in some loggers and now it DOES save?? This is my code now: def assign_three_speed Rails.logger.info "What is self?? #{self.inspect}" if CreateFulfillmentService::NON_US_MARKETPLACES.include? (self.marketplace) self.three_speed = false else self.three_speed = true end Rails.logger.info "Now what is self?? #{self.inspect}" end A: In versions of Rails prior to 5.0.0, returning false from a callback method will cancel the save. From the Rails 4.2.7 documentation: If a before_* callback returns false, all the later callbacks and the associated action are cancelled. Callbacks are generally run in the order they are defined, with the exception of callbacks defined as methods on the model, which are called last. When setting self.three_speed = false, it is the last statement that is run in the method, so that false is the return value of the assign_three_speed method. That's why adding the logger to the last line fixed it. Have the method return some other value instead. Return true as the last line if you never want to cancel the callback: def assign_three_speed if CreateFulfillmentService::NON_US_MARKETPLACES.include(self.marketplace) self.three_speed = false else self.three_speed = true end true end