diff --git "a/data/evaluation/train_data_01.csv" "b/data/evaluation/train_data_01.csv" new file mode 100644--- /dev/null +++ "b/data/evaluation/train_data_01.csv" @@ -0,0 +1,61838 @@ +qid,question,date,metadata,response_j,response_k +10262114,"I need to script my app (not a game) and I have a problem, choosing a script lang for this. +Lua looks fine (actually, it is ideal for my task), but it has problems with unicode strings, which will be used. +Also, I thought about Python, but I don't like It's syntax, and it's Dll is too big for me ( about 2.5 Mib). +Python and other such langs have too much functions, battaries and modules which i do not need (e.g. I/O functions) - script just need to implement logic, all other will do my app. +So, I'd like to know is there a scripting lang, which satisfies this conditions: + +* unicode strings +* I can import C++ functions and then call them from +script +* Can be embedded to app (no dll's) without any problems + +Reinventing the wheel is not a good idea, so I don't want to develop my own lang. +Or there is a way to write unicode strings in Lua's source? Like in C++ L""Unicode string""",2012/04/21,"['https://Stackoverflow.com/questions/10262114', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/684275/']","There isn't really such a thing as a ""unicode string"". Strings are a sequence of bytes that can contain anything. Knowing the encoding of the data in the string matters, though. + +I use Lua with [UTF-8 strings](http://en.wikipedia.org/wiki/UTF-8), which just works for all the operations I care about. I do not use any Unicode string library, though those are available for Lua ([ICU4Lua](http://luaforge.net/projects/icu-lua/), [slnunicode](http://luaforge.net/projects/sln/), etc.). + +Some notes about using UTF-8 strings in Lua: + +* String length (# operator) returns the string length in bytes, not characters or codepoints (non-ASCII characters may be sequences of multiple bytes). +* String splitting (e.g. string.sub) must not split up UTF-8 sequences. +* String matching works (string.find, string.match) fine with ASCII patterns. +* Substring searching (such as string.find in 'plain' mode) works with UTF-8 as the needle or the haystack. + +Counting codepoints in UTF-8 is quite straightforward, if slightly less efficient than other encodings. For example in Lua: + +``` +function utf8_length(str) + return select(2, string.gsub(str, ""[^\128-\193]"", """")); +end + +``` + +If you need more than this kind of thing, the unicode libraries I mentioned give you APIs for everything, including conversion between encodings. + +Personally I prefer this straightforward approach to any of the languages that force a certain flavour of unicode on you (such as Javascript) or try and be clever by having multiple encodings built into the language (such as Python). In my experience they only cause headaches and performance bottlenecks. + +In any case, I think every developer should have a good basic understanding of how unicode works, and the principle differences between different encodings so that they can make the best choice about how to handle unicode in their application. + +For example if all your existing strings in your application are in a wide-char encoding, it would be much less convenient to use Lua as you would have to add a conversion to every string in and out of Lua. This is entirely possible, but if your app might be CPU-bound (as in a game) then it would be a negative point performance-wise.","Take look at [Jim Tcl](http://jim.tcl.tk). It's small, easily embeddable and extendable, supports UTF-8 strings, and it's pretty powerful" +43979563,"We have code that loads html to div with class content. We have div element with link class which has data-href and some other data-\* properties. The code looks like: + +``` +$(document).on('click', '.link', linkClick); +linkClick: function (event) { + event.stopPropagation(); + $('.content').load($(this).data('href'), function (response, status) { + if (status == 'error') { + $('.content').html(""Something went wrong. Please try again later""); + } + }); + } + +``` + +I want to access $(this) inside this callback of load function to get values of all other data-\* properties of link clicked, how can i do that?",2017/05/15,"['https://Stackoverflow.com/questions/43979563', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4930231/']","Create a scoped reference to it before the load call: + +``` +function (event) { + event.stopPropagation(); + + var $that = $(this); // <- Like this + + $('.content').load($(this).data('href'), function (response, status) { + + // You can use $that here + + if (status == 'error') { + $('.content').html(""Something went wrong. Please try again later""); + } + }); +} + +```","``` +$(document).on('click', '.link', linkClick); +var href = $(this).data('href'); +linkClick: function (event) { + event.stopPropagation(); + $('.content').load(href, function (response, status) { + if (status == 'error') { + $('.content').html(""Something went wrong. Please try again later""); + } + }); +} + +```" +43979563,"We have code that loads html to div with class content. We have div element with link class which has data-href and some other data-\* properties. The code looks like: + +``` +$(document).on('click', '.link', linkClick); +linkClick: function (event) { + event.stopPropagation(); + $('.content').load($(this).data('href'), function (response, status) { + if (status == 'error') { + $('.content').html(""Something went wrong. Please try again later""); + } + }); + } + +``` + +I want to access $(this) inside this callback of load function to get values of all other data-\* properties of link clicked, how can i do that?",2017/05/15,"['https://Stackoverflow.com/questions/43979563', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4930231/']","Create a scoped reference to it before the load call: + +``` +function (event) { + event.stopPropagation(); + + var $that = $(this); // <- Like this + + $('.content').load($(this).data('href'), function (response, status) { + + // You can use $that here + + if (status == 'error') { + $('.content').html(""Something went wrong. Please try again later""); + } + }); +} + +```","You can use `event.target` to access clicked element. Most common way is to store it under *that* or *self* variable. + +``` +$(document).on('click', '.link', linkClick); +linkClick = function (event) { + event.stopPropagation(); + var that = event.target; + $('.content').load($(that).data('href'), function (response, status) { + if (status == 'error') { + $('.content').html(""Something went wrong. Please try again later""); + } + }); +} + +```" +14465060,"Ok so I have a map loaded with pins from a remote JSON feed which is loaded into the app. This all works fine. + +Now from initial experimenting `regionDidChangeAnimated` gets called multiple times and so I moved my post request to a method that uses a drag map gesture recogniser which then performs a post request to get data from a JSON feed and reload my map pins after removing them. This also works perfectly. + +Now the only issue I have left is if I select an annotation that is close to the edge of the screen the map moves slightly to accommodate the display of the annotation callout. The problem is `regionDidChangeAnimated` gets called when this happens however my post request doesn't as I call it using the gesture recogniser and so the map was not moved by user intervention but the OS. I don't want to move my Post request to the `regionDidChangeAnimated` as this gets called multiple times but I would like to know if there is a way to do a test if user caused map to move or it did it its-self to accommodate the callout as explained above. The `regionDidChangeAnimated` from the research I have looked at may get called more times than necessary so some guidance would be good on how to prevent that or detect user interaction vs OS moving the map.",2013/01/22,"['https://Stackoverflow.com/questions/14465060', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/652028/']","I have a similar problem: I want do distinguish if the displayed part of a map has been changed by program or by user interaction. Apparently, `MKMapView` objects do not tell me so, i.e. `regionDidChangeAnimated` is called in both cases without an indication why. + +But since `MKMapView` is a subclass of `UIView`, and this one of `UIResponder`, one can implement the methods `touchesBegan:withEvent:` and `touchesEnded:withEvent:` to find out, if the map has been touched during the change of the displayed region. + +If so, one can assume that the change in the displayed region was caused by user interaction. Of course you can be more specific if you investigate the set of touches and the event type of these methods more precisely.",I am such a plank sometimes writing problems can help. I simply removed the regionDidChangeAnimated as I have no need for it and the code that was present there I moved to my gesture which was to removeAnnotations before re-adding them doh! +6394968,"Yet another template issue ! I'm trying to get a template method that will output an object if it has an overload for the operator <<. +I have pretty much everything working, and implemented an enable\_if in order to make g++ choose the intended specialization for each type of objects. + +Thing is, with a non-overloaded object, it works quite fine. But with an overloaded one, both of my specialization are reasonable choices for g++, and instead of compiling it outputs me an ambiguous overload error. + +Here's the code : + +``` +template + static void Print(Stream& out, T& param, typename enable_if::value>::type = 0) + { + out << param; + } + + template + static void Print(Stream& out, T& param) + { + out << ""/!\\"" << typeid(param).name() << "" does not have any overload for <<.\n""; + } + +``` + +I understand why such a thing is ambiguous. Yet I can't think of a way to make it more obvious... how do I make the compiler understand that the second overload is to be chosen only when the first cannot be ?",2011/06/18,"['https://Stackoverflow.com/questions/6394968', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/538377/']","You'll get the ambiguity because in both cases you have a function that takes a stream followed by your type `T` as the first two arguments. This works though: + +``` +#include +#include +#include + +template +struct CanPrint { enum { value = 0 }; }; + +template <> +struct CanPrint { enum { value = 1 }; }; + +template +typename boost::enable_if, void>::type + Print(std::ostream& out, T& param) +{ + out << param << std::endl; +} + +template +typename boost::disable_if, void>::type + Print(std::ostream& out, T& param) +{ + out << ""/!\\"" << typeid(param).name() << "" does not have any overload for <<.\n""; +} + +int main() +{ + int i = 1; + double d = 2; + + Print(std::cout, i); + Print(std::cout, d); +} + +```","The ambiguity is because of the default parameter value. + +Calling `Print(stream, whatever)` can be resolved to either the first version with the default third parameter or the second version with no third parameter. + +Remove the default value, and the compiler will understand. Otherwise both of them can be chosen always." +6394968,"Yet another template issue ! I'm trying to get a template method that will output an object if it has an overload for the operator <<. +I have pretty much everything working, and implemented an enable\_if in order to make g++ choose the intended specialization for each type of objects. + +Thing is, with a non-overloaded object, it works quite fine. But with an overloaded one, both of my specialization are reasonable choices for g++, and instead of compiling it outputs me an ambiguous overload error. + +Here's the code : + +``` +template + static void Print(Stream& out, T& param, typename enable_if::value>::type = 0) + { + out << param; + } + + template + static void Print(Stream& out, T& param) + { + out << ""/!\\"" << typeid(param).name() << "" does not have any overload for <<.\n""; + } + +``` + +I understand why such a thing is ambiguous. Yet I can't think of a way to make it more obvious... how do I make the compiler understand that the second overload is to be chosen only when the first cannot be ?",2011/06/18,"['https://Stackoverflow.com/questions/6394968', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/538377/']","You'll get the ambiguity because in both cases you have a function that takes a stream followed by your type `T` as the first two arguments. This works though: + +``` +#include +#include +#include + +template +struct CanPrint { enum { value = 0 }; }; + +template <> +struct CanPrint { enum { value = 1 }; }; + +template +typename boost::enable_if, void>::type + Print(std::ostream& out, T& param) +{ + out << param << std::endl; +} + +template +typename boost::disable_if, void>::type + Print(std::ostream& out, T& param) +{ + out << ""/!\\"" << typeid(param).name() << "" does not have any overload for <<.\n""; +} + +int main() +{ + int i = 1; + double d = 2; + + Print(std::cout, i); + Print(std::cout, d); +} + +```","I believe this has nothing to do with templates. A free function overloaded in this fashion would give the same ambigious error. + +check this simple code example, It is similar to what you are doing in your template example: + +``` +void doSomething(int i, int j, int k ); +void doSomething(int i, int j, int k = 10); + +void doSomething(int i, int j, int k) +{ + +} + +void doSomething(int i, int j) +{ + +} + +int main() +{ + doSomething(10,20); + return 0; +} + +``` + +The error is: + +``` +prog.cpp:18: error: call of overloaded ‘doSomething(int, int)’ is ambiguous +prog.cpp:5: note: candidates are: void doSomething(int, int, int) +prog.cpp:10: note: void doSomething(int, int) + +``` + +***Clearly, You cannot overload the functions this way on just the basis of default arguments.***" +53596009,"I am trying to remove the last `"",""` of a string however i am getting an error stating that + +> +> System.ArgumentOutOfRangeException: 'StartIndex cannot be less than zero. +> +> +> + +the string is written to the file fine but it breaks when running with the above error. I'm unsure as to why this is happening, any suggestions would be appreciated. + +the code I am using is as follows + +``` +for (int z = 0; z <= totalNumberOfCaves; z++) + { + for (int i = 0; i < totalNumberOfCaves && connectionStack.Count > 0; i++) + { + connectionData.Add(int.Parse(connectionStack.Pop())); + } + string fileName2 = @""D:\UNI\Year 5\AI - SET09122\SET09122 - CW1\WriteConnectionData.txt""; + string writeUnEditedData = """"; + foreach (int s in connectionData) + { + writeUnEditedData += (s + "",""); + } + using (StreamWriter sw = File.AppendText(fileName2)) + { + string writeData = writeUnEditedData.Remove(writeUnEditedData.Length - 1); + sw.Write(""{ "" + writeData + "" },"" + Environment.NewLine); + } + connectionData.Clear(); +} + +```",2018/12/03,"['https://Stackoverflow.com/questions/53596009', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5424254/']","Appending `string` in a loop: + +``` + foreach (int s in connectionData) + { + writeUnEditedData += (s + "",""); + } + +``` + +is *not* a good idea. Put `Join`: + +``` + writeUnEditedData = string.Join("","", connectionData); + +``` + +Having this done, you don't have to remove anything: + +``` + using (StreamWriter sw = File.AppendText(fileName2)) + { + // No Remove here + string writeData = writeUnEditedData; + ... + +```","This usually means that the string is empty. + +Try to put this guard code in: + +``` +string writeData = string.IsNullOrEmpty(writeUnEditedData) + ? string.Empty + : writeUnEditedData.Remove(writeUnEditedData.Length - 1); + +```" +53596009,"I am trying to remove the last `"",""` of a string however i am getting an error stating that + +> +> System.ArgumentOutOfRangeException: 'StartIndex cannot be less than zero. +> +> +> + +the string is written to the file fine but it breaks when running with the above error. I'm unsure as to why this is happening, any suggestions would be appreciated. + +the code I am using is as follows + +``` +for (int z = 0; z <= totalNumberOfCaves; z++) + { + for (int i = 0; i < totalNumberOfCaves && connectionStack.Count > 0; i++) + { + connectionData.Add(int.Parse(connectionStack.Pop())); + } + string fileName2 = @""D:\UNI\Year 5\AI - SET09122\SET09122 - CW1\WriteConnectionData.txt""; + string writeUnEditedData = """"; + foreach (int s in connectionData) + { + writeUnEditedData += (s + "",""); + } + using (StreamWriter sw = File.AppendText(fileName2)) + { + string writeData = writeUnEditedData.Remove(writeUnEditedData.Length - 1); + sw.Write(""{ "" + writeData + "" },"" + Environment.NewLine); + } + connectionData.Clear(); +} + +```",2018/12/03,"['https://Stackoverflow.com/questions/53596009', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5424254/']",Add a check to see if writeUnEditedData is not an empty string before you do the Remove. An empty string will results in a Remove(-1) which I would assume would throw an error that the StartIndex cannot be less then 0.,"This usually means that the string is empty. + +Try to put this guard code in: + +``` +string writeData = string.IsNullOrEmpty(writeUnEditedData) + ? string.Empty + : writeUnEditedData.Remove(writeUnEditedData.Length - 1); + +```" +53596009,"I am trying to remove the last `"",""` of a string however i am getting an error stating that + +> +> System.ArgumentOutOfRangeException: 'StartIndex cannot be less than zero. +> +> +> + +the string is written to the file fine but it breaks when running with the above error. I'm unsure as to why this is happening, any suggestions would be appreciated. + +the code I am using is as follows + +``` +for (int z = 0; z <= totalNumberOfCaves; z++) + { + for (int i = 0; i < totalNumberOfCaves && connectionStack.Count > 0; i++) + { + connectionData.Add(int.Parse(connectionStack.Pop())); + } + string fileName2 = @""D:\UNI\Year 5\AI - SET09122\SET09122 - CW1\WriteConnectionData.txt""; + string writeUnEditedData = """"; + foreach (int s in connectionData) + { + writeUnEditedData += (s + "",""); + } + using (StreamWriter sw = File.AppendText(fileName2)) + { + string writeData = writeUnEditedData.Remove(writeUnEditedData.Length - 1); + sw.Write(""{ "" + writeData + "" },"" + Environment.NewLine); + } + connectionData.Clear(); +} + +```",2018/12/03,"['https://Stackoverflow.com/questions/53596009', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5424254/']","Try `string.TrimEnd()`: + +``` +writeUnEditedData = writeUnEditedData.TrimEnd(','); + +```","This usually means that the string is empty. + +Try to put this guard code in: + +``` +string writeData = string.IsNullOrEmpty(writeUnEditedData) + ? string.Empty + : writeUnEditedData.Remove(writeUnEditedData.Length - 1); + +```" +53596009,"I am trying to remove the last `"",""` of a string however i am getting an error stating that + +> +> System.ArgumentOutOfRangeException: 'StartIndex cannot be less than zero. +> +> +> + +the string is written to the file fine but it breaks when running with the above error. I'm unsure as to why this is happening, any suggestions would be appreciated. + +the code I am using is as follows + +``` +for (int z = 0; z <= totalNumberOfCaves; z++) + { + for (int i = 0; i < totalNumberOfCaves && connectionStack.Count > 0; i++) + { + connectionData.Add(int.Parse(connectionStack.Pop())); + } + string fileName2 = @""D:\UNI\Year 5\AI - SET09122\SET09122 - CW1\WriteConnectionData.txt""; + string writeUnEditedData = """"; + foreach (int s in connectionData) + { + writeUnEditedData += (s + "",""); + } + using (StreamWriter sw = File.AppendText(fileName2)) + { + string writeData = writeUnEditedData.Remove(writeUnEditedData.Length - 1); + sw.Write(""{ "" + writeData + "" },"" + Environment.NewLine); + } + connectionData.Clear(); +} + +```",2018/12/03,"['https://Stackoverflow.com/questions/53596009', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5424254/']","Appending `string` in a loop: + +``` + foreach (int s in connectionData) + { + writeUnEditedData += (s + "",""); + } + +``` + +is *not* a good idea. Put `Join`: + +``` + writeUnEditedData = string.Join("","", connectionData); + +``` + +Having this done, you don't have to remove anything: + +``` + using (StreamWriter sw = File.AppendText(fileName2)) + { + // No Remove here + string writeData = writeUnEditedData; + ... + +```",Add a check to see if writeUnEditedData is not an empty string before you do the Remove. An empty string will results in a Remove(-1) which I would assume would throw an error that the StartIndex cannot be less then 0. +53596009,"I am trying to remove the last `"",""` of a string however i am getting an error stating that + +> +> System.ArgumentOutOfRangeException: 'StartIndex cannot be less than zero. +> +> +> + +the string is written to the file fine but it breaks when running with the above error. I'm unsure as to why this is happening, any suggestions would be appreciated. + +the code I am using is as follows + +``` +for (int z = 0; z <= totalNumberOfCaves; z++) + { + for (int i = 0; i < totalNumberOfCaves && connectionStack.Count > 0; i++) + { + connectionData.Add(int.Parse(connectionStack.Pop())); + } + string fileName2 = @""D:\UNI\Year 5\AI - SET09122\SET09122 - CW1\WriteConnectionData.txt""; + string writeUnEditedData = """"; + foreach (int s in connectionData) + { + writeUnEditedData += (s + "",""); + } + using (StreamWriter sw = File.AppendText(fileName2)) + { + string writeData = writeUnEditedData.Remove(writeUnEditedData.Length - 1); + sw.Write(""{ "" + writeData + "" },"" + Environment.NewLine); + } + connectionData.Clear(); +} + +```",2018/12/03,"['https://Stackoverflow.com/questions/53596009', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5424254/']","Appending `string` in a loop: + +``` + foreach (int s in connectionData) + { + writeUnEditedData += (s + "",""); + } + +``` + +is *not* a good idea. Put `Join`: + +``` + writeUnEditedData = string.Join("","", connectionData); + +``` + +Having this done, you don't have to remove anything: + +``` + using (StreamWriter sw = File.AppendText(fileName2)) + { + // No Remove here + string writeData = writeUnEditedData; + ... + +```","Try `string.TrimEnd()`: + +``` +writeUnEditedData = writeUnEditedData.TrimEnd(','); + +```" +53596009,"I am trying to remove the last `"",""` of a string however i am getting an error stating that + +> +> System.ArgumentOutOfRangeException: 'StartIndex cannot be less than zero. +> +> +> + +the string is written to the file fine but it breaks when running with the above error. I'm unsure as to why this is happening, any suggestions would be appreciated. + +the code I am using is as follows + +``` +for (int z = 0; z <= totalNumberOfCaves; z++) + { + for (int i = 0; i < totalNumberOfCaves && connectionStack.Count > 0; i++) + { + connectionData.Add(int.Parse(connectionStack.Pop())); + } + string fileName2 = @""D:\UNI\Year 5\AI - SET09122\SET09122 - CW1\WriteConnectionData.txt""; + string writeUnEditedData = """"; + foreach (int s in connectionData) + { + writeUnEditedData += (s + "",""); + } + using (StreamWriter sw = File.AppendText(fileName2)) + { + string writeData = writeUnEditedData.Remove(writeUnEditedData.Length - 1); + sw.Write(""{ "" + writeData + "" },"" + Environment.NewLine); + } + connectionData.Clear(); +} + +```",2018/12/03,"['https://Stackoverflow.com/questions/53596009', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5424254/']","Appending `string` in a loop: + +``` + foreach (int s in connectionData) + { + writeUnEditedData += (s + "",""); + } + +``` + +is *not* a good idea. Put `Join`: + +``` + writeUnEditedData = string.Join("","", connectionData); + +``` + +Having this done, you don't have to remove anything: + +``` + using (StreamWriter sw = File.AppendText(fileName2)) + { + // No Remove here + string writeData = writeUnEditedData; + ... + +```","You can improve on this pattern: + +``` +string writeUnEditedData = """"; +foreach (int s in connectionData) +{ + writeUnEditedData += (s + "",""); +} + +``` + +to avoid adding the comma in the first place: + +``` +string delimiter = """"; +string writeUnEditedData = """"; +foreach (int s in connectionData) +{ + writeUnEditedData += $""{delimiter}{s}""; + delimiter = "",""; +} + +``` + +or with a `StringBuilder`... though contrary to popular belief this only helps if the `connectionData` collection is kinda big: + +``` +string delimiter = """"; +var writeUnEditedData = new StringBuilder(); +foreach (int s in connectionData) +{ + writeUnEditedData.Append(delimiter).Append(s); + delimiter = "",""; +} + +``` + +Even better still, stream the whole thing, to avoid needing all that extra memory and processing: + +``` +string fileName2 = @""D:\UNI\Year 5\AI - SET09122\SET09122 - CW1\WriteConnectionData.txt""; +using (var sw = new StreamWriter(fileName2, true)) +{ + for (int z = 0; z <= totalNumberOfCaves; z++) + { + string delimiter = """"; + for (int i = 0; i < totalNumberOfCaves && connectionStack.Count > 0; i++) + { + sw.Write(delimiter); + sw.Write(connectionStack.Pop()); + delimiter = "",""; + } + sw.Write(Environment.NewLine); + } +} + +```" +53596009,"I am trying to remove the last `"",""` of a string however i am getting an error stating that + +> +> System.ArgumentOutOfRangeException: 'StartIndex cannot be less than zero. +> +> +> + +the string is written to the file fine but it breaks when running with the above error. I'm unsure as to why this is happening, any suggestions would be appreciated. + +the code I am using is as follows + +``` +for (int z = 0; z <= totalNumberOfCaves; z++) + { + for (int i = 0; i < totalNumberOfCaves && connectionStack.Count > 0; i++) + { + connectionData.Add(int.Parse(connectionStack.Pop())); + } + string fileName2 = @""D:\UNI\Year 5\AI - SET09122\SET09122 - CW1\WriteConnectionData.txt""; + string writeUnEditedData = """"; + foreach (int s in connectionData) + { + writeUnEditedData += (s + "",""); + } + using (StreamWriter sw = File.AppendText(fileName2)) + { + string writeData = writeUnEditedData.Remove(writeUnEditedData.Length - 1); + sw.Write(""{ "" + writeData + "" },"" + Environment.NewLine); + } + connectionData.Clear(); +} + +```",2018/12/03,"['https://Stackoverflow.com/questions/53596009', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5424254/']","Try `string.TrimEnd()`: + +``` +writeUnEditedData = writeUnEditedData.TrimEnd(','); + +```",Add a check to see if writeUnEditedData is not an empty string before you do the Remove. An empty string will results in a Remove(-1) which I would assume would throw an error that the StartIndex cannot be less then 0. +53596009,"I am trying to remove the last `"",""` of a string however i am getting an error stating that + +> +> System.ArgumentOutOfRangeException: 'StartIndex cannot be less than zero. +> +> +> + +the string is written to the file fine but it breaks when running with the above error. I'm unsure as to why this is happening, any suggestions would be appreciated. + +the code I am using is as follows + +``` +for (int z = 0; z <= totalNumberOfCaves; z++) + { + for (int i = 0; i < totalNumberOfCaves && connectionStack.Count > 0; i++) + { + connectionData.Add(int.Parse(connectionStack.Pop())); + } + string fileName2 = @""D:\UNI\Year 5\AI - SET09122\SET09122 - CW1\WriteConnectionData.txt""; + string writeUnEditedData = """"; + foreach (int s in connectionData) + { + writeUnEditedData += (s + "",""); + } + using (StreamWriter sw = File.AppendText(fileName2)) + { + string writeData = writeUnEditedData.Remove(writeUnEditedData.Length - 1); + sw.Write(""{ "" + writeData + "" },"" + Environment.NewLine); + } + connectionData.Clear(); +} + +```",2018/12/03,"['https://Stackoverflow.com/questions/53596009', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5424254/']",Add a check to see if writeUnEditedData is not an empty string before you do the Remove. An empty string will results in a Remove(-1) which I would assume would throw an error that the StartIndex cannot be less then 0.,"You can improve on this pattern: + +``` +string writeUnEditedData = """"; +foreach (int s in connectionData) +{ + writeUnEditedData += (s + "",""); +} + +``` + +to avoid adding the comma in the first place: + +``` +string delimiter = """"; +string writeUnEditedData = """"; +foreach (int s in connectionData) +{ + writeUnEditedData += $""{delimiter}{s}""; + delimiter = "",""; +} + +``` + +or with a `StringBuilder`... though contrary to popular belief this only helps if the `connectionData` collection is kinda big: + +``` +string delimiter = """"; +var writeUnEditedData = new StringBuilder(); +foreach (int s in connectionData) +{ + writeUnEditedData.Append(delimiter).Append(s); + delimiter = "",""; +} + +``` + +Even better still, stream the whole thing, to avoid needing all that extra memory and processing: + +``` +string fileName2 = @""D:\UNI\Year 5\AI - SET09122\SET09122 - CW1\WriteConnectionData.txt""; +using (var sw = new StreamWriter(fileName2, true)) +{ + for (int z = 0; z <= totalNumberOfCaves; z++) + { + string delimiter = """"; + for (int i = 0; i < totalNumberOfCaves && connectionStack.Count > 0; i++) + { + sw.Write(delimiter); + sw.Write(connectionStack.Pop()); + delimiter = "",""; + } + sw.Write(Environment.NewLine); + } +} + +```" +53596009,"I am trying to remove the last `"",""` of a string however i am getting an error stating that + +> +> System.ArgumentOutOfRangeException: 'StartIndex cannot be less than zero. +> +> +> + +the string is written to the file fine but it breaks when running with the above error. I'm unsure as to why this is happening, any suggestions would be appreciated. + +the code I am using is as follows + +``` +for (int z = 0; z <= totalNumberOfCaves; z++) + { + for (int i = 0; i < totalNumberOfCaves && connectionStack.Count > 0; i++) + { + connectionData.Add(int.Parse(connectionStack.Pop())); + } + string fileName2 = @""D:\UNI\Year 5\AI - SET09122\SET09122 - CW1\WriteConnectionData.txt""; + string writeUnEditedData = """"; + foreach (int s in connectionData) + { + writeUnEditedData += (s + "",""); + } + using (StreamWriter sw = File.AppendText(fileName2)) + { + string writeData = writeUnEditedData.Remove(writeUnEditedData.Length - 1); + sw.Write(""{ "" + writeData + "" },"" + Environment.NewLine); + } + connectionData.Clear(); +} + +```",2018/12/03,"['https://Stackoverflow.com/questions/53596009', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5424254/']","Try `string.TrimEnd()`: + +``` +writeUnEditedData = writeUnEditedData.TrimEnd(','); + +```","You can improve on this pattern: + +``` +string writeUnEditedData = """"; +foreach (int s in connectionData) +{ + writeUnEditedData += (s + "",""); +} + +``` + +to avoid adding the comma in the first place: + +``` +string delimiter = """"; +string writeUnEditedData = """"; +foreach (int s in connectionData) +{ + writeUnEditedData += $""{delimiter}{s}""; + delimiter = "",""; +} + +``` + +or with a `StringBuilder`... though contrary to popular belief this only helps if the `connectionData` collection is kinda big: + +``` +string delimiter = """"; +var writeUnEditedData = new StringBuilder(); +foreach (int s in connectionData) +{ + writeUnEditedData.Append(delimiter).Append(s); + delimiter = "",""; +} + +``` + +Even better still, stream the whole thing, to avoid needing all that extra memory and processing: + +``` +string fileName2 = @""D:\UNI\Year 5\AI - SET09122\SET09122 - CW1\WriteConnectionData.txt""; +using (var sw = new StreamWriter(fileName2, true)) +{ + for (int z = 0; z <= totalNumberOfCaves; z++) + { + string delimiter = """"; + for (int i = 0; i < totalNumberOfCaves && connectionStack.Count > 0; i++) + { + sw.Write(delimiter); + sw.Write(connectionStack.Pop()); + delimiter = "",""; + } + sw.Write(Environment.NewLine); + } +} + +```" +49182,"The question goes: + +Expand $(1-2x)^{1/2}-(1-3x)^{2/3}$ as far as the 4th term. + +Ans: $x + x^2/2 + 5x^3/6 + 41x^4/24$ + +How should I do it?",2011/07/03,"['https://math.stackexchange.com/questions/49182', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/11103/']","You can translate the inequality to $\frac{y^2 \cdot y'}{1+y^6} \leq x^{2011}$ and then integrate from $x\_00$ to $s$ with respect to $x$. + +$$ \int\_{x\_0}^s \frac{y(x)^2 \cdot y(x)'}{1+y(x)^6} dx \leq \frac{s^{2012}}{2012}-\frac{x\_0^{2012}}{2012}$$ + +$$ \frac{1}{3} \arctan y^3(s) -\frac{1}{3}\arctan y^3(x\_0) \leq \frac{s^{2012}}{2012}-\frac{x\_0^{2012}}{2012}$$ + +In your case, take $x\_0=\frac{\pi}{4}$","What you basically have is this: + +\begin{align\*} +\frac{dy}{dx} & \leq \frac{x^{2011}\cdot (1+y^{6})}{y^{2}} \\ \Longrightarrow \int\frac{y^{2}}{1+y^{6}}\ dy &\leq \int x^{2011} \ dx +\end{align\*}" +52074170,"I've got two data frames: `zerowy_nazwa5`, `zatwierdzony_nazwa5`, + +and working 2 lines: + +``` +setdiff(zatwierdzony_nazwa5, zerowy_nazwa5) +setdiff(zerowy_nazwa5, zatwierdzony_nazwa5) + +``` + +how I implement this in PowerBi? + +Thanks for help",2018/08/29,"['https://Stackoverflow.com/questions/52074170', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2298197/']","If you remove the `seleniumAddress` from your protractor `conf.js`, protractor will start the selenium automatically. Example: + +**With the `seleniumAddress` on the `conf.js`:** + +``` +exports.config = { + seleniumAddress: 'http://localhost:4444/wd/hub', + specs: [ 'spec.js' ] +}; + +``` + +**Removing the `seleniumAddress` on the `conf.js`:** + +``` +exports.config = { + specs: [ 'spec.js' ] +}; + +``` + +Now, using the `protractor conf.js`, protractor will start the selenium server automatically as you need.","You can archive your goal with npm packages: [concurrently](https://www.npmjs.com/package/concurrently) and [delay-cli](https://www.npmjs.com/package/delay-cli). + +Add them as dependencies. + +``` +// package.json + +""scripts"": [ + ""wstart"": ""webdriver-manager update && webdriver-manager start"", + ""test"": ""concurrently --kill-others \""npm run wstart\"" \""delay 10 && protractor conf.js\"""" +] + +``` + +execute `npm run test`" +12803508,"I have a program that recevice message in udp in visual studio. + +sometime I miss a message.I want to use select to see udp buffer used size if udp rec buffer is full. + +How I can use select for this purpose? + +where can I see a example?",2012/10/09,"['https://Stackoverflow.com/questions/12803508', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/598470/']","Post-fact discovery that your receive buffer is full will not do you any good - packets have already been dropped. Even more - you need to set your buffer sizes before `connect()` or `bind()`, they will not change after that. + +What you should do is pre-set socket receive buffer to some large value that would accommodate your traffic spikes, and try to process your network input faster. That usually means doing `select()` on non-blocking sockets (or even better - some advanced API like Linux `epoll(7)` in edge-triggered mode), and draining socket input until you get `EWOULDBLOCK`. + +### Edit 0: + +You cannot discover that you missed a UDP packet by using `select()` or any other socket API. This has to be done in the **application-level protocol**, i.e. one layer up from the transport. Common practice is including sequence numbers in application message header.","I think one of the main properties of UDP (as opposed to TCP) is that you will sometimes lose messages. You have to design your protocol to account for that. I'm not an expert in UDP, but I don't understand how seeing the size of the buffer will help you, and I don't understand why you want to use `select` to do it." +12803508,"I have a program that recevice message in udp in visual studio. + +sometime I miss a message.I want to use select to see udp buffer used size if udp rec buffer is full. + +How I can use select for this purpose? + +where can I see a example?",2012/10/09,"['https://Stackoverflow.com/questions/12803508', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/598470/']","Post-fact discovery that your receive buffer is full will not do you any good - packets have already been dropped. Even more - you need to set your buffer sizes before `connect()` or `bind()`, they will not change after that. + +What you should do is pre-set socket receive buffer to some large value that would accommodate your traffic spikes, and try to process your network input faster. That usually means doing `select()` on non-blocking sockets (or even better - some advanced API like Linux `epoll(7)` in edge-triggered mode), and draining socket input until you get `EWOULDBLOCK`. + +### Edit 0: + +You cannot discover that you missed a UDP packet by using `select()` or any other socket API. This has to be done in the **application-level protocol**, i.e. one layer up from the transport. Common practice is including sequence numbers in application message header.","You can use [`getsockopt`](http://linux.die.net/man/3/getsockopt) to get socket options, including receive buffer size. Use [`setsockopt`](http://linux.die.net/man/3/setsockopt) to set the size. + +Example of getting the size: + +``` +int size; +getsockopt(socket_fd, SOL_SOCKET, SO_RCVBUF, &size); +std::cout << ""Buffer size is currently "" << size << "" bytes\n""; + +```" +1569238,"I am having performance problem when truing to fill typed list. Below is my simplified code: + +``` + public static List GetProducts() + { + List products = new List(); + using (DbQuery query = new DbQuery()) //this is database access class + { + + query.CommandText = ""SELECT ProdID, ProdName,Price FROM SomeTable "" ;+ + + using (IDataReader rdr = query.ExecuteReader()) + { + while (rdr.Read()) + { + Product prd = new Product(); + prd.ProdID = DbQuery.ReadInt ( rdr, ""ProdID"", -1 ); + prd.ProdName = DbQuery.ReadString(rdr, ""ProdName"", """"); + prd.Price = DbQuery.ReadDouble(rdr, ""Price"", 0); + products.Add(prd); + } + } + } + } + +``` + +I also have simple struct Product (ProdID, ProdName,Price). + +my problem is that it takes 4 seconds to execute GetProducts(). The query returns about 600 records and it takes miliseconds to return result, so I am perrty sure that filling up products collection takes all this time. Am I doing something inefficient here? Please, help. +Thanks, +Gerda",2009/10/14,"['https://Stackoverflow.com/questions/1569238', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/190204/']",Have you tried to put an index on the fields you're filtering on? This will definitely speed up your queries versus not having indices.,"I would be surprised if that is your bottleneck. I would try making a little test app that has a mock database connection. + +You can usually do a little bit better if you can pre-size the list. If there is a reasonable minimum size for the query, or if you have some other way of knowing (or reasonably guessing) a good initial size you might get a tiny boost." +1569238,"I am having performance problem when truing to fill typed list. Below is my simplified code: + +``` + public static List GetProducts() + { + List products = new List(); + using (DbQuery query = new DbQuery()) //this is database access class + { + + query.CommandText = ""SELECT ProdID, ProdName,Price FROM SomeTable "" ;+ + + using (IDataReader rdr = query.ExecuteReader()) + { + while (rdr.Read()) + { + Product prd = new Product(); + prd.ProdID = DbQuery.ReadInt ( rdr, ""ProdID"", -1 ); + prd.ProdName = DbQuery.ReadString(rdr, ""ProdName"", """"); + prd.Price = DbQuery.ReadDouble(rdr, ""Price"", 0); + products.Add(prd); + } + } + } + } + +``` + +I also have simple struct Product (ProdID, ProdName,Price). + +my problem is that it takes 4 seconds to execute GetProducts(). The query returns about 600 records and it takes miliseconds to return result, so I am perrty sure that filling up products collection takes all this time. Am I doing something inefficient here? Please, help. +Thanks, +Gerda",2009/10/14,"['https://Stackoverflow.com/questions/1569238', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/190204/']",Have you tried to put an index on the fields you're filtering on? This will definitely speed up your queries versus not having indices.,"Just from the sounds of it, this has to be a database performance or latency issue (if connecting remotely.)" +1569238,"I am having performance problem when truing to fill typed list. Below is my simplified code: + +``` + public static List GetProducts() + { + List products = new List(); + using (DbQuery query = new DbQuery()) //this is database access class + { + + query.CommandText = ""SELECT ProdID, ProdName,Price FROM SomeTable "" ;+ + + using (IDataReader rdr = query.ExecuteReader()) + { + while (rdr.Read()) + { + Product prd = new Product(); + prd.ProdID = DbQuery.ReadInt ( rdr, ""ProdID"", -1 ); + prd.ProdName = DbQuery.ReadString(rdr, ""ProdName"", """"); + prd.Price = DbQuery.ReadDouble(rdr, ""Price"", 0); + products.Add(prd); + } + } + } + } + +``` + +I also have simple struct Product (ProdID, ProdName,Price). + +my problem is that it takes 4 seconds to execute GetProducts(). The query returns about 600 records and it takes miliseconds to return result, so I am perrty sure that filling up products collection takes all this time. Am I doing something inefficient here? Please, help. +Thanks, +Gerda",2009/10/14,"['https://Stackoverflow.com/questions/1569238', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/190204/']","List insertion is very fast. Something else must be going on here. Try timing it with and without `products.Add(prd)` commented out. I suspect you'll find they're almost identical. + +Here's how I'd solve this: comment out one line at a time until you see a big jump in performance-- then you'll have found your culprit. + +Another thing to watch out for: database performance is not static. For example, a query which takes 4 seconds to execute the first time might only take 100 msecs to execute the second time, because all the data is cached into RAM so no physical I/O needs to be done the second time. And the very first query to a database will be slow as SQL spins up lots of things. My suggestion: always start with a warm cache, meaning run the code once and then run it again, and only consider the second timing real. Even better, run the code 10 times, then time it 10 times, and throw out the first 10 and average the second.","I would be surprised if that is your bottleneck. I would try making a little test app that has a mock database connection. + +You can usually do a little bit better if you can pre-size the list. If there is a reasonable minimum size for the query, or if you have some other way of knowing (or reasonably guessing) a good initial size you might get a tiny boost." +1569238,"I am having performance problem when truing to fill typed list. Below is my simplified code: + +``` + public static List GetProducts() + { + List products = new List(); + using (DbQuery query = new DbQuery()) //this is database access class + { + + query.CommandText = ""SELECT ProdID, ProdName,Price FROM SomeTable "" ;+ + + using (IDataReader rdr = query.ExecuteReader()) + { + while (rdr.Read()) + { + Product prd = new Product(); + prd.ProdID = DbQuery.ReadInt ( rdr, ""ProdID"", -1 ); + prd.ProdName = DbQuery.ReadString(rdr, ""ProdName"", """"); + prd.Price = DbQuery.ReadDouble(rdr, ""Price"", 0); + products.Add(prd); + } + } + } + } + +``` + +I also have simple struct Product (ProdID, ProdName,Price). + +my problem is that it takes 4 seconds to execute GetProducts(). The query returns about 600 records and it takes miliseconds to return result, so I am perrty sure that filling up products collection takes all this time. Am I doing something inefficient here? Please, help. +Thanks, +Gerda",2009/10/14,"['https://Stackoverflow.com/questions/1569238', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/190204/']","List insertion is very fast. Something else must be going on here. Try timing it with and without `products.Add(prd)` commented out. I suspect you'll find they're almost identical. + +Here's how I'd solve this: comment out one line at a time until you see a big jump in performance-- then you'll have found your culprit. + +Another thing to watch out for: database performance is not static. For example, a query which takes 4 seconds to execute the first time might only take 100 msecs to execute the second time, because all the data is cached into RAM so no physical I/O needs to be done the second time. And the very first query to a database will be slow as SQL spins up lots of things. My suggestion: always start with a warm cache, meaning run the code once and then run it again, and only consider the second timing real. Even better, run the code 10 times, then time it 10 times, and throw out the first 10 and average the second.","Just from the sounds of it, this has to be a database performance or latency issue (if connecting remotely.)" +1569238,"I am having performance problem when truing to fill typed list. Below is my simplified code: + +``` + public static List GetProducts() + { + List products = new List(); + using (DbQuery query = new DbQuery()) //this is database access class + { + + query.CommandText = ""SELECT ProdID, ProdName,Price FROM SomeTable "" ;+ + + using (IDataReader rdr = query.ExecuteReader()) + { + while (rdr.Read()) + { + Product prd = new Product(); + prd.ProdID = DbQuery.ReadInt ( rdr, ""ProdID"", -1 ); + prd.ProdName = DbQuery.ReadString(rdr, ""ProdName"", """"); + prd.Price = DbQuery.ReadDouble(rdr, ""Price"", 0); + products.Add(prd); + } + } + } + } + +``` + +I also have simple struct Product (ProdID, ProdName,Price). + +my problem is that it takes 4 seconds to execute GetProducts(). The query returns about 600 records and it takes miliseconds to return result, so I am perrty sure that filling up products collection takes all this time. Am I doing something inefficient here? Please, help. +Thanks, +Gerda",2009/10/14,"['https://Stackoverflow.com/questions/1569238', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/190204/']","As Justin recommends, I personally would start commenting out sections of code until I found what was causing the bottleneck. For example, I might start by making the routine only run the database-centric code: + +``` +public static List GetProducts() + { + List products = new List(); + + using (DbQuery query = new DbQuery()) + { + query.CommandText = ""SELECT ProdID, ProdName,Price FROM SomeTable ""; + + using (IDataReader rdr = query.ExecuteReader()) + { + while (rdr.Read()) + { + //Product prd = new Product(); + //prd.ProdID = DbQuery.ReadInt(rdr, ""ProdID"", -1); + //prd.ProdName = DbQuery.ReadString(rdr, ""ProdName"", """"); + //prd.Price = DbQuery.ReadDouble(rdr, ""Price"", 0); + //products.Add(prd); + } + } + } + + return products; + } + +``` + +By commenting out the section which creates the Product objects and adds them to the list, I can see how fast the database related code runs. If that runs quicker then 4 seconds then I know that it's something to do with the Product object creation and/or the calls to DBQuery which are taking a long time to complete. + +It's trial and error, but since this routine if very simple, it should not take long to do this type of analysis.","I would be surprised if that is your bottleneck. I would try making a little test app that has a mock database connection. + +You can usually do a little bit better if you can pre-size the list. If there is a reasonable minimum size for the query, or if you have some other way of knowing (or reasonably guessing) a good initial size you might get a tiny boost." +1569238,"I am having performance problem when truing to fill typed list. Below is my simplified code: + +``` + public static List GetProducts() + { + List products = new List(); + using (DbQuery query = new DbQuery()) //this is database access class + { + + query.CommandText = ""SELECT ProdID, ProdName,Price FROM SomeTable "" ;+ + + using (IDataReader rdr = query.ExecuteReader()) + { + while (rdr.Read()) + { + Product prd = new Product(); + prd.ProdID = DbQuery.ReadInt ( rdr, ""ProdID"", -1 ); + prd.ProdName = DbQuery.ReadString(rdr, ""ProdName"", """"); + prd.Price = DbQuery.ReadDouble(rdr, ""Price"", 0); + products.Add(prd); + } + } + } + } + +``` + +I also have simple struct Product (ProdID, ProdName,Price). + +my problem is that it takes 4 seconds to execute GetProducts(). The query returns about 600 records and it takes miliseconds to return result, so I am perrty sure that filling up products collection takes all this time. Am I doing something inefficient here? Please, help. +Thanks, +Gerda",2009/10/14,"['https://Stackoverflow.com/questions/1569238', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/190204/']","As Justin recommends, I personally would start commenting out sections of code until I found what was causing the bottleneck. For example, I might start by making the routine only run the database-centric code: + +``` +public static List GetProducts() + { + List products = new List(); + + using (DbQuery query = new DbQuery()) + { + query.CommandText = ""SELECT ProdID, ProdName,Price FROM SomeTable ""; + + using (IDataReader rdr = query.ExecuteReader()) + { + while (rdr.Read()) + { + //Product prd = new Product(); + //prd.ProdID = DbQuery.ReadInt(rdr, ""ProdID"", -1); + //prd.ProdName = DbQuery.ReadString(rdr, ""ProdName"", """"); + //prd.Price = DbQuery.ReadDouble(rdr, ""Price"", 0); + //products.Add(prd); + } + } + } + + return products; + } + +``` + +By commenting out the section which creates the Product objects and adds them to the list, I can see how fast the database related code runs. If that runs quicker then 4 seconds then I know that it's something to do with the Product object creation and/or the calls to DBQuery which are taking a long time to complete. + +It's trial and error, but since this routine if very simple, it should not take long to do this type of analysis.","Just from the sounds of it, this has to be a database performance or latency issue (if connecting remotely.)" +9866679,"I came across `html>body` in one of the stylesheets and wanted to know as to why it is used. + +``` +html>body { + font-size: 16px; + font-size: 78.75%; +} + +```",2012/03/26,"['https://Stackoverflow.com/questions/9866679', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1184100/']","It's called a [Child Selector](http://www.w3.org/TR/CSS2/selector.html#child-selectors). + +The reason it's being used is likely because it's a hack to exclude IE6 and below. Those browsers don't understand the `>` selector. + +**[More Information](http://en.wikipedia.org/wiki/CSS_filter#Child_selector_hack)**","Child selector, more info here: + +So in your code it would be any body child of html" +9866679,"I came across `html>body` in one of the stylesheets and wanted to know as to why it is used. + +``` +html>body { + font-size: 16px; + font-size: 78.75%; +} + +```",2012/03/26,"['https://Stackoverflow.com/questions/9866679', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1184100/']","It's called a [Child Selector](http://www.w3.org/TR/CSS2/selector.html#child-selectors). + +The reason it's being used is likely because it's a hack to exclude IE6 and below. Those browsers don't understand the `>` selector. + +**[More Information](http://en.wikipedia.org/wiki/CSS_filter#Child_selector_hack)**","'> symbol indicates `child of` +Above code means +The style applies to all the tag body which is a child of html + +``` + #sample>div + +``` + +above applies to all divs which are children of the element with id sample" +9866679,"I came across `html>body` in one of the stylesheets and wanted to know as to why it is used. + +``` +html>body { + font-size: 16px; + font-size: 78.75%; +} + +```",2012/03/26,"['https://Stackoverflow.com/questions/9866679', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1184100/']","It's called a [Child Selector](http://www.w3.org/TR/CSS2/selector.html#child-selectors). + +The reason it's being used is likely because it's a hack to exclude IE6 and below. Those browsers don't understand the `>` selector. + +**[More Information](http://en.wikipedia.org/wiki/CSS_filter#Child_selector_hack)**","the '>' means that it is referencing on child elements of the parent (in this case 'html') + +so for example I could have an arrangement of divs that look like so + +``` +
+
+
+
+
+
+ +``` + +and i wrote some css like so + +``` +#outermost>.inner { background-color: #CCC; } + +``` + +it would only apply the rules to the first level '#inner' + +Obviously there is only one body tag however it used to be a hack to exclude ie6 and below to write different rules for ie7+ ;)" +9866679,"I came across `html>body` in one of the stylesheets and wanted to know as to why it is used. + +``` +html>body { + font-size: 16px; + font-size: 78.75%; +} + +```",2012/03/26,"['https://Stackoverflow.com/questions/9866679', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1184100/']","the '>' means that it is referencing on child elements of the parent (in this case 'html') + +so for example I could have an arrangement of divs that look like so + +``` +
+
+
+
+
+
+ +``` + +and i wrote some css like so + +``` +#outermost>.inner { background-color: #CCC; } + +``` + +it would only apply the rules to the first level '#inner' + +Obviously there is only one body tag however it used to be a hack to exclude ie6 and below to write different rules for ie7+ ;)","Child selector, more info here: + +So in your code it would be any body child of html" +9866679,"I came across `html>body` in one of the stylesheets and wanted to know as to why it is used. + +``` +html>body { + font-size: 16px; + font-size: 78.75%; +} + +```",2012/03/26,"['https://Stackoverflow.com/questions/9866679', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1184100/']","the '>' means that it is referencing on child elements of the parent (in this case 'html') + +so for example I could have an arrangement of divs that look like so + +``` +
+
+
+
+
+
+ +``` + +and i wrote some css like so + +``` +#outermost>.inner { background-color: #CCC; } + +``` + +it would only apply the rules to the first level '#inner' + +Obviously there is only one body tag however it used to be a hack to exclude ie6 and below to write different rules for ie7+ ;)","'> symbol indicates `child of` +Above code means +The style applies to all the tag body which is a child of html + +``` + #sample>div + +``` + +above applies to all divs which are children of the element with id sample" +124342,When a singer asks to tune a song a half step down from Gbm would that be Fminor or Gb?,2022/08/12,"['https://music.stackexchange.com/questions/124342', 'https://music.stackexchange.com', 'https://music.stackexchange.com/users/88138/']","It means F minor. + +Singers frequently change the key of (transpose) a song in order to best fit their vocal range. + +Changing to Gb major would be a change of mode, which would entirely change the character of the music. + +The below video is timed to a performance of the Beatles's ""Here Comes the Sun"", first in major, then shifted to minor.","I'd be surprised if the original key was G♭m - F♯m is far more the common way to call it. But you wouldn't change the key of any song from minor to major - or vice versa, just to suit someone's range. In fact, merely dropping a semitone is unusual. if it's that awkward to sing in G♭m, Em could be even better! (And probably easier to play...) + +So, basic premise - if the original is in minor, change key to another minor, if major, new key needs to be also major." +108713,"I'm thinking of buying entry level DSLR Nikon D3500. I haven't used DSLR before, so I'm not sure if it is a good decision to buy DSLR. I would like to know if with this camera I can shoot portraits with blured background such as on the new smartphones with two cameras. Another thing I want to know if buying DSLR is good for beginners in photography and amateur photographers and is it worth the money. + +I'm new in this community, so I'm not sure if this is the right place to ask this question.",2019/06/05,"['https://photo.stackexchange.com/questions/108713', 'https://photo.stackexchange.com', 'https://photo.stackexchange.com/users/85164/']","If you read the other answers, it should be apparent that the qualities you seek such as (a) better portraits and (b) the desire to have a blurred background ... aren't really one thing, but a combination of many factors. + +There are some nuances but the short answer is ... portraits do not require advanced DSLRs (so entry level is fine) but... there are nuances to consider. I discuss these below. + +The advantage of the DSLR isn't that the camera is 'better' per se, but rather that it allows interchangeable accessories (such as lenses, lighting, etc.) to create the right conditions in order to capture the results you want. + +Much of this is based on the knowledge & skill of the photographer. Buying a more expensive musical instrument doesn't make a person a better musician... learning music and practicing makes a person a better musician. The camera can't propel you forward ... but a camera with limited capabilities might hold you back. + +If I buy a better guitar than anything Peter Frampton uses ... I will *still* not be a better musician than Peter Frampton (nowhere even close). His knowledge and skill in that area of music is legendary and mine ... not so much. + +**Better portraits** + +We're getting into a subjective area, but flip through portraits you like and try to notice why you like them. Inspect the posing of the model, the composition of the frame and how foreground or background elements are used. Check out the lighting (*especially* check out the lighting). + +My personal thoughts are that: + +1. Photographer knowledge & experience (skill) is probably the most important factor to influence the results. There's no getting around the notion that there will be a lot of learning and a lot of practice. The camera itself isn't a substitute for those considerations ... no matter how much a person pays for the equipment. Compositional skills, posing skills, exposure skills, lighting skills, etc. all require knowledge & experience ... regardless of how good the gear is. The camera will offer an 'automatic' mode and while that mode will capture adequate shots, they probably will not be the artistic results you were hoping to get. +2. Lighting is next. I put this ahead of lens selection. A key idea here is that you cannot have good light ... without good shadow. An image of a full moon never looks as good as an image of a 1st Quarter moon. The difference is that one has 'flat' lighting and the other has the light coming from the side. When the light comes from the side, any 3D textures produce shadows. It's the interplay of those highlights and shadows that causes the subject to appear three-dimensional with loads of textures. This isn't just true of the moon... it's true of anything you photograph. Shadows queue the eye (and the human brain) and provide information about the textures and contours. Another consideration is whether the transition from highlight to shadow is an abrupt line ... or a gentle transition. Is it 'hard' lighting or 'soft' lighting (hard & soft refer to those transitions... a hard-edge has an abrupt transition with a sharp line separating light & shadow. A soft-edge is a very gentle transition from one to the other.) Lighting can create moods... you can use light to convey emotions such as joy or peace or despair. In my opinion this is one of the most powerful tools a photographer has (and yet so very many photographers seem to be obsessed with just their camera.) The best lighting is the lighting that does what you want ... and this often means you may need ways to control the lighting (which is why advanced photographers own auxiliary lighting and lighting modifiers). +3. Lens selection is next on my personal list of priorities. A helpful way to think of lenses isn't so much by focal length ... but by *angle-of-view*. A lens can be *wide*, *normal*, or *narrow*. A normal angle of view is one that matches roughly what a human eye would perceive. A technical point to keep in mind (it's not hard to remember this) is that a lens will provide a *normal* angle of view if the focal length of the lens is the same as the diagonal measure of the sensor. For most DSLRs with an APS-C size sensor this is roughly 28mm (that's not exact). A 28mm lens on such a camera will offer a normal angle of view. If you use a shorter focal length (e.g. 20mm) you will have a moderately wide angle of view. If you use a much lower focal length (e.g. 10mm) you will have a very wide angle of view. A 50mm focal length will offer a moderately narrow angle of view. A 200mm lens will offer a very narrow angle of view. These angles-of-view create some interesting and useful side-effects. Wide angle lenses do not just shoot wider scenes... they also *stretch* the sense of the depth in a scene (want to make a room look larger or make a subject appear farther away... use a wider lens). The opposite happens with a narrow lens. Narrow lenses (long focal lengths) produce *compression*. Far away subjects don't look so far. The sense of depth in a scene is 'compressed'. +4. The camera body is in last place on my list. It isn't that it is not important... it is important. But it wields less influence than the three factors above it. There are many instances where the physical sensor used in an entry level body is actually the *same* sensor used in a higher-end body. So what's the difference? Usually the difference is other features such as the number and type of focus points used ... or how quickly the camera can rapidly burst shots ... or the size of the camera's internal memory buffer. If you're doing a lot of action photography, there are features a camera might have that optimizes it toward action photography. But if you're shooting a landscape on a tripod using a remote shutter release and you have all the time in the world to get that shot... having loads of auto-focus points and high-speed burst isn't really going to help you. On the other hand if you are a sports/action photographer ... the lack of those features might mean you get fewer 'keepers' as the camera struggles to have the focus system and shutter keep up with the action. + +The above is my priority list. A different photographer might give you a different order. I don't get to hung up on brand names or equipment. Loads of companies make fantastic cameras. It is possible to select a camera that may not be ideal for a particular type of photography ... and it is possible to select a lens that isn't ideal. + +**Blurred Backgrounds** + +Ultimately the ability to have one thing in sharp focus and another thing far out of focus (to make that thing blurry) is based on an idea called the **Depth of Field** (you'll often see this abbreviated as DoF). + +If my subject is 10 feet away and I point the lens at the subject, we'll need to focus the lens on the subject. In reality we are adjusting the focus for a 10 foot distance. If something is not *precisely* 10' away... suppose something is 9'11"" or 10'1"" -- will being fractionally nearer or farther make a difference? Probably not when you consider the ratios... 10' = 10 x 12 inches or 120 inches away. So a 1"" difference works out to a difference of just 0.8% (not even 1%). But what if a lens was focused to 10' and something else was 100' away... now the difference is more significant. + +DoF is the idea that there's a range of distances at which you will judge the subject to be ... more or less ... acceptably focused (I didn't say perfectly focused). How you judge this will also be affected by how closely you inspect the image. + +There are a few factors that ... when added together ... affect the overall depth-of-field. + +This include things such as: + +* Focal length of the lens where short focal length lenses tend to produce much broader depth of field and very long focal length lenses tend to produce much narrower depth of field. +* Focal ratio of the lens. The focal ratio considers the size of the physical opening in the lens through which light may pass. But instead of being a simple diameter ... it is expressed as a *ratio* of the lens' overall focal length divided by that physical diameter. If a lens with a 100mm focal length has an aperture opening 50mm across than that lens has a focal ratio of 2 ... since 100 ÷ 50 = 2. That would be expressed as f/2 (the 'f/' is short-hand for *focal ratio*). If we adjust the opening so that it has a diameter of 25mm then the focal ratio becomes f/4 because 100 ÷ 25 = 4. One take-away is notice that the lower-focal ratio example (f/2) had the larger physical diameter opening in the lens (50mm opening on a 100mm lens). If the lens had a very tiny opening (a pin-hole) then all the light has to pass through just that one very tiny point. Such a lens would have and extremely large depth-of-field. If you use a lens with a very large opening, the photons have a choice of many different paths through the lens. This reduces the overall depth-of-field. +* Subject distance is another factor. If a subject is very far away a lens needs to be focused to near the *infinity* point. Of course everything in the background is even farther ... so *also* focused to near the infinity point. Since there isn't much difference ... the background seems to be more or less just as well focused as the subject. Foreground subjects might appear blurry. But if the subject were close to you... and the background was quite far away, the background will probably appear to be more blurred. As a photographer I *rarely* place a subject against a wall for a portrait shoot... unless that wall is *extremely* interesting and will add to the overall value of the shot. Better to pull them away from the wall so that the wall can fall begins to get farther outside the depth-of-field. + +All of these factors have to be combined... each one simply influences the overall depth of field. None of them completely rule the depth of field. + +A camera with a long focal length lens using a very low focal ratio and a subject placed somewhat close to the camera with a background placed much farther away ... will result in strong background blur. Doing the opposite ... short-focal length lens, high focal ratio, and a more distant subject ... will produce very large DoF and you won't notice much blur in the background. + +**Other Considerations for Blur** + +There is a term used in photography called 'bokeh'. This term refers to the *quality* of the blur... not the *strength* of the blur. + +Once upon a time, Canon produce a particular 50mm f/1.8 lens that had merely 5 aperture blades inside the lens and these were not well-rounded blades. This means the opening in the lens was a pentagon instead of a circle. As points of light blur, they blur with the geometry of the aperture opening. This means that as pentagons overlap pentagons it created a rather strange effect ... the quality of the blur was not very smooth. It was somewhat jagged ... jittery ... almost nervous looking. It did not evoke emotions of peace and beauty that will add to the effect most photographers were going for. + +Canon replaced that lens with a lens that has identical optics (not similar... identical!) But that newer lens has 7 aperture blades instead of 5 and the blades on the newer lens do a bit better w.r.t. to being more well-rounded. This produces a more circular opening and the results in images produce a much better quality in the background blur (the blur appears more smooth). + +The lenses are optically identical and they have identical focal ratios. But one lens produce a poor quality blur. The other produces a higher quality blur. + +*This* is what the term 'bokeh' is meant to convey... the quality (over quantity). + +This means that even if you combine the conditions such as focal length, focal ratio, and subject distance (relative to background distance) to try to maximize the background blur... it is possible to have a blur ... but a blur that you may not enjoy. + +**Summary** + +* An entry-level DSLR body is fine for portrait work. Portraits usually do not require advanced camera features. +* You'll need to pair it with an appropriate lens to achieve the results you want (blurred background portraits). A DSLR is often packaged with a 'kit' lens and this is usually a standard zoom offering a bit of wide angle and a bit of narrow angle but not a particularly low focal ratio (manufacturers try to pair the camera body with an affordable lens to put them with financial reach of more consumers). Using a 50mm lens would be better ... using an 85mm lens would be even better still. +* Your skill will be very important ... the equipment alone wont be enough. If you use the 'automatic' setting mode it will tend to go for 'safe' exposures ... not artistic exposures. Skill is needed to learn which settings produce the results you want. +* Lighting will also be an important factor. Good lighting isn't just natural lighting... it's lighting that does what you want. Photographers with deeper pockets invest in equipment (although a lot of lighting gear can be surprisingly cheap when you compare lighting costs to lens costs and other equipment costs) ... but they invest in this gear specifically because it lets them control the lighting.","I had an entry level for years (Canon 550D) and I have taken really good shots on it. Although lenses are important, I would like to enumerate a few other factors (sorted from the most important to the less important) that will influence on your results + +1. **The subject**: This is by far the most important of all. Your cellphone can make a much better picture than your camera if you point it to the right subject. I have wasted a lot of time taking pictures of not so interesting subjects and thinking about saving money to buy a better camera until I finally discovered that it is a much better investment to spend that money on short travels to parks with view-sights and animals, or neighborhoods with cute streets and interesting people, etc etc. +2. **Light and weather conditions**: Remember the park I said you should go? If you really want good results, you should check the forecast, go really early in the morning or maybe after rains, it depends on what you want, but this the right conditions will add the right ""life"" to your photos +3. **The lenses**: You may be in the right place but maybe the right light you want is something that just doesn't occur naturally. Or maybe you want to be much closer to some animal, or to take a much wider picture. For this, you have the lenses. An f/4 outside in a clear day can make really good pictures, but an f/2.8 will let you work under more severe light conditions. However, an f/4 is much lighter than an f/2.8 and this may allow you to make longer journeys. An 70-200mm will make you fell amazed on how much close you can get to some subjects and a 16mm will let you make excellent wide photos. And good lens are forever. They will always do their job and you can sell them well if in good condition. They are an instant change in possibilities: you change the lens, everything changes +4. **How you use your camera and lenses**: You have to know your equipment. To know where are the button, the limitations, which possibilities do you have and so on. After upgrading for a better camera, you will feel for a while that you were more capable with your old camera until you get to know your new one +5. **The camera**: Finally, the camera. In my experience, a better camera gives you a better ISO, better shutter, more durable components, more functionalities, more photos per second, etc. Not necessarily a better sensor, for example. The better camera will make it easier for you to go further, but if you don't have what I told you above, there will be not a lot of difference in your results. + +Best thing I can recommend in order to achieve maturity as a photographer so you finally feel that your entry level camera is limiting you is to go outside and take pictures. Just go out for it every weekend and you will start to understand the places, the lights, your equipment. After that, the day will come where you will know exactly why you need a better camera and what camera you need. And you will probably keep the entry level, because they are good anyway." +108713,"I'm thinking of buying entry level DSLR Nikon D3500. I haven't used DSLR before, so I'm not sure if it is a good decision to buy DSLR. I would like to know if with this camera I can shoot portraits with blured background such as on the new smartphones with two cameras. Another thing I want to know if buying DSLR is good for beginners in photography and amateur photographers and is it worth the money. + +I'm new in this community, so I'm not sure if this is the right place to ask this question.",2019/06/05,"['https://photo.stackexchange.com/questions/108713', 'https://photo.stackexchange.com', 'https://photo.stackexchange.com/users/85164/']","**It's not the camera, it's the lens.** + +If you want a cheap and good option for shooting portrait pictures, you should definitely purchase in addition to a DSLR, a 50mm f/1.8 ""nifty fifty"" lens. Do expect to spend $100-$200 for the lens. + +50mm is about optimal for portraits, because the relatively long 50mm focal length on crop sensor cameras is long enough to obtain blurred background while being short enough that the distance to the subject need not be excessive. + +At 50mm, the kit zoom probably has f/5.6 aperture. A nifty fifty has f/1.8 aperture, which is more than 3x the difference. Three times the background blur with a nifty fifty. + +Even an expensive (and heavy and large!) zoom (17-55mm f/2.8, $700-$1000) cannot match a nifty fifty (50mm f/1.8, $100-$200). + +Also, the f/1.8 aperture is useful in low light no flash situations: the f/1.8 collects 9.68x the amount of light than the f/5.6 (@50mm) zoom.","A DX sensor has a crop factor of 2/3. You are presumably talking about the 18-55mm kit lens. For portrait work, you'd likely use it at its long end, giving you about 83mm equivalent focal length with an aperture of 1:5.6. That will give you the same depth of field as an 1:8 aperture setting on a 35mm film camera with the same kind of effective focal length which is quite discernible but not terribly strong. You'll want to arrange your scene appropriately so that the background is indeed some distance away. + +The computational blurring on a smartphone aims to emulate the visuals of quite smaller depth of field, namely larger sensors/aperture. If your viewing device ends up being a smartphone, you'll not likely be able to appreciate the much more natural action of optical object isolation (but due to camera and lens parameters, more subtle) over computational approaches, particularly since the small display scale increases the perceived depth of field. + +If you are going for print, things will look different already, however. + +Is it worth the money? It depends on your purpose. If you don't intend to throw further money at the problem of doing portraits (namely buying a suitable prime lens or a less basic zoom lens), you'd likely be better off with a 15-year old Sony DSC-R1. It has about the same sensor size, goes to 120mm equivalent at 1:4.8 aperture. Its age has definite implications for handling (no image stabilisation, so tripod wanted), speed, storage media, convenience, autofocus, sensor resolution (10MP) and sensitivity (ISO400 is where noise starts) and so on. But for your principal criterion of a small depth of field at reasonable image quality in portrait situations, it will deliver more than the D3500 with a kit lens, but you will be left without an upgrade path. + +Of course, analog cameras will deliver effortlessly in that category at quite cheaper secondhand prices but handling film is a hassle in comparison. Even if you do want to end up using film, learning your photographic skills using digital first is going to save you a lot of time and money. + +To summarize: you want to throw money at a problem. The direction you are planning to throw it in is a good starting point but you'll need to throw more in that direction before achieving your goals. Partial goals may be achieved cheaper by throwing in a different direction first and thus getting a good idea how and where to throw larger wads of money for best effect at some later point of time. + +Buying your learning gear preowned often means that as you develop a good idea where you want to be heading for real, the gear retains most of its resale value. Newer gear often is more supportive with regard to getting good results with moderate effort, however." +108713,"I'm thinking of buying entry level DSLR Nikon D3500. I haven't used DSLR before, so I'm not sure if it is a good decision to buy DSLR. I would like to know if with this camera I can shoot portraits with blured background such as on the new smartphones with two cameras. Another thing I want to know if buying DSLR is good for beginners in photography and amateur photographers and is it worth the money. + +I'm new in this community, so I'm not sure if this is the right place to ask this question.",2019/06/05,"['https://photo.stackexchange.com/questions/108713', 'https://photo.stackexchange.com', 'https://photo.stackexchange.com/users/85164/']","Is an entry level DSLR going to shoot nice portrait pictures? By itself, *no*, absolutely not. + +It's easy to make the joke that the camera by itself just sits there and doesn't take pictures at all, being an inanimate object and all. Of course, we know what you actually mean, but there's really some truth to that. A DSLR is by nature a flexible tool, and that includes the flexibility to *get bad results* as well as good ones. So, in a very real way, whether you get nice pictures is up to you, not the camera. + +If you put some time, effort, and brain-power into learning how to operate a DSLR *and to understand fundamental concepts about light and composition*, you can **absolutely** get better results with a DSLR (entry level or above) than with a phone camera. + +However, if you just want to snap pictures without learning anything or working for each shot, a high-end smartphone is guaranteed to produce results you'll be happier with 99% of the time. + +**Spending your money on a DSLR (or other interchangeable lens camera) and hoping that that alone will produce good photographs is a recipe for frustration and disappointment.** + +You say: + +> +> Another thing I want to know if buying DSLR is good for beginners in photography and amateur photographers and is it worth the money. +> +> +> + +and fundamentally, to answer this, you need to know if you want to actually be a *beginner in photography* — that is, someone who is *starting on the path to something bigger*. Do you want to be an *amateur* in the true sense of ""someone who does something because they love it""? + +If the answer is yes, then it's probably worth quite a bit of money (and in fact, I'd suggest starting beyond so-called ""entry level"" cameras — see [Are there disadvantages to a prosumer camera for a beginner, aside from cost?](https://photo.stackexchange.com/questions/5883/are-there-disadvantages-to-a-prosumer-camera-for-a-beginner-aside-from-cost)). + +On the other hand, if you mean ""someone who doesn't know much and doesn't care to"" (a [dabbler](https://english.stackexchange.com/questions/319354/whats-a-word-for-someone-with-low-level-of-knowledge-in-an-area-and-no-intenti), perhaps), then without even knowing your financial situation I can say that no, it would not be worth the money.","Yes, low-end DSLRs can get you nice photos. But it depends a lot on the photographer, not just the camera. + +The main thing to keep in mind for blurry backgrounds is the ratio between two distances: + +* camera to the point of focus; and +* camera to background. + +The further the background relative to the subject, the blurrier the background. + +Also, the bigger the aperture opens, the more pronounced the effect. The size of the opening is represented by the f-stop. The smaller the number, the wider the aperture (harder to focus). So f/16 will give you a much sharper overall picture than f/4. Much of the time, f/8 is pretty sharp all around, and if your lens can reach it, f/1.8 will give you good subject isolation with a blurry background. But you’ll need to experiment to see what *you* like." +108713,"I'm thinking of buying entry level DSLR Nikon D3500. I haven't used DSLR before, so I'm not sure if it is a good decision to buy DSLR. I would like to know if with this camera I can shoot portraits with blured background such as on the new smartphones with two cameras. Another thing I want to know if buying DSLR is good for beginners in photography and amateur photographers and is it worth the money. + +I'm new in this community, so I'm not sure if this is the right place to ask this question.",2019/06/05,"['https://photo.stackexchange.com/questions/108713', 'https://photo.stackexchange.com', 'https://photo.stackexchange.com/users/85164/']","**It's not the camera, it's the lens.** + +If you want a cheap and good option for shooting portrait pictures, you should definitely purchase in addition to a DSLR, a 50mm f/1.8 ""nifty fifty"" lens. Do expect to spend $100-$200 for the lens. + +50mm is about optimal for portraits, because the relatively long 50mm focal length on crop sensor cameras is long enough to obtain blurred background while being short enough that the distance to the subject need not be excessive. + +At 50mm, the kit zoom probably has f/5.6 aperture. A nifty fifty has f/1.8 aperture, which is more than 3x the difference. Three times the background blur with a nifty fifty. + +Even an expensive (and heavy and large!) zoom (17-55mm f/2.8, $700-$1000) cannot match a nifty fifty (50mm f/1.8, $100-$200). + +Also, the f/1.8 aperture is useful in low light no flash situations: the f/1.8 collects 9.68x the amount of light than the f/5.6 (@50mm) zoom.","Is an entry level DSLR going to shoot nice portrait pictures? By itself, *no*, absolutely not. + +It's easy to make the joke that the camera by itself just sits there and doesn't take pictures at all, being an inanimate object and all. Of course, we know what you actually mean, but there's really some truth to that. A DSLR is by nature a flexible tool, and that includes the flexibility to *get bad results* as well as good ones. So, in a very real way, whether you get nice pictures is up to you, not the camera. + +If you put some time, effort, and brain-power into learning how to operate a DSLR *and to understand fundamental concepts about light and composition*, you can **absolutely** get better results with a DSLR (entry level or above) than with a phone camera. + +However, if you just want to snap pictures without learning anything or working for each shot, a high-end smartphone is guaranteed to produce results you'll be happier with 99% of the time. + +**Spending your money on a DSLR (or other interchangeable lens camera) and hoping that that alone will produce good photographs is a recipe for frustration and disappointment.** + +You say: + +> +> Another thing I want to know if buying DSLR is good for beginners in photography and amateur photographers and is it worth the money. +> +> +> + +and fundamentally, to answer this, you need to know if you want to actually be a *beginner in photography* — that is, someone who is *starting on the path to something bigger*. Do you want to be an *amateur* in the true sense of ""someone who does something because they love it""? + +If the answer is yes, then it's probably worth quite a bit of money (and in fact, I'd suggest starting beyond so-called ""entry level"" cameras — see [Are there disadvantages to a prosumer camera for a beginner, aside from cost?](https://photo.stackexchange.com/questions/5883/are-there-disadvantages-to-a-prosumer-camera-for-a-beginner-aside-from-cost)). + +On the other hand, if you mean ""someone who doesn't know much and doesn't care to"" (a [dabbler](https://english.stackexchange.com/questions/319354/whats-a-word-for-someone-with-low-level-of-knowledge-in-an-area-and-no-intenti), perhaps), then without even knowing your financial situation I can say that no, it would not be worth the money." +108713,"I'm thinking of buying entry level DSLR Nikon D3500. I haven't used DSLR before, so I'm not sure if it is a good decision to buy DSLR. I would like to know if with this camera I can shoot portraits with blured background such as on the new smartphones with two cameras. Another thing I want to know if buying DSLR is good for beginners in photography and amateur photographers and is it worth the money. + +I'm new in this community, so I'm not sure if this is the right place to ask this question.",2019/06/05,"['https://photo.stackexchange.com/questions/108713', 'https://photo.stackexchange.com', 'https://photo.stackexchange.com/users/85164/']","If you read the other answers, it should be apparent that the qualities you seek such as (a) better portraits and (b) the desire to have a blurred background ... aren't really one thing, but a combination of many factors. + +There are some nuances but the short answer is ... portraits do not require advanced DSLRs (so entry level is fine) but... there are nuances to consider. I discuss these below. + +The advantage of the DSLR isn't that the camera is 'better' per se, but rather that it allows interchangeable accessories (such as lenses, lighting, etc.) to create the right conditions in order to capture the results you want. + +Much of this is based on the knowledge & skill of the photographer. Buying a more expensive musical instrument doesn't make a person a better musician... learning music and practicing makes a person a better musician. The camera can't propel you forward ... but a camera with limited capabilities might hold you back. + +If I buy a better guitar than anything Peter Frampton uses ... I will *still* not be a better musician than Peter Frampton (nowhere even close). His knowledge and skill in that area of music is legendary and mine ... not so much. + +**Better portraits** + +We're getting into a subjective area, but flip through portraits you like and try to notice why you like them. Inspect the posing of the model, the composition of the frame and how foreground or background elements are used. Check out the lighting (*especially* check out the lighting). + +My personal thoughts are that: + +1. Photographer knowledge & experience (skill) is probably the most important factor to influence the results. There's no getting around the notion that there will be a lot of learning and a lot of practice. The camera itself isn't a substitute for those considerations ... no matter how much a person pays for the equipment. Compositional skills, posing skills, exposure skills, lighting skills, etc. all require knowledge & experience ... regardless of how good the gear is. The camera will offer an 'automatic' mode and while that mode will capture adequate shots, they probably will not be the artistic results you were hoping to get. +2. Lighting is next. I put this ahead of lens selection. A key idea here is that you cannot have good light ... without good shadow. An image of a full moon never looks as good as an image of a 1st Quarter moon. The difference is that one has 'flat' lighting and the other has the light coming from the side. When the light comes from the side, any 3D textures produce shadows. It's the interplay of those highlights and shadows that causes the subject to appear three-dimensional with loads of textures. This isn't just true of the moon... it's true of anything you photograph. Shadows queue the eye (and the human brain) and provide information about the textures and contours. Another consideration is whether the transition from highlight to shadow is an abrupt line ... or a gentle transition. Is it 'hard' lighting or 'soft' lighting (hard & soft refer to those transitions... a hard-edge has an abrupt transition with a sharp line separating light & shadow. A soft-edge is a very gentle transition from one to the other.) Lighting can create moods... you can use light to convey emotions such as joy or peace or despair. In my opinion this is one of the most powerful tools a photographer has (and yet so very many photographers seem to be obsessed with just their camera.) The best lighting is the lighting that does what you want ... and this often means you may need ways to control the lighting (which is why advanced photographers own auxiliary lighting and lighting modifiers). +3. Lens selection is next on my personal list of priorities. A helpful way to think of lenses isn't so much by focal length ... but by *angle-of-view*. A lens can be *wide*, *normal*, or *narrow*. A normal angle of view is one that matches roughly what a human eye would perceive. A technical point to keep in mind (it's not hard to remember this) is that a lens will provide a *normal* angle of view if the focal length of the lens is the same as the diagonal measure of the sensor. For most DSLRs with an APS-C size sensor this is roughly 28mm (that's not exact). A 28mm lens on such a camera will offer a normal angle of view. If you use a shorter focal length (e.g. 20mm) you will have a moderately wide angle of view. If you use a much lower focal length (e.g. 10mm) you will have a very wide angle of view. A 50mm focal length will offer a moderately narrow angle of view. A 200mm lens will offer a very narrow angle of view. These angles-of-view create some interesting and useful side-effects. Wide angle lenses do not just shoot wider scenes... they also *stretch* the sense of the depth in a scene (want to make a room look larger or make a subject appear farther away... use a wider lens). The opposite happens with a narrow lens. Narrow lenses (long focal lengths) produce *compression*. Far away subjects don't look so far. The sense of depth in a scene is 'compressed'. +4. The camera body is in last place on my list. It isn't that it is not important... it is important. But it wields less influence than the three factors above it. There are many instances where the physical sensor used in an entry level body is actually the *same* sensor used in a higher-end body. So what's the difference? Usually the difference is other features such as the number and type of focus points used ... or how quickly the camera can rapidly burst shots ... or the size of the camera's internal memory buffer. If you're doing a lot of action photography, there are features a camera might have that optimizes it toward action photography. But if you're shooting a landscape on a tripod using a remote shutter release and you have all the time in the world to get that shot... having loads of auto-focus points and high-speed burst isn't really going to help you. On the other hand if you are a sports/action photographer ... the lack of those features might mean you get fewer 'keepers' as the camera struggles to have the focus system and shutter keep up with the action. + +The above is my priority list. A different photographer might give you a different order. I don't get to hung up on brand names or equipment. Loads of companies make fantastic cameras. It is possible to select a camera that may not be ideal for a particular type of photography ... and it is possible to select a lens that isn't ideal. + +**Blurred Backgrounds** + +Ultimately the ability to have one thing in sharp focus and another thing far out of focus (to make that thing blurry) is based on an idea called the **Depth of Field** (you'll often see this abbreviated as DoF). + +If my subject is 10 feet away and I point the lens at the subject, we'll need to focus the lens on the subject. In reality we are adjusting the focus for a 10 foot distance. If something is not *precisely* 10' away... suppose something is 9'11"" or 10'1"" -- will being fractionally nearer or farther make a difference? Probably not when you consider the ratios... 10' = 10 x 12 inches or 120 inches away. So a 1"" difference works out to a difference of just 0.8% (not even 1%). But what if a lens was focused to 10' and something else was 100' away... now the difference is more significant. + +DoF is the idea that there's a range of distances at which you will judge the subject to be ... more or less ... acceptably focused (I didn't say perfectly focused). How you judge this will also be affected by how closely you inspect the image. + +There are a few factors that ... when added together ... affect the overall depth-of-field. + +This include things such as: + +* Focal length of the lens where short focal length lenses tend to produce much broader depth of field and very long focal length lenses tend to produce much narrower depth of field. +* Focal ratio of the lens. The focal ratio considers the size of the physical opening in the lens through which light may pass. But instead of being a simple diameter ... it is expressed as a *ratio* of the lens' overall focal length divided by that physical diameter. If a lens with a 100mm focal length has an aperture opening 50mm across than that lens has a focal ratio of 2 ... since 100 ÷ 50 = 2. That would be expressed as f/2 (the 'f/' is short-hand for *focal ratio*). If we adjust the opening so that it has a diameter of 25mm then the focal ratio becomes f/4 because 100 ÷ 25 = 4. One take-away is notice that the lower-focal ratio example (f/2) had the larger physical diameter opening in the lens (50mm opening on a 100mm lens). If the lens had a very tiny opening (a pin-hole) then all the light has to pass through just that one very tiny point. Such a lens would have and extremely large depth-of-field. If you use a lens with a very large opening, the photons have a choice of many different paths through the lens. This reduces the overall depth-of-field. +* Subject distance is another factor. If a subject is very far away a lens needs to be focused to near the *infinity* point. Of course everything in the background is even farther ... so *also* focused to near the infinity point. Since there isn't much difference ... the background seems to be more or less just as well focused as the subject. Foreground subjects might appear blurry. But if the subject were close to you... and the background was quite far away, the background will probably appear to be more blurred. As a photographer I *rarely* place a subject against a wall for a portrait shoot... unless that wall is *extremely* interesting and will add to the overall value of the shot. Better to pull them away from the wall so that the wall can fall begins to get farther outside the depth-of-field. + +All of these factors have to be combined... each one simply influences the overall depth of field. None of them completely rule the depth of field. + +A camera with a long focal length lens using a very low focal ratio and a subject placed somewhat close to the camera with a background placed much farther away ... will result in strong background blur. Doing the opposite ... short-focal length lens, high focal ratio, and a more distant subject ... will produce very large DoF and you won't notice much blur in the background. + +**Other Considerations for Blur** + +There is a term used in photography called 'bokeh'. This term refers to the *quality* of the blur... not the *strength* of the blur. + +Once upon a time, Canon produce a particular 50mm f/1.8 lens that had merely 5 aperture blades inside the lens and these were not well-rounded blades. This means the opening in the lens was a pentagon instead of a circle. As points of light blur, they blur with the geometry of the aperture opening. This means that as pentagons overlap pentagons it created a rather strange effect ... the quality of the blur was not very smooth. It was somewhat jagged ... jittery ... almost nervous looking. It did not evoke emotions of peace and beauty that will add to the effect most photographers were going for. + +Canon replaced that lens with a lens that has identical optics (not similar... identical!) But that newer lens has 7 aperture blades instead of 5 and the blades on the newer lens do a bit better w.r.t. to being more well-rounded. This produces a more circular opening and the results in images produce a much better quality in the background blur (the blur appears more smooth). + +The lenses are optically identical and they have identical focal ratios. But one lens produce a poor quality blur. The other produces a higher quality blur. + +*This* is what the term 'bokeh' is meant to convey... the quality (over quantity). + +This means that even if you combine the conditions such as focal length, focal ratio, and subject distance (relative to background distance) to try to maximize the background blur... it is possible to have a blur ... but a blur that you may not enjoy. + +**Summary** + +* An entry-level DSLR body is fine for portrait work. Portraits usually do not require advanced camera features. +* You'll need to pair it with an appropriate lens to achieve the results you want (blurred background portraits). A DSLR is often packaged with a 'kit' lens and this is usually a standard zoom offering a bit of wide angle and a bit of narrow angle but not a particularly low focal ratio (manufacturers try to pair the camera body with an affordable lens to put them with financial reach of more consumers). Using a 50mm lens would be better ... using an 85mm lens would be even better still. +* Your skill will be very important ... the equipment alone wont be enough. If you use the 'automatic' setting mode it will tend to go for 'safe' exposures ... not artistic exposures. Skill is needed to learn which settings produce the results you want. +* Lighting will also be an important factor. Good lighting isn't just natural lighting... it's lighting that does what you want. Photographers with deeper pockets invest in equipment (although a lot of lighting gear can be surprisingly cheap when you compare lighting costs to lens costs and other equipment costs) ... but they invest in this gear specifically because it lets them control the lighting.","A DX sensor has a crop factor of 2/3. You are presumably talking about the 18-55mm kit lens. For portrait work, you'd likely use it at its long end, giving you about 83mm equivalent focal length with an aperture of 1:5.6. That will give you the same depth of field as an 1:8 aperture setting on a 35mm film camera with the same kind of effective focal length which is quite discernible but not terribly strong. You'll want to arrange your scene appropriately so that the background is indeed some distance away. + +The computational blurring on a smartphone aims to emulate the visuals of quite smaller depth of field, namely larger sensors/aperture. If your viewing device ends up being a smartphone, you'll not likely be able to appreciate the much more natural action of optical object isolation (but due to camera and lens parameters, more subtle) over computational approaches, particularly since the small display scale increases the perceived depth of field. + +If you are going for print, things will look different already, however. + +Is it worth the money? It depends on your purpose. If you don't intend to throw further money at the problem of doing portraits (namely buying a suitable prime lens or a less basic zoom lens), you'd likely be better off with a 15-year old Sony DSC-R1. It has about the same sensor size, goes to 120mm equivalent at 1:4.8 aperture. Its age has definite implications for handling (no image stabilisation, so tripod wanted), speed, storage media, convenience, autofocus, sensor resolution (10MP) and sensitivity (ISO400 is where noise starts) and so on. But for your principal criterion of a small depth of field at reasonable image quality in portrait situations, it will deliver more than the D3500 with a kit lens, but you will be left without an upgrade path. + +Of course, analog cameras will deliver effortlessly in that category at quite cheaper secondhand prices but handling film is a hassle in comparison. Even if you do want to end up using film, learning your photographic skills using digital first is going to save you a lot of time and money. + +To summarize: you want to throw money at a problem. The direction you are planning to throw it in is a good starting point but you'll need to throw more in that direction before achieving your goals. Partial goals may be achieved cheaper by throwing in a different direction first and thus getting a good idea how and where to throw larger wads of money for best effect at some later point of time. + +Buying your learning gear preowned often means that as you develop a good idea where you want to be heading for real, the gear retains most of its resale value. Newer gear often is more supportive with regard to getting good results with moderate effort, however." +108713,"I'm thinking of buying entry level DSLR Nikon D3500. I haven't used DSLR before, so I'm not sure if it is a good decision to buy DSLR. I would like to know if with this camera I can shoot portraits with blured background such as on the new smartphones with two cameras. Another thing I want to know if buying DSLR is good for beginners in photography and amateur photographers and is it worth the money. + +I'm new in this community, so I'm not sure if this is the right place to ask this question.",2019/06/05,"['https://photo.stackexchange.com/questions/108713', 'https://photo.stackexchange.com', 'https://photo.stackexchange.com/users/85164/']","Is an entry level DSLR going to shoot nice portrait pictures? By itself, *no*, absolutely not. + +It's easy to make the joke that the camera by itself just sits there and doesn't take pictures at all, being an inanimate object and all. Of course, we know what you actually mean, but there's really some truth to that. A DSLR is by nature a flexible tool, and that includes the flexibility to *get bad results* as well as good ones. So, in a very real way, whether you get nice pictures is up to you, not the camera. + +If you put some time, effort, and brain-power into learning how to operate a DSLR *and to understand fundamental concepts about light and composition*, you can **absolutely** get better results with a DSLR (entry level or above) than with a phone camera. + +However, if you just want to snap pictures without learning anything or working for each shot, a high-end smartphone is guaranteed to produce results you'll be happier with 99% of the time. + +**Spending your money on a DSLR (or other interchangeable lens camera) and hoping that that alone will produce good photographs is a recipe for frustration and disappointment.** + +You say: + +> +> Another thing I want to know if buying DSLR is good for beginners in photography and amateur photographers and is it worth the money. +> +> +> + +and fundamentally, to answer this, you need to know if you want to actually be a *beginner in photography* — that is, someone who is *starting on the path to something bigger*. Do you want to be an *amateur* in the true sense of ""someone who does something because they love it""? + +If the answer is yes, then it's probably worth quite a bit of money (and in fact, I'd suggest starting beyond so-called ""entry level"" cameras — see [Are there disadvantages to a prosumer camera for a beginner, aside from cost?](https://photo.stackexchange.com/questions/5883/are-there-disadvantages-to-a-prosumer-camera-for-a-beginner-aside-from-cost)). + +On the other hand, if you mean ""someone who doesn't know much and doesn't care to"" (a [dabbler](https://english.stackexchange.com/questions/319354/whats-a-word-for-someone-with-low-level-of-knowledge-in-an-area-and-no-intenti), perhaps), then without even knowing your financial situation I can say that no, it would not be worth the money.","I had an entry level for years (Canon 550D) and I have taken really good shots on it. Although lenses are important, I would like to enumerate a few other factors (sorted from the most important to the less important) that will influence on your results + +1. **The subject**: This is by far the most important of all. Your cellphone can make a much better picture than your camera if you point it to the right subject. I have wasted a lot of time taking pictures of not so interesting subjects and thinking about saving money to buy a better camera until I finally discovered that it is a much better investment to spend that money on short travels to parks with view-sights and animals, or neighborhoods with cute streets and interesting people, etc etc. +2. **Light and weather conditions**: Remember the park I said you should go? If you really want good results, you should check the forecast, go really early in the morning or maybe after rains, it depends on what you want, but this the right conditions will add the right ""life"" to your photos +3. **The lenses**: You may be in the right place but maybe the right light you want is something that just doesn't occur naturally. Or maybe you want to be much closer to some animal, or to take a much wider picture. For this, you have the lenses. An f/4 outside in a clear day can make really good pictures, but an f/2.8 will let you work under more severe light conditions. However, an f/4 is much lighter than an f/2.8 and this may allow you to make longer journeys. An 70-200mm will make you fell amazed on how much close you can get to some subjects and a 16mm will let you make excellent wide photos. And good lens are forever. They will always do their job and you can sell them well if in good condition. They are an instant change in possibilities: you change the lens, everything changes +4. **How you use your camera and lenses**: You have to know your equipment. To know where are the button, the limitations, which possibilities do you have and so on. After upgrading for a better camera, you will feel for a while that you were more capable with your old camera until you get to know your new one +5. **The camera**: Finally, the camera. In my experience, a better camera gives you a better ISO, better shutter, more durable components, more functionalities, more photos per second, etc. Not necessarily a better sensor, for example. The better camera will make it easier for you to go further, but if you don't have what I told you above, there will be not a lot of difference in your results. + +Best thing I can recommend in order to achieve maturity as a photographer so you finally feel that your entry level camera is limiting you is to go outside and take pictures. Just go out for it every weekend and you will start to understand the places, the lights, your equipment. After that, the day will come where you will know exactly why you need a better camera and what camera you need. And you will probably keep the entry level, because they are good anyway." +108713,"I'm thinking of buying entry level DSLR Nikon D3500. I haven't used DSLR before, so I'm not sure if it is a good decision to buy DSLR. I would like to know if with this camera I can shoot portraits with blured background such as on the new smartphones with two cameras. Another thing I want to know if buying DSLR is good for beginners in photography and amateur photographers and is it worth the money. + +I'm new in this community, so I'm not sure if this is the right place to ask this question.",2019/06/05,"['https://photo.stackexchange.com/questions/108713', 'https://photo.stackexchange.com', 'https://photo.stackexchange.com/users/85164/']","Is an entry level DSLR going to shoot nice portrait pictures? By itself, *no*, absolutely not. + +It's easy to make the joke that the camera by itself just sits there and doesn't take pictures at all, being an inanimate object and all. Of course, we know what you actually mean, but there's really some truth to that. A DSLR is by nature a flexible tool, and that includes the flexibility to *get bad results* as well as good ones. So, in a very real way, whether you get nice pictures is up to you, not the camera. + +If you put some time, effort, and brain-power into learning how to operate a DSLR *and to understand fundamental concepts about light and composition*, you can **absolutely** get better results with a DSLR (entry level or above) than with a phone camera. + +However, if you just want to snap pictures without learning anything or working for each shot, a high-end smartphone is guaranteed to produce results you'll be happier with 99% of the time. + +**Spending your money on a DSLR (or other interchangeable lens camera) and hoping that that alone will produce good photographs is a recipe for frustration and disappointment.** + +You say: + +> +> Another thing I want to know if buying DSLR is good for beginners in photography and amateur photographers and is it worth the money. +> +> +> + +and fundamentally, to answer this, you need to know if you want to actually be a *beginner in photography* — that is, someone who is *starting on the path to something bigger*. Do you want to be an *amateur* in the true sense of ""someone who does something because they love it""? + +If the answer is yes, then it's probably worth quite a bit of money (and in fact, I'd suggest starting beyond so-called ""entry level"" cameras — see [Are there disadvantages to a prosumer camera for a beginner, aside from cost?](https://photo.stackexchange.com/questions/5883/are-there-disadvantages-to-a-prosumer-camera-for-a-beginner-aside-from-cost)). + +On the other hand, if you mean ""someone who doesn't know much and doesn't care to"" (a [dabbler](https://english.stackexchange.com/questions/319354/whats-a-word-for-someone-with-low-level-of-knowledge-in-an-area-and-no-intenti), perhaps), then without even knowing your financial situation I can say that no, it would not be worth the money.","A DX sensor has a crop factor of 2/3. You are presumably talking about the 18-55mm kit lens. For portrait work, you'd likely use it at its long end, giving you about 83mm equivalent focal length with an aperture of 1:5.6. That will give you the same depth of field as an 1:8 aperture setting on a 35mm film camera with the same kind of effective focal length which is quite discernible but not terribly strong. You'll want to arrange your scene appropriately so that the background is indeed some distance away. + +The computational blurring on a smartphone aims to emulate the visuals of quite smaller depth of field, namely larger sensors/aperture. If your viewing device ends up being a smartphone, you'll not likely be able to appreciate the much more natural action of optical object isolation (but due to camera and lens parameters, more subtle) over computational approaches, particularly since the small display scale increases the perceived depth of field. + +If you are going for print, things will look different already, however. + +Is it worth the money? It depends on your purpose. If you don't intend to throw further money at the problem of doing portraits (namely buying a suitable prime lens or a less basic zoom lens), you'd likely be better off with a 15-year old Sony DSC-R1. It has about the same sensor size, goes to 120mm equivalent at 1:4.8 aperture. Its age has definite implications for handling (no image stabilisation, so tripod wanted), speed, storage media, convenience, autofocus, sensor resolution (10MP) and sensitivity (ISO400 is where noise starts) and so on. But for your principal criterion of a small depth of field at reasonable image quality in portrait situations, it will deliver more than the D3500 with a kit lens, but you will be left without an upgrade path. + +Of course, analog cameras will deliver effortlessly in that category at quite cheaper secondhand prices but handling film is a hassle in comparison. Even if you do want to end up using film, learning your photographic skills using digital first is going to save you a lot of time and money. + +To summarize: you want to throw money at a problem. The direction you are planning to throw it in is a good starting point but you'll need to throw more in that direction before achieving your goals. Partial goals may be achieved cheaper by throwing in a different direction first and thus getting a good idea how and where to throw larger wads of money for best effect at some later point of time. + +Buying your learning gear preowned often means that as you develop a good idea where you want to be heading for real, the gear retains most of its resale value. Newer gear often is more supportive with regard to getting good results with moderate effort, however." +108713,"I'm thinking of buying entry level DSLR Nikon D3500. I haven't used DSLR before, so I'm not sure if it is a good decision to buy DSLR. I would like to know if with this camera I can shoot portraits with blured background such as on the new smartphones with two cameras. Another thing I want to know if buying DSLR is good for beginners in photography and amateur photographers and is it worth the money. + +I'm new in this community, so I'm not sure if this is the right place to ask this question.",2019/06/05,"['https://photo.stackexchange.com/questions/108713', 'https://photo.stackexchange.com', 'https://photo.stackexchange.com/users/85164/']","**It's not the camera, it's the lens.** + +If you want a cheap and good option for shooting portrait pictures, you should definitely purchase in addition to a DSLR, a 50mm f/1.8 ""nifty fifty"" lens. Do expect to spend $100-$200 for the lens. + +50mm is about optimal for portraits, because the relatively long 50mm focal length on crop sensor cameras is long enough to obtain blurred background while being short enough that the distance to the subject need not be excessive. + +At 50mm, the kit zoom probably has f/5.6 aperture. A nifty fifty has f/1.8 aperture, which is more than 3x the difference. Three times the background blur with a nifty fifty. + +Even an expensive (and heavy and large!) zoom (17-55mm f/2.8, $700-$1000) cannot match a nifty fifty (50mm f/1.8, $100-$200). + +Also, the f/1.8 aperture is useful in low light no flash situations: the f/1.8 collects 9.68x the amount of light than the f/5.6 (@50mm) zoom.","I had an entry level for years (Canon 550D) and I have taken really good shots on it. Although lenses are important, I would like to enumerate a few other factors (sorted from the most important to the less important) that will influence on your results + +1. **The subject**: This is by far the most important of all. Your cellphone can make a much better picture than your camera if you point it to the right subject. I have wasted a lot of time taking pictures of not so interesting subjects and thinking about saving money to buy a better camera until I finally discovered that it is a much better investment to spend that money on short travels to parks with view-sights and animals, or neighborhoods with cute streets and interesting people, etc etc. +2. **Light and weather conditions**: Remember the park I said you should go? If you really want good results, you should check the forecast, go really early in the morning or maybe after rains, it depends on what you want, but this the right conditions will add the right ""life"" to your photos +3. **The lenses**: You may be in the right place but maybe the right light you want is something that just doesn't occur naturally. Or maybe you want to be much closer to some animal, or to take a much wider picture. For this, you have the lenses. An f/4 outside in a clear day can make really good pictures, but an f/2.8 will let you work under more severe light conditions. However, an f/4 is much lighter than an f/2.8 and this may allow you to make longer journeys. An 70-200mm will make you fell amazed on how much close you can get to some subjects and a 16mm will let you make excellent wide photos. And good lens are forever. They will always do their job and you can sell them well if in good condition. They are an instant change in possibilities: you change the lens, everything changes +4. **How you use your camera and lenses**: You have to know your equipment. To know where are the button, the limitations, which possibilities do you have and so on. After upgrading for a better camera, you will feel for a while that you were more capable with your old camera until you get to know your new one +5. **The camera**: Finally, the camera. In my experience, a better camera gives you a better ISO, better shutter, more durable components, more functionalities, more photos per second, etc. Not necessarily a better sensor, for example. The better camera will make it easier for you to go further, but if you don't have what I told you above, there will be not a lot of difference in your results. + +Best thing I can recommend in order to achieve maturity as a photographer so you finally feel that your entry level camera is limiting you is to go outside and take pictures. Just go out for it every weekend and you will start to understand the places, the lights, your equipment. After that, the day will come where you will know exactly why you need a better camera and what camera you need. And you will probably keep the entry level, because they are good anyway." +108713,"I'm thinking of buying entry level DSLR Nikon D3500. I haven't used DSLR before, so I'm not sure if it is a good decision to buy DSLR. I would like to know if with this camera I can shoot portraits with blured background such as on the new smartphones with two cameras. Another thing I want to know if buying DSLR is good for beginners in photography and amateur photographers and is it worth the money. + +I'm new in this community, so I'm not sure if this is the right place to ask this question.",2019/06/05,"['https://photo.stackexchange.com/questions/108713', 'https://photo.stackexchange.com', 'https://photo.stackexchange.com/users/85164/']","If you read the other answers, it should be apparent that the qualities you seek such as (a) better portraits and (b) the desire to have a blurred background ... aren't really one thing, but a combination of many factors. + +There are some nuances but the short answer is ... portraits do not require advanced DSLRs (so entry level is fine) but... there are nuances to consider. I discuss these below. + +The advantage of the DSLR isn't that the camera is 'better' per se, but rather that it allows interchangeable accessories (such as lenses, lighting, etc.) to create the right conditions in order to capture the results you want. + +Much of this is based on the knowledge & skill of the photographer. Buying a more expensive musical instrument doesn't make a person a better musician... learning music and practicing makes a person a better musician. The camera can't propel you forward ... but a camera with limited capabilities might hold you back. + +If I buy a better guitar than anything Peter Frampton uses ... I will *still* not be a better musician than Peter Frampton (nowhere even close). His knowledge and skill in that area of music is legendary and mine ... not so much. + +**Better portraits** + +We're getting into a subjective area, but flip through portraits you like and try to notice why you like them. Inspect the posing of the model, the composition of the frame and how foreground or background elements are used. Check out the lighting (*especially* check out the lighting). + +My personal thoughts are that: + +1. Photographer knowledge & experience (skill) is probably the most important factor to influence the results. There's no getting around the notion that there will be a lot of learning and a lot of practice. The camera itself isn't a substitute for those considerations ... no matter how much a person pays for the equipment. Compositional skills, posing skills, exposure skills, lighting skills, etc. all require knowledge & experience ... regardless of how good the gear is. The camera will offer an 'automatic' mode and while that mode will capture adequate shots, they probably will not be the artistic results you were hoping to get. +2. Lighting is next. I put this ahead of lens selection. A key idea here is that you cannot have good light ... without good shadow. An image of a full moon never looks as good as an image of a 1st Quarter moon. The difference is that one has 'flat' lighting and the other has the light coming from the side. When the light comes from the side, any 3D textures produce shadows. It's the interplay of those highlights and shadows that causes the subject to appear three-dimensional with loads of textures. This isn't just true of the moon... it's true of anything you photograph. Shadows queue the eye (and the human brain) and provide information about the textures and contours. Another consideration is whether the transition from highlight to shadow is an abrupt line ... or a gentle transition. Is it 'hard' lighting or 'soft' lighting (hard & soft refer to those transitions... a hard-edge has an abrupt transition with a sharp line separating light & shadow. A soft-edge is a very gentle transition from one to the other.) Lighting can create moods... you can use light to convey emotions such as joy or peace or despair. In my opinion this is one of the most powerful tools a photographer has (and yet so very many photographers seem to be obsessed with just their camera.) The best lighting is the lighting that does what you want ... and this often means you may need ways to control the lighting (which is why advanced photographers own auxiliary lighting and lighting modifiers). +3. Lens selection is next on my personal list of priorities. A helpful way to think of lenses isn't so much by focal length ... but by *angle-of-view*. A lens can be *wide*, *normal*, or *narrow*. A normal angle of view is one that matches roughly what a human eye would perceive. A technical point to keep in mind (it's not hard to remember this) is that a lens will provide a *normal* angle of view if the focal length of the lens is the same as the diagonal measure of the sensor. For most DSLRs with an APS-C size sensor this is roughly 28mm (that's not exact). A 28mm lens on such a camera will offer a normal angle of view. If you use a shorter focal length (e.g. 20mm) you will have a moderately wide angle of view. If you use a much lower focal length (e.g. 10mm) you will have a very wide angle of view. A 50mm focal length will offer a moderately narrow angle of view. A 200mm lens will offer a very narrow angle of view. These angles-of-view create some interesting and useful side-effects. Wide angle lenses do not just shoot wider scenes... they also *stretch* the sense of the depth in a scene (want to make a room look larger or make a subject appear farther away... use a wider lens). The opposite happens with a narrow lens. Narrow lenses (long focal lengths) produce *compression*. Far away subjects don't look so far. The sense of depth in a scene is 'compressed'. +4. The camera body is in last place on my list. It isn't that it is not important... it is important. But it wields less influence than the three factors above it. There are many instances where the physical sensor used in an entry level body is actually the *same* sensor used in a higher-end body. So what's the difference? Usually the difference is other features such as the number and type of focus points used ... or how quickly the camera can rapidly burst shots ... or the size of the camera's internal memory buffer. If you're doing a lot of action photography, there are features a camera might have that optimizes it toward action photography. But if you're shooting a landscape on a tripod using a remote shutter release and you have all the time in the world to get that shot... having loads of auto-focus points and high-speed burst isn't really going to help you. On the other hand if you are a sports/action photographer ... the lack of those features might mean you get fewer 'keepers' as the camera struggles to have the focus system and shutter keep up with the action. + +The above is my priority list. A different photographer might give you a different order. I don't get to hung up on brand names or equipment. Loads of companies make fantastic cameras. It is possible to select a camera that may not be ideal for a particular type of photography ... and it is possible to select a lens that isn't ideal. + +**Blurred Backgrounds** + +Ultimately the ability to have one thing in sharp focus and another thing far out of focus (to make that thing blurry) is based on an idea called the **Depth of Field** (you'll often see this abbreviated as DoF). + +If my subject is 10 feet away and I point the lens at the subject, we'll need to focus the lens on the subject. In reality we are adjusting the focus for a 10 foot distance. If something is not *precisely* 10' away... suppose something is 9'11"" or 10'1"" -- will being fractionally nearer or farther make a difference? Probably not when you consider the ratios... 10' = 10 x 12 inches or 120 inches away. So a 1"" difference works out to a difference of just 0.8% (not even 1%). But what if a lens was focused to 10' and something else was 100' away... now the difference is more significant. + +DoF is the idea that there's a range of distances at which you will judge the subject to be ... more or less ... acceptably focused (I didn't say perfectly focused). How you judge this will also be affected by how closely you inspect the image. + +There are a few factors that ... when added together ... affect the overall depth-of-field. + +This include things such as: + +* Focal length of the lens where short focal length lenses tend to produce much broader depth of field and very long focal length lenses tend to produce much narrower depth of field. +* Focal ratio of the lens. The focal ratio considers the size of the physical opening in the lens through which light may pass. But instead of being a simple diameter ... it is expressed as a *ratio* of the lens' overall focal length divided by that physical diameter. If a lens with a 100mm focal length has an aperture opening 50mm across than that lens has a focal ratio of 2 ... since 100 ÷ 50 = 2. That would be expressed as f/2 (the 'f/' is short-hand for *focal ratio*). If we adjust the opening so that it has a diameter of 25mm then the focal ratio becomes f/4 because 100 ÷ 25 = 4. One take-away is notice that the lower-focal ratio example (f/2) had the larger physical diameter opening in the lens (50mm opening on a 100mm lens). If the lens had a very tiny opening (a pin-hole) then all the light has to pass through just that one very tiny point. Such a lens would have and extremely large depth-of-field. If you use a lens with a very large opening, the photons have a choice of many different paths through the lens. This reduces the overall depth-of-field. +* Subject distance is another factor. If a subject is very far away a lens needs to be focused to near the *infinity* point. Of course everything in the background is even farther ... so *also* focused to near the infinity point. Since there isn't much difference ... the background seems to be more or less just as well focused as the subject. Foreground subjects might appear blurry. But if the subject were close to you... and the background was quite far away, the background will probably appear to be more blurred. As a photographer I *rarely* place a subject against a wall for a portrait shoot... unless that wall is *extremely* interesting and will add to the overall value of the shot. Better to pull them away from the wall so that the wall can fall begins to get farther outside the depth-of-field. + +All of these factors have to be combined... each one simply influences the overall depth of field. None of them completely rule the depth of field. + +A camera with a long focal length lens using a very low focal ratio and a subject placed somewhat close to the camera with a background placed much farther away ... will result in strong background blur. Doing the opposite ... short-focal length lens, high focal ratio, and a more distant subject ... will produce very large DoF and you won't notice much blur in the background. + +**Other Considerations for Blur** + +There is a term used in photography called 'bokeh'. This term refers to the *quality* of the blur... not the *strength* of the blur. + +Once upon a time, Canon produce a particular 50mm f/1.8 lens that had merely 5 aperture blades inside the lens and these were not well-rounded blades. This means the opening in the lens was a pentagon instead of a circle. As points of light blur, they blur with the geometry of the aperture opening. This means that as pentagons overlap pentagons it created a rather strange effect ... the quality of the blur was not very smooth. It was somewhat jagged ... jittery ... almost nervous looking. It did not evoke emotions of peace and beauty that will add to the effect most photographers were going for. + +Canon replaced that lens with a lens that has identical optics (not similar... identical!) But that newer lens has 7 aperture blades instead of 5 and the blades on the newer lens do a bit better w.r.t. to being more well-rounded. This produces a more circular opening and the results in images produce a much better quality in the background blur (the blur appears more smooth). + +The lenses are optically identical and they have identical focal ratios. But one lens produce a poor quality blur. The other produces a higher quality blur. + +*This* is what the term 'bokeh' is meant to convey... the quality (over quantity). + +This means that even if you combine the conditions such as focal length, focal ratio, and subject distance (relative to background distance) to try to maximize the background blur... it is possible to have a blur ... but a blur that you may not enjoy. + +**Summary** + +* An entry-level DSLR body is fine for portrait work. Portraits usually do not require advanced camera features. +* You'll need to pair it with an appropriate lens to achieve the results you want (blurred background portraits). A DSLR is often packaged with a 'kit' lens and this is usually a standard zoom offering a bit of wide angle and a bit of narrow angle but not a particularly low focal ratio (manufacturers try to pair the camera body with an affordable lens to put them with financial reach of more consumers). Using a 50mm lens would be better ... using an 85mm lens would be even better still. +* Your skill will be very important ... the equipment alone wont be enough. If you use the 'automatic' setting mode it will tend to go for 'safe' exposures ... not artistic exposures. Skill is needed to learn which settings produce the results you want. +* Lighting will also be an important factor. Good lighting isn't just natural lighting... it's lighting that does what you want. Photographers with deeper pockets invest in equipment (although a lot of lighting gear can be surprisingly cheap when you compare lighting costs to lens costs and other equipment costs) ... but they invest in this gear specifically because it lets them control the lighting.","Is an entry level DSLR going to shoot nice portrait pictures? By itself, *no*, absolutely not. + +It's easy to make the joke that the camera by itself just sits there and doesn't take pictures at all, being an inanimate object and all. Of course, we know what you actually mean, but there's really some truth to that. A DSLR is by nature a flexible tool, and that includes the flexibility to *get bad results* as well as good ones. So, in a very real way, whether you get nice pictures is up to you, not the camera. + +If you put some time, effort, and brain-power into learning how to operate a DSLR *and to understand fundamental concepts about light and composition*, you can **absolutely** get better results with a DSLR (entry level or above) than with a phone camera. + +However, if you just want to snap pictures without learning anything or working for each shot, a high-end smartphone is guaranteed to produce results you'll be happier with 99% of the time. + +**Spending your money on a DSLR (or other interchangeable lens camera) and hoping that that alone will produce good photographs is a recipe for frustration and disappointment.** + +You say: + +> +> Another thing I want to know if buying DSLR is good for beginners in photography and amateur photographers and is it worth the money. +> +> +> + +and fundamentally, to answer this, you need to know if you want to actually be a *beginner in photography* — that is, someone who is *starting on the path to something bigger*. Do you want to be an *amateur* in the true sense of ""someone who does something because they love it""? + +If the answer is yes, then it's probably worth quite a bit of money (and in fact, I'd suggest starting beyond so-called ""entry level"" cameras — see [Are there disadvantages to a prosumer camera for a beginner, aside from cost?](https://photo.stackexchange.com/questions/5883/are-there-disadvantages-to-a-prosumer-camera-for-a-beginner-aside-from-cost)). + +On the other hand, if you mean ""someone who doesn't know much and doesn't care to"" (a [dabbler](https://english.stackexchange.com/questions/319354/whats-a-word-for-someone-with-low-level-of-knowledge-in-an-area-and-no-intenti), perhaps), then without even knowing your financial situation I can say that no, it would not be worth the money." +108713,"I'm thinking of buying entry level DSLR Nikon D3500. I haven't used DSLR before, so I'm not sure if it is a good decision to buy DSLR. I would like to know if with this camera I can shoot portraits with blured background such as on the new smartphones with two cameras. Another thing I want to know if buying DSLR is good for beginners in photography and amateur photographers and is it worth the money. + +I'm new in this community, so I'm not sure if this is the right place to ask this question.",2019/06/05,"['https://photo.stackexchange.com/questions/108713', 'https://photo.stackexchange.com', 'https://photo.stackexchange.com/users/85164/']","I had an entry level for years (Canon 550D) and I have taken really good shots on it. Although lenses are important, I would like to enumerate a few other factors (sorted from the most important to the less important) that will influence on your results + +1. **The subject**: This is by far the most important of all. Your cellphone can make a much better picture than your camera if you point it to the right subject. I have wasted a lot of time taking pictures of not so interesting subjects and thinking about saving money to buy a better camera until I finally discovered that it is a much better investment to spend that money on short travels to parks with view-sights and animals, or neighborhoods with cute streets and interesting people, etc etc. +2. **Light and weather conditions**: Remember the park I said you should go? If you really want good results, you should check the forecast, go really early in the morning or maybe after rains, it depends on what you want, but this the right conditions will add the right ""life"" to your photos +3. **The lenses**: You may be in the right place but maybe the right light you want is something that just doesn't occur naturally. Or maybe you want to be much closer to some animal, or to take a much wider picture. For this, you have the lenses. An f/4 outside in a clear day can make really good pictures, but an f/2.8 will let you work under more severe light conditions. However, an f/4 is much lighter than an f/2.8 and this may allow you to make longer journeys. An 70-200mm will make you fell amazed on how much close you can get to some subjects and a 16mm will let you make excellent wide photos. And good lens are forever. They will always do their job and you can sell them well if in good condition. They are an instant change in possibilities: you change the lens, everything changes +4. **How you use your camera and lenses**: You have to know your equipment. To know where are the button, the limitations, which possibilities do you have and so on. After upgrading for a better camera, you will feel for a while that you were more capable with your old camera until you get to know your new one +5. **The camera**: Finally, the camera. In my experience, a better camera gives you a better ISO, better shutter, more durable components, more functionalities, more photos per second, etc. Not necessarily a better sensor, for example. The better camera will make it easier for you to go further, but if you don't have what I told you above, there will be not a lot of difference in your results. + +Best thing I can recommend in order to achieve maturity as a photographer so you finally feel that your entry level camera is limiting you is to go outside and take pictures. Just go out for it every weekend and you will start to understand the places, the lights, your equipment. After that, the day will come where you will know exactly why you need a better camera and what camera you need. And you will probably keep the entry level, because they are good anyway.","A DX sensor has a crop factor of 2/3. You are presumably talking about the 18-55mm kit lens. For portrait work, you'd likely use it at its long end, giving you about 83mm equivalent focal length with an aperture of 1:5.6. That will give you the same depth of field as an 1:8 aperture setting on a 35mm film camera with the same kind of effective focal length which is quite discernible but not terribly strong. You'll want to arrange your scene appropriately so that the background is indeed some distance away. + +The computational blurring on a smartphone aims to emulate the visuals of quite smaller depth of field, namely larger sensors/aperture. If your viewing device ends up being a smartphone, you'll not likely be able to appreciate the much more natural action of optical object isolation (but due to camera and lens parameters, more subtle) over computational approaches, particularly since the small display scale increases the perceived depth of field. + +If you are going for print, things will look different already, however. + +Is it worth the money? It depends on your purpose. If you don't intend to throw further money at the problem of doing portraits (namely buying a suitable prime lens or a less basic zoom lens), you'd likely be better off with a 15-year old Sony DSC-R1. It has about the same sensor size, goes to 120mm equivalent at 1:4.8 aperture. Its age has definite implications for handling (no image stabilisation, so tripod wanted), speed, storage media, convenience, autofocus, sensor resolution (10MP) and sensitivity (ISO400 is where noise starts) and so on. But for your principal criterion of a small depth of field at reasonable image quality in portrait situations, it will deliver more than the D3500 with a kit lens, but you will be left without an upgrade path. + +Of course, analog cameras will deliver effortlessly in that category at quite cheaper secondhand prices but handling film is a hassle in comparison. Even if you do want to end up using film, learning your photographic skills using digital first is going to save you a lot of time and money. + +To summarize: you want to throw money at a problem. The direction you are planning to throw it in is a good starting point but you'll need to throw more in that direction before achieving your goals. Partial goals may be achieved cheaper by throwing in a different direction first and thus getting a good idea how and where to throw larger wads of money for best effect at some later point of time. + +Buying your learning gear preowned often means that as you develop a good idea where you want to be heading for real, the gear retains most of its resale value. Newer gear often is more supportive with regard to getting good results with moderate effort, however." +11967306,"I am trying to use the package doBy, which requires an installation of the package lme4. + +I have found the CRAN for it here + +However when I try download the .zip version I get the error ""Object not found!"". +From what I gather it is not an out of date package (with it last been updated in June of this year). + +Does anyone know a way to get around this, or do I just need to wait for lme4 to be fixed/find an alternative for doBy? + +Thanks",2012/08/15,"['https://Stackoverflow.com/questions/11967306', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1545812/']","try + +``` +install.packages(""lme4"",repos=""http://r-forge.r-project.org"") + +```","Do you use R Studio? I was having the same issue but then I used R Studio's tab ""Packages"" -> Install tab --> write lme4 from th CRAN repository." +5738073,"I know from [this question](https://stackoverflow.com/questions/356846/c-var-vs-specific-type-performance) that `var i = 1` and `int i = 1` are exactly the same in IL. The compiler simply replaces `var` with the actual type at compile time. But, are there any instances where `var` could cause problem behavior (maybe the compiler guesses the wrong type?)",2011/04/21,"['https://Stackoverflow.com/questions/5738073', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/221061/']","No, I don't think so. The only time it can't figure things out is if you try to do something like + +``` +var product = null; + +``` + +Which makes sense, and in this case you get a compile error.","In addition to the ambiguous: + +``` +var x = null; + +``` + +the compiler will also not infer the type of overloaded method groups: + +``` +var m = String.Equals; + +``` + +nor will it infer the type of lambda expressions, which can be either `Func<>` or `Expression>`: + +``` +var l = (int x) => x + 1; + +``` + +All that said, Anthony is right: the compiler will never do the wrong thing, though it might not do what you expect. When in doubt, hover over `var` in VS to see the static type." +5738073,"I know from [this question](https://stackoverflow.com/questions/356846/c-var-vs-specific-type-performance) that `var i = 1` and `int i = 1` are exactly the same in IL. The compiler simply replaces `var` with the actual type at compile time. But, are there any instances where `var` could cause problem behavior (maybe the compiler guesses the wrong type?)",2011/04/21,"['https://Stackoverflow.com/questions/5738073', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/221061/']","I don't believe the compiler will *guess the wrong type.* However, it might *infer a type you didn't intend*, but that's not the same. + +Consider the perfectly legal + +``` +decimal foo = 10; +decimal bar = 4; +decimal baz = foo / bar; + +``` + +In the code, `baz` will very clearly be 2.5. The integer literals will be converted to decimals prior to being stored and then the math takes place on the decimal values. Remove the explicit typing and the result is different. + +``` +var foo = 10; +var bar = 4; +var baz = foo / bar; + +``` + +Now everything infers to int and `baz` is 2 because now the math is taking place with integers. + +So, yes, code semantics could theoretically change if you introduce `var` where it was not before. So the key is to understand what type inference is really going to do with your code and if you want something to be a decimal (or any specific type X), declare it in such a way that it will be. For type inference, that would be + +``` +var foo = 10m; + +```","No, I don't think so. The only time it can't figure things out is if you try to do something like + +``` +var product = null; + +``` + +Which makes sense, and in this case you get a compile error." +5738073,"I know from [this question](https://stackoverflow.com/questions/356846/c-var-vs-specific-type-performance) that `var i = 1` and `int i = 1` are exactly the same in IL. The compiler simply replaces `var` with the actual type at compile time. But, are there any instances where `var` could cause problem behavior (maybe the compiler guesses the wrong type?)",2011/04/21,"['https://Stackoverflow.com/questions/5738073', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/221061/']","No, I don't think so. The only time it can't figure things out is if you try to do something like + +``` +var product = null; + +``` + +Which makes sense, and in this case you get a compile error.","``` +var x = 0 +x = 0.10 + +``` + +`Cannot convert source type 'double' to target type 'int'` + +An example: + +``` +double x = 0; //to initialize it +switch (something) { + case condition1: + x = 0.1; + break; + case condition2: + x = 0.2; + break; +} + +``` + +Using `var` instead of `double` will give a compiler error." +5738073,"I know from [this question](https://stackoverflow.com/questions/356846/c-var-vs-specific-type-performance) that `var i = 1` and `int i = 1` are exactly the same in IL. The compiler simply replaces `var` with the actual type at compile time. But, are there any instances where `var` could cause problem behavior (maybe the compiler guesses the wrong type?)",2011/04/21,"['https://Stackoverflow.com/questions/5738073', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/221061/']","It won't cause any ""issues"", regarding code however you could have a regression issue... + +``` +IObject1 +{ + void DoSomething(); +} + +IObject2 +{ + void DoSomething(); +} + +var result = SomeMethod(); +result.DoSomething(); + +``` + +Now, if SomeMethod returned IObject1 and then was changed to return IObject2 this would still compile. ***However***, if you expect DoSomething to execute particular code then this could potentially be a regression issue. + +However, if you have + +``` +IObject1 result = SomeMethod(); + +``` + +If the return type of SomeMethod is changed you'll know it right away.","In addition to the ambiguous: + +``` +var x = null; + +``` + +the compiler will also not infer the type of overloaded method groups: + +``` +var m = String.Equals; + +``` + +nor will it infer the type of lambda expressions, which can be either `Func<>` or `Expression>`: + +``` +var l = (int x) => x + 1; + +``` + +All that said, Anthony is right: the compiler will never do the wrong thing, though it might not do what you expect. When in doubt, hover over `var` in VS to see the static type." +5738073,"I know from [this question](https://stackoverflow.com/questions/356846/c-var-vs-specific-type-performance) that `var i = 1` and `int i = 1` are exactly the same in IL. The compiler simply replaces `var` with the actual type at compile time. But, are there any instances where `var` could cause problem behavior (maybe the compiler guesses the wrong type?)",2011/04/21,"['https://Stackoverflow.com/questions/5738073', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/221061/']","I don't believe the compiler will *guess the wrong type.* However, it might *infer a type you didn't intend*, but that's not the same. + +Consider the perfectly legal + +``` +decimal foo = 10; +decimal bar = 4; +decimal baz = foo / bar; + +``` + +In the code, `baz` will very clearly be 2.5. The integer literals will be converted to decimals prior to being stored and then the math takes place on the decimal values. Remove the explicit typing and the result is different. + +``` +var foo = 10; +var bar = 4; +var baz = foo / bar; + +``` + +Now everything infers to int and `baz` is 2 because now the math is taking place with integers. + +So, yes, code semantics could theoretically change if you introduce `var` where it was not before. So the key is to understand what type inference is really going to do with your code and if you want something to be a decimal (or any specific type X), declare it in such a way that it will be. For type inference, that would be + +``` +var foo = 10m; + +```","It won't cause any ""issues"", regarding code however you could have a regression issue... + +``` +IObject1 +{ + void DoSomething(); +} + +IObject2 +{ + void DoSomething(); +} + +var result = SomeMethod(); +result.DoSomething(); + +``` + +Now, if SomeMethod returned IObject1 and then was changed to return IObject2 this would still compile. ***However***, if you expect DoSomething to execute particular code then this could potentially be a regression issue. + +However, if you have + +``` +IObject1 result = SomeMethod(); + +``` + +If the return type of SomeMethod is changed you'll know it right away." +5738073,"I know from [this question](https://stackoverflow.com/questions/356846/c-var-vs-specific-type-performance) that `var i = 1` and `int i = 1` are exactly the same in IL. The compiler simply replaces `var` with the actual type at compile time. But, are there any instances where `var` could cause problem behavior (maybe the compiler guesses the wrong type?)",2011/04/21,"['https://Stackoverflow.com/questions/5738073', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/221061/']","It won't cause any ""issues"", regarding code however you could have a regression issue... + +``` +IObject1 +{ + void DoSomething(); +} + +IObject2 +{ + void DoSomething(); +} + +var result = SomeMethod(); +result.DoSomething(); + +``` + +Now, if SomeMethod returned IObject1 and then was changed to return IObject2 this would still compile. ***However***, if you expect DoSomething to execute particular code then this could potentially be a regression issue. + +However, if you have + +``` +IObject1 result = SomeMethod(); + +``` + +If the return type of SomeMethod is changed you'll know it right away.","``` +var x = 0 +x = 0.10 + +``` + +`Cannot convert source type 'double' to target type 'int'` + +An example: + +``` +double x = 0; //to initialize it +switch (something) { + case condition1: + x = 0.1; + break; + case condition2: + x = 0.2; + break; +} + +``` + +Using `var` instead of `double` will give a compiler error." +5738073,"I know from [this question](https://stackoverflow.com/questions/356846/c-var-vs-specific-type-performance) that `var i = 1` and `int i = 1` are exactly the same in IL. The compiler simply replaces `var` with the actual type at compile time. But, are there any instances where `var` could cause problem behavior (maybe the compiler guesses the wrong type?)",2011/04/21,"['https://Stackoverflow.com/questions/5738073', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/221061/']","I don't believe the compiler will *guess the wrong type.* However, it might *infer a type you didn't intend*, but that's not the same. + +Consider the perfectly legal + +``` +decimal foo = 10; +decimal bar = 4; +decimal baz = foo / bar; + +``` + +In the code, `baz` will very clearly be 2.5. The integer literals will be converted to decimals prior to being stored and then the math takes place on the decimal values. Remove the explicit typing and the result is different. + +``` +var foo = 10; +var bar = 4; +var baz = foo / bar; + +``` + +Now everything infers to int and `baz` is 2 because now the math is taking place with integers. + +So, yes, code semantics could theoretically change if you introduce `var` where it was not before. So the key is to understand what type inference is really going to do with your code and if you want something to be a decimal (or any specific type X), declare it in such a way that it will be. For type inference, that would be + +``` +var foo = 10m; + +```","In addition to the ambiguous: + +``` +var x = null; + +``` + +the compiler will also not infer the type of overloaded method groups: + +``` +var m = String.Equals; + +``` + +nor will it infer the type of lambda expressions, which can be either `Func<>` or `Expression>`: + +``` +var l = (int x) => x + 1; + +``` + +All that said, Anthony is right: the compiler will never do the wrong thing, though it might not do what you expect. When in doubt, hover over `var` in VS to see the static type." +5738073,"I know from [this question](https://stackoverflow.com/questions/356846/c-var-vs-specific-type-performance) that `var i = 1` and `int i = 1` are exactly the same in IL. The compiler simply replaces `var` with the actual type at compile time. But, are there any instances where `var` could cause problem behavior (maybe the compiler guesses the wrong type?)",2011/04/21,"['https://Stackoverflow.com/questions/5738073', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/221061/']","In addition to the ambiguous: + +``` +var x = null; + +``` + +the compiler will also not infer the type of overloaded method groups: + +``` +var m = String.Equals; + +``` + +nor will it infer the type of lambda expressions, which can be either `Func<>` or `Expression>`: + +``` +var l = (int x) => x + 1; + +``` + +All that said, Anthony is right: the compiler will never do the wrong thing, though it might not do what you expect. When in doubt, hover over `var` in VS to see the static type.","``` +var x = 0 +x = 0.10 + +``` + +`Cannot convert source type 'double' to target type 'int'` + +An example: + +``` +double x = 0; //to initialize it +switch (something) { + case condition1: + x = 0.1; + break; + case condition2: + x = 0.2; + break; +} + +``` + +Using `var` instead of `double` will give a compiler error." +5738073,"I know from [this question](https://stackoverflow.com/questions/356846/c-var-vs-specific-type-performance) that `var i = 1` and `int i = 1` are exactly the same in IL. The compiler simply replaces `var` with the actual type at compile time. But, are there any instances where `var` could cause problem behavior (maybe the compiler guesses the wrong type?)",2011/04/21,"['https://Stackoverflow.com/questions/5738073', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/221061/']","I don't believe the compiler will *guess the wrong type.* However, it might *infer a type you didn't intend*, but that's not the same. + +Consider the perfectly legal + +``` +decimal foo = 10; +decimal bar = 4; +decimal baz = foo / bar; + +``` + +In the code, `baz` will very clearly be 2.5. The integer literals will be converted to decimals prior to being stored and then the math takes place on the decimal values. Remove the explicit typing and the result is different. + +``` +var foo = 10; +var bar = 4; +var baz = foo / bar; + +``` + +Now everything infers to int and `baz` is 2 because now the math is taking place with integers. + +So, yes, code semantics could theoretically change if you introduce `var` where it was not before. So the key is to understand what type inference is really going to do with your code and if you want something to be a decimal (or any specific type X), declare it in such a way that it will be. For type inference, that would be + +``` +var foo = 10m; + +```","``` +var x = 0 +x = 0.10 + +``` + +`Cannot convert source type 'double' to target type 'int'` + +An example: + +``` +double x = 0; //to initialize it +switch (something) { + case condition1: + x = 0.1; + break; + case condition2: + x = 0.2; + break; +} + +``` + +Using `var` instead of `double` will give a compiler error." +4138,"I'd like to know whether the messages delivered to the ethereum network by my wallet are encrypted such that any identifying information about the wallet is inaccessible to the ISP? + +in other words, can ownership of the wallet be traced to me via knowledge of the IP address I'm using at the time of the communication? + +I can't seem to find an answer to this anywhere...",2016/05/21,"['https://ethereum.stackexchange.com/questions/4138', 'https://ethereum.stackexchange.com', 'https://ethereum.stackexchange.com/users/2164/']","### No, they cannot trace your IP from the data stored in ethereum network. + +Your wallet, if it is Mist, it is actually writing the transaction data to your wn private Ethereum node and then only publishes to the live ethereum network. + +So, it is traceable back to you if and only if they are logging all the requests or you have published your wallet address along with postal address somewhere :)","The network is public, messages across it aren't encrypted and your ISP can see the transactions you're sending. + +Edit: I'm wrong, see @dbryson's comment." +4138,"I'd like to know whether the messages delivered to the ethereum network by my wallet are encrypted such that any identifying information about the wallet is inaccessible to the ISP? + +in other words, can ownership of the wallet be traced to me via knowledge of the IP address I'm using at the time of the communication? + +I can't seem to find an answer to this anywhere...",2016/05/21,"['https://ethereum.stackexchange.com/questions/4138', 'https://ethereum.stackexchange.com', 'https://ethereum.stackexchange.com/users/2164/']","### No, they cannot trace your IP from the data stored in ethereum network. + +Your wallet, if it is Mist, it is actually writing the transaction data to your wn private Ethereum node and then only publishes to the live ethereum network. + +So, it is traceable back to you if and only if they are logging all the requests or you have published your wallet address along with postal address somewhere :)","You mention your ISP. If you use a VPN, Tor or I2P you ISP may be able to see that but they cannot see what you are doing on those private networks. + +Encryption of your message and the metadata you ask about (ip address, etc) are two separate issues." +71493412,"I have elasticsearch and Kibana are up and running and I want to read logs using logstash so for that I have passed csv file as an input in logstash.conf file but its not reading logs and shutting down automatically. + +This is how I am running logstash command: + +``` +D:\logstash-8.1.0\bin>logstash -f ""D:/logstash.conf"" + +``` + +**logstash.conf** + +``` +input{ + file{ + path => ""D:/unicorn.csv"" + start_position => beginning + } +} +output{ + elasticsearch{ + hosts => ""localhost:9200"" + index => ""indexforlogstash"" +} +stdout{} +} + +``` + +Below are the terminal output: + +``` + ""Using bundled JDK: ."" +OpenJDK 64-Bit Server VM warning: Option UseConcMarkSweepGC was deprecated in version 9.0 and +will likely be removed in a future release. +Sending Logstash logs to D:/logstash-8.1.0/logs which is now configured via log4j2.properties +[2022-03-16T12:59:47,905][INFO ][logstash.runner ] Log4j configuration path used is: +D:\logstash-8.1.0\config\log4j2.properties +[2022-03-16T12:59:47,938][WARN ][logstash.runner ] The use of JAVA_HOME has been d +deprecated. Logstash 8.0 and later ignores JAVA_HOME and uses the bundled JDK. Running +Logstash with the bundled JDK is recommended. The bundled JDK has been verified to work with +each specific version of Logstash, and generally provides best performance and reliability. If +you have compelling reasons for using your own JDK (organizational-specific compliance +requirements, for example), you can configure LS_JAVA_HOME to use that version instead. +[2022-03-16T12:59:47,942][INFO ][logstash.runner ] Starting Logstash +{""logstash.version""=>""8.1.0"", ""jruby.version""=>""jruby 9.2.20.1 (2.5.8) 2021-11-30 2a2962fbd1 +OpenJDK 64-Bit Server VM 11.0.13+8 on 11.0.13+8 +indy +jit [mswin32-x86_64]""} +[2022-03-16T12:59:47,947][INFO ][logstash.runner ] JVM bootstrap flags: [-Xms1g, - +Xmx1g, -XX:+UseConcMarkSweepGC, -XX:CMSInitiatingOccupancyFraction=75, - +XX:+UseCMSInitiatingOccupancyOnly, -Djava.awt.headless=true, -Dfile.encoding=UTF-8, - +Djruby.compile.invokedynamic=true, -Djruby.jit.threshold=0, -Djruby.regexp.interruptible=true, +-XX:+HeapDumpOnOutOfMemoryError, -Djava.security.egd=file:/dev/urandom, - +Dlog4j2.isThreadContextMapInheritable=true, --add-opens=java.base/java.security=ALL-UNNAMED, -- +add-opens=java.base/java.io=ALL-UNNAMED, --add-opens=java.base/java.nio.channels=ALL-UNNAMED, - +-add-opens=java.base/sun.nio.ch=ALL-UNNAMED, --add-opens=java.management/sun.management=ALL- +UNNAMED] + [2022-03-16T12:59:48,058][INFO ][logstash.settings ] Creating directory + {:setting=>""path.queue"", :path=>""D:/logstash-8.1.0/data/queue""} + [2022-03-16T12:59:48,104][INFO ][logstash.settings ] Creating directory + {:setting=>""path.dead_letter_queue"", :path=>""D:/logstash-8.1.0/data/dead_letter_queue""} + [2022-03-16T12:59:48,285][WARN ][logstash.config.source.multilocal] Ignoring the + 'pipelines.yml' file because modules or command line options are specified + [2022-03-16T12:59:48,347][INFO ][logstash.agent ] No persistent UUID file found. + Generating new UUID {:uuid=>""84410117-2fa7-499b-b55a-43a29192540e"", :path=>""D:/logstash- +8.1.0/data/uuid""} + [2022-03-16T12:59:55,063][ERROR][logstash.config.sourceloader] No configuration found in the + configured sources. + [2022-03-16T12:59:55,424][INFO ][logstash.agent ] Successfully started Logstash API + endpoint {:port=>9600, :ssl_enabled=>false} + [2022-03-16T13:00:00,591][INFO ][logstash.runner ] Logstash shut down. + [2022-03-16T13:00:00,609][FATAL][org.logstash.Logstash ] Logstash stopped processing + because of an error: (SystemExit) exit + org.jruby.exceptions.SystemExit: (SystemExit) exit + at org.jruby.RubyKernel.exit(org/jruby/RubyKernel.java:747) ~[jruby.jar:?] + at org.jruby.RubyKernel.exit(org/jruby/RubyKernel.java:710) ~[jruby.jar:?] + at D_3a_.logstash_minus_8_dot_1_dot_0.lib.bootstrap.environment.
(D:\logstash- +8.1.0\lib\bootstrap\environment.rb:94) ~[?:?] + +``` + +Someone let me know what I am doing wrong.",2022/03/16,"['https://Stackoverflow.com/questions/71493412', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7780102/']","It's actually very simple. Since you use `&&` as an operator, gcc can deduce that the condition always yields false. + +If you use the bitwise and operator (`&`), gcc adds code for the if: + +``` +#include +unsigned char c = 0xff; +int n = 1; + +int main(){ + if ((c & 0xc0) == 0xc0 ) { + n=0; + } + printf(""%d\n"", n); +} + +``` + +yields: + +``` +ronald@oncilla:~/tmp$ cc -S x.c && cat x.s + .file ""x.c"" + .text + .globl c + .data + .type c, @object + .size c, 1 +c: + .byte -1 + .globl n + .align 4 + .type n, @object + .size n, 4 +n: + .long 1 + .section .rodata +.LC0: + .string ""%d\n"" + .text + .globl main + .type main, @function +main: +.LFB0: + .cfi_startproc + endbr64 + pushq %rbp + .cfi_def_cfa_offset 16 + .cfi_offset 6, -16 + movq %rsp, %rbp + .cfi_def_cfa_register 6 + movzbl c(%rip), %eax + movzbl %al, %eax + andl $192, %eax + cmpl $192, %eax + jne .L2 + movl $0, n(%rip) +.L2: + movl n(%rip), %eax + movl %eax, %esi + leaq .LC0(%rip), %rdi + movl $0, %eax + call printf@PLT + movl $0, %eax + popq %rbp + .cfi_def_cfa 7, 8 + ret + .cfi_endproc +.LFE0: + .size main, .-main + .ident ""GCC: (Ubuntu 9.4.0-1ubuntu1~20.04) 9.4.0"" + .section .note.GNU-stack,"""",@progbits + .section .note.gnu.property,""a"" + .align 8 + .long 1f - 0f + .long 4f - 1f + .long 5 +0: + .string ""GNU"" +1: + .align 8 + .long 0xc0000002 + .long 3f - 2f +2: + .long 0x3 +3: + .align 8 +4: + +```","In C `&&` casts operands to `bool` which even though its an `int`, it is changed to 1 meaning true, if nonzero. + +`&` is a bitwise and, which returns the bits that are the same. If you combine this with `&&` it returns true if there are any bits left. + +If you compile with `-Wall` you will get a warning when something gets optimized out at compile time." +33264891,"I'm a new baby in Dapper. Trying to incorporate CRUD operations with Dapper and Dapper.SimpleCRUD lib. Here is the sample code... + +My Data Model Looks like + +``` +Class Product +{ + public string prodId {get;set;} + public string prodName {get;set;} + public string Location {get;set;} +} + +``` + +Dapper Implementation - Insert + +``` +public void Insert(Product item) +{ + using(var con = GetConnection()) + { + con.Insert(item); + } +} + +``` + +Since the ProdId in the Db is an Identity Column it fails. How does it indicate ProdId is an Identity Column in DB? + +Dapper Implementation - Get + +``` +public IEnumerable GetAll() +{ + IEnumerable item = null; + using (var con = GetConnection()) + { + item = con.GetList(); + } + return item; +} + +``` + +It gives an exception: + +> +> ""Entity must have at least one [Key] property""! +> +> +>",2015/10/21,"['https://Stackoverflow.com/questions/33264891', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2066540/']","This is happening since you are using a Dapper Extension, which has implemented the `Insert` CRUD extension method. Ideally this can be achieved using simple + +`con.Execute` in the Dapper, but since you want to pass an object and create an insert query automatically by the extension, you need to help it understand, which is the Primary Key for the given product entity, following modification shall help: + +``` +[Key] +public string prodId {get;set;} + +``` + +where Key attribute shall be either implemented in `Dapper Extension` or the `Component Model`. + +Alternatively you may rename `prodId` to `Id`, which will automatically make it the key. Also check the following [link](http://rnsx.co.uk/an-introduction-to-dapper-extensions/), where you can create a separate mapper for the entity, thus defining the key, whatever works in your case","Connecting to SQL Server 2016, I had this error with both Dapper.Contrib & Dapper.SimpleCRUD when I forgot to attach the Primary Key to the Id column of the table. + +Primary Key added to the table, project rebuilt & published to clear cache and all is good with both [Key] & [ExplicitKey] ( the latter in DapperContrib)." +321083,"I've got [DavMail](http://davmail.sourceforge.net/) running in Linux Mint so Thunderbird can access IMAP/SMTP/LDAP/CalDav. I've got everything working at this point except LDAP. Basically I can't figure out what the base DN should be. Where on my Windows XP box can I find this? I've tried a few things, and the address book always shows up blank once I add the LDAP server.",2011/08/09,"['https://superuser.com/questions/321083', 'https://superuser.com', 'https://superuser.com/users/75269/']","The ""Base DN"" when adding a new LDAP directory in Thunderbird should be `ou=people` as specified on [this page](http://davmail.sourceforge.net/thunderbirddirectorysetup.html) [davmail.sourceforge.net]. + +Contrary to what the screenshot in those instructions shows (in French, no less), your ""Bind DN"" should might actually be **your email address**. At least this was the case for me, with the educational (""Live@edu"") version of Office365. + +Also, not sure if this is worth mentioning, but I did have a really annoying problem with Thunderbird on Mac OS X which caused me to think that the LDAP lookup wasn't working at all: the dialog box which prompted for the password (to access the DavMail server) got stuck **under** a bunch of other windows, **and** on the wrong virtual desktop (I believe Apple calls these ""Spaces""). Once I ""discovered"" the password prompt and gave it my OWA password, LDAP lookups in the addressbook with Shift + ⌘ + F worked just fine.","The `base object` for searches is something that your directory server administrator tells you. It might be possible to discover the `namingContext` of the directory server if you know the hostname and port upon which the server listens by querying the root DSE. See *[The root DSE](http://bit.ly/osZXFG)* for more information. + +The information regarding the `namingContext` might be protected by access control, in which case you must get the name of the `base object` from the directory server administrator. The directory server might master or shadow multiple naming contexts, in which case you must get the name of the `base object` from the directory server administrator." +9389381,"In order to demonstrate the security feature of Oracle one has to call **OCIServerVersion()** or **OCIServerRelease()** when the user session has not yet been established. + +While having the database parameter `sec_return_server_release_banner = false`. +I am using Python cx\_Oracle module for this, but I am not sure how to get the server version before establishing the connection. Any ideas?",2012/02/22,"['https://Stackoverflow.com/questions/9389381', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1224977/']","If you want the snapshot, make sure you have the repository tags for it as well, for wherever you are getting that build from. Otherwise use the latest release, `3.0.0-beta3`. + +If you are building your own local copies, or deploying to an internal repo, then 3.0.0-SNAPSHOT should work - make sure the jar can be found in your repo, and that you aren't running as offline.","GXT 3.0.1 is on maven central + +``` + + com.sencha.gxt + gxt + 3.0.1 + + +```" +9389381,"In order to demonstrate the security feature of Oracle one has to call **OCIServerVersion()** or **OCIServerRelease()** when the user session has not yet been established. + +While having the database parameter `sec_return_server_release_banner = false`. +I am using Python cx\_Oracle module for this, but I am not sure how to get the server version before establishing the connection. Any ideas?",2012/02/22,"['https://Stackoverflow.com/questions/9389381', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1224977/']","If you want the snapshot, make sure you have the repository tags for it as well, for wherever you are getting that build from. Otherwise use the latest release, `3.0.0-beta3`. + +If you are building your own local copies, or deploying to an internal repo, then 3.0.0-SNAPSHOT should work - make sure the jar can be found in your repo, and that you aren't running as offline.","Use these dependencies: + +``` + + com.google.gwt + gwt-user + 2.5.0 + + + com.google.gwt + gwt-servlet + 2.5.0 + + + com.sencha.gxt + gxt + 3.0.1 + + +``` + +GXT does not require `uibinder-bridge` anymore [according to Sencha forum](http://www.sencha.com/forum/showthread.php?246246-uibinder-bridge-for-GWT-2.5.0). +All GXT uibinder features were incorporated into GWT 2.5.0 release." +9389381,"In order to demonstrate the security feature of Oracle one has to call **OCIServerVersion()** or **OCIServerRelease()** when the user session has not yet been established. + +While having the database parameter `sec_return_server_release_banner = false`. +I am using Python cx\_Oracle module for this, but I am not sure how to get the server version before establishing the connection. Any ideas?",2012/02/22,"['https://Stackoverflow.com/questions/9389381', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1224977/']","Use these dependencies: + +``` + + com.google.gwt + gwt-user + 2.5.0 + + + com.google.gwt + gwt-servlet + 2.5.0 + + + com.sencha.gxt + gxt + 3.0.1 + + +``` + +GXT does not require `uibinder-bridge` anymore [according to Sencha forum](http://www.sencha.com/forum/showthread.php?246246-uibinder-bridge-for-GWT-2.5.0). +All GXT uibinder features were incorporated into GWT 2.5.0 release.","GXT 3.0.1 is on maven central + +``` + + com.sencha.gxt + gxt + 3.0.1 + + +```" +40585550,"i want a make a feed reader...i want load politics news from multiple data dource in one tableview synchronously. +what do i do? +i went to this link: [table view with multiple data sources/nibs](https://stackoverflow.com/questions/35960403/ios-swift-table-view-with-multiple-data-sources-nibs) + +but this solution is not synchronously +So basically what should be the approach when we have multiple data source but single instance of table view to show the data?",2016/11/14,"['https://Stackoverflow.com/questions/40585550', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6856597/']","you are sorting from the older to the newer date which is ok, +if you need upside down then do invert the comparation criteria by doing: + +``` +return date2.compareTo(date1); + +``` + +another way to go is inverte the sorted list... + +1st sort then do `Collections.reverse();` + +Edit: +===== + +I try your code and the reason is the format is not well defined, therefore the dates are wrong + +try this: + +``` + DateFormat format = new SimpleDateFormat(""MM/dd/yyyy""); + Date date1 = null; + Date date2 = null; + try { + date1 = format.parse(o1); + date2 = format.parse(o2); + } catch (ParseException e) { + e.printStackTrace(); + } + + return date2.compareTo(date1); + +```","In java 8 you can write it in this way.. + +Please note that I have used apache CompareToBuilder. + +``` +Collections.sort(opportunities, + Collections.reverseOrder((item1, item2) -> new CompareToBuilder() + .append(item1.getExpires(), item2.getExpires()).toComparison())); + +```" +40585550,"i want a make a feed reader...i want load politics news from multiple data dource in one tableview synchronously. +what do i do? +i went to this link: [table view with multiple data sources/nibs](https://stackoverflow.com/questions/35960403/ios-swift-table-view-with-multiple-data-sources-nibs) + +but this solution is not synchronously +So basically what should be the approach when we have multiple data source but single instance of table view to show the data?",2016/11/14,"['https://Stackoverflow.com/questions/40585550', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6856597/']","Because format ""YYYY"" in your `DateFormat` +Change `MM/DD/YYYY` to `MM/DD/yyyy` will work","you are sorting from the older to the newer date which is ok, +if you need upside down then do invert the comparation criteria by doing: + +``` +return date2.compareTo(date1); + +``` + +another way to go is inverte the sorted list... + +1st sort then do `Collections.reverse();` + +Edit: +===== + +I try your code and the reason is the format is not well defined, therefore the dates are wrong + +try this: + +``` + DateFormat format = new SimpleDateFormat(""MM/dd/yyyy""); + Date date1 = null; + Date date2 = null; + try { + date1 = format.parse(o1); + date2 = format.parse(o2); + } catch (ParseException e) { + e.printStackTrace(); + } + + return date2.compareTo(date1); + +```" +40585550,"i want a make a feed reader...i want load politics news from multiple data dource in one tableview synchronously. +what do i do? +i went to this link: [table view with multiple data sources/nibs](https://stackoverflow.com/questions/35960403/ios-swift-table-view-with-multiple-data-sources-nibs) + +but this solution is not synchronously +So basically what should be the approach when we have multiple data source but single instance of table view to show the data?",2016/11/14,"['https://Stackoverflow.com/questions/40585550', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6856597/']","Because format ""YYYY"" in your `DateFormat` +Change `MM/DD/YYYY` to `MM/DD/yyyy` will work","In java 8 you can write it in this way.. + +Please note that I have used apache CompareToBuilder. + +``` +Collections.sort(opportunities, + Collections.reverseOrder((item1, item2) -> new CompareToBuilder() + .append(item1.getExpires(), item2.getExpires()).toComparison())); + +```" +61689419,"I am trying to find the max and min of a line of text from a data file. Though there is plenty of lines of text in this data file. + +**DATA** + +``` +-99 1 2 3 4 5 6 7 8 9 10 12345 +10 9 8 7 6 5 4 3 2 1 -99 +10 20 30 40 50 -11818 40 30 20 10 +32767 +255 255 +9 10 -88 100 -555 1000 +10 10 10 11 456 +-111 1 2 3 9 11 20 30 +9 8 7 6 5 4 3 2 0 -2 -989 +12 15 18 21 23 1000 +250 19 17 15 13 11 10 9 6 3 2 1 -455 +9 10 -8 10000 -5000 1000 + +``` + +I have tried turning the lines into arrays and that has got me somewhere. + +**HERE IS MY CODE** + +``` +import java.io.File; +import java.io.IOException; +import java.util.Scanner; + +// It is called ""Average"". Don't mind that. +public class Average +{ + public static void main(String[] args) throws IOException + { + Scanner file = new Scanner(new File(""average.dat"")); + + String[] array = null; + + while(file.hasNextLine()) + { + //Storing the ints from the data file into an array. + String line = file.nextLine(); + String[] str = line.split(""\\s+""); + array = new String[str.length]; + for (int i = 0; i < str.length; i++){ + array[i] = (str[i]); + } + System.out.println(""Max:"" + Average.getMax(array)); + System.out.println(""Min:"" + Average.getMin(array)); + System.out.println(); + } + + } + //Simple way of getting max value. Nabbed it off google. + public static String getMax(String[] inputArray) + { + String maxValue = inputArray[0]; + for(int i=1;i < inputArray.length;i++){ + if(inputArray[i].compareTo(maxValue)>0){ + maxValue = inputArray[i]; + } + } + return maxValue; + } + //Simple way of getting min value. Took off google as well. + public static String getMin(String[] inputArray){ + String minValue = inputArray[0]; + for(int i=1;i Integer.parseInt(inputArray[i])){ + minValue = Integer.parseInt(inputArray[i]); + } + } + return String.valueOf(minValue); + } + +```","You should use: Integer.pharseToInt() +Then when you'll have an array of integers and you can find the max value easily: + +``` +int getMax(int [] array){ + int max = INTEGER.MIN_VALUE; + for (int i=0: imax) + max = array[i]; +return max; +} + +``` + +Totally symetric function for finding min value." +61689419,"I am trying to find the max and min of a line of text from a data file. Though there is plenty of lines of text in this data file. + +**DATA** + +``` +-99 1 2 3 4 5 6 7 8 9 10 12345 +10 9 8 7 6 5 4 3 2 1 -99 +10 20 30 40 50 -11818 40 30 20 10 +32767 +255 255 +9 10 -88 100 -555 1000 +10 10 10 11 456 +-111 1 2 3 9 11 20 30 +9 8 7 6 5 4 3 2 0 -2 -989 +12 15 18 21 23 1000 +250 19 17 15 13 11 10 9 6 3 2 1 -455 +9 10 -8 10000 -5000 1000 + +``` + +I have tried turning the lines into arrays and that has got me somewhere. + +**HERE IS MY CODE** + +``` +import java.io.File; +import java.io.IOException; +import java.util.Scanner; + +// It is called ""Average"". Don't mind that. +public class Average +{ + public static void main(String[] args) throws IOException + { + Scanner file = new Scanner(new File(""average.dat"")); + + String[] array = null; + + while(file.hasNextLine()) + { + //Storing the ints from the data file into an array. + String line = file.nextLine(); + String[] str = line.split(""\\s+""); + array = new String[str.length]; + for (int i = 0; i < str.length; i++){ + array[i] = (str[i]); + } + System.out.println(""Max:"" + Average.getMax(array)); + System.out.println(""Min:"" + Average.getMin(array)); + System.out.println(); + } + + } + //Simple way of getting max value. Nabbed it off google. + public static String getMax(String[] inputArray) + { + String maxValue = inputArray[0]; + for(int i=1;i < inputArray.length;i++){ + if(inputArray[i].compareTo(maxValue)>0){ + maxValue = inputArray[i]; + } + } + return maxValue; + } + //Simple way of getting min value. Took off google as well. + public static String getMin(String[] inputArray){ + String minValue = inputArray[0]; + for(int i=1;i stream = Files.lines(Paths.get(""average.dat""))) { + + // Get each line from the stream + stream.forEach(line -> { + + // Cut the line into peaces + String[] numbers = line.split("" ""); + + // Create a list of integers from the pieces + List integers = Arrays.stream(numbers).map(Integer::parseInt).collect(Collectors.toList()); + + // Calculate max + System.out.println(""Max:"" + integers.stream().flatMapToInt(IntStream::of).max().orElseThrow()); + + // Calculate min + System.out.println(""Min:"" + integers.stream().flatMapToInt(IntStream::of).min().orElseThrow()); + + // Ouput a new line + System.out.println(); + }); + } catch (IOException e) { + e.printStackTrace(); + } + +```","You should use: Integer.pharseToInt() +Then when you'll have an array of integers and you can find the max value easily: + +``` +int getMax(int [] array){ + int max = INTEGER.MIN_VALUE; + for (int i=0: imax) + max = array[i]; +return max; +} + +``` + +Totally symetric function for finding min value." +61689419,"I am trying to find the max and min of a line of text from a data file. Though there is plenty of lines of text in this data file. + +**DATA** + +``` +-99 1 2 3 4 5 6 7 8 9 10 12345 +10 9 8 7 6 5 4 3 2 1 -99 +10 20 30 40 50 -11818 40 30 20 10 +32767 +255 255 +9 10 -88 100 -555 1000 +10 10 10 11 456 +-111 1 2 3 9 11 20 30 +9 8 7 6 5 4 3 2 0 -2 -989 +12 15 18 21 23 1000 +250 19 17 15 13 11 10 9 6 3 2 1 -455 +9 10 -8 10000 -5000 1000 + +``` + +I have tried turning the lines into arrays and that has got me somewhere. + +**HERE IS MY CODE** + +``` +import java.io.File; +import java.io.IOException; +import java.util.Scanner; + +// It is called ""Average"". Don't mind that. +public class Average +{ + public static void main(String[] args) throws IOException + { + Scanner file = new Scanner(new File(""average.dat"")); + + String[] array = null; + + while(file.hasNextLine()) + { + //Storing the ints from the data file into an array. + String line = file.nextLine(); + String[] str = line.split(""\\s+""); + array = new String[str.length]; + for (int i = 0; i < str.length; i++){ + array[i] = (str[i]); + } + System.out.println(""Max:"" + Average.getMax(array)); + System.out.println(""Min:"" + Average.getMin(array)); + System.out.println(); + } + + } + //Simple way of getting max value. Nabbed it off google. + public static String getMax(String[] inputArray) + { + String maxValue = inputArray[0]; + for(int i=1;i < inputArray.length;i++){ + if(inputArray[i].compareTo(maxValue)>0){ + maxValue = inputArray[i]; + } + } + return maxValue; + } + //Simple way of getting min value. Took off google as well. + public static String getMin(String[] inputArray){ + String minValue = inputArray[0]; + for(int i=1;i max) { + max = v; + } else if (v < min) { + min = v; + } + } + System.out.println(""Max:"" + max); + System.out.println(""Min:"" + min); + System.out.println(); +} + +```","You should use: Integer.pharseToInt() +Then when you'll have an array of integers and you can find the max value easily: + +``` +int getMax(int [] array){ + int max = INTEGER.MIN_VALUE; + for (int i=0: imax) + max = array[i]; +return max; +} + +``` + +Totally symetric function for finding min value." +14576,"for typesetting tables with design of experiments, I have to typeset strings like ""+ - + +"", - - - +"", etc. in a column of a table to represent the so called pattern of the experimental run (sometimes they also contain ""a"", ""A"" and ""0"" (zero)). + +However, the width of the ""+"" and ""-"" sign are very different in the used font (standard font in KOMA script class scrreprt) and a sequence of 2 or 3 dashes creates one long or very long dash.... + +So I'm searching for a way to easily typeset e. g. ""+ - - - + -"" with a little spacing between the characters and (if possible) that several different strings composed of the same number of characters (""+"" or ""-"", ""a"", ""A"" and ""0"") would be aligned with each other, when they are in the same column of a table. + +I hope I could make clear what I need, some examples how it shall NOT look are found here: + +![bad example](https://i.stack.imgur.com/YZkQH.png) +in line 9 it should be ""+ - -"" and in 10 ""- - +"", line 5 should be ""- - -"" + +It looks a little better, if I insert `\,` between the characters, but as the widths are different, it is still not aligned: + +![enter image description here](https://i.stack.imgur.com/dC5x3.png) + +Sure, I could split it up in centered columns like `- & + & - & - & ...`, but the tables are already complicated enough and I do not want to add 3 to 7 columns... + +Does anybody have an idea how to solve that? +Maybe a command that parses the string like --+--++ and typesets it with a ""constant spacing""? + +------- edit: + +added math mode for ""+"" and ""-"", looks better now, but not perfect: +![math mode for plus and minus](https://i.stack.imgur.com/D3hFt.png) + +``` + \documentclass[11pt, a4paper%, halfparskip + ]{scrreprt} + + \usepackage{booktabs} + + \begin{document} + +\begin{tabular}{cccccccc} +\midrule + 1 & $+$$+$$-$ \\ + 2 & $+$$-$$+$ \\ + 3 & $-$$+$$+$ \\ + 4 & 000 \\ + 5 & $-$$-$$-$ \\ + 6 & 000 \\ +\midrule + 7 & $-$$+$$-$ \\ + 8 & 000 \\ + 9 & $+$$-$$-$ \\ + 10 & $-$$-$$+$ \\ + 11 & $+$$+$$+$ \\ + 12 & 000 \\ +\midrule + 13 & 000 \\ + 14 & 00a \\ + 15 & 00A \\ + 16 & 0A0 \\ + 17 & A00 \\ + 18 & 0a0 \\ + 19 & a00 \\ + 20 & 000 \\ +\toprule +\end{tabular} + +\end{document} + +``` + +--- + +example and further question about side-effects: + +I used the solution of Michel and it looks good, but there is one thing I'm not sure about: +Is it possible that it changes the free space between columns? +I have the impression that the first 3 columns are closer together than the rest... +How can I fix that? + +![solution with side effects?!](https://i.stack.imgur.com/25OVA.png)",2011/03/30,"['https://tex.stackexchange.com/questions/14576', 'https://tex.stackexchange.com', 'https://tex.stackexchange.com/users/4009/']","Make sure you typeset them it **math-mode**, i.e. `$-$` and `$+$`. + +Be aware that it makes a difference if you use a single math-mode or separate ones for them. The last sign has different spacing in the first case because it +is taken as an unary sign but the others are operators. + +Compare the following: + +``` +\documentclass{article} + +\begin{document} + +$-$$-$$-$$+$$+$$+$ + +$+$$+$$+$$+$$+$$+$ + +$-$$-$$-$$-$$-$$-$ + +$---+++$ + +$++++++$ + +$------$ + +\end{document} + +``` + +### Result: + +![Result](https://i.stack.imgur.com/8AnbD.png) + +--- + +For the alignment with the other signs `a`, `A` and `0` I would recommend that you make macros for all and set the width manually the one of the widest (should be `$+$`). + +This can be done either with `\hbox to {\hss \hss}` (TeX) or using `\makebox[][c]{}` (LaTeX). The width is provided by `\settowidth{}{}`. + +``` +\documentclass[11pt, a4paper]{scrreprt} + +\usepackage{booktabs} + +\newlength{\slength} +\settowidth{\slength}{$+$} +\newcommand*{\Sz}{\makebox[\slength][c]{0}} +\newcommand*{\SA}{\makebox[\slength][c]{A}} +\newcommand*{\Sa}{\makebox[\slength][c]{a}} +\newcommand*{\Sp}{\makebox[\slength][c]{$+$}} +\newcommand*{\Sm}{\makebox[\slength][c]{$-$}} + +\begin{document} + +\begin{tabular}{cc} +\toprule + 1 & \Sp\Sp\Sm \\ + 2 & \Sp\Sm\Sp \\ + 3 & \Sm\Sp\Sp \\ + 4 & \Sz\Sz\Sz \\ + 5 & \Sm\Sm\Sm \\ + 6 & \Sz\Sz\Sz \\ +\midrule + 7 & \Sm\Sp\Sm \\ + 8 & \Sz\Sz\Sz \\ + 9 & \Sp\Sm\Sm \\ + 10 & \Sm\Sm\Sp \\ + 11 & \Sp\Sp\Sp \\ + 12 & \Sz\Sz\Sz \\ +\midrule + 13 & \Sz\Sz\Sz \\ + 14 & \Sz\Sz\Sa \\ + 15 & \Sz\Sz\SA \\ + 16 & \Sz\SA\Sz \\ + 17 & \SA\Sz\Sz \\ + 18 & \Sz\Sa\Sz \\ + 19 & \Sa\Sz\Sz \\ + 20 & \Sz\Sz\Sz \\ +\bottomrule +\end{tabular} + +\end{document} + +``` + +### Result: + +![Result 2](https://i.stack.imgur.com/1d879.png)","one possible form to typeset your table would be to use a table column for each character: + +``` +\documentclass[11pt, a4paper]{scrreprt} +\usepackage{booktabs} + +\newcommand\Pl{${}+{}$} +\newcommand\Mi{${}-{}$} + +\begin{document} + +\begin{tabular}{cc@{\hspace{-2pt}}c@{\hspace{-2pt}}c} + \toprule + 1 & \Pl & \Pl & \Mi \\ + 4 & 0 & 0 & 0 \\ + 12 & a & 0 & A \\ + 15 & 0 & 0 & A \\ + \bottomrule +\end{tabular} + +\end{document} + +``` + +![](https://i.stack.imgur.com/RxGDb.png)" +14576,"for typesetting tables with design of experiments, I have to typeset strings like ""+ - + +"", - - - +"", etc. in a column of a table to represent the so called pattern of the experimental run (sometimes they also contain ""a"", ""A"" and ""0"" (zero)). + +However, the width of the ""+"" and ""-"" sign are very different in the used font (standard font in KOMA script class scrreprt) and a sequence of 2 or 3 dashes creates one long or very long dash.... + +So I'm searching for a way to easily typeset e. g. ""+ - - - + -"" with a little spacing between the characters and (if possible) that several different strings composed of the same number of characters (""+"" or ""-"", ""a"", ""A"" and ""0"") would be aligned with each other, when they are in the same column of a table. + +I hope I could make clear what I need, some examples how it shall NOT look are found here: + +![bad example](https://i.stack.imgur.com/YZkQH.png) +in line 9 it should be ""+ - -"" and in 10 ""- - +"", line 5 should be ""- - -"" + +It looks a little better, if I insert `\,` between the characters, but as the widths are different, it is still not aligned: + +![enter image description here](https://i.stack.imgur.com/dC5x3.png) + +Sure, I could split it up in centered columns like `- & + & - & - & ...`, but the tables are already complicated enough and I do not want to add 3 to 7 columns... + +Does anybody have an idea how to solve that? +Maybe a command that parses the string like --+--++ and typesets it with a ""constant spacing""? + +------- edit: + +added math mode for ""+"" and ""-"", looks better now, but not perfect: +![math mode for plus and minus](https://i.stack.imgur.com/D3hFt.png) + +``` + \documentclass[11pt, a4paper%, halfparskip + ]{scrreprt} + + \usepackage{booktabs} + + \begin{document} + +\begin{tabular}{cccccccc} +\midrule + 1 & $+$$+$$-$ \\ + 2 & $+$$-$$+$ \\ + 3 & $-$$+$$+$ \\ + 4 & 000 \\ + 5 & $-$$-$$-$ \\ + 6 & 000 \\ +\midrule + 7 & $-$$+$$-$ \\ + 8 & 000 \\ + 9 & $+$$-$$-$ \\ + 10 & $-$$-$$+$ \\ + 11 & $+$$+$$+$ \\ + 12 & 000 \\ +\midrule + 13 & 000 \\ + 14 & 00a \\ + 15 & 00A \\ + 16 & 0A0 \\ + 17 & A00 \\ + 18 & 0a0 \\ + 19 & a00 \\ + 20 & 000 \\ +\toprule +\end{tabular} + +\end{document} + +``` + +--- + +example and further question about side-effects: + +I used the solution of Michel and it looks good, but there is one thing I'm not sure about: +Is it possible that it changes the free space between columns? +I have the impression that the first 3 columns are closer together than the rest... +How can I fix that? + +![solution with side effects?!](https://i.stack.imgur.com/25OVA.png)",2011/03/30,"['https://tex.stackexchange.com/questions/14576', 'https://tex.stackexchange.com', 'https://tex.stackexchange.com/users/4009/']","An easy way to achieve this would be to typeset the plusses and minuses in a monospace font with `\verb|+-+-|` + +There are however [issues](https://tex.stackexchange.com/q/203/215) with verbatim text which you might run into... +Another solution might be to use `\texttt` and macros for your plusses etc. Here's an example: + +``` +\documentclass{article} +\usepackage[T1]{fontenc} +\newcommand\p{+} +\newcommand\m{-{}} +\begin{document} +\texttt{++---++} + +\texttt{\p\p\m\m\m\p\p} + +\texttt{++\m\m aA0} +\end{document} + +``` + +You need to use a macro like this for the minus sign because otherwise they get turned into en-dashes if you use the `fontenc` package. This should also mono-space letters easily.","A quick and dirty solution might be to enclose the symbols in braces: `${-}{+}{+}{+}$` looks better than `$-+++$`, as LaTeX won't try to interpret each `+` or `-` as a binary operator." +14576,"for typesetting tables with design of experiments, I have to typeset strings like ""+ - + +"", - - - +"", etc. in a column of a table to represent the so called pattern of the experimental run (sometimes they also contain ""a"", ""A"" and ""0"" (zero)). + +However, the width of the ""+"" and ""-"" sign are very different in the used font (standard font in KOMA script class scrreprt) and a sequence of 2 or 3 dashes creates one long or very long dash.... + +So I'm searching for a way to easily typeset e. g. ""+ - - - + -"" with a little spacing between the characters and (if possible) that several different strings composed of the same number of characters (""+"" or ""-"", ""a"", ""A"" and ""0"") would be aligned with each other, when they are in the same column of a table. + +I hope I could make clear what I need, some examples how it shall NOT look are found here: + +![bad example](https://i.stack.imgur.com/YZkQH.png) +in line 9 it should be ""+ - -"" and in 10 ""- - +"", line 5 should be ""- - -"" + +It looks a little better, if I insert `\,` between the characters, but as the widths are different, it is still not aligned: + +![enter image description here](https://i.stack.imgur.com/dC5x3.png) + +Sure, I could split it up in centered columns like `- & + & - & - & ...`, but the tables are already complicated enough and I do not want to add 3 to 7 columns... + +Does anybody have an idea how to solve that? +Maybe a command that parses the string like --+--++ and typesets it with a ""constant spacing""? + +------- edit: + +added math mode for ""+"" and ""-"", looks better now, but not perfect: +![math mode for plus and minus](https://i.stack.imgur.com/D3hFt.png) + +``` + \documentclass[11pt, a4paper%, halfparskip + ]{scrreprt} + + \usepackage{booktabs} + + \begin{document} + +\begin{tabular}{cccccccc} +\midrule + 1 & $+$$+$$-$ \\ + 2 & $+$$-$$+$ \\ + 3 & $-$$+$$+$ \\ + 4 & 000 \\ + 5 & $-$$-$$-$ \\ + 6 & 000 \\ +\midrule + 7 & $-$$+$$-$ \\ + 8 & 000 \\ + 9 & $+$$-$$-$ \\ + 10 & $-$$-$$+$ \\ + 11 & $+$$+$$+$ \\ + 12 & 000 \\ +\midrule + 13 & 000 \\ + 14 & 00a \\ + 15 & 00A \\ + 16 & 0A0 \\ + 17 & A00 \\ + 18 & 0a0 \\ + 19 & a00 \\ + 20 & 000 \\ +\toprule +\end{tabular} + +\end{document} + +``` + +--- + +example and further question about side-effects: + +I used the solution of Michel and it looks good, but there is one thing I'm not sure about: +Is it possible that it changes the free space between columns? +I have the impression that the first 3 columns are closer together than the rest... +How can I fix that? + +![solution with side effects?!](https://i.stack.imgur.com/25OVA.png)",2011/03/30,"['https://tex.stackexchange.com/questions/14576', 'https://tex.stackexchange.com', 'https://tex.stackexchange.com/users/4009/']","Make sure you typeset them it **math-mode**, i.e. `$-$` and `$+$`. + +Be aware that it makes a difference if you use a single math-mode or separate ones for them. The last sign has different spacing in the first case because it +is taken as an unary sign but the others are operators. + +Compare the following: + +``` +\documentclass{article} + +\begin{document} + +$-$$-$$-$$+$$+$$+$ + +$+$$+$$+$$+$$+$$+$ + +$-$$-$$-$$-$$-$$-$ + +$---+++$ + +$++++++$ + +$------$ + +\end{document} + +``` + +### Result: + +![Result](https://i.stack.imgur.com/8AnbD.png) + +--- + +For the alignment with the other signs `a`, `A` and `0` I would recommend that you make macros for all and set the width manually the one of the widest (should be `$+$`). + +This can be done either with `\hbox to {\hss \hss}` (TeX) or using `\makebox[][c]{}` (LaTeX). The width is provided by `\settowidth{}{}`. + +``` +\documentclass[11pt, a4paper]{scrreprt} + +\usepackage{booktabs} + +\newlength{\slength} +\settowidth{\slength}{$+$} +\newcommand*{\Sz}{\makebox[\slength][c]{0}} +\newcommand*{\SA}{\makebox[\slength][c]{A}} +\newcommand*{\Sa}{\makebox[\slength][c]{a}} +\newcommand*{\Sp}{\makebox[\slength][c]{$+$}} +\newcommand*{\Sm}{\makebox[\slength][c]{$-$}} + +\begin{document} + +\begin{tabular}{cc} +\toprule + 1 & \Sp\Sp\Sm \\ + 2 & \Sp\Sm\Sp \\ + 3 & \Sm\Sp\Sp \\ + 4 & \Sz\Sz\Sz \\ + 5 & \Sm\Sm\Sm \\ + 6 & \Sz\Sz\Sz \\ +\midrule + 7 & \Sm\Sp\Sm \\ + 8 & \Sz\Sz\Sz \\ + 9 & \Sp\Sm\Sm \\ + 10 & \Sm\Sm\Sp \\ + 11 & \Sp\Sp\Sp \\ + 12 & \Sz\Sz\Sz \\ +\midrule + 13 & \Sz\Sz\Sz \\ + 14 & \Sz\Sz\Sa \\ + 15 & \Sz\Sz\SA \\ + 16 & \Sz\SA\Sz \\ + 17 & \SA\Sz\Sz \\ + 18 & \Sz\Sa\Sz \\ + 19 & \Sa\Sz\Sz \\ + 20 & \Sz\Sz\Sz \\ +\bottomrule +\end{tabular} + +\end{document} + +``` + +### Result: + +![Result 2](https://i.stack.imgur.com/1d879.png)","An easy way to achieve this would be to typeset the plusses and minuses in a monospace font with `\verb|+-+-|` + +There are however [issues](https://tex.stackexchange.com/q/203/215) with verbatim text which you might run into... +Another solution might be to use `\texttt` and macros for your plusses etc. Here's an example: + +``` +\documentclass{article} +\usepackage[T1]{fontenc} +\newcommand\p{+} +\newcommand\m{-{}} +\begin{document} +\texttt{++---++} + +\texttt{\p\p\m\m\m\p\p} + +\texttt{++\m\m aA0} +\end{document} + +``` + +You need to use a macro like this for the minus sign because otherwise they get turned into en-dashes if you use the `fontenc` package. This should also mono-space letters easily." +14576,"for typesetting tables with design of experiments, I have to typeset strings like ""+ - + +"", - - - +"", etc. in a column of a table to represent the so called pattern of the experimental run (sometimes they also contain ""a"", ""A"" and ""0"" (zero)). + +However, the width of the ""+"" and ""-"" sign are very different in the used font (standard font in KOMA script class scrreprt) and a sequence of 2 or 3 dashes creates one long or very long dash.... + +So I'm searching for a way to easily typeset e. g. ""+ - - - + -"" with a little spacing between the characters and (if possible) that several different strings composed of the same number of characters (""+"" or ""-"", ""a"", ""A"" and ""0"") would be aligned with each other, when they are in the same column of a table. + +I hope I could make clear what I need, some examples how it shall NOT look are found here: + +![bad example](https://i.stack.imgur.com/YZkQH.png) +in line 9 it should be ""+ - -"" and in 10 ""- - +"", line 5 should be ""- - -"" + +It looks a little better, if I insert `\,` between the characters, but as the widths are different, it is still not aligned: + +![enter image description here](https://i.stack.imgur.com/dC5x3.png) + +Sure, I could split it up in centered columns like `- & + & - & - & ...`, but the tables are already complicated enough and I do not want to add 3 to 7 columns... + +Does anybody have an idea how to solve that? +Maybe a command that parses the string like --+--++ and typesets it with a ""constant spacing""? + +------- edit: + +added math mode for ""+"" and ""-"", looks better now, but not perfect: +![math mode for plus and minus](https://i.stack.imgur.com/D3hFt.png) + +``` + \documentclass[11pt, a4paper%, halfparskip + ]{scrreprt} + + \usepackage{booktabs} + + \begin{document} + +\begin{tabular}{cccccccc} +\midrule + 1 & $+$$+$$-$ \\ + 2 & $+$$-$$+$ \\ + 3 & $-$$+$$+$ \\ + 4 & 000 \\ + 5 & $-$$-$$-$ \\ + 6 & 000 \\ +\midrule + 7 & $-$$+$$-$ \\ + 8 & 000 \\ + 9 & $+$$-$$-$ \\ + 10 & $-$$-$$+$ \\ + 11 & $+$$+$$+$ \\ + 12 & 000 \\ +\midrule + 13 & 000 \\ + 14 & 00a \\ + 15 & 00A \\ + 16 & 0A0 \\ + 17 & A00 \\ + 18 & 0a0 \\ + 19 & a00 \\ + 20 & 000 \\ +\toprule +\end{tabular} + +\end{document} + +``` + +--- + +example and further question about side-effects: + +I used the solution of Michel and it looks good, but there is one thing I'm not sure about: +Is it possible that it changes the free space between columns? +I have the impression that the first 3 columns are closer together than the rest... +How can I fix that? + +![solution with side effects?!](https://i.stack.imgur.com/25OVA.png)",2011/03/30,"['https://tex.stackexchange.com/questions/14576', 'https://tex.stackexchange.com', 'https://tex.stackexchange.com/users/4009/']","``` +\documentclass{minimal} +\begin{document} +\setlength{\parindent}{0pt} +\newlength{\stretchlen}\setlength{\stretchlen}{1em} +\def\splitterm{\_} +\newcommand{\stretchit}[1]{\leavevmode\realstretch#1\_} +\def\realstretch#1{% + \def\temp{#1}% + \ifx\temp\splitterm + \else + \hbox to \stretchlen{\hss#1\hss}\expandafter\realstretch +\fi} +\stretchit{abcd}\par +\stretchit{----}\par +\stretchit{++++}\par +\stretchit{-+-+}\par +\stretchit{0aA+}\par +\end{document} + +``` + +`\stretchit` appends an underscore to its argument and passes it to `\realstretch`, which recursively 'eats' one letter at a time, and typesets it centered in an `\hbox` stretched to `\stretchlen`. All letters are thus equally wide, and since they are centered, aligned nicely. + +--- **solution for the question:** + +``` +\documentclass[10pt, a4paper ]{scrreprt} + +\usepackage{booktabs} +\usepackage{collcell} +\usepackage{array} +\begin{document} + +\setlength{\parindent}{0pt} +\newlength{\stretchlen}\setlength{\stretchlen}{1em} +\def\splitterm{\_} +\newcommand{\stretchit}[1]{\leavevmode\realstretch#1\_} +\def\realstretch#1{% + \def\temp{#1}% + \ifx\temp\splitterm + \else + \hbox to \stretchlen{\hss#1\hss}\expandafter\realstretch +\fi} + +without the stretchit command + +\begin{tabular}{cccccccc} +\midrule + 1 & ++- \\ + 2 & +-+ \\ + 3 & -++ \\ + 4 & 000 \\ + 5 & --- \\ + 6 & 000 \\ +\midrule + 7 & -+- \\ + 8 & 000 \\ + 9 & +-- \\ + 10 & --+ \\ + 11 & +++ \\ + 12 & 000 \\ +\midrule + 13 & 000 \\ + 14 & 00a \\ + 15 & 00A \\ + 16 & 0A0 \\ + 17 & A00 \\ + 18 & 0a0 \\ + 19 & a00 \\ + 20 & 000 \\ +\toprule +\end{tabular} + +\medskip + +\emph{with} the stretchit command + +\begin{tabular}{c>{\collectcell\stretchit}c<{\endcollectcell}ccccccc} +\midrule + 1 & ++- \\ + 2 & +-+ \\ + 3 & -++ \\ + 4 & 000 \\ + 5 & --- \\ + 6 & 000 \\ +\midrule + 7 & -+- \\ + 8 & 000 \\ + 9 & +-- \\ + 10 & --+ \\ + 11 & +++ \\ + 12 & 000 \\ +\midrule + 13 & 000 \\ + 14 & 00a \\ + 15 & 00A \\ + 16 & 0A0 \\ + 17 & A00 \\ + 18 & 0a0 \\ + 19 & a00 \\ + 20 & 000 \\ +\toprule +\end{tabular} + +\end{document} + +```","Make sure you typeset them it **math-mode**, i.e. `$-$` and `$+$`. + +Be aware that it makes a difference if you use a single math-mode or separate ones for them. The last sign has different spacing in the first case because it +is taken as an unary sign but the others are operators. + +Compare the following: + +``` +\documentclass{article} + +\begin{document} + +$-$$-$$-$$+$$+$$+$ + +$+$$+$$+$$+$$+$$+$ + +$-$$-$$-$$-$$-$$-$ + +$---+++$ + +$++++++$ + +$------$ + +\end{document} + +``` + +### Result: + +![Result](https://i.stack.imgur.com/8AnbD.png) + +--- + +For the alignment with the other signs `a`, `A` and `0` I would recommend that you make macros for all and set the width manually the one of the widest (should be `$+$`). + +This can be done either with `\hbox to {\hss \hss}` (TeX) or using `\makebox[][c]{}` (LaTeX). The width is provided by `\settowidth{}{}`. + +``` +\documentclass[11pt, a4paper]{scrreprt} + +\usepackage{booktabs} + +\newlength{\slength} +\settowidth{\slength}{$+$} +\newcommand*{\Sz}{\makebox[\slength][c]{0}} +\newcommand*{\SA}{\makebox[\slength][c]{A}} +\newcommand*{\Sa}{\makebox[\slength][c]{a}} +\newcommand*{\Sp}{\makebox[\slength][c]{$+$}} +\newcommand*{\Sm}{\makebox[\slength][c]{$-$}} + +\begin{document} + +\begin{tabular}{cc} +\toprule + 1 & \Sp\Sp\Sm \\ + 2 & \Sp\Sm\Sp \\ + 3 & \Sm\Sp\Sp \\ + 4 & \Sz\Sz\Sz \\ + 5 & \Sm\Sm\Sm \\ + 6 & \Sz\Sz\Sz \\ +\midrule + 7 & \Sm\Sp\Sm \\ + 8 & \Sz\Sz\Sz \\ + 9 & \Sp\Sm\Sm \\ + 10 & \Sm\Sm\Sp \\ + 11 & \Sp\Sp\Sp \\ + 12 & \Sz\Sz\Sz \\ +\midrule + 13 & \Sz\Sz\Sz \\ + 14 & \Sz\Sz\Sa \\ + 15 & \Sz\Sz\SA \\ + 16 & \Sz\SA\Sz \\ + 17 & \SA\Sz\Sz \\ + 18 & \Sz\Sa\Sz \\ + 19 & \Sa\Sz\Sz \\ + 20 & \Sz\Sz\Sz \\ +\bottomrule +\end{tabular} + +\end{document} + +``` + +### Result: + +![Result 2](https://i.stack.imgur.com/1d879.png)" +14576,"for typesetting tables with design of experiments, I have to typeset strings like ""+ - + +"", - - - +"", etc. in a column of a table to represent the so called pattern of the experimental run (sometimes they also contain ""a"", ""A"" and ""0"" (zero)). + +However, the width of the ""+"" and ""-"" sign are very different in the used font (standard font in KOMA script class scrreprt) and a sequence of 2 or 3 dashes creates one long or very long dash.... + +So I'm searching for a way to easily typeset e. g. ""+ - - - + -"" with a little spacing between the characters and (if possible) that several different strings composed of the same number of characters (""+"" or ""-"", ""a"", ""A"" and ""0"") would be aligned with each other, when they are in the same column of a table. + +I hope I could make clear what I need, some examples how it shall NOT look are found here: + +![bad example](https://i.stack.imgur.com/YZkQH.png) +in line 9 it should be ""+ - -"" and in 10 ""- - +"", line 5 should be ""- - -"" + +It looks a little better, if I insert `\,` between the characters, but as the widths are different, it is still not aligned: + +![enter image description here](https://i.stack.imgur.com/dC5x3.png) + +Sure, I could split it up in centered columns like `- & + & - & - & ...`, but the tables are already complicated enough and I do not want to add 3 to 7 columns... + +Does anybody have an idea how to solve that? +Maybe a command that parses the string like --+--++ and typesets it with a ""constant spacing""? + +------- edit: + +added math mode for ""+"" and ""-"", looks better now, but not perfect: +![math mode for plus and minus](https://i.stack.imgur.com/D3hFt.png) + +``` + \documentclass[11pt, a4paper%, halfparskip + ]{scrreprt} + + \usepackage{booktabs} + + \begin{document} + +\begin{tabular}{cccccccc} +\midrule + 1 & $+$$+$$-$ \\ + 2 & $+$$-$$+$ \\ + 3 & $-$$+$$+$ \\ + 4 & 000 \\ + 5 & $-$$-$$-$ \\ + 6 & 000 \\ +\midrule + 7 & $-$$+$$-$ \\ + 8 & 000 \\ + 9 & $+$$-$$-$ \\ + 10 & $-$$-$$+$ \\ + 11 & $+$$+$$+$ \\ + 12 & 000 \\ +\midrule + 13 & 000 \\ + 14 & 00a \\ + 15 & 00A \\ + 16 & 0A0 \\ + 17 & A00 \\ + 18 & 0a0 \\ + 19 & a00 \\ + 20 & 000 \\ +\toprule +\end{tabular} + +\end{document} + +``` + +--- + +example and further question about side-effects: + +I used the solution of Michel and it looks good, but there is one thing I'm not sure about: +Is it possible that it changes the free space between columns? +I have the impression that the first 3 columns are closer together than the rest... +How can I fix that? + +![solution with side effects?!](https://i.stack.imgur.com/25OVA.png)",2011/03/30,"['https://tex.stackexchange.com/questions/14576', 'https://tex.stackexchange.com', 'https://tex.stackexchange.com/users/4009/']","``` +\documentclass{minimal} +\begin{document} +\setlength{\parindent}{0pt} +\newlength{\stretchlen}\setlength{\stretchlen}{1em} +\def\splitterm{\_} +\newcommand{\stretchit}[1]{\leavevmode\realstretch#1\_} +\def\realstretch#1{% + \def\temp{#1}% + \ifx\temp\splitterm + \else + \hbox to \stretchlen{\hss#1\hss}\expandafter\realstretch +\fi} +\stretchit{abcd}\par +\stretchit{----}\par +\stretchit{++++}\par +\stretchit{-+-+}\par +\stretchit{0aA+}\par +\end{document} + +``` + +`\stretchit` appends an underscore to its argument and passes it to `\realstretch`, which recursively 'eats' one letter at a time, and typesets it centered in an `\hbox` stretched to `\stretchlen`. All letters are thus equally wide, and since they are centered, aligned nicely. + +--- **solution for the question:** + +``` +\documentclass[10pt, a4paper ]{scrreprt} + +\usepackage{booktabs} +\usepackage{collcell} +\usepackage{array} +\begin{document} + +\setlength{\parindent}{0pt} +\newlength{\stretchlen}\setlength{\stretchlen}{1em} +\def\splitterm{\_} +\newcommand{\stretchit}[1]{\leavevmode\realstretch#1\_} +\def\realstretch#1{% + \def\temp{#1}% + \ifx\temp\splitterm + \else + \hbox to \stretchlen{\hss#1\hss}\expandafter\realstretch +\fi} + +without the stretchit command + +\begin{tabular}{cccccccc} +\midrule + 1 & ++- \\ + 2 & +-+ \\ + 3 & -++ \\ + 4 & 000 \\ + 5 & --- \\ + 6 & 000 \\ +\midrule + 7 & -+- \\ + 8 & 000 \\ + 9 & +-- \\ + 10 & --+ \\ + 11 & +++ \\ + 12 & 000 \\ +\midrule + 13 & 000 \\ + 14 & 00a \\ + 15 & 00A \\ + 16 & 0A0 \\ + 17 & A00 \\ + 18 & 0a0 \\ + 19 & a00 \\ + 20 & 000 \\ +\toprule +\end{tabular} + +\medskip + +\emph{with} the stretchit command + +\begin{tabular}{c>{\collectcell\stretchit}c<{\endcollectcell}ccccccc} +\midrule + 1 & ++- \\ + 2 & +-+ \\ + 3 & -++ \\ + 4 & 000 \\ + 5 & --- \\ + 6 & 000 \\ +\midrule + 7 & -+- \\ + 8 & 000 \\ + 9 & +-- \\ + 10 & --+ \\ + 11 & +++ \\ + 12 & 000 \\ +\midrule + 13 & 000 \\ + 14 & 00a \\ + 15 & 00A \\ + 16 & 0A0 \\ + 17 & A00 \\ + 18 & 0a0 \\ + 19 & a00 \\ + 20 & 000 \\ +\toprule +\end{tabular} + +\end{document} + +```","one possible form to typeset your table would be to use a table column for each character: + +``` +\documentclass[11pt, a4paper]{scrreprt} +\usepackage{booktabs} + +\newcommand\Pl{${}+{}$} +\newcommand\Mi{${}-{}$} + +\begin{document} + +\begin{tabular}{cc@{\hspace{-2pt}}c@{\hspace{-2pt}}c} + \toprule + 1 & \Pl & \Pl & \Mi \\ + 4 & 0 & 0 & 0 \\ + 12 & a & 0 & A \\ + 15 & 0 & 0 & A \\ + \bottomrule +\end{tabular} + +\end{document} + +``` + +![](https://i.stack.imgur.com/RxGDb.png)" +14576,"for typesetting tables with design of experiments, I have to typeset strings like ""+ - + +"", - - - +"", etc. in a column of a table to represent the so called pattern of the experimental run (sometimes they also contain ""a"", ""A"" and ""0"" (zero)). + +However, the width of the ""+"" and ""-"" sign are very different in the used font (standard font in KOMA script class scrreprt) and a sequence of 2 or 3 dashes creates one long or very long dash.... + +So I'm searching for a way to easily typeset e. g. ""+ - - - + -"" with a little spacing between the characters and (if possible) that several different strings composed of the same number of characters (""+"" or ""-"", ""a"", ""A"" and ""0"") would be aligned with each other, when they are in the same column of a table. + +I hope I could make clear what I need, some examples how it shall NOT look are found here: + +![bad example](https://i.stack.imgur.com/YZkQH.png) +in line 9 it should be ""+ - -"" and in 10 ""- - +"", line 5 should be ""- - -"" + +It looks a little better, if I insert `\,` between the characters, but as the widths are different, it is still not aligned: + +![enter image description here](https://i.stack.imgur.com/dC5x3.png) + +Sure, I could split it up in centered columns like `- & + & - & - & ...`, but the tables are already complicated enough and I do not want to add 3 to 7 columns... + +Does anybody have an idea how to solve that? +Maybe a command that parses the string like --+--++ and typesets it with a ""constant spacing""? + +------- edit: + +added math mode for ""+"" and ""-"", looks better now, but not perfect: +![math mode for plus and minus](https://i.stack.imgur.com/D3hFt.png) + +``` + \documentclass[11pt, a4paper%, halfparskip + ]{scrreprt} + + \usepackage{booktabs} + + \begin{document} + +\begin{tabular}{cccccccc} +\midrule + 1 & $+$$+$$-$ \\ + 2 & $+$$-$$+$ \\ + 3 & $-$$+$$+$ \\ + 4 & 000 \\ + 5 & $-$$-$$-$ \\ + 6 & 000 \\ +\midrule + 7 & $-$$+$$-$ \\ + 8 & 000 \\ + 9 & $+$$-$$-$ \\ + 10 & $-$$-$$+$ \\ + 11 & $+$$+$$+$ \\ + 12 & 000 \\ +\midrule + 13 & 000 \\ + 14 & 00a \\ + 15 & 00A \\ + 16 & 0A0 \\ + 17 & A00 \\ + 18 & 0a0 \\ + 19 & a00 \\ + 20 & 000 \\ +\toprule +\end{tabular} + +\end{document} + +``` + +--- + +example and further question about side-effects: + +I used the solution of Michel and it looks good, but there is one thing I'm not sure about: +Is it possible that it changes the free space between columns? +I have the impression that the first 3 columns are closer together than the rest... +How can I fix that? + +![solution with side effects?!](https://i.stack.imgur.com/25OVA.png)",2011/03/30,"['https://tex.stackexchange.com/questions/14576', 'https://tex.stackexchange.com', 'https://tex.stackexchange.com/users/4009/']","Make sure you typeset them it **math-mode**, i.e. `$-$` and `$+$`. + +Be aware that it makes a difference if you use a single math-mode or separate ones for them. The last sign has different spacing in the first case because it +is taken as an unary sign but the others are operators. + +Compare the following: + +``` +\documentclass{article} + +\begin{document} + +$-$$-$$-$$+$$+$$+$ + +$+$$+$$+$$+$$+$$+$ + +$-$$-$$-$$-$$-$$-$ + +$---+++$ + +$++++++$ + +$------$ + +\end{document} + +``` + +### Result: + +![Result](https://i.stack.imgur.com/8AnbD.png) + +--- + +For the alignment with the other signs `a`, `A` and `0` I would recommend that you make macros for all and set the width manually the one of the widest (should be `$+$`). + +This can be done either with `\hbox to {\hss \hss}` (TeX) or using `\makebox[][c]{}` (LaTeX). The width is provided by `\settowidth{}{}`. + +``` +\documentclass[11pt, a4paper]{scrreprt} + +\usepackage{booktabs} + +\newlength{\slength} +\settowidth{\slength}{$+$} +\newcommand*{\Sz}{\makebox[\slength][c]{0}} +\newcommand*{\SA}{\makebox[\slength][c]{A}} +\newcommand*{\Sa}{\makebox[\slength][c]{a}} +\newcommand*{\Sp}{\makebox[\slength][c]{$+$}} +\newcommand*{\Sm}{\makebox[\slength][c]{$-$}} + +\begin{document} + +\begin{tabular}{cc} +\toprule + 1 & \Sp\Sp\Sm \\ + 2 & \Sp\Sm\Sp \\ + 3 & \Sm\Sp\Sp \\ + 4 & \Sz\Sz\Sz \\ + 5 & \Sm\Sm\Sm \\ + 6 & \Sz\Sz\Sz \\ +\midrule + 7 & \Sm\Sp\Sm \\ + 8 & \Sz\Sz\Sz \\ + 9 & \Sp\Sm\Sm \\ + 10 & \Sm\Sm\Sp \\ + 11 & \Sp\Sp\Sp \\ + 12 & \Sz\Sz\Sz \\ +\midrule + 13 & \Sz\Sz\Sz \\ + 14 & \Sz\Sz\Sa \\ + 15 & \Sz\Sz\SA \\ + 16 & \Sz\SA\Sz \\ + 17 & \SA\Sz\Sz \\ + 18 & \Sz\Sa\Sz \\ + 19 & \Sa\Sz\Sz \\ + 20 & \Sz\Sz\Sz \\ +\bottomrule +\end{tabular} + +\end{document} + +``` + +### Result: + +![Result 2](https://i.stack.imgur.com/1d879.png)","Michel's solution is nice, but I'd like to present some improvements. + +``` +\newlength{\stretchlen} +\settowidth{\stretchlen}{+} +\newcommand{\stretchit}[1]{\realstretch#1\_} +\newcommand\realstretch[1]{% + \ifx#1\_% + \else + \makebox[\stretchlen]{\ifx#1-$-$\else#1\fi}% + %\hbox to \stretchlen{\hss\ifx#1-$-$\else#1\fi\hss}% + \expandafter\realstretch + \fi} + +``` + +It's not necessary to have `\splitterm` and to define `\temp` at each stage, since we're collecting tokens one by one and those tokens are simple characters. It's best also to set `\stretchlen` to the widest character, in this case `+`. Finally, there's the particular case of `-` that should be treated differently with a `$-$`. + +I've left commented the line with `\hbox`: with `\makebox` it's more in the LaTeX way of thinking; the two lines give the same result, but of course `\makebox` is a bit less efficient than `\hbox`. + +--- + +Some years later, the solution can be made more robust, with the possibility of managing other characters that need special treatment. + +``` +\documentclass[10pt,a4paper]{scrreprt} + +\usepackage{booktabs} +\usepackage{collcell} +\usepackage{array} +\usepackage{xparse} + +\ExplSyntaxOn +\NewDocumentCommand{\stretchit}{m} + { + \tl_map_inline:nn { #1 } + { + \makebox[\stretchlen] + { + \str_case:nnF { ##1 } + { + {-}{$-$} + {+}{$+$} + {*}{$*$} + } + {##1} + } + } + } +\ExplSyntaxOff + +\newlength{\stretchlen} +\AtBeginDocument{\settowidth{\stretchlen}{$-$}} + +\begin{document} + +\begin{tabular}{r >{\collectcell\stretchit}c<{\endcollectcell}} +\midrule + 1 & ++- \\ + 2 & +-+ \\ + 3 & -++ \\ + 4 & 000 \\ + 5 & --- \\ + 6 & 000 \\ +\midrule + 7 & -+- \\ + 8 & -*x \\ + 9 & +-- \\ +10 & --+ \\ +11 & +++ \\ +12 & 000 \\ +\bottomrule +\end{tabular} + +\end{document} + +``` + +[![enter image description here](https://i.stack.imgur.com/mQ2VO.png)](https://i.stack.imgur.com/mQ2VO.png)" +14576,"for typesetting tables with design of experiments, I have to typeset strings like ""+ - + +"", - - - +"", etc. in a column of a table to represent the so called pattern of the experimental run (sometimes they also contain ""a"", ""A"" and ""0"" (zero)). + +However, the width of the ""+"" and ""-"" sign are very different in the used font (standard font in KOMA script class scrreprt) and a sequence of 2 or 3 dashes creates one long or very long dash.... + +So I'm searching for a way to easily typeset e. g. ""+ - - - + -"" with a little spacing between the characters and (if possible) that several different strings composed of the same number of characters (""+"" or ""-"", ""a"", ""A"" and ""0"") would be aligned with each other, when they are in the same column of a table. + +I hope I could make clear what I need, some examples how it shall NOT look are found here: + +![bad example](https://i.stack.imgur.com/YZkQH.png) +in line 9 it should be ""+ - -"" and in 10 ""- - +"", line 5 should be ""- - -"" + +It looks a little better, if I insert `\,` between the characters, but as the widths are different, it is still not aligned: + +![enter image description here](https://i.stack.imgur.com/dC5x3.png) + +Sure, I could split it up in centered columns like `- & + & - & - & ...`, but the tables are already complicated enough and I do not want to add 3 to 7 columns... + +Does anybody have an idea how to solve that? +Maybe a command that parses the string like --+--++ and typesets it with a ""constant spacing""? + +------- edit: + +added math mode for ""+"" and ""-"", looks better now, but not perfect: +![math mode for plus and minus](https://i.stack.imgur.com/D3hFt.png) + +``` + \documentclass[11pt, a4paper%, halfparskip + ]{scrreprt} + + \usepackage{booktabs} + + \begin{document} + +\begin{tabular}{cccccccc} +\midrule + 1 & $+$$+$$-$ \\ + 2 & $+$$-$$+$ \\ + 3 & $-$$+$$+$ \\ + 4 & 000 \\ + 5 & $-$$-$$-$ \\ + 6 & 000 \\ +\midrule + 7 & $-$$+$$-$ \\ + 8 & 000 \\ + 9 & $+$$-$$-$ \\ + 10 & $-$$-$$+$ \\ + 11 & $+$$+$$+$ \\ + 12 & 000 \\ +\midrule + 13 & 000 \\ + 14 & 00a \\ + 15 & 00A \\ + 16 & 0A0 \\ + 17 & A00 \\ + 18 & 0a0 \\ + 19 & a00 \\ + 20 & 000 \\ +\toprule +\end{tabular} + +\end{document} + +``` + +--- + +example and further question about side-effects: + +I used the solution of Michel and it looks good, but there is one thing I'm not sure about: +Is it possible that it changes the free space between columns? +I have the impression that the first 3 columns are closer together than the rest... +How can I fix that? + +![solution with side effects?!](https://i.stack.imgur.com/25OVA.png)",2011/03/30,"['https://tex.stackexchange.com/questions/14576', 'https://tex.stackexchange.com', 'https://tex.stackexchange.com/users/4009/']","one possible form to typeset your table would be to use a table column for each character: + +``` +\documentclass[11pt, a4paper]{scrreprt} +\usepackage{booktabs} + +\newcommand\Pl{${}+{}$} +\newcommand\Mi{${}-{}$} + +\begin{document} + +\begin{tabular}{cc@{\hspace{-2pt}}c@{\hspace{-2pt}}c} + \toprule + 1 & \Pl & \Pl & \Mi \\ + 4 & 0 & 0 & 0 \\ + 12 & a & 0 & A \\ + 15 & 0 & 0 & A \\ + \bottomrule +\end{tabular} + +\end{document} + +``` + +![](https://i.stack.imgur.com/RxGDb.png)","A quick and dirty solution might be to enclose the symbols in braces: `${-}{+}{+}{+}$` looks better than `$-+++$`, as LaTeX won't try to interpret each `+` or `-` as a binary operator." +14576,"for typesetting tables with design of experiments, I have to typeset strings like ""+ - + +"", - - - +"", etc. in a column of a table to represent the so called pattern of the experimental run (sometimes they also contain ""a"", ""A"" and ""0"" (zero)). + +However, the width of the ""+"" and ""-"" sign are very different in the used font (standard font in KOMA script class scrreprt) and a sequence of 2 or 3 dashes creates one long or very long dash.... + +So I'm searching for a way to easily typeset e. g. ""+ - - - + -"" with a little spacing between the characters and (if possible) that several different strings composed of the same number of characters (""+"" or ""-"", ""a"", ""A"" and ""0"") would be aligned with each other, when they are in the same column of a table. + +I hope I could make clear what I need, some examples how it shall NOT look are found here: + +![bad example](https://i.stack.imgur.com/YZkQH.png) +in line 9 it should be ""+ - -"" and in 10 ""- - +"", line 5 should be ""- - -"" + +It looks a little better, if I insert `\,` between the characters, but as the widths are different, it is still not aligned: + +![enter image description here](https://i.stack.imgur.com/dC5x3.png) + +Sure, I could split it up in centered columns like `- & + & - & - & ...`, but the tables are already complicated enough and I do not want to add 3 to 7 columns... + +Does anybody have an idea how to solve that? +Maybe a command that parses the string like --+--++ and typesets it with a ""constant spacing""? + +------- edit: + +added math mode for ""+"" and ""-"", looks better now, but not perfect: +![math mode for plus and minus](https://i.stack.imgur.com/D3hFt.png) + +``` + \documentclass[11pt, a4paper%, halfparskip + ]{scrreprt} + + \usepackage{booktabs} + + \begin{document} + +\begin{tabular}{cccccccc} +\midrule + 1 & $+$$+$$-$ \\ + 2 & $+$$-$$+$ \\ + 3 & $-$$+$$+$ \\ + 4 & 000 \\ + 5 & $-$$-$$-$ \\ + 6 & 000 \\ +\midrule + 7 & $-$$+$$-$ \\ + 8 & 000 \\ + 9 & $+$$-$$-$ \\ + 10 & $-$$-$$+$ \\ + 11 & $+$$+$$+$ \\ + 12 & 000 \\ +\midrule + 13 & 000 \\ + 14 & 00a \\ + 15 & 00A \\ + 16 & 0A0 \\ + 17 & A00 \\ + 18 & 0a0 \\ + 19 & a00 \\ + 20 & 000 \\ +\toprule +\end{tabular} + +\end{document} + +``` + +--- + +example and further question about side-effects: + +I used the solution of Michel and it looks good, but there is one thing I'm not sure about: +Is it possible that it changes the free space between columns? +I have the impression that the first 3 columns are closer together than the rest... +How can I fix that? + +![solution with side effects?!](https://i.stack.imgur.com/25OVA.png)",2011/03/30,"['https://tex.stackexchange.com/questions/14576', 'https://tex.stackexchange.com', 'https://tex.stackexchange.com/users/4009/']","``` +\documentclass{minimal} +\begin{document} +\setlength{\parindent}{0pt} +\newlength{\stretchlen}\setlength{\stretchlen}{1em} +\def\splitterm{\_} +\newcommand{\stretchit}[1]{\leavevmode\realstretch#1\_} +\def\realstretch#1{% + \def\temp{#1}% + \ifx\temp\splitterm + \else + \hbox to \stretchlen{\hss#1\hss}\expandafter\realstretch +\fi} +\stretchit{abcd}\par +\stretchit{----}\par +\stretchit{++++}\par +\stretchit{-+-+}\par +\stretchit{0aA+}\par +\end{document} + +``` + +`\stretchit` appends an underscore to its argument and passes it to `\realstretch`, which recursively 'eats' one letter at a time, and typesets it centered in an `\hbox` stretched to `\stretchlen`. All letters are thus equally wide, and since they are centered, aligned nicely. + +--- **solution for the question:** + +``` +\documentclass[10pt, a4paper ]{scrreprt} + +\usepackage{booktabs} +\usepackage{collcell} +\usepackage{array} +\begin{document} + +\setlength{\parindent}{0pt} +\newlength{\stretchlen}\setlength{\stretchlen}{1em} +\def\splitterm{\_} +\newcommand{\stretchit}[1]{\leavevmode\realstretch#1\_} +\def\realstretch#1{% + \def\temp{#1}% + \ifx\temp\splitterm + \else + \hbox to \stretchlen{\hss#1\hss}\expandafter\realstretch +\fi} + +without the stretchit command + +\begin{tabular}{cccccccc} +\midrule + 1 & ++- \\ + 2 & +-+ \\ + 3 & -++ \\ + 4 & 000 \\ + 5 & --- \\ + 6 & 000 \\ +\midrule + 7 & -+- \\ + 8 & 000 \\ + 9 & +-- \\ + 10 & --+ \\ + 11 & +++ \\ + 12 & 000 \\ +\midrule + 13 & 000 \\ + 14 & 00a \\ + 15 & 00A \\ + 16 & 0A0 \\ + 17 & A00 \\ + 18 & 0a0 \\ + 19 & a00 \\ + 20 & 000 \\ +\toprule +\end{tabular} + +\medskip + +\emph{with} the stretchit command + +\begin{tabular}{c>{\collectcell\stretchit}c<{\endcollectcell}ccccccc} +\midrule + 1 & ++- \\ + 2 & +-+ \\ + 3 & -++ \\ + 4 & 000 \\ + 5 & --- \\ + 6 & 000 \\ +\midrule + 7 & -+- \\ + 8 & 000 \\ + 9 & +-- \\ + 10 & --+ \\ + 11 & +++ \\ + 12 & 000 \\ +\midrule + 13 & 000 \\ + 14 & 00a \\ + 15 & 00A \\ + 16 & 0A0 \\ + 17 & A00 \\ + 18 & 0a0 \\ + 19 & a00 \\ + 20 & 000 \\ +\toprule +\end{tabular} + +\end{document} + +```","A quick and dirty solution might be to enclose the symbols in braces: `${-}{+}{+}{+}$` looks better than `$-+++$`, as LaTeX won't try to interpret each `+` or `-` as a binary operator." +14576,"for typesetting tables with design of experiments, I have to typeset strings like ""+ - + +"", - - - +"", etc. in a column of a table to represent the so called pattern of the experimental run (sometimes they also contain ""a"", ""A"" and ""0"" (zero)). + +However, the width of the ""+"" and ""-"" sign are very different in the used font (standard font in KOMA script class scrreprt) and a sequence of 2 or 3 dashes creates one long or very long dash.... + +So I'm searching for a way to easily typeset e. g. ""+ - - - + -"" with a little spacing between the characters and (if possible) that several different strings composed of the same number of characters (""+"" or ""-"", ""a"", ""A"" and ""0"") would be aligned with each other, when they are in the same column of a table. + +I hope I could make clear what I need, some examples how it shall NOT look are found here: + +![bad example](https://i.stack.imgur.com/YZkQH.png) +in line 9 it should be ""+ - -"" and in 10 ""- - +"", line 5 should be ""- - -"" + +It looks a little better, if I insert `\,` between the characters, but as the widths are different, it is still not aligned: + +![enter image description here](https://i.stack.imgur.com/dC5x3.png) + +Sure, I could split it up in centered columns like `- & + & - & - & ...`, but the tables are already complicated enough and I do not want to add 3 to 7 columns... + +Does anybody have an idea how to solve that? +Maybe a command that parses the string like --+--++ and typesets it with a ""constant spacing""? + +------- edit: + +added math mode for ""+"" and ""-"", looks better now, but not perfect: +![math mode for plus and minus](https://i.stack.imgur.com/D3hFt.png) + +``` + \documentclass[11pt, a4paper%, halfparskip + ]{scrreprt} + + \usepackage{booktabs} + + \begin{document} + +\begin{tabular}{cccccccc} +\midrule + 1 & $+$$+$$-$ \\ + 2 & $+$$-$$+$ \\ + 3 & $-$$+$$+$ \\ + 4 & 000 \\ + 5 & $-$$-$$-$ \\ + 6 & 000 \\ +\midrule + 7 & $-$$+$$-$ \\ + 8 & 000 \\ + 9 & $+$$-$$-$ \\ + 10 & $-$$-$$+$ \\ + 11 & $+$$+$$+$ \\ + 12 & 000 \\ +\midrule + 13 & 000 \\ + 14 & 00a \\ + 15 & 00A \\ + 16 & 0A0 \\ + 17 & A00 \\ + 18 & 0a0 \\ + 19 & a00 \\ + 20 & 000 \\ +\toprule +\end{tabular} + +\end{document} + +``` + +--- + +example and further question about side-effects: + +I used the solution of Michel and it looks good, but there is one thing I'm not sure about: +Is it possible that it changes the free space between columns? +I have the impression that the first 3 columns are closer together than the rest... +How can I fix that? + +![solution with side effects?!](https://i.stack.imgur.com/25OVA.png)",2011/03/30,"['https://tex.stackexchange.com/questions/14576', 'https://tex.stackexchange.com', 'https://tex.stackexchange.com/users/4009/']","``` +\documentclass{minimal} +\begin{document} +\setlength{\parindent}{0pt} +\newlength{\stretchlen}\setlength{\stretchlen}{1em} +\def\splitterm{\_} +\newcommand{\stretchit}[1]{\leavevmode\realstretch#1\_} +\def\realstretch#1{% + \def\temp{#1}% + \ifx\temp\splitterm + \else + \hbox to \stretchlen{\hss#1\hss}\expandafter\realstretch +\fi} +\stretchit{abcd}\par +\stretchit{----}\par +\stretchit{++++}\par +\stretchit{-+-+}\par +\stretchit{0aA+}\par +\end{document} + +``` + +`\stretchit` appends an underscore to its argument and passes it to `\realstretch`, which recursively 'eats' one letter at a time, and typesets it centered in an `\hbox` stretched to `\stretchlen`. All letters are thus equally wide, and since they are centered, aligned nicely. + +--- **solution for the question:** + +``` +\documentclass[10pt, a4paper ]{scrreprt} + +\usepackage{booktabs} +\usepackage{collcell} +\usepackage{array} +\begin{document} + +\setlength{\parindent}{0pt} +\newlength{\stretchlen}\setlength{\stretchlen}{1em} +\def\splitterm{\_} +\newcommand{\stretchit}[1]{\leavevmode\realstretch#1\_} +\def\realstretch#1{% + \def\temp{#1}% + \ifx\temp\splitterm + \else + \hbox to \stretchlen{\hss#1\hss}\expandafter\realstretch +\fi} + +without the stretchit command + +\begin{tabular}{cccccccc} +\midrule + 1 & ++- \\ + 2 & +-+ \\ + 3 & -++ \\ + 4 & 000 \\ + 5 & --- \\ + 6 & 000 \\ +\midrule + 7 & -+- \\ + 8 & 000 \\ + 9 & +-- \\ + 10 & --+ \\ + 11 & +++ \\ + 12 & 000 \\ +\midrule + 13 & 000 \\ + 14 & 00a \\ + 15 & 00A \\ + 16 & 0A0 \\ + 17 & A00 \\ + 18 & 0a0 \\ + 19 & a00 \\ + 20 & 000 \\ +\toprule +\end{tabular} + +\medskip + +\emph{with} the stretchit command + +\begin{tabular}{c>{\collectcell\stretchit}c<{\endcollectcell}ccccccc} +\midrule + 1 & ++- \\ + 2 & +-+ \\ + 3 & -++ \\ + 4 & 000 \\ + 5 & --- \\ + 6 & 000 \\ +\midrule + 7 & -+- \\ + 8 & 000 \\ + 9 & +-- \\ + 10 & --+ \\ + 11 & +++ \\ + 12 & 000 \\ +\midrule + 13 & 000 \\ + 14 & 00a \\ + 15 & 00A \\ + 16 & 0A0 \\ + 17 & A00 \\ + 18 & 0a0 \\ + 19 & a00 \\ + 20 & 000 \\ +\toprule +\end{tabular} + +\end{document} + +```","An easy way to achieve this would be to typeset the plusses and minuses in a monospace font with `\verb|+-+-|` + +There are however [issues](https://tex.stackexchange.com/q/203/215) with verbatim text which you might run into... +Another solution might be to use `\texttt` and macros for your plusses etc. Here's an example: + +``` +\documentclass{article} +\usepackage[T1]{fontenc} +\newcommand\p{+} +\newcommand\m{-{}} +\begin{document} +\texttt{++---++} + +\texttt{\p\p\m\m\m\p\p} + +\texttt{++\m\m aA0} +\end{document} + +``` + +You need to use a macro like this for the minus sign because otherwise they get turned into en-dashes if you use the `fontenc` package. This should also mono-space letters easily." +14576,"for typesetting tables with design of experiments, I have to typeset strings like ""+ - + +"", - - - +"", etc. in a column of a table to represent the so called pattern of the experimental run (sometimes they also contain ""a"", ""A"" and ""0"" (zero)). + +However, the width of the ""+"" and ""-"" sign are very different in the used font (standard font in KOMA script class scrreprt) and a sequence of 2 or 3 dashes creates one long or very long dash.... + +So I'm searching for a way to easily typeset e. g. ""+ - - - + -"" with a little spacing between the characters and (if possible) that several different strings composed of the same number of characters (""+"" or ""-"", ""a"", ""A"" and ""0"") would be aligned with each other, when they are in the same column of a table. + +I hope I could make clear what I need, some examples how it shall NOT look are found here: + +![bad example](https://i.stack.imgur.com/YZkQH.png) +in line 9 it should be ""+ - -"" and in 10 ""- - +"", line 5 should be ""- - -"" + +It looks a little better, if I insert `\,` between the characters, but as the widths are different, it is still not aligned: + +![enter image description here](https://i.stack.imgur.com/dC5x3.png) + +Sure, I could split it up in centered columns like `- & + & - & - & ...`, but the tables are already complicated enough and I do not want to add 3 to 7 columns... + +Does anybody have an idea how to solve that? +Maybe a command that parses the string like --+--++ and typesets it with a ""constant spacing""? + +------- edit: + +added math mode for ""+"" and ""-"", looks better now, but not perfect: +![math mode for plus and minus](https://i.stack.imgur.com/D3hFt.png) + +``` + \documentclass[11pt, a4paper%, halfparskip + ]{scrreprt} + + \usepackage{booktabs} + + \begin{document} + +\begin{tabular}{cccccccc} +\midrule + 1 & $+$$+$$-$ \\ + 2 & $+$$-$$+$ \\ + 3 & $-$$+$$+$ \\ + 4 & 000 \\ + 5 & $-$$-$$-$ \\ + 6 & 000 \\ +\midrule + 7 & $-$$+$$-$ \\ + 8 & 000 \\ + 9 & $+$$-$$-$ \\ + 10 & $-$$-$$+$ \\ + 11 & $+$$+$$+$ \\ + 12 & 000 \\ +\midrule + 13 & 000 \\ + 14 & 00a \\ + 15 & 00A \\ + 16 & 0A0 \\ + 17 & A00 \\ + 18 & 0a0 \\ + 19 & a00 \\ + 20 & 000 \\ +\toprule +\end{tabular} + +\end{document} + +``` + +--- + +example and further question about side-effects: + +I used the solution of Michel and it looks good, but there is one thing I'm not sure about: +Is it possible that it changes the free space between columns? +I have the impression that the first 3 columns are closer together than the rest... +How can I fix that? + +![solution with side effects?!](https://i.stack.imgur.com/25OVA.png)",2011/03/30,"['https://tex.stackexchange.com/questions/14576', 'https://tex.stackexchange.com', 'https://tex.stackexchange.com/users/4009/']","Make sure you typeset them it **math-mode**, i.e. `$-$` and `$+$`. + +Be aware that it makes a difference if you use a single math-mode or separate ones for them. The last sign has different spacing in the first case because it +is taken as an unary sign but the others are operators. + +Compare the following: + +``` +\documentclass{article} + +\begin{document} + +$-$$-$$-$$+$$+$$+$ + +$+$$+$$+$$+$$+$$+$ + +$-$$-$$-$$-$$-$$-$ + +$---+++$ + +$++++++$ + +$------$ + +\end{document} + +``` + +### Result: + +![Result](https://i.stack.imgur.com/8AnbD.png) + +--- + +For the alignment with the other signs `a`, `A` and `0` I would recommend that you make macros for all and set the width manually the one of the widest (should be `$+$`). + +This can be done either with `\hbox to {\hss \hss}` (TeX) or using `\makebox[][c]{}` (LaTeX). The width is provided by `\settowidth{}{}`. + +``` +\documentclass[11pt, a4paper]{scrreprt} + +\usepackage{booktabs} + +\newlength{\slength} +\settowidth{\slength}{$+$} +\newcommand*{\Sz}{\makebox[\slength][c]{0}} +\newcommand*{\SA}{\makebox[\slength][c]{A}} +\newcommand*{\Sa}{\makebox[\slength][c]{a}} +\newcommand*{\Sp}{\makebox[\slength][c]{$+$}} +\newcommand*{\Sm}{\makebox[\slength][c]{$-$}} + +\begin{document} + +\begin{tabular}{cc} +\toprule + 1 & \Sp\Sp\Sm \\ + 2 & \Sp\Sm\Sp \\ + 3 & \Sm\Sp\Sp \\ + 4 & \Sz\Sz\Sz \\ + 5 & \Sm\Sm\Sm \\ + 6 & \Sz\Sz\Sz \\ +\midrule + 7 & \Sm\Sp\Sm \\ + 8 & \Sz\Sz\Sz \\ + 9 & \Sp\Sm\Sm \\ + 10 & \Sm\Sm\Sp \\ + 11 & \Sp\Sp\Sp \\ + 12 & \Sz\Sz\Sz \\ +\midrule + 13 & \Sz\Sz\Sz \\ + 14 & \Sz\Sz\Sa \\ + 15 & \Sz\Sz\SA \\ + 16 & \Sz\SA\Sz \\ + 17 & \SA\Sz\Sz \\ + 18 & \Sz\Sa\Sz \\ + 19 & \Sa\Sz\Sz \\ + 20 & \Sz\Sz\Sz \\ +\bottomrule +\end{tabular} + +\end{document} + +``` + +### Result: + +![Result 2](https://i.stack.imgur.com/1d879.png)","A quick and dirty solution might be to enclose the symbols in braces: `${-}{+}{+}{+}$` looks better than `$-+++$`, as LaTeX won't try to interpret each `+` or `-` as a binary operator." +6628452,"I want Django to send an email to user email-address with Login details once admin adds a new user to admin site.So I tried using Django signals for that but just becoz django user registration is a two step process signals get notified in first step only and called email function without email address(which comes in second step). +My signal code: + +``` +def email_new_user(sender, **kwargs): + if kwargs[""created""]: # only for new users + new_user = kwargs[""instance""] + send_mail('Subject here', 'Here is the message.', 'from@example.com',['to@example.com'], fail_silently=False) + +post_save.connect(email_new_user, sender=User) + +``` + +So what i tried to overcome this problem.I use this code in admin.py + +``` +class UserAdmin(admin.ModelAdmin): + list_display = ('username', 'email', 'first_name', 'last_name', 'date_joined', 'last_login') + search_fields = ['username', 'email'] + filter_horizontal = ('user_permissions',) + +admin.site.unregister(User) +admin.site.register(User, UserAdmin) + +``` + +This makes all registration process a single step process and my signals start working and sending mail to user\_id on new user addition.But the problem came after this were: + +**1. User password is not converted into hash and is visible while entering into form,that makes user not able to login into admin site.** + +**2.Email field in form is not compulsory which I want to be compulsory.** + +Please help me :( + +**[EDIT]** + +``` +I tried your code But I m still at same place where i was before posting this question. +the code i used in my admin.py is: +from django.contrib import admin +from mysite.naturefarms.models import * +from django.contrib.auth.models import User,Group +from django.contrib.auth.admin import UserAdmin +from django.contrib.auth.forms import UserCreationForm, UserChangeForm +from django import forms +from django.contrib.admin.views.main import * + +class MyUserCreationForm(UserCreationForm): + class Meta: + model = User + fields = ('username', 'email',) +class UserAdmin(admin.ModelAdmin): + add_form = MyUserCreationForm + +admin.site.unregister(User) + +class MyUserAdmin(UserAdmin): + add_form = MyUserCreationForm + add_fieldsets = ( + (None, { + 'classes': ('wide',), + 'fields': ('username', 'email', 'password1', 'password2')} + ), + ) + +admin.site.register(User, MyUserAdmin) + +``` + +![This is the output I m getting using this code which is even not converting password field into hash.](https://i.stack.imgur.com/ps5Qz.jpg)",2011/07/08,"['https://Stackoverflow.com/questions/6628452', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/632467/']","If you look in django.contrib.auth admin.py, you'll see that the UserAdmin class specifies the add\_form as UserCreationForm. + +UserCreationForm only includes the 'username' field from the User model. + +Since you're providing your own UserAdmin, you can just override the add\_form to a custom UserCreationForm that includes the fields you need to make your signal work properly. + +Hope that helps you out. + +[Edit] + +Here's the UserCreationForm from contrib.auth forms.py: + +``` +class UserCreationForm(forms.ModelForm): + """""" + A form that creates a user, with no privileges, from the given username and password. + """""" + username = forms.RegexField(label=_(""Username""), max_length=30, regex=r'^[\w.@+-]+$', + help_text = _(""Required. 30 characters or fewer. Letters, digits and @/./+/-/_ only.""), + error_messages = {'invalid': _(""This value may contain only letters, numbers and @/./+/-/_ characters."")}) + password1 = forms.CharField(label=_(""Password""), widget=forms.PasswordInput) + password2 = forms.CharField(label=_(""Password confirmation""), widget=forms.PasswordInput, + help_text = _(""Enter the same password as above, for verification."")) + + class Meta: + model = User + fields = (""username"",) + + def clean_username(self): + username = self.cleaned_data[""username""] + try: + User.objects.get(username=username) + except User.DoesNotExist: + return username + raise forms.ValidationError(_(""A user with that username already exists."")) + + def clean_password2(self): + password1 = self.cleaned_data.get(""password1"", """") + password2 = self.cleaned_data[""password2""] + if password1 != password2: + raise forms.ValidationError(_(""The two password fields didn't match."")) + return password2 + + def save(self, commit=True): + user = super(UserCreationForm, self).save(commit=False) + user.set_password(self.cleaned_data[""password1""]) + if commit: + user.save() + return user + +``` + +Notice the fields = (""username"",) tuple which excludes all other fields on the User model. You need something like: + +``` +class MyUserCreationForm(UserCreationForm): + class Meta: + model = User + fields = ('username', 'email',) + +``` + +then you can use that as the add\_form in your custom UserAdmin: + +``` +class UserAdmin(admin.ModelAdmin): + add_form = MyUserCreationForm + +``` + +It's pretty late in my part of the world, but I'll see if I can get a working sample for you tomorrow. + +[Edit] + +Ok, here's the necessary changes you'll need to make to make this work. I've tested it using Django 1.3: + +``` +from django.contrib.auth.forms import UserCreationForm +from django.contrib.auth.admin import UserAdmin +from django.contrib.auth.models import User +from django import forms + +admin.site.unregister(User) + +class MyUserAdmin(UserAdmin): + add_form = MyUserCreationForm + add_fieldsets = ( + (None, { + 'classes': ('wide',), + 'fields': ('username', 'email', 'password1', 'password2')} + ), + ) + +admin.site.register(User, MyUserAdmin) + +``` + +I didn't see that the UserAdmin had an add\_fieldset property initially. That's why the email field wasn't displaying in the add form.","From [this example](http://jessenoller.com/blog/2011/12/19/quick-example-of-extending-usercreationform-in-django) try defining email in your custom UserCreationForm as required=True: + +``` +class MyUserCreationForm(UserCreationForm): + email = forms.EmailField(required=True) + + class Meta: + model = User + fields = ('username', 'email',) + +```" +224643,"It says: + +> +> Please list up to three projects (in order of preference) you are +> interested in. +> +> +> + +So I am not sure: Do I have to put in exactly three projects or can I also just put in two?",2015/01/30,"['https://english.stackexchange.com/questions/224643', 'https://english.stackexchange.com', 'https://english.stackexchange.com/users/108012/']","You can put in three or fewer projects, since up to is a limiting factor, but does not require a minimum, so by this grammar, two projects would be an acceptable response.","Yes. You can put two. + +You can put one, two, or three." +62993565,"I'm using `logging.config.dictconfig()` and my formatter is: + +``` +'formatters': { + 'logfileFormat': { + 'format': '%(asctime)s %(name)-12s: %(levelname)s %(message)s' + } + } + +``` + +When there's an exception, I would like the formatter to show the error message, as well as print out the exec\_info. How do I alter the `format` to do this? Or do I need to implement my own formatter in code, and reference it here?",2020/07/20,"['https://Stackoverflow.com/questions/62993565', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1724926/']","For me working nice if assign back output, but very similar method [`DataFrame.update`](http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.update.html) working inplace: + +``` +df = df1.combine_first(df2) +print (df) + Gen1 Gen2 +0 5.0 1.0 +1 4.0 2.0 +2 3.0 3.0 +3 2.0 4.0 +4 1.0 5.0 + +``` + +--- + +``` +df1.update(df2) +print (df1) + Gen1 Gen2 +0 5.0 1.0 +1 4.0 2.0 +2 3.0 3.0 +3 2.0 4.0 +4 1.0 5.0 + +```","`combine_first` returns a dataframe which has the change and not updating the existing dataframe so you should get the return dataframe + +``` +df1=df1.combine_first(df2) + +```" +66027931,"I have table like: + +``` +name | timeStamp | previousValue | newValue +--------+---------------+-------------------+------------ +Mark | 13.12.2020 | 123 | 155 +Mark | 12.12.2020 | 123 | 12 +Tom | 14.12.2020 | 123 | 534 +Mark | 12.12.2020 | 123 | 31 +Tom | 11.12.2020 | 123 | 84 +Mark | 19.12.2020 | 123 | 33 +Mark | 17.12.2020 | 123 | 96 +John | 22.12.2020 | 123 | 69 +John | 19.12.2020 | 123 | 33 + +``` + +I'd like to mix last\_value, count (\*) and group to get this result: + +``` +name | count | lastValue +--------+-----------+------------- +Mark | 5 | 33 +Tom | 2 | 534 +John | 2 | 69 + +``` + +This part: + +``` +select name, count(*) +from table +group by name + +``` + +returns table: + +``` +name | count +--------+--------- +Mark | 5 +Tom | 2 +John | 2 + +``` + +but I have to add the last value for each name. + +How to do it? + +Best regards!",2021/02/03,"['https://Stackoverflow.com/questions/66027931', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/15133478/']","`LAST_VALUE` is a windowed function, so you'll need to get that value first, and then aggregate: + +```sql +WITH CTE AS( + SELECT [name], + [timeStamp], --This is a poor choice for a column's name. timestamp is a (deprecated) synonym of rowversion, and a rowversion is not a date and time value + previousValue, + newValue, + LAST_VALUE(newValue) OVER (PARTITION BY [name] ORDER BY [timeStamp] ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS lastValue + FROM dbo.YourTable) +SELECT [Name], + COUNT(*) AS [count], + lastValue +FROM CTE +GROUP BY [Name], + lastValue; + +```","I got a solution that works, but here's another one: + +``` +SELECT +[name], COUNT([name]), [lastValue] +FROM ( + SELECT + [name], FIRST_VALUE([newValue]) OVER (PARTITION BY [name] ORDER BY TimeStamp DESC ROWS UNBOUNDED PRECEDING) AS [lastValue] + FROM [table] + ) xyz GROUP BY [name], [lastValue] + +``` + +Keep well!" +73659886,"I have a JSON file with a category structure of unknown depth. I want to make sure all pages can be accessed. I established three nested calls, but I think it would be better to recursion here. Unfortunately, I have no experience with Typescript regarding recursion. Can someone be so kind as to help me put the logic into a function I can call? + +``` + test.setTimeout(28800000); // 8 hours max. + // console.log(ofcJSON) + for (let i = 0; i < ofcJSON.items.length; i++) { + let currentPage = ofcJSON.items[i].link + console.log(currentPage) + if (!currentPage.startsWith(""http"")) await page.goto(currentPage) + if (ofcJSON.items[i].items != null) { + for (let j = 0; j < ofcJSON.items[i].items!.length; j++) { + let currentPage1 = ofcJSON.items[i].items![j].link + console.log(currentPage1) + if (!currentPage1.startsWith(""http"")) await page.goto(currentPage1) + if (ofcJSON.items[i].items![j].items != null) { + for(let k = 0; k < ofcJSON.items[i].items![j].items!.length; k++) { + let currentPage2 = ofcJSON.items[i].items![j].items![k].link + console.log(currentPage2) + if (!currentPage2.startsWith(""http"")) await page.goto(currentPage2) + if (ofcJSON.items![i].items![j].items![k].items != null) { + for(let l = 0; l < ofcJSON.items[i].items![j].items![k].items!.length; l++) { + let currentPage3 = ofcJSON.items[i].items![j].items![k].items![l].link + console.log(currentPage3) + if (!currentPage3.startsWith(""http"")) await page.goto(currentPage3) + } + } + } + } + } + } + } +}); + +``` + +The JSON has 1 **items** object, which in turn can have 1 **items** object. This is optional. I don't know the depth.",2022/09/09,"['https://Stackoverflow.com/questions/73659886', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/558120/']","Can I suggest that you use an f-string if you're on a version of python that supports them. + +``` +sqlcuery=f""insert into position ('position'), values('{position}')"" + +```","Try this: + +``` +""insert into position ('position'), values('""+str(position)+""')"" + +``` + +To transform the integer or float to a string. + +You can do this more elegantly with a f-string: + +``` +f""insert into position ('position'), values('{position}')"" + +```" +73659886,"I have a JSON file with a category structure of unknown depth. I want to make sure all pages can be accessed. I established three nested calls, but I think it would be better to recursion here. Unfortunately, I have no experience with Typescript regarding recursion. Can someone be so kind as to help me put the logic into a function I can call? + +``` + test.setTimeout(28800000); // 8 hours max. + // console.log(ofcJSON) + for (let i = 0; i < ofcJSON.items.length; i++) { + let currentPage = ofcJSON.items[i].link + console.log(currentPage) + if (!currentPage.startsWith(""http"")) await page.goto(currentPage) + if (ofcJSON.items[i].items != null) { + for (let j = 0; j < ofcJSON.items[i].items!.length; j++) { + let currentPage1 = ofcJSON.items[i].items![j].link + console.log(currentPage1) + if (!currentPage1.startsWith(""http"")) await page.goto(currentPage1) + if (ofcJSON.items[i].items![j].items != null) { + for(let k = 0; k < ofcJSON.items[i].items![j].items!.length; k++) { + let currentPage2 = ofcJSON.items[i].items![j].items![k].link + console.log(currentPage2) + if (!currentPage2.startsWith(""http"")) await page.goto(currentPage2) + if (ofcJSON.items![i].items![j].items![k].items != null) { + for(let l = 0; l < ofcJSON.items[i].items![j].items![k].items!.length; l++) { + let currentPage3 = ofcJSON.items[i].items![j].items![k].items![l].link + console.log(currentPage3) + if (!currentPage3.startsWith(""http"")) await page.goto(currentPage3) + } + } + } + } + } + } + } +}); + +``` + +The JSON has 1 **items** object, which in turn can have 1 **items** object. This is optional. I don't know the depth.",2022/09/09,"['https://Stackoverflow.com/questions/73659886', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/558120/']","Personally, I'd recommend using an f-string. These allow you to input variables of any type within your code without too much issue. Wrap your variables in {}, like I've shown below. + +``` +sqlcuery=f""insert into position {position}"" + +```","Try this: + +``` +""insert into position ('position'), values('""+str(position)+""')"" + +``` + +To transform the integer or float to a string. + +You can do this more elegantly with a f-string: + +``` +f""insert into position ('position'), values('{position}')"" + +```" +73659886,"I have a JSON file with a category structure of unknown depth. I want to make sure all pages can be accessed. I established three nested calls, but I think it would be better to recursion here. Unfortunately, I have no experience with Typescript regarding recursion. Can someone be so kind as to help me put the logic into a function I can call? + +``` + test.setTimeout(28800000); // 8 hours max. + // console.log(ofcJSON) + for (let i = 0; i < ofcJSON.items.length; i++) { + let currentPage = ofcJSON.items[i].link + console.log(currentPage) + if (!currentPage.startsWith(""http"")) await page.goto(currentPage) + if (ofcJSON.items[i].items != null) { + for (let j = 0; j < ofcJSON.items[i].items!.length; j++) { + let currentPage1 = ofcJSON.items[i].items![j].link + console.log(currentPage1) + if (!currentPage1.startsWith(""http"")) await page.goto(currentPage1) + if (ofcJSON.items[i].items![j].items != null) { + for(let k = 0; k < ofcJSON.items[i].items![j].items!.length; k++) { + let currentPage2 = ofcJSON.items[i].items![j].items![k].link + console.log(currentPage2) + if (!currentPage2.startsWith(""http"")) await page.goto(currentPage2) + if (ofcJSON.items![i].items![j].items![k].items != null) { + for(let l = 0; l < ofcJSON.items[i].items![j].items![k].items!.length; l++) { + let currentPage3 = ofcJSON.items[i].items![j].items![k].items![l].link + console.log(currentPage3) + if (!currentPage3.startsWith(""http"")) await page.goto(currentPage3) + } + } + } + } + } + } + } +}); + +``` + +The JSON has 1 **items** object, which in turn can have 1 **items** object. This is optional. I don't know the depth.",2022/09/09,"['https://Stackoverflow.com/questions/73659886', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/558120/']","Personally, I'd recommend using an f-string. These allow you to input variables of any type within your code without too much issue. Wrap your variables in {}, like I've shown below. + +``` +sqlcuery=f""insert into position {position}"" + +```","Can I suggest that you use an f-string if you're on a version of python that supports them. + +``` +sqlcuery=f""insert into position ('position'), values('{position}')"" + +```" +43310947,"I'm trying to replace all full stops in an email with an x character - for example ""my.email@email.com"" would become ""myxemail@emailxcom"". Email is set to a string. + +My problem is it's not replacing just full stops, it's replacing every character, so I just get a string of x's. + +I can get it working with just one full stop, so I'm assuming I'm wrong on the global instance part. Here's my code: + +``` +let re = "".""; +let new = email.replace(/re/gi, ""x""); + +``` + +I've also tried + +``` +re = /./gi; +new = email.replace(re, ""x""); + +``` + +If anyone can shed any light I'd really appreciate it, I've been stuck on this for so long and can't seem to figure out where I'm going wrong. + +\*\* Edit: Whoops, my new variable was actually called newemail, keyword new wasn't causing the issue!",2017/04/09,"['https://Stackoverflow.com/questions/43310947', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7232648/']","Your second example is the closest. The first problem is your variable name, **`new`**, which happens to be one of JavaScript's [reserved keywords](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Keywords) (and is instead used to construct objects, like `new RegExp` or `new Set`). This means that your program will throw a Syntax Error. + +Also, since the dot (`.`) is a special character inside regex grammar, you should escape it as `\.`. Otherwise you would end up with `result == ""xxxxxxxxxxxxxxxxxx""`, which is undesirable. + +```js +let email = ""my.email@email.com"" + +let re = /\./gi; +let result = email.replace(re, ""x""); + +console.log(result) +```","You can try `split()` and `join()` method that was work for me. (For normal string text) +It was short and simple to implement and understand. +Below is an example. + +``` +let email = ""my.email@email.com""; +email.split('.').join('x'); + +``` + +So, it will replace all your `.` with `x`. So, after the above example, `email` variable will have value `myxemail@gmailxcom`" +43310947,"I'm trying to replace all full stops in an email with an x character - for example ""my.email@email.com"" would become ""myxemail@emailxcom"". Email is set to a string. + +My problem is it's not replacing just full stops, it's replacing every character, so I just get a string of x's. + +I can get it working with just one full stop, so I'm assuming I'm wrong on the global instance part. Here's my code: + +``` +let re = "".""; +let new = email.replace(/re/gi, ""x""); + +``` + +I've also tried + +``` +re = /./gi; +new = email.replace(re, ""x""); + +``` + +If anyone can shed any light I'd really appreciate it, I've been stuck on this for so long and can't seem to figure out where I'm going wrong. + +\*\* Edit: Whoops, my new variable was actually called newemail, keyword new wasn't causing the issue!",2017/04/09,"['https://Stackoverflow.com/questions/43310947', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7232648/']","Your second example is the closest. The first problem is your variable name, **`new`**, which happens to be one of JavaScript's [reserved keywords](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Keywords) (and is instead used to construct objects, like `new RegExp` or `new Set`). This means that your program will throw a Syntax Error. + +Also, since the dot (`.`) is a special character inside regex grammar, you should escape it as `\.`. Otherwise you would end up with `result == ""xxxxxxxxxxxxxxxxxx""`, which is undesirable. + +```js +let email = ""my.email@email.com"" + +let re = /\./gi; +let result = email.replace(re, ""x""); + +console.log(result) +```","You may just use `replaceAll()` String function, described here: + + +If you are getting +**Property 'replaceAll' does not exist on type 'string'** +error - go to `tsconfig.json` and within ""lib"" change or add ""es2021"". + +Like this: + +[![enter image description here](https://i.stack.imgur.com/TKIil.png)](https://i.stack.imgur.com/TKIil.png) + +More info here: [Property 'replaceAll' does not exist on type 'string'](https://stackoverflow.com/questions/63616486/property-replaceall-does-not-exist-on-type-string)" +43310947,"I'm trying to replace all full stops in an email with an x character - for example ""my.email@email.com"" would become ""myxemail@emailxcom"". Email is set to a string. + +My problem is it's not replacing just full stops, it's replacing every character, so I just get a string of x's. + +I can get it working with just one full stop, so I'm assuming I'm wrong on the global instance part. Here's my code: + +``` +let re = "".""; +let new = email.replace(/re/gi, ""x""); + +``` + +I've also tried + +``` +re = /./gi; +new = email.replace(re, ""x""); + +``` + +If anyone can shed any light I'd really appreciate it, I've been stuck on this for so long and can't seem to figure out where I'm going wrong. + +\*\* Edit: Whoops, my new variable was actually called newemail, keyword new wasn't causing the issue!",2017/04/09,"['https://Stackoverflow.com/questions/43310947', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7232648/']","You can try `split()` and `join()` method that was work for me. (For normal string text) +It was short and simple to implement and understand. +Below is an example. + +``` +let email = ""my.email@email.com""; +email.split('.').join('x'); + +``` + +So, it will replace all your `.` with `x`. So, after the above example, `email` variable will have value `myxemail@gmailxcom`","You may just use `replaceAll()` String function, described here: + + +If you are getting +**Property 'replaceAll' does not exist on type 'string'** +error - go to `tsconfig.json` and within ""lib"" change or add ""es2021"". + +Like this: + +[![enter image description here](https://i.stack.imgur.com/TKIil.png)](https://i.stack.imgur.com/TKIil.png) + +More info here: [Property 'replaceAll' does not exist on type 'string'](https://stackoverflow.com/questions/63616486/property-replaceall-does-not-exist-on-type-string)" +38740587,"How do I make sure that a file is not branchable across different projects in UCM ? + +It should always be picked from `/main/LATEST/` for all the parallel projects",2016/08/03,"['https://Stackoverflow.com/questions/38740587', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3119109/']","Did you read the JavaDocs on `isDirectory()` etc.? For `isDirectory()` it says: + +> +> returns true if and only if the file denoted by this abstract pathname exists and is a directory; false otherwise +> +> +> + +So if the directory doesn't exist you get false and don't create one. Then you continue trying to write and create and write etc. until you get the StackOverFlowError. + +To fix the stackoverflow you should check the return value of your create file, e.g. + +``` +boolean created = this.createFileMain(path); +if( created ) { + this.writeInFile(path, content); +} + +``` + +To fix your file/directory creation you need to check whether the file already exists and otherwise create it (optionally also creating the parent directories via `file.getParentFile().mkdirs()`). + +The problem is that you should know whether you want to create a file or a directory, since you can't tell by the name alone whether the path is meant to be a directory or file name (unless you invent some markup like always ending a directory path with a separator or requiring files to always have an extension). If you want to write some content you need to create a file anyways, a directory would break your code again.","``` +private boolean createFile(File file) { + if(!file.exists()) { + if(file.getParentFile().exists()) { + // ... + } else { // In this case, neither file nor its parent exist + if(this.createDirectory(file)) { + this.createFile(file); // HERE, you're calling the same method again + } else { + // ...; + } + } + } + return true; +} + +``` + +I believe you want to replace the line marked `HERE` with `this.createFile(file.getParentFile());`. Here what happens is that your function recursively calls itself with the same arguments, so nothing ever happens, and your program gets stuck in a loop until it runs out of stack memory." +38740587,"How do I make sure that a file is not branchable across different projects in UCM ? + +It should always be picked from `/main/LATEST/` for all the parallel projects",2016/08/03,"['https://Stackoverflow.com/questions/38740587', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3119109/']","Did you read the JavaDocs on `isDirectory()` etc.? For `isDirectory()` it says: + +> +> returns true if and only if the file denoted by this abstract pathname exists and is a directory; false otherwise +> +> +> + +So if the directory doesn't exist you get false and don't create one. Then you continue trying to write and create and write etc. until you get the StackOverFlowError. + +To fix the stackoverflow you should check the return value of your create file, e.g. + +``` +boolean created = this.createFileMain(path); +if( created ) { + this.writeInFile(path, content); +} + +``` + +To fix your file/directory creation you need to check whether the file already exists and otherwise create it (optionally also creating the parent directories via `file.getParentFile().mkdirs()`). + +The problem is that you should know whether you want to create a file or a directory, since you can't tell by the name alone whether the path is meant to be a directory or file name (unless you invent some markup like always ending a directory path with a separator or requiring files to always have an extension). If you want to write some content you need to create a file anyways, a directory would break your code again.","Your `createFileMain` only creates files which already exist. + +You don't need to create a file to write to it, all you need is the directory you want to write it into. + +``` +public void writeInFile(String path, List content) { + File file = new File(path); + File parent = file.getParentFile(); + if (parent != null && !parent.exists()) + parent.mkdirs(); + + try (PrintWriter writer = new PrintWriter(path, ""ASCII"")) { + for (String contentItem : content) { + writer.println(contentItem); + } + writer.close(); + } catch (IOException e1) { + //DO STUFF + } +} + +```" +38740587,"How do I make sure that a file is not branchable across different projects in UCM ? + +It should always be picked from `/main/LATEST/` for all the parallel projects",2016/08/03,"['https://Stackoverflow.com/questions/38740587', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3119109/']","Your `createFileMain` only creates files which already exist. + +You don't need to create a file to write to it, all you need is the directory you want to write it into. + +``` +public void writeInFile(String path, List content) { + File file = new File(path); + File parent = file.getParentFile(); + if (parent != null && !parent.exists()) + parent.mkdirs(); + + try (PrintWriter writer = new PrintWriter(path, ""ASCII"")) { + for (String contentItem : content) { + writer.println(contentItem); + } + writer.close(); + } catch (IOException e1) { + //DO STUFF + } +} + +```","``` +private boolean createFile(File file) { + if(!file.exists()) { + if(file.getParentFile().exists()) { + // ... + } else { // In this case, neither file nor its parent exist + if(this.createDirectory(file)) { + this.createFile(file); // HERE, you're calling the same method again + } else { + // ...; + } + } + } + return true; +} + +``` + +I believe you want to replace the line marked `HERE` with `this.createFile(file.getParentFile());`. Here what happens is that your function recursively calls itself with the same arguments, so nothing ever happens, and your program gets stuck in a loop until it runs out of stack memory." +384030,"So we have realtime events and they are great but the issue we are having is very often we don't need the full ""hosepipe"" of events only events related to a specific record or user where based on some method they are marked as high risk. Is there any way to filter these events before they are sent to us as 99% of all of these events we have no interest in and are just dropping it seems wasteful.",2022/08/27,"['https://salesforce.stackexchange.com/questions/384030', 'https://salesforce.stackexchange.com', 'https://salesforce.stackexchange.com/users/94095/']","With winter 23 one can easily filter platform event by defining a filter expression via the metadata or the tooling API! + +Check out the details [here](https://developer.salesforce.com/docs/atlas.en-us.platform_events.meta/platform_events/platform_events_filters.htm) + +Read more about the General Availability of the [feature](https://help.salesforce.com/s/articleView?id=release-notes.rn_platform_events_filtering_ga.htm&type=5&release=240).","You can use [PushTopic](https://developer.salesforce.com/docs/atlas.en-us.api_streaming.meta/api_streaming/pushtopic_events_intro.htm) to listen for specific updates, assuming you can define those updates in a SOQL statement. Each client can create a PushTopic to listen for specific events, then cancel them when they see no longer necessary." +35455315,"I have a problem outputting the date which is created within my `PHP` file. + +I've been following a tutorial on how to make a really Basic-CMS Platform to help me understand some of the basics for `databases` and `PHP`, everything has been going well up until I was trying to output the date of when the page was created. + +This is the error I get + +``` +Fatal error: Uncaught exception 'Exception' with message 'DateTime::__construct(): It is not safe to rely on the system's timezone settings. +You are *required* to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of +those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected the timezone 'UTC' for now, but please set date.timezone to select your timezone.' in +C:\MAMP\htdocs\basic-cms\page.php:22 Stack trace: #0 C:\MAMP\htdocs\basic-cms\page.php(22): DateTime->__construct('2016-02-17 10:3...') #1 {main} thrown in C:\MAMP\htdocs\basic-cms\page.php on line 22 + +``` + +Now when I remove line 22 inside my `page.php` it outputs the full date that is inside the database i.e `2016-02-17 10:38:05` but I'm trying to format it to show the date like `jS M, Y (17th Feb 2016)`. + +This is the code inside my `page.php` file + +``` +if ( $page ) { + $page['created'] = new DateTime( $page['created'] ); + + if ( $page['updated'] ) { + $page['updated'] = new DateTime( $page['created'] ); + } +} + +``` + +Then inside my `show.php` where I'm displaying this I have this code to format the date. + +``` +Created on format('jS M, Y'); ?> + +``` + +Now removing this from my `show.php` doesn't do anything as that's not where the error is contained - but I thought I'd show you guys what I am trying to achieve. + +Like I said this is a very Basic-CMS site that I am creating by following a [tutorial on YouTube](https://www.youtube.com/watch?v=Hvb0oeMbH0U&list=PLfdtiltiRHWF0O8kS5D_3-nTzsFiPMOfM&index=4) and I have copied his code exactly and he got no error so I'm sure it has to be a typo I just can't find.",2016/02/17,"['https://Stackoverflow.com/questions/35455315', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5006451/']","This is because no timezone has set in php configuration. + +Add the following line of code to top of your php.ini file + +``` +date.timezone = ""US/Central"" + +``` + +And restart web server + +**OR** + +you can set it via php script also by using following function: + +``` +date_default_timezone_set('America/Los_Angeles'); + +``` + +Dont forget to reload/restart apache server","**If you're using a database to hold the page details when its created:** + +You can actually just add a DateTime Column in your database and then when the page is created and you Insert whatever you need to add, make the Column a default TimeStamp and it should automatically add the time and date the page was created for you. + +To then get the TimeStamp out of the database (MySQLi version): + +``` +$db = mysqli_connect('host', 'user', 'pass', 'dbname'); +$result = $db->query(""SELECT * FROM tbl_name""); +// add an error check here +while($row = mysqli_fetch_array($result)){ + if($row['columnPageID'] == 'the page ID you are on'){ + $createdOn = $row['columnName']; + } +} +$db->close(); + +``` + +This code will **not** work, its so you get an understanding." +55641172,"I'm having some trouble getting the correct output when printing an array. Essentially what I'm trying to do is set up an array in the main method, then send that array to another method that would print out something like this: + +``` + 89 12 33 7 72 42 76 49 + 69 85 61 23 + +``` + +With it being 3 spaces to the right and starting a new print line after the 8th number. Seems easy enough but I get something like this instead. + +``` + 89 + 69 85 61 23 + +``` + +It doesn't print out the values between position 1 and 7 for some reason. This is what I have. + +``` +public class Test +{ + public static void main (String [] args) + { + int [] myInches = {89,12,33,7,72,42,76,49,69,85,61,23}; + printArrayValues(myInches); + } + + public static void printArrayValues(int [] myInchesParam) { + for (int i = 0; i < 8; i++) { + System.out.print("" "" + myInchesParam[i]); + System.out.println(); + for (i = 8; i < 12; i++) { + System.out.print("" "" + myInchesParam[i]); + } + } + } +} + +``` + +Should I use a do-while instead? Or can I still do it with a for loop and I'm just doing it wrong?",2019/04/11,"['https://Stackoverflow.com/questions/55641172', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11167410/']","If you insist on using loops, take @Dason's comment and do the following: + +``` +for(i in 1:length(Letters)) { + for(j in 1:length(Letters)) { + Combined <- paste0(Letters[i], ' vs ', Letters[j]) + print(Combined) + } +} + +```","We can either use `expand.grid` or `CJ` (from `data.table`) and then do a `paste` + +``` +library(data.table) +CJ(Letters, Letters)[, paste(V1, 'vs', V2)] + +```" +19940038,"Is there any way to disable auto-save for `UIManagedDocument` ? + +I present `NSManagedObjects` in a controller where the user can add and delete them. But I just want to save those changes when the user explicitly fires a save action. Otherwise I want to discard the changes. + +Thanks for your help!",2013/11/12,"['https://Stackoverflow.com/questions/19940038', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1263739/']","Can't you override the method below in the `UIManagedDocument` subclass + +``` +- (void)autosaveWithCompletionHandler:(void (^)(BOOL success))completionHandler + +``` + +EDIT: Here are some additional methods you might want to include. I use the first one to confirm if and when auto-saves were happening and the second to debug certain errors, the details of which can't be obtained any other way. That's all thats in my subclass so its pretty trivial to add this. + +``` +@implementation YourManagedDocument + +- (id)contentsForType:(NSString *)typeName error:(NSError *__autoreleasing *)outError +{ + NSLog(@""Auto-Saving Document""); + return [super contentsForType:typeName error:outError]; +} + +- (void)handleError:(NSError *)error userInteractionPermitted:(BOOL)userInteractionPermitted +{ + NSLog(@"" error: %@"", error.localizedDescription); + NSArray* errors = [[error userInfo] objectForKey:NSDetailedErrorsKey]; + if(errors != nil && errors.count > 0) { + for (NSError *error in errors) { + NSLog(@"" Error: %@"", error.userInfo); + } + } else { + NSLog(@"" error.userInfo = %@"", error.userInfo); + } +} +@end + +```","See [this SO answer](https://stackoverflow.com/a/8425546/953105) for the details, but unless you explicitly save your `NSManagedObjectContext`, you can call `[managedObjectContext rollback]` to undo any changes the user made." +861911,"Is it 32 bit, or 64 bit or 128 bit or bigger?",2009/05/14,"['https://Stackoverflow.com/questions/861911', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/106866/']","I would go with 88 bytes. If you look at the ASP.NET state database, that is how it is defined.","Because it's generated as a [System.Guid](http://msdn.microsoft.com/en-us/library/system.guid(VS.90).aspx) Valuetype, it's a 128-bit integer, which is 16 bytes." +861911,"Is it 32 bit, or 64 bit or 128 bit or bigger?",2009/05/14,"['https://Stackoverflow.com/questions/861911', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/106866/']","It's neither int nor guid; from the [MSDN help file](http://msdn.microsoft.com/en-us/library/system.web.sessionstate.sessionidmanager.aspx)... + +> +> The ASP.NET session identifier is a randomly generated number encoded into a 24-character string consisting of lowercase characters from a to z and numbers from 0 to 5. +> +> +>","Because it's generated as a [System.Guid](http://msdn.microsoft.com/en-us/library/system.guid(VS.90).aspx) Valuetype, it's a 128-bit integer, which is 16 bytes." +861911,"Is it 32 bit, or 64 bit or 128 bit or bigger?",2009/05/14,"['https://Stackoverflow.com/questions/861911', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/106866/']","The reason for the extra 8 characters in the database vs what you get in code is the application id. In the database the session is appended with the tempApplicationID from ASPStateTempApplications table. This is why you get 24 characters in code, and 32 in the db.","Because it's generated as a [System.Guid](http://msdn.microsoft.com/en-us/library/system.guid(VS.90).aspx) Valuetype, it's a 128-bit integer, which is 16 bytes." +861911,"Is it 32 bit, or 64 bit or 128 bit or bigger?",2009/05/14,"['https://Stackoverflow.com/questions/861911', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/106866/']","It's neither int nor guid; from the [MSDN help file](http://msdn.microsoft.com/en-us/library/system.web.sessionstate.sessionidmanager.aspx)... + +> +> The ASP.NET session identifier is a randomly generated number encoded into a 24-character string consisting of lowercase characters from a to z and numbers from 0 to 5. +> +> +>","I would go with 88 bytes. If you look at the ASP.NET state database, that is how it is defined." +861911,"Is it 32 bit, or 64 bit or 128 bit or bigger?",2009/05/14,"['https://Stackoverflow.com/questions/861911', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/106866/']","The reason for the extra 8 characters in the database vs what you get in code is the application id. In the database the session is appended with the tempApplicationID from ASPStateTempApplications table. This is why you get 24 characters in code, and 32 in the db.","I would go with 88 bytes. If you look at the ASP.NET state database, that is how it is defined." +861911,"Is it 32 bit, or 64 bit or 128 bit or bigger?",2009/05/14,"['https://Stackoverflow.com/questions/861911', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/106866/']","It's neither int nor guid; from the [MSDN help file](http://msdn.microsoft.com/en-us/library/system.web.sessionstate.sessionidmanager.aspx)... + +> +> The ASP.NET session identifier is a randomly generated number encoded into a 24-character string consisting of lowercase characters from a to z and numbers from 0 to 5. +> +> +>","The reason for the extra 8 characters in the database vs what you get in code is the application id. In the database the session is appended with the tempApplicationID from ASPStateTempApplications table. This is why you get 24 characters in code, and 32 in the db." +56888,"At work we make websites for other companies. One of our client wanted us to make a e-commerce website for them. Nothing out of the ordinary until we realized they had 50 000+ products to sell and their classification is inexistant. In other words, we don't have ay categories to work with. They just told us to ""Put a search bar and it'll be fine"". + +So, how would you make an e-commerce site work for the users without any kind of browsing through lists of products ? + +**EDIT** +The client is a reseller. He sells power outlets, light bulbs, electrical cords and stuff like that. The reselling part is why he doesn't have categories, because every single seller manage their own database with their own description for each product.",2014/05/07,"['https://ux.stackexchange.com/questions/56888', 'https://ux.stackexchange.com', 'https://ux.stackexchange.com/users/47784/']","I would recommend a [masonry-like](http://masonry.desandro.com/) experience as Pinterest implements. Infinite scrolling of all 50k products and have a details page for each one. Keep track of which products are viewed the most on a weekly basis and display those towards the top. + +It sounds like this client wants an adventure-like experience with a search bar that searches on just one field; product name. + +That is my 1/50th of a dollar; 2 cents =)","Your client might not be able to assign categories to products, but there is noting stopping them assigning categories to *sellers*. + +The kind of sellers using a resale ecommerce site are likely to be specialists in certain categories already, rather than having a diverse range of products (e.g. there will likely be sellers that specialise in lightbulbs and related items). You could build loose categories around this information to augment the search functionality. For example you could have an option to ""view more sellers like this"", or ""view all items from similar sellers""." +56888,"At work we make websites for other companies. One of our client wanted us to make a e-commerce website for them. Nothing out of the ordinary until we realized they had 50 000+ products to sell and their classification is inexistant. In other words, we don't have ay categories to work with. They just told us to ""Put a search bar and it'll be fine"". + +So, how would you make an e-commerce site work for the users without any kind of browsing through lists of products ? + +**EDIT** +The client is a reseller. He sells power outlets, light bulbs, electrical cords and stuff like that. The reselling part is why he doesn't have categories, because every single seller manage their own database with their own description for each product.",2014/05/07,"['https://ux.stackexchange.com/questions/56888', 'https://ux.stackexchange.com', 'https://ux.stackexchange.com/users/47784/']","I would recommend a [masonry-like](http://masonry.desandro.com/) experience as Pinterest implements. Infinite scrolling of all 50k products and have a details page for each one. Keep track of which products are viewed the most on a weekly basis and display those towards the top. + +It sounds like this client wants an adventure-like experience with a search bar that searches on just one field; product name. + +That is my 1/50th of a dollar; 2 cents =)","If there is no way of categorizing the products then search must be the primary method of traversing the catalog. But as a previous answer suggests you should guide the user with top products sold for a search, top products viewed for a search etc. The other users behavior should help guide them, consider adding a method for users to tag products to build the categories may be an option. You may also be able to build a straw man structure by querying the product names for things like bulb, switch, socket etc and start with that to see what sort of a category structure may be involved." +56888,"At work we make websites for other companies. One of our client wanted us to make a e-commerce website for them. Nothing out of the ordinary until we realized they had 50 000+ products to sell and their classification is inexistant. In other words, we don't have ay categories to work with. They just told us to ""Put a search bar and it'll be fine"". + +So, how would you make an e-commerce site work for the users without any kind of browsing through lists of products ? + +**EDIT** +The client is a reseller. He sells power outlets, light bulbs, electrical cords and stuff like that. The reselling part is why he doesn't have categories, because every single seller manage their own database with their own description for each product.",2014/05/07,"['https://ux.stackexchange.com/questions/56888', 'https://ux.stackexchange.com', 'https://ux.stackexchange.com/users/47784/']","Your client might not be able to assign categories to products, but there is noting stopping them assigning categories to *sellers*. + +The kind of sellers using a resale ecommerce site are likely to be specialists in certain categories already, rather than having a diverse range of products (e.g. there will likely be sellers that specialise in lightbulbs and related items). You could build loose categories around this information to augment the search functionality. For example you could have an option to ""view more sellers like this"", or ""view all items from similar sellers"".","If there is no way of categorizing the products then search must be the primary method of traversing the catalog. But as a previous answer suggests you should guide the user with top products sold for a search, top products viewed for a search etc. The other users behavior should help guide them, consider adding a method for users to tag products to build the categories may be an option. You may also be able to build a straw man structure by querying the product names for things like bulb, switch, socket etc and start with that to see what sort of a category structure may be involved." +203891,"I found part of my answer here: [If g(f(x)) is one-to-one (injective) show f(x) is also one-to-one (given that...)](https://math.stackexchange.com/questions/28123/if-gfx-is-one-to-one-injective-show-fx-is-also-one-to-one-given-that); however I wanted to flesh out the last two statements I had in a proposition in my notes. + +> +> **Proposition:** +> Let $f: A \rightarrow B$ and $g: B \rightarrow C$. Then: +> +> +> (i) If $g \circ f$ is one-to-one, then $f$ is one-to-one. +> +> +> (ii) If $g \circ f$ is onto, then $g$ is onto. +> +> +> + +Proof: +(i) Suppose $f(x)=f(y)$ for some $x,y$. + +Since $g \circ f$ is one-to-one: $$g\circ f(x) = g\circ f(y) \Rightarrow x=y,\forall x,y \in A.$$ + +Therefore $f$ must be one-to-one. + +(ii) Since $g \circ f (x)$ is onto, then for every $c \in C$ there exists an $a \in A$ such that $c=g(f(a))$. Then there exists a $b \in B$ with $b=f(a)$ such that $g(b)=c$. Thus g is onto. + +I wanted to confirm that these proofs are both correct for my peace of mind (as they weren't proven in class).",2012/09/28,"['https://math.stackexchange.com/questions/203891', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/8324/']",Both of your proofs are correct.,"I've never taken an analysis course but I don't believe that your first proof is correct. Since take for example $f=x^2$, which isn't one-to-one. $g \circ f (-2)$ and $g \circ f (2)$ would be equal, since in both cases it is $g(4)$ and $g$ is a function. So $x$ would not have to equal $y$ and thus $f$ does not have a requirement of being one-to-one for the composition $g(f(x))$ to be one to one. However I do believe that $g$ would have to be one to one for that to be the case. Please correct me if I am wrong. Just my two cents." +203891,"I found part of my answer here: [If g(f(x)) is one-to-one (injective) show f(x) is also one-to-one (given that...)](https://math.stackexchange.com/questions/28123/if-gfx-is-one-to-one-injective-show-fx-is-also-one-to-one-given-that); however I wanted to flesh out the last two statements I had in a proposition in my notes. + +> +> **Proposition:** +> Let $f: A \rightarrow B$ and $g: B \rightarrow C$. Then: +> +> +> (i) If $g \circ f$ is one-to-one, then $f$ is one-to-one. +> +> +> (ii) If $g \circ f$ is onto, then $g$ is onto. +> +> +> + +Proof: +(i) Suppose $f(x)=f(y)$ for some $x,y$. + +Since $g \circ f$ is one-to-one: $$g\circ f(x) = g\circ f(y) \Rightarrow x=y,\forall x,y \in A.$$ + +Therefore $f$ must be one-to-one. + +(ii) Since $g \circ f (x)$ is onto, then for every $c \in C$ there exists an $a \in A$ such that $c=g(f(a))$. Then there exists a $b \in B$ with $b=f(a)$ such that $g(b)=c$. Thus g is onto. + +I wanted to confirm that these proofs are both correct for my peace of mind (as they weren't proven in class).",2012/09/28,"['https://math.stackexchange.com/questions/203891', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/8324/']",Both of your proofs are correct.,"On the first one i would say since g composed of f is one-to-one, if g(f(x))=g(f(y)) for all x,y in A then x=y. By definition of f then there exist some value f(x) and f(y) in B. Then because we already noted x=y. F(x) must equal F(y) by the definition of a function." +203891,"I found part of my answer here: [If g(f(x)) is one-to-one (injective) show f(x) is also one-to-one (given that...)](https://math.stackexchange.com/questions/28123/if-gfx-is-one-to-one-injective-show-fx-is-also-one-to-one-given-that); however I wanted to flesh out the last two statements I had in a proposition in my notes. + +> +> **Proposition:** +> Let $f: A \rightarrow B$ and $g: B \rightarrow C$. Then: +> +> +> (i) If $g \circ f$ is one-to-one, then $f$ is one-to-one. +> +> +> (ii) If $g \circ f$ is onto, then $g$ is onto. +> +> +> + +Proof: +(i) Suppose $f(x)=f(y)$ for some $x,y$. + +Since $g \circ f$ is one-to-one: $$g\circ f(x) = g\circ f(y) \Rightarrow x=y,\forall x,y \in A.$$ + +Therefore $f$ must be one-to-one. + +(ii) Since $g \circ f (x)$ is onto, then for every $c \in C$ there exists an $a \in A$ such that $c=g(f(a))$. Then there exists a $b \in B$ with $b=f(a)$ such that $g(b)=c$. Thus g is onto. + +I wanted to confirm that these proofs are both correct for my peace of mind (as they weren't proven in class).",2012/09/28,"['https://math.stackexchange.com/questions/203891', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/8324/']",Both of your proofs are correct.,"(i) If $f \circ g$ is one-to-one, then it is invertible. Its inverse is $g^{-1} \circ f^{-1}.$ Thus $f^{-1}$ exists. Therefore, $f$ is invertible, and thus is one-to-one. QED." +203891,"I found part of my answer here: [If g(f(x)) is one-to-one (injective) show f(x) is also one-to-one (given that...)](https://math.stackexchange.com/questions/28123/if-gfx-is-one-to-one-injective-show-fx-is-also-one-to-one-given-that); however I wanted to flesh out the last two statements I had in a proposition in my notes. + +> +> **Proposition:** +> Let $f: A \rightarrow B$ and $g: B \rightarrow C$. Then: +> +> +> (i) If $g \circ f$ is one-to-one, then $f$ is one-to-one. +> +> +> (ii) If $g \circ f$ is onto, then $g$ is onto. +> +> +> + +Proof: +(i) Suppose $f(x)=f(y)$ for some $x,y$. + +Since $g \circ f$ is one-to-one: $$g\circ f(x) = g\circ f(y) \Rightarrow x=y,\forall x,y \in A.$$ + +Therefore $f$ must be one-to-one. + +(ii) Since $g \circ f (x)$ is onto, then for every $c \in C$ there exists an $a \in A$ such that $c=g(f(a))$. Then there exists a $b \in B$ with $b=f(a)$ such that $g(b)=c$. Thus g is onto. + +I wanted to confirm that these proofs are both correct for my peace of mind (as they weren't proven in class).",2012/09/28,"['https://math.stackexchange.com/questions/203891', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/8324/']","I've never taken an analysis course but I don't believe that your first proof is correct. Since take for example $f=x^2$, which isn't one-to-one. $g \circ f (-2)$ and $g \circ f (2)$ would be equal, since in both cases it is $g(4)$ and $g$ is a function. So $x$ would not have to equal $y$ and thus $f$ does not have a requirement of being one-to-one for the composition $g(f(x))$ to be one to one. However I do believe that $g$ would have to be one to one for that to be the case. Please correct me if I am wrong. Just my two cents.","On the first one i would say since g composed of f is one-to-one, if g(f(x))=g(f(y)) for all x,y in A then x=y. By definition of f then there exist some value f(x) and f(y) in B. Then because we already noted x=y. F(x) must equal F(y) by the definition of a function." +203891,"I found part of my answer here: [If g(f(x)) is one-to-one (injective) show f(x) is also one-to-one (given that...)](https://math.stackexchange.com/questions/28123/if-gfx-is-one-to-one-injective-show-fx-is-also-one-to-one-given-that); however I wanted to flesh out the last two statements I had in a proposition in my notes. + +> +> **Proposition:** +> Let $f: A \rightarrow B$ and $g: B \rightarrow C$. Then: +> +> +> (i) If $g \circ f$ is one-to-one, then $f$ is one-to-one. +> +> +> (ii) If $g \circ f$ is onto, then $g$ is onto. +> +> +> + +Proof: +(i) Suppose $f(x)=f(y)$ for some $x,y$. + +Since $g \circ f$ is one-to-one: $$g\circ f(x) = g\circ f(y) \Rightarrow x=y,\forall x,y \in A.$$ + +Therefore $f$ must be one-to-one. + +(ii) Since $g \circ f (x)$ is onto, then for every $c \in C$ there exists an $a \in A$ such that $c=g(f(a))$. Then there exists a $b \in B$ with $b=f(a)$ such that $g(b)=c$. Thus g is onto. + +I wanted to confirm that these proofs are both correct for my peace of mind (as they weren't proven in class).",2012/09/28,"['https://math.stackexchange.com/questions/203891', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/8324/']","(i) If $f \circ g$ is one-to-one, then it is invertible. Its inverse is $g^{-1} \circ f^{-1}.$ Thus $f^{-1}$ exists. Therefore, $f$ is invertible, and thus is one-to-one. QED.","On the first one i would say since g composed of f is one-to-one, if g(f(x))=g(f(y)) for all x,y in A then x=y. By definition of f then there exist some value f(x) and f(y) in B. Then because we already noted x=y. F(x) must equal F(y) by the definition of a function." +3257640,"Let $\gamma:[0,1] \longrightarrow \mathbf{C} \backslash \{0\}$ be a closed curve (continuous and of bounded variation). +We call +$$\operatorname{Ind}\_\gamma(0) \overset{\mathrm{def}}{=} \frac{1}{2 \pi i}\int\_\gamma \frac{1}{z}\ dz.$$ +$\textbf{the index of $\gamma$ around $0$.}$ +As for the winding number, we can take a pair of continuous real valued functions $r$ and $\theta$ that satisfies +$$r:[0,1] \longrightarrow (0,\infty),$$ +$$\theta:[0,1] \longrightarrow \mathbf{R},$$ +$$\forall t \in [0,1]\, \left[\, \gamma(t) = r(t) \cdot e^{i \cdot \theta(t)}\, \right],$$ +and +$$-\pi < \theta(0) \leq \pi.$$ +(The proof of this can be found in chapter 7 of A. F. Beardon, Complex Analysis: The Argument Principle in Analysis and Topology, Wiley-Interscience publication 1979). +We call +$$\operatorname{Wnd}\_\gamma(0) \overset{\mathrm{def}}{=}\frac{\theta(1) - \theta(0)}{2\pi}$$ +$\textbf{the winding number of $\gamma$ around $0$}$. + +It is already known that if $\gamma$ is $C^1$-curve, then +$$\operatorname{Ind}\_\gamma(0) = \operatorname{Wnd}\_\gamma(0)$$ +(see [definition of winding number, have doubt in definition.](https://math.stackexchange.com/questions/186512/definition-of-winding-number-have-doubt-in-definition)). + +My question: When $\gamma$ is not $C^1$ path, +$$\operatorname{Ind}\_\gamma(0) = \operatorname{Wnd}\_\gamma(0)?$$ + +Thank you for reading.",2019/06/10,"['https://math.stackexchange.com/questions/3257640', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/680871/']","First, we observe that +$$ +f(x)=x-\ln x -1\geq \frac{(x-1)^2}{2}-\frac{(x-1)^3}{3}=g(x). +$$ +Now clearly if +$$ +g(x)\geq\varepsilon \Rightarrow f(x)\geq \varepsilon +$$ + +Now all we have to do is to find the roots $f(x)-\varepsilon=0$ and identify the one which is larger than, but close to $1$. +It is given by +$$ +x(\varepsilon)=-\frac{1}{4}(1-12\varepsilon+2\sqrt{36\varepsilon^2-6\varepsilon})^\tfrac{1}{3}-\frac{1}{4(1-12\varepsilon+2\sqrt{36\varepsilon^2-6\varepsilon})^\tfrac{1}{3}}+\frac{3}{2}-\frac{i\sqrt{3}}{2}\left(\frac{1-12\varepsilon+2\sqrt{36\varepsilon^2-6\varepsilon})^\tfrac{1}{3}}{2}-\frac{1}{2(1-12\varepsilon+2\sqrt{36\varepsilon^2-6\varepsilon})^\tfrac{1}{3})}\right) +$$ + +edit: If this expression does not satisfy you, you can of, of course expand it around $\varepsilon=0$ to get: + +$$ +x(\varepsilon)\approx 1+\sqrt{2\varepsilon}+\tfrac{2}{3}\varepsilon+\tfrac{5}{9}\sqrt{2}\varepsilon^\tfrac{3}{2} +$$","$x(\epsilon)=x-\ln(x)-1$ is the largest upper bound possible, and also happens to be in closed form." +125202,"I'm writing a simple utility to crop batches of multi-band geotiff raster files to the same (smaller) area. Using gdalwarp, I can easily crop a file using a single-polygon clipping shapefile: + +``` +gdalwarp -cutline clipper.shp -crop_to_cutline input.tif output.tif + +``` + +However, the actual area I want to clip to will always be initially defined by another geotiff raster file, not a shapefile. It would be nice if I could use the extent of that raster as the clipping file, but I'm not sure how to do this. Unsurprisingly, the following doesn't work (it doesn't raise an error, it just doesn't produce anything): + +``` +gdalwarp -cutline clipper.tif-crop_to_cutline input.tif output.tif + +``` + +So, my question is, is there a way to supply a raster to `gdalwarp -cutline`? Alternately, is there another gdal function that can clip a raster using another raster? If neither of these are possible, is there a very simple way to produce a shapefile with a single polygon defined by the extent of a raster? + +This code will be wrapped in a more extensive python script, so I can use either command line gdal utilities or any of the python bindings for gdal. + +As a side note, I know that I could easily just make a clipping shapefile that covers the extent of my raster in QGIS. I may wind up doing that if I don't find a straightforward solution, but I will ultimately wind up using this utility on dozens if not hundreds of areas as part of a large automated analysis, so I'd prefer not to have a tedious manual step even if it is very easy.",2014/12/10,"['https://gis.stackexchange.com/questions/125202', 'https://gis.stackexchange.com', 'https://gis.stackexchange.com/users/37589/']","I don't know if it's possible to clip a raster with an other raster but +you could use gdaltindex to build the shapefile with the extent of your raster. + +","For irregular polygons, and assuming that your geotiff raster file is a binary raster, you could use [GDAL\_Calc](http://www.gdal.org/gdal_calc.html): + +``` +GDAL_Calc.py -A Mask.tif -B CutBigImageToClip.tif --outfile=SmallerFile.tif --NoDataValue=0 --Calc=""B*(A>0)"" + +``` + +This query will populate 0 where Mask.tif <= 0 and BigImage where the Mask > 0. To do this both rasters must be the same cell size, rows and columns. To extract the same extents use GDAL\_Translate with the `-projwin ulx uly lrx lry` option (box is in projected coordinates), but ensure that the projwin box does not extend over the edges of either raster. + +``` +GDAL_Translate -of GTIFF -projwin ulx uly lrx lry BigImageToClip.tif CutBigImageToClip.tif + +``` + +Substitute values for the projwin box derived from the Mask." +125202,"I'm writing a simple utility to crop batches of multi-band geotiff raster files to the same (smaller) area. Using gdalwarp, I can easily crop a file using a single-polygon clipping shapefile: + +``` +gdalwarp -cutline clipper.shp -crop_to_cutline input.tif output.tif + +``` + +However, the actual area I want to clip to will always be initially defined by another geotiff raster file, not a shapefile. It would be nice if I could use the extent of that raster as the clipping file, but I'm not sure how to do this. Unsurprisingly, the following doesn't work (it doesn't raise an error, it just doesn't produce anything): + +``` +gdalwarp -cutline clipper.tif-crop_to_cutline input.tif output.tif + +``` + +So, my question is, is there a way to supply a raster to `gdalwarp -cutline`? Alternately, is there another gdal function that can clip a raster using another raster? If neither of these are possible, is there a very simple way to produce a shapefile with a single polygon defined by the extent of a raster? + +This code will be wrapped in a more extensive python script, so I can use either command line gdal utilities or any of the python bindings for gdal. + +As a side note, I know that I could easily just make a clipping shapefile that covers the extent of my raster in QGIS. I may wind up doing that if I don't find a straightforward solution, but I will ultimately wind up using this utility on dozens if not hundreds of areas as part of a large automated analysis, so I'd prefer not to have a tedious manual step even if it is very easy.",2014/12/10,"['https://gis.stackexchange.com/questions/125202', 'https://gis.stackexchange.com', 'https://gis.stackexchange.com/users/37589/']","I don't know if it's possible to clip a raster with an other raster but +you could use gdaltindex to build the shapefile with the extent of your raster. + +","The solution in Python directly, without making shape: + +``` +import gdal +from gdalconst import GA_ReadOnly + +data = gdal.Open('img_mask.tif', GA_ReadOnly) +geoTransform = data.GetGeoTransform() +minx = geoTransform[0] +maxy = geoTransform[3] +maxx = minx + geoTransform[1] * data.RasterXSize +miny = maxy + geoTransform[5] * data.RasterYSize +call('gdal_translate -projwin ' + ' '.join([str(x) for x in [minx, maxy, maxx, miny]]) + ' -of GTiff img_orig.tif img_out.tif', shell=True) + +```" +125202,"I'm writing a simple utility to crop batches of multi-band geotiff raster files to the same (smaller) area. Using gdalwarp, I can easily crop a file using a single-polygon clipping shapefile: + +``` +gdalwarp -cutline clipper.shp -crop_to_cutline input.tif output.tif + +``` + +However, the actual area I want to clip to will always be initially defined by another geotiff raster file, not a shapefile. It would be nice if I could use the extent of that raster as the clipping file, but I'm not sure how to do this. Unsurprisingly, the following doesn't work (it doesn't raise an error, it just doesn't produce anything): + +``` +gdalwarp -cutline clipper.tif-crop_to_cutline input.tif output.tif + +``` + +So, my question is, is there a way to supply a raster to `gdalwarp -cutline`? Alternately, is there another gdal function that can clip a raster using another raster? If neither of these are possible, is there a very simple way to produce a shapefile with a single polygon defined by the extent of a raster? + +This code will be wrapped in a more extensive python script, so I can use either command line gdal utilities or any of the python bindings for gdal. + +As a side note, I know that I could easily just make a clipping shapefile that covers the extent of my raster in QGIS. I may wind up doing that if I don't find a straightforward solution, but I will ultimately wind up using this utility on dozens if not hundreds of areas as part of a large automated analysis, so I'd prefer not to have a tedious manual step even if it is very easy.",2014/12/10,"['https://gis.stackexchange.com/questions/125202', 'https://gis.stackexchange.com', 'https://gis.stackexchange.com/users/37589/']","I don't know if it's possible to clip a raster with an other raster but +you could use gdaltindex to build the shapefile with the extent of your raster. + +","Here u can use this code to run an intersection raster tool. You need to be aware of CRS and pixel size (cols and rows). + +``` +# This file is part of Brazil Data Cube Validation Tools. +# Copyright (C) 2020. + +# Python Native +import os +# 3rd party +import gdal +import numpy + +def raster_intersection(ds1, ds2, nodata1=None, nodata2=None, output_name1=None, +output_name2=None): +""""""Perform image intersection of two rasters with different extent and +projection. + Args: + ds1 (GDAL dataset) - GDAL dataset of an image + ds2 (GDAL dataset) - GDAL dataset of an image + nodata1 (number) - nodata value of image 1 + nodata2 (number) - nodata value of image 2 + output_name1 (string) - path to output intersection of ds1 + output_name2 (string) - path to output intersection of ds2 + Returns: + dataset1 (GDAL dataset), dataset2 (GDAL dataset): intersection dataset1 +and intersection dataset2. +"""""" +###Setting nodata +nodata = 0 +###Check if images NoData is set +if nodata2 is not None: + nodata = nodata2 + ds2.GetRasterBand(1).SetNoDataValue(nodata) +else: + if ds2.GetRasterBand(1).GetNoDataValue() is None: + ds2.GetRasterBand(1).SetNoDataValue(nodata) + +if nodata1 is not None: + nodata = nodata1 + ds1.GetRasterBand(1).SetNoDataValue(nodata1) +else: + if ds1.GetRasterBand(1).GetNoDataValue() is None: + ds1.GetRasterBand(1).SetNoDataValue(nodata) + +### Get extent from ds1 +projection = ds1.GetProjectionRef() +geoTransform = ds1.GetGeoTransform() + +###Get minx and max y +minx = geoTransform[0] +maxy = geoTransform[3] + +###Raster dimensions +xsize = ds1.RasterXSize +ysize = ds1.RasterYSize + +maxx = minx + geoTransform[1] * xsize +miny = maxy + geoTransform[5] * ysize + +###Warp to same spatial resolution +gdaloptions = {'format': 'MEM', 'xRes': geoTransform[1], 'yRes': +geoTransform[5], 'dstSRS': projection} +ds2w = gdal.Warp('', ds2, **gdaloptions) +ds2 = None + +###Translate to same projection +ds2c = gdal.Translate('', ds2w, format='MEM', projWin=[minx, maxy, maxx, miny], +outputSRS=projection) +ds2w = None +ds1c = gdal.Translate('', ds1, format='MEM', projWin=[minx, maxy, maxx, miny], +outputSRS=projection) +ds1 = None + +###Check if will create file on disk +if output_name1 is not None or output_name2 is not None: + driver = gdal.GetDriverByName(""GTiff"") + if output_name1 is None: + output_name1 = 'intersection1.tif' + if output_name2 is None: + output_name2 = 'intersection2.tif' +else: + driver = gdal.GetDriverByName(""MEM"") + output_name1 = '' + output_name2 = '' + +dataset1 = driver.Create(output_name1, xsize, ysize, 1, +ds1c.GetRasterBand(1).DataType) +dataset1.SetGeoTransform(geoTransform) +dataset1.SetProjection(projection) +dataset1.GetRasterBand(1).SetNoDataValue(nodata) ###Setting nodata value +dataset1.GetRasterBand(1).WriteArray(ds1c.GetRasterBand(1).ReadAsArray()) + +dataset2 = driver.Create(output_name2, xsize, ysize, 1, +ds2c.GetRasterBand(1).DataType) +dataset2.SetGeoTransform(geoTransform) +dataset2.SetProjection(projection) +dataset2.GetRasterBand(1).SetNoDataValue(nodata) ###Setting nodata value +dataset2.GetRasterBand(1).WriteArray(ds2c.GetRasterBand(1).ReadAsArray()) + +ds1c = None +ds2c = None + +return dataset1, dataset2 + +def raster_absolute_diff(ds1, ds2, nodata1=None, nodata2=None, +output_file=None): +""""""Perform image absolute difference (support different extent and projection). + Args: + path1 (string) - path to image 1 (reference) + path2 (string) - path to image 2 (target) + output_dir (string) - path to output files + nodata1 (number) - nodata value of image 1 + nodata2 (number) - nodata value of image 2 + Returns: + dataset (GDAL dataset): dataset containing absolute difference between +ds1 and ds2. +"""""" +if output_file is None: + output_file = 'abs_diff.tif' +ds1_intersec, ds2_intersec = raster_intersection(ds1, ds2, nodata1, nodata2, +None, None) + +### Read bands with numpy to algebra +nodata = ds1_intersec.GetRasterBand(1).GetNoDataValue() +bandtar = numpy.array(ds1_intersec.GetRasterBand(1).ReadAsArray().astype(float)) +fill_bandtar = numpy.where(bandtar == nodata) +bandref = numpy.array(ds2_intersec.GetRasterBand(1).ReadAsArray().astype(float)) +fill_bandref = numpy.where(bandref == nodata) + +### Get extent from ds1 +projection = ds1.GetProjectionRef() +geoTransform = ds1.GetGeoTransform() +[cols, rows] = ds1.GetRasterBand(1).ReadAsArray().shape + +ds1 = None +ds2 = None +diff = numpy.abs(bandtar - bandref) +diff[fill_bandtar] = nodata +diff[fill_bandref] = nodata + +###Check if will create file on disk +if output_file is not None: + driver = gdal.GetDriverByName(""GTiff"") +else: + driver = gdal.GetDriverByName(""MEM"") + output_file = '' + +dataset = driver.Create(output_file, rows, cols, 1, +ds1_intersec.GetRasterBand(1).DataType) +dataset.SetGeoTransform(geoTransform) +dataset.SetProjection(projection) +dataset.GetRasterBand(1).SetNoDataValue(nodata) +dataset.GetRasterBand(1).WriteArray(diff) + +return dataset + +```" +125202,"I'm writing a simple utility to crop batches of multi-band geotiff raster files to the same (smaller) area. Using gdalwarp, I can easily crop a file using a single-polygon clipping shapefile: + +``` +gdalwarp -cutline clipper.shp -crop_to_cutline input.tif output.tif + +``` + +However, the actual area I want to clip to will always be initially defined by another geotiff raster file, not a shapefile. It would be nice if I could use the extent of that raster as the clipping file, but I'm not sure how to do this. Unsurprisingly, the following doesn't work (it doesn't raise an error, it just doesn't produce anything): + +``` +gdalwarp -cutline clipper.tif-crop_to_cutline input.tif output.tif + +``` + +So, my question is, is there a way to supply a raster to `gdalwarp -cutline`? Alternately, is there another gdal function that can clip a raster using another raster? If neither of these are possible, is there a very simple way to produce a shapefile with a single polygon defined by the extent of a raster? + +This code will be wrapped in a more extensive python script, so I can use either command line gdal utilities or any of the python bindings for gdal. + +As a side note, I know that I could easily just make a clipping shapefile that covers the extent of my raster in QGIS. I may wind up doing that if I don't find a straightforward solution, but I will ultimately wind up using this utility on dozens if not hundreds of areas as part of a large automated analysis, so I'd prefer not to have a tedious manual step even if it is very easy.",2014/12/10,"['https://gis.stackexchange.com/questions/125202', 'https://gis.stackexchange.com', 'https://gis.stackexchange.com/users/37589/']","For irregular polygons, and assuming that your geotiff raster file is a binary raster, you could use [GDAL\_Calc](http://www.gdal.org/gdal_calc.html): + +``` +GDAL_Calc.py -A Mask.tif -B CutBigImageToClip.tif --outfile=SmallerFile.tif --NoDataValue=0 --Calc=""B*(A>0)"" + +``` + +This query will populate 0 where Mask.tif <= 0 and BigImage where the Mask > 0. To do this both rasters must be the same cell size, rows and columns. To extract the same extents use GDAL\_Translate with the `-projwin ulx uly lrx lry` option (box is in projected coordinates), but ensure that the projwin box does not extend over the edges of either raster. + +``` +GDAL_Translate -of GTIFF -projwin ulx uly lrx lry BigImageToClip.tif CutBigImageToClip.tif + +``` + +Substitute values for the projwin box derived from the Mask.","Here u can use this code to run an intersection raster tool. You need to be aware of CRS and pixel size (cols and rows). + +``` +# This file is part of Brazil Data Cube Validation Tools. +# Copyright (C) 2020. + +# Python Native +import os +# 3rd party +import gdal +import numpy + +def raster_intersection(ds1, ds2, nodata1=None, nodata2=None, output_name1=None, +output_name2=None): +""""""Perform image intersection of two rasters with different extent and +projection. + Args: + ds1 (GDAL dataset) - GDAL dataset of an image + ds2 (GDAL dataset) - GDAL dataset of an image + nodata1 (number) - nodata value of image 1 + nodata2 (number) - nodata value of image 2 + output_name1 (string) - path to output intersection of ds1 + output_name2 (string) - path to output intersection of ds2 + Returns: + dataset1 (GDAL dataset), dataset2 (GDAL dataset): intersection dataset1 +and intersection dataset2. +"""""" +###Setting nodata +nodata = 0 +###Check if images NoData is set +if nodata2 is not None: + nodata = nodata2 + ds2.GetRasterBand(1).SetNoDataValue(nodata) +else: + if ds2.GetRasterBand(1).GetNoDataValue() is None: + ds2.GetRasterBand(1).SetNoDataValue(nodata) + +if nodata1 is not None: + nodata = nodata1 + ds1.GetRasterBand(1).SetNoDataValue(nodata1) +else: + if ds1.GetRasterBand(1).GetNoDataValue() is None: + ds1.GetRasterBand(1).SetNoDataValue(nodata) + +### Get extent from ds1 +projection = ds1.GetProjectionRef() +geoTransform = ds1.GetGeoTransform() + +###Get minx and max y +minx = geoTransform[0] +maxy = geoTransform[3] + +###Raster dimensions +xsize = ds1.RasterXSize +ysize = ds1.RasterYSize + +maxx = minx + geoTransform[1] * xsize +miny = maxy + geoTransform[5] * ysize + +###Warp to same spatial resolution +gdaloptions = {'format': 'MEM', 'xRes': geoTransform[1], 'yRes': +geoTransform[5], 'dstSRS': projection} +ds2w = gdal.Warp('', ds2, **gdaloptions) +ds2 = None + +###Translate to same projection +ds2c = gdal.Translate('', ds2w, format='MEM', projWin=[minx, maxy, maxx, miny], +outputSRS=projection) +ds2w = None +ds1c = gdal.Translate('', ds1, format='MEM', projWin=[minx, maxy, maxx, miny], +outputSRS=projection) +ds1 = None + +###Check if will create file on disk +if output_name1 is not None or output_name2 is not None: + driver = gdal.GetDriverByName(""GTiff"") + if output_name1 is None: + output_name1 = 'intersection1.tif' + if output_name2 is None: + output_name2 = 'intersection2.tif' +else: + driver = gdal.GetDriverByName(""MEM"") + output_name1 = '' + output_name2 = '' + +dataset1 = driver.Create(output_name1, xsize, ysize, 1, +ds1c.GetRasterBand(1).DataType) +dataset1.SetGeoTransform(geoTransform) +dataset1.SetProjection(projection) +dataset1.GetRasterBand(1).SetNoDataValue(nodata) ###Setting nodata value +dataset1.GetRasterBand(1).WriteArray(ds1c.GetRasterBand(1).ReadAsArray()) + +dataset2 = driver.Create(output_name2, xsize, ysize, 1, +ds2c.GetRasterBand(1).DataType) +dataset2.SetGeoTransform(geoTransform) +dataset2.SetProjection(projection) +dataset2.GetRasterBand(1).SetNoDataValue(nodata) ###Setting nodata value +dataset2.GetRasterBand(1).WriteArray(ds2c.GetRasterBand(1).ReadAsArray()) + +ds1c = None +ds2c = None + +return dataset1, dataset2 + +def raster_absolute_diff(ds1, ds2, nodata1=None, nodata2=None, +output_file=None): +""""""Perform image absolute difference (support different extent and projection). + Args: + path1 (string) - path to image 1 (reference) + path2 (string) - path to image 2 (target) + output_dir (string) - path to output files + nodata1 (number) - nodata value of image 1 + nodata2 (number) - nodata value of image 2 + Returns: + dataset (GDAL dataset): dataset containing absolute difference between +ds1 and ds2. +"""""" +if output_file is None: + output_file = 'abs_diff.tif' +ds1_intersec, ds2_intersec = raster_intersection(ds1, ds2, nodata1, nodata2, +None, None) + +### Read bands with numpy to algebra +nodata = ds1_intersec.GetRasterBand(1).GetNoDataValue() +bandtar = numpy.array(ds1_intersec.GetRasterBand(1).ReadAsArray().astype(float)) +fill_bandtar = numpy.where(bandtar == nodata) +bandref = numpy.array(ds2_intersec.GetRasterBand(1).ReadAsArray().astype(float)) +fill_bandref = numpy.where(bandref == nodata) + +### Get extent from ds1 +projection = ds1.GetProjectionRef() +geoTransform = ds1.GetGeoTransform() +[cols, rows] = ds1.GetRasterBand(1).ReadAsArray().shape + +ds1 = None +ds2 = None +diff = numpy.abs(bandtar - bandref) +diff[fill_bandtar] = nodata +diff[fill_bandref] = nodata + +###Check if will create file on disk +if output_file is not None: + driver = gdal.GetDriverByName(""GTiff"") +else: + driver = gdal.GetDriverByName(""MEM"") + output_file = '' + +dataset = driver.Create(output_file, rows, cols, 1, +ds1_intersec.GetRasterBand(1).DataType) +dataset.SetGeoTransform(geoTransform) +dataset.SetProjection(projection) +dataset.GetRasterBand(1).SetNoDataValue(nodata) +dataset.GetRasterBand(1).WriteArray(diff) + +return dataset + +```" +125202,"I'm writing a simple utility to crop batches of multi-band geotiff raster files to the same (smaller) area. Using gdalwarp, I can easily crop a file using a single-polygon clipping shapefile: + +``` +gdalwarp -cutline clipper.shp -crop_to_cutline input.tif output.tif + +``` + +However, the actual area I want to clip to will always be initially defined by another geotiff raster file, not a shapefile. It would be nice if I could use the extent of that raster as the clipping file, but I'm not sure how to do this. Unsurprisingly, the following doesn't work (it doesn't raise an error, it just doesn't produce anything): + +``` +gdalwarp -cutline clipper.tif-crop_to_cutline input.tif output.tif + +``` + +So, my question is, is there a way to supply a raster to `gdalwarp -cutline`? Alternately, is there another gdal function that can clip a raster using another raster? If neither of these are possible, is there a very simple way to produce a shapefile with a single polygon defined by the extent of a raster? + +This code will be wrapped in a more extensive python script, so I can use either command line gdal utilities or any of the python bindings for gdal. + +As a side note, I know that I could easily just make a clipping shapefile that covers the extent of my raster in QGIS. I may wind up doing that if I don't find a straightforward solution, but I will ultimately wind up using this utility on dozens if not hundreds of areas as part of a large automated analysis, so I'd prefer not to have a tedious manual step even if it is very easy.",2014/12/10,"['https://gis.stackexchange.com/questions/125202', 'https://gis.stackexchange.com', 'https://gis.stackexchange.com/users/37589/']","The solution in Python directly, without making shape: + +``` +import gdal +from gdalconst import GA_ReadOnly + +data = gdal.Open('img_mask.tif', GA_ReadOnly) +geoTransform = data.GetGeoTransform() +minx = geoTransform[0] +maxy = geoTransform[3] +maxx = minx + geoTransform[1] * data.RasterXSize +miny = maxy + geoTransform[5] * data.RasterYSize +call('gdal_translate -projwin ' + ' '.join([str(x) for x in [minx, maxy, maxx, miny]]) + ' -of GTiff img_orig.tif img_out.tif', shell=True) + +```","Here u can use this code to run an intersection raster tool. You need to be aware of CRS and pixel size (cols and rows). + +``` +# This file is part of Brazil Data Cube Validation Tools. +# Copyright (C) 2020. + +# Python Native +import os +# 3rd party +import gdal +import numpy + +def raster_intersection(ds1, ds2, nodata1=None, nodata2=None, output_name1=None, +output_name2=None): +""""""Perform image intersection of two rasters with different extent and +projection. + Args: + ds1 (GDAL dataset) - GDAL dataset of an image + ds2 (GDAL dataset) - GDAL dataset of an image + nodata1 (number) - nodata value of image 1 + nodata2 (number) - nodata value of image 2 + output_name1 (string) - path to output intersection of ds1 + output_name2 (string) - path to output intersection of ds2 + Returns: + dataset1 (GDAL dataset), dataset2 (GDAL dataset): intersection dataset1 +and intersection dataset2. +"""""" +###Setting nodata +nodata = 0 +###Check if images NoData is set +if nodata2 is not None: + nodata = nodata2 + ds2.GetRasterBand(1).SetNoDataValue(nodata) +else: + if ds2.GetRasterBand(1).GetNoDataValue() is None: + ds2.GetRasterBand(1).SetNoDataValue(nodata) + +if nodata1 is not None: + nodata = nodata1 + ds1.GetRasterBand(1).SetNoDataValue(nodata1) +else: + if ds1.GetRasterBand(1).GetNoDataValue() is None: + ds1.GetRasterBand(1).SetNoDataValue(nodata) + +### Get extent from ds1 +projection = ds1.GetProjectionRef() +geoTransform = ds1.GetGeoTransform() + +###Get minx and max y +minx = geoTransform[0] +maxy = geoTransform[3] + +###Raster dimensions +xsize = ds1.RasterXSize +ysize = ds1.RasterYSize + +maxx = minx + geoTransform[1] * xsize +miny = maxy + geoTransform[5] * ysize + +###Warp to same spatial resolution +gdaloptions = {'format': 'MEM', 'xRes': geoTransform[1], 'yRes': +geoTransform[5], 'dstSRS': projection} +ds2w = gdal.Warp('', ds2, **gdaloptions) +ds2 = None + +###Translate to same projection +ds2c = gdal.Translate('', ds2w, format='MEM', projWin=[minx, maxy, maxx, miny], +outputSRS=projection) +ds2w = None +ds1c = gdal.Translate('', ds1, format='MEM', projWin=[minx, maxy, maxx, miny], +outputSRS=projection) +ds1 = None + +###Check if will create file on disk +if output_name1 is not None or output_name2 is not None: + driver = gdal.GetDriverByName(""GTiff"") + if output_name1 is None: + output_name1 = 'intersection1.tif' + if output_name2 is None: + output_name2 = 'intersection2.tif' +else: + driver = gdal.GetDriverByName(""MEM"") + output_name1 = '' + output_name2 = '' + +dataset1 = driver.Create(output_name1, xsize, ysize, 1, +ds1c.GetRasterBand(1).DataType) +dataset1.SetGeoTransform(geoTransform) +dataset1.SetProjection(projection) +dataset1.GetRasterBand(1).SetNoDataValue(nodata) ###Setting nodata value +dataset1.GetRasterBand(1).WriteArray(ds1c.GetRasterBand(1).ReadAsArray()) + +dataset2 = driver.Create(output_name2, xsize, ysize, 1, +ds2c.GetRasterBand(1).DataType) +dataset2.SetGeoTransform(geoTransform) +dataset2.SetProjection(projection) +dataset2.GetRasterBand(1).SetNoDataValue(nodata) ###Setting nodata value +dataset2.GetRasterBand(1).WriteArray(ds2c.GetRasterBand(1).ReadAsArray()) + +ds1c = None +ds2c = None + +return dataset1, dataset2 + +def raster_absolute_diff(ds1, ds2, nodata1=None, nodata2=None, +output_file=None): +""""""Perform image absolute difference (support different extent and projection). + Args: + path1 (string) - path to image 1 (reference) + path2 (string) - path to image 2 (target) + output_dir (string) - path to output files + nodata1 (number) - nodata value of image 1 + nodata2 (number) - nodata value of image 2 + Returns: + dataset (GDAL dataset): dataset containing absolute difference between +ds1 and ds2. +"""""" +if output_file is None: + output_file = 'abs_diff.tif' +ds1_intersec, ds2_intersec = raster_intersection(ds1, ds2, nodata1, nodata2, +None, None) + +### Read bands with numpy to algebra +nodata = ds1_intersec.GetRasterBand(1).GetNoDataValue() +bandtar = numpy.array(ds1_intersec.GetRasterBand(1).ReadAsArray().astype(float)) +fill_bandtar = numpy.where(bandtar == nodata) +bandref = numpy.array(ds2_intersec.GetRasterBand(1).ReadAsArray().astype(float)) +fill_bandref = numpy.where(bandref == nodata) + +### Get extent from ds1 +projection = ds1.GetProjectionRef() +geoTransform = ds1.GetGeoTransform() +[cols, rows] = ds1.GetRasterBand(1).ReadAsArray().shape + +ds1 = None +ds2 = None +diff = numpy.abs(bandtar - bandref) +diff[fill_bandtar] = nodata +diff[fill_bandref] = nodata + +###Check if will create file on disk +if output_file is not None: + driver = gdal.GetDriverByName(""GTiff"") +else: + driver = gdal.GetDriverByName(""MEM"") + output_file = '' + +dataset = driver.Create(output_file, rows, cols, 1, +ds1_intersec.GetRasterBand(1).DataType) +dataset.SetGeoTransform(geoTransform) +dataset.SetProjection(projection) +dataset.GetRasterBand(1).SetNoDataValue(nodata) +dataset.GetRasterBand(1).WriteArray(diff) + +return dataset + +```" +72475,"There is an African plain, there are trees, grasses, some seasonal rivers/lakes, and snakes. + +Upon the plain lives a society of tribesmen (think along the lines of the [Maasai Mara](https://en.wikipedia.org/wiki/Maasai_Mara) people) + +[![enter image description here](https://l7.alamy.com/zooms/5e1e3bdb36f9477cbb4c5d1f00c5a17b/kenya-narok-district-maasai-men-walk-home-across-the-short-grassy-bfmrj0.jpg)](https://l7.alamy.com/zooms/5e1e3bdb36f9477cbb4c5d1f00c5a17b/kenya-narok-district-maasai-men-walk-home-across-the-short-grassy-bfmrj0.jpg) +[This image used with permission: Source (Alamy)](http://www.alamy.com/stock-photo/masai-mara-tribe.html) + +These tribes love life, but hate snakes - they are the embodiment of the evil spirits, they cannot be eaten, they also cannot be killed (life is more treasured than evil is hated). + +Of course, there's plenty of snakes around. + +So the question (obviously) is how can the tribesmen get the snakes off the plain?",2017/02/28,"['https://worldbuilding.stackexchange.com/questions/72475', 'https://worldbuilding.stackexchange.com', 'https://worldbuilding.stackexchange.com/users/-1/']","Just ask Moses +============== + +From [Artapansus of Alexandria](https://en.wikipedia.org/wiki/Artapanus_of_Alexandria) in his History of the Jews: + +> +> Jealousy of Moses' excellent qualities induced Chenephres to send him +> with unskilled troops on a military expedition to Ethiopia, where he +> won great victories. After having built the city of Hermopolis, he +> taught the people the value of the ibis as a protection against the +> serpents, making the bird the sacred guardian spirit of the city... +> +> +> + +Behold, your savior +=================== + +[![enter image description here](https://i.stack.imgur.com/TbKjq.jpg)](https://i.stack.imgur.com/TbKjq.jpg) + +Your people worship the Ibis +============================ + +Not only are [Sacred Ibis](https://en.wikipedia.org/wiki/African_sacred_ibis)' great for keeping around and eating snakes, they are also native to the same plains that the Masai Mara live on, and they are [easy to worship](https://en.wikipedia.org/wiki/Thoth) too! + +[![enter image description here](https://i.stack.imgur.com/rWMQ1.jpg)](https://i.stack.imgur.com/rWMQ1.jpg)","Do what any human does and kill them +------------------------------------ + +Look at human history, you can likely easily name 5 animals off the top of your head that humanity has hunted to extinction. Unless the animals mass breeds like insects, early man has always had dominion over animal life. + +If these people truly hated and despised the snakes, to the point that they saw it their religious duty to god to kill them, the snakes wouldn't stand a chance. Humans always win." +72475,"There is an African plain, there are trees, grasses, some seasonal rivers/lakes, and snakes. + +Upon the plain lives a society of tribesmen (think along the lines of the [Maasai Mara](https://en.wikipedia.org/wiki/Maasai_Mara) people) + +[![enter image description here](https://l7.alamy.com/zooms/5e1e3bdb36f9477cbb4c5d1f00c5a17b/kenya-narok-district-maasai-men-walk-home-across-the-short-grassy-bfmrj0.jpg)](https://l7.alamy.com/zooms/5e1e3bdb36f9477cbb4c5d1f00c5a17b/kenya-narok-district-maasai-men-walk-home-across-the-short-grassy-bfmrj0.jpg) +[This image used with permission: Source (Alamy)](http://www.alamy.com/stock-photo/masai-mara-tribe.html) + +These tribes love life, but hate snakes - they are the embodiment of the evil spirits, they cannot be eaten, they also cannot be killed (life is more treasured than evil is hated). + +Of course, there's plenty of snakes around. + +So the question (obviously) is how can the tribesmen get the snakes off the plain?",2017/02/28,"['https://worldbuilding.stackexchange.com/questions/72475', 'https://worldbuilding.stackexchange.com', 'https://worldbuilding.stackexchange.com/users/-1/']","Just ask Moses +============== + +From [Artapansus of Alexandria](https://en.wikipedia.org/wiki/Artapanus_of_Alexandria) in his History of the Jews: + +> +> Jealousy of Moses' excellent qualities induced Chenephres to send him +> with unskilled troops on a military expedition to Ethiopia, where he +> won great victories. After having built the city of Hermopolis, he +> taught the people the value of the ibis as a protection against the +> serpents, making the bird the sacred guardian spirit of the city... +> +> +> + +Behold, your savior +=================== + +[![enter image description here](https://i.stack.imgur.com/TbKjq.jpg)](https://i.stack.imgur.com/TbKjq.jpg) + +Your people worship the Ibis +============================ + +Not only are [Sacred Ibis](https://en.wikipedia.org/wiki/African_sacred_ibis)' great for keeping around and eating snakes, they are also native to the same plains that the Masai Mara live on, and they are [easy to worship](https://en.wikipedia.org/wiki/Thoth) too! + +[![enter image description here](https://i.stack.imgur.com/rWMQ1.jpg)](https://i.stack.imgur.com/rWMQ1.jpg)","Why do you have snakes on the plain in the first place? Rodents! So you need to find a way to control the rodent populations. If the snakes have nothing to eat, they won't hang about in large numbers. + +Introduce species that will eliminate the rodents and the snakes won't have prey. This is why Bast was an Egyptian Goddess. She represented cats, which kept critters out of the grain cribs. Also weasels and ferrets and mongoose might help. The mongoose will also eat the snakes as well. Then the whole killing snakes becomes a circle of life thing. + +Mammals are going to have an advantage in that they are not as affected by cold. + +In a culture like you describe, though, I would think the snake might at least be respected because it does help control the rodent population without endangering the food supply. So Sam L Jackson may not be necessary after all." +72475,"There is an African plain, there are trees, grasses, some seasonal rivers/lakes, and snakes. + +Upon the plain lives a society of tribesmen (think along the lines of the [Maasai Mara](https://en.wikipedia.org/wiki/Maasai_Mara) people) + +[![enter image description here](https://l7.alamy.com/zooms/5e1e3bdb36f9477cbb4c5d1f00c5a17b/kenya-narok-district-maasai-men-walk-home-across-the-short-grassy-bfmrj0.jpg)](https://l7.alamy.com/zooms/5e1e3bdb36f9477cbb4c5d1f00c5a17b/kenya-narok-district-maasai-men-walk-home-across-the-short-grassy-bfmrj0.jpg) +[This image used with permission: Source (Alamy)](http://www.alamy.com/stock-photo/masai-mara-tribe.html) + +These tribes love life, but hate snakes - they are the embodiment of the evil spirits, they cannot be eaten, they also cannot be killed (life is more treasured than evil is hated). + +Of course, there's plenty of snakes around. + +So the question (obviously) is how can the tribesmen get the snakes off the plain?",2017/02/28,"['https://worldbuilding.stackexchange.com/questions/72475', 'https://worldbuilding.stackexchange.com', 'https://worldbuilding.stackexchange.com/users/-1/']","Just ask Moses +============== + +From [Artapansus of Alexandria](https://en.wikipedia.org/wiki/Artapanus_of_Alexandria) in his History of the Jews: + +> +> Jealousy of Moses' excellent qualities induced Chenephres to send him +> with unskilled troops on a military expedition to Ethiopia, where he +> won great victories. After having built the city of Hermopolis, he +> taught the people the value of the ibis as a protection against the +> serpents, making the bird the sacred guardian spirit of the city... +> +> +> + +Behold, your savior +=================== + +[![enter image description here](https://i.stack.imgur.com/TbKjq.jpg)](https://i.stack.imgur.com/TbKjq.jpg) + +Your people worship the Ibis +============================ + +Not only are [Sacred Ibis](https://en.wikipedia.org/wiki/African_sacred_ibis)' great for keeping around and eating snakes, they are also native to the same plains that the Masai Mara live on, and they are [easy to worship](https://en.wikipedia.org/wiki/Thoth) too! + +[![enter image description here](https://i.stack.imgur.com/rWMQ1.jpg)](https://i.stack.imgur.com/rWMQ1.jpg)","> +> Kookaburra roams through the plains with glee, eating all the snakes +> with a grin is he, laugh, Kookaburra laugh, Kookaburra full your stomach +> must be. +> +> +> + +The humble Kookaburra! +A less well known Australian bird who loves to eat snakes and small rodents (solves two suspected problems here!!) + +My only problem would be that they would usually nest in a tree, so if there are no suitable trees around, we may have to make a hybrid kingfisher-kookaburra breed which would use the habitat of the kingfisher which is small holes in sand-mounds." +72475,"There is an African plain, there are trees, grasses, some seasonal rivers/lakes, and snakes. + +Upon the plain lives a society of tribesmen (think along the lines of the [Maasai Mara](https://en.wikipedia.org/wiki/Maasai_Mara) people) + +[![enter image description here](https://l7.alamy.com/zooms/5e1e3bdb36f9477cbb4c5d1f00c5a17b/kenya-narok-district-maasai-men-walk-home-across-the-short-grassy-bfmrj0.jpg)](https://l7.alamy.com/zooms/5e1e3bdb36f9477cbb4c5d1f00c5a17b/kenya-narok-district-maasai-men-walk-home-across-the-short-grassy-bfmrj0.jpg) +[This image used with permission: Source (Alamy)](http://www.alamy.com/stock-photo/masai-mara-tribe.html) + +These tribes love life, but hate snakes - they are the embodiment of the evil spirits, they cannot be eaten, they also cannot be killed (life is more treasured than evil is hated). + +Of course, there's plenty of snakes around. + +So the question (obviously) is how can the tribesmen get the snakes off the plain?",2017/02/28,"['https://worldbuilding.stackexchange.com/questions/72475', 'https://worldbuilding.stackexchange.com', 'https://worldbuilding.stackexchange.com/users/-1/']","Why do you have snakes on the plain in the first place? Rodents! So you need to find a way to control the rodent populations. If the snakes have nothing to eat, they won't hang about in large numbers. + +Introduce species that will eliminate the rodents and the snakes won't have prey. This is why Bast was an Egyptian Goddess. She represented cats, which kept critters out of the grain cribs. Also weasels and ferrets and mongoose might help. The mongoose will also eat the snakes as well. Then the whole killing snakes becomes a circle of life thing. + +Mammals are going to have an advantage in that they are not as affected by cold. + +In a culture like you describe, though, I would think the snake might at least be respected because it does help control the rodent population without endangering the food supply. So Sam L Jackson may not be necessary after all.","Do what any human does and kill them +------------------------------------ + +Look at human history, you can likely easily name 5 animals off the top of your head that humanity has hunted to extinction. Unless the animals mass breeds like insects, early man has always had dominion over animal life. + +If these people truly hated and despised the snakes, to the point that they saw it their religious duty to god to kill them, the snakes wouldn't stand a chance. Humans always win." +72475,"There is an African plain, there are trees, grasses, some seasonal rivers/lakes, and snakes. + +Upon the plain lives a society of tribesmen (think along the lines of the [Maasai Mara](https://en.wikipedia.org/wiki/Maasai_Mara) people) + +[![enter image description here](https://l7.alamy.com/zooms/5e1e3bdb36f9477cbb4c5d1f00c5a17b/kenya-narok-district-maasai-men-walk-home-across-the-short-grassy-bfmrj0.jpg)](https://l7.alamy.com/zooms/5e1e3bdb36f9477cbb4c5d1f00c5a17b/kenya-narok-district-maasai-men-walk-home-across-the-short-grassy-bfmrj0.jpg) +[This image used with permission: Source (Alamy)](http://www.alamy.com/stock-photo/masai-mara-tribe.html) + +These tribes love life, but hate snakes - they are the embodiment of the evil spirits, they cannot be eaten, they also cannot be killed (life is more treasured than evil is hated). + +Of course, there's plenty of snakes around. + +So the question (obviously) is how can the tribesmen get the snakes off the plain?",2017/02/28,"['https://worldbuilding.stackexchange.com/questions/72475', 'https://worldbuilding.stackexchange.com', 'https://worldbuilding.stackexchange.com/users/-1/']","> +> Kookaburra roams through the plains with glee, eating all the snakes +> with a grin is he, laugh, Kookaburra laugh, Kookaburra full your stomach +> must be. +> +> +> + +The humble Kookaburra! +A less well known Australian bird who loves to eat snakes and small rodents (solves two suspected problems here!!) + +My only problem would be that they would usually nest in a tree, so if there are no suitable trees around, we may have to make a hybrid kingfisher-kookaburra breed which would use the habitat of the kingfisher which is small holes in sand-mounds.","Do what any human does and kill them +------------------------------------ + +Look at human history, you can likely easily name 5 animals off the top of your head that humanity has hunted to extinction. Unless the animals mass breeds like insects, early man has always had dominion over animal life. + +If these people truly hated and despised the snakes, to the point that they saw it their religious duty to god to kill them, the snakes wouldn't stand a chance. Humans always win." +72475,"There is an African plain, there are trees, grasses, some seasonal rivers/lakes, and snakes. + +Upon the plain lives a society of tribesmen (think along the lines of the [Maasai Mara](https://en.wikipedia.org/wiki/Maasai_Mara) people) + +[![enter image description here](https://l7.alamy.com/zooms/5e1e3bdb36f9477cbb4c5d1f00c5a17b/kenya-narok-district-maasai-men-walk-home-across-the-short-grassy-bfmrj0.jpg)](https://l7.alamy.com/zooms/5e1e3bdb36f9477cbb4c5d1f00c5a17b/kenya-narok-district-maasai-men-walk-home-across-the-short-grassy-bfmrj0.jpg) +[This image used with permission: Source (Alamy)](http://www.alamy.com/stock-photo/masai-mara-tribe.html) + +These tribes love life, but hate snakes - they are the embodiment of the evil spirits, they cannot be eaten, they also cannot be killed (life is more treasured than evil is hated). + +Of course, there's plenty of snakes around. + +So the question (obviously) is how can the tribesmen get the snakes off the plain?",2017/02/28,"['https://worldbuilding.stackexchange.com/questions/72475', 'https://worldbuilding.stackexchange.com', 'https://worldbuilding.stackexchange.com/users/-1/']","Why do you have snakes on the plain in the first place? Rodents! So you need to find a way to control the rodent populations. If the snakes have nothing to eat, they won't hang about in large numbers. + +Introduce species that will eliminate the rodents and the snakes won't have prey. This is why Bast was an Egyptian Goddess. She represented cats, which kept critters out of the grain cribs. Also weasels and ferrets and mongoose might help. The mongoose will also eat the snakes as well. Then the whole killing snakes becomes a circle of life thing. + +Mammals are going to have an advantage in that they are not as affected by cold. + +In a culture like you describe, though, I would think the snake might at least be respected because it does help control the rodent population without endangering the food supply. So Sam L Jackson may not be necessary after all.","> +> Kookaburra roams through the plains with glee, eating all the snakes +> with a grin is he, laugh, Kookaburra laugh, Kookaburra full your stomach +> must be. +> +> +> + +The humble Kookaburra! +A less well known Australian bird who loves to eat snakes and small rodents (solves two suspected problems here!!) + +My only problem would be that they would usually nest in a tree, so if there are no suitable trees around, we may have to make a hybrid kingfisher-kookaburra breed which would use the habitat of the kingfisher which is small holes in sand-mounds." +36096018,"This may be a very typical task yet i am having issued cracking a solution for it. + +I am using a form which has 2 select options in it + +``` +
+ + + +
+ + +
+ +``` + +Based on the category chosen in ""parentCatSel"" the ""subcatcontainer"" is populated with a select option of subcategories +for the chosen parent category +listsubcategory() + +returns + +``` + + +``` + +the display of subcategory works fine with no errors, however when i try to post the values in the form , i am not able to retrieve the value of chosen option in ""subCatSel"" as below + +``` + document.getelement['subCatSel']= null +post['subCatSel'] = null + +``` + +please suggest an alternative.",2016/03/18,"['https://Stackoverflow.com/questions/36096018', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1332909/']","Add name attribute to your select inputs. + +``` + + + + + + + ) + } +} + +``` + +In the console.log() I'm receiving only the selected value. Is there a way to pass the entire event object to the function handleOnChange()?",2017/08/15,"['https://Stackoverflow.com/questions/45684925', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4956634/']","I found a solution. Just use: onSelect(), passing the value and the event. + +``` +handleOnChange = (value, event) => { + ...code here +} + + render() { + render( +
+ +
+ ) + } + +```","The `Select` component that you use is the one that handle the `onChange` and call your ""outer"" function. + +What you can try is use the synthetic event variable inside your function, it might work: + +``` +handleOnChange = (selectedValue) => { + console.log(selectedValue); // The value from the inner component + console.log(event); // usually you have access to this variable +} + +```" +45684925,"I have a drop down in my form (). In this select drop down I have the onChange to call a function. Inside 'onChange' I want to pass the event as a parameter to my function. The problem is: when the onChange occurs, only the selected value is passed, but I want the entire event. + +**Here is the code:** + +``` +export default class MyForm extends Component { + constructor() { + super(); + + this.handleOnChange = this.handleOnChange.bind(this); + } + + handleOnChange = (event) => { + console.log(event); // here I'm receiving only the value selected (1 or 2) + } + + render() { + render( +
+ +
+ ) + } +} + +``` + +In the console.log() I'm receiving only the selected value. Is there a way to pass the entire event object to the function handleOnChange()?",2017/08/15,"['https://Stackoverflow.com/questions/45684925', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4956634/']","The `Select` component that you use is the one that handle the `onChange` and call your ""outer"" function. + +What you can try is use the synthetic event variable inside your function, it might work: + +``` +handleOnChange = (selectedValue) => { + console.log(selectedValue); // The value from the inner component + console.log(event); // usually you have access to this variable +} + +```","Try this, if you dont want to bind in callback in Select onSelect/onChange: + +``` +toggleActive = name => event => { + console.log(""name: "",name) // prints ""name: Active!"" + console.log(""event: "",event) // event is some data +} + + + + + + + + ) + } +} + +``` + +In the console.log() I'm receiving only the selected value. Is there a way to pass the entire event object to the function handleOnChange()?",2017/08/15,"['https://Stackoverflow.com/questions/45684925', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4956634/']","I found a solution. Just use: onSelect(), passing the value and the event. + +``` +handleOnChange = (value, event) => { + ...code here +} + + render() { + render( +
+ +
+ ) + } + +```","Try this, if you dont want to bind in callback in Select onSelect/onChange: + +``` +toggleActive = name => event => { + console.log(""name: "",name) // prints ""name: Active!"" + console.log(""event: "",event) // event is some data +} + +email_1
+email_2
+email_3
+email_4
+
+Add All Email
+ + +```","Try something like this, using an array with a final `join()` once your array is populated. I think it's a lot cleaner: + +``` + checkbox.onclick = (function(chk){ + return function() { + var valueArray = []; + for (var j = 0; j < checkboxes.length; j++) { + if (checkboxes[j].checked) { + valueArray.push(checkboxes[j].value); //add value to array + } + } + textbox.value = valueArray.join("", ""); //join with comma separators + } + })(checkbox); + +``` + +You could also extract the function and invoke the extracted function rather than adding the content of the function to every checkbox, but w/out seeing your HTML, it's a little hard to discern exactly what you're doing and why you're looping the way you are." +46006705,"I need to get the OS version and Revision number using PowerShell on a list of remote systems. + +I need the results that you get from [environment]::OSVersion.Version but on the remote systems. + +when I run [environment]::OSVersion.Version + +it returns + +Major Minor Build Revision + +6 1 7601 65536 + +the ultimate goal would be for it to look like this (where system name is the remote system I am querying.) + +SystemName 6.1.7601.65536 + +my current code: + +``` +$expectedVersion = ""6.1.7601.65536"" +$computer = Get-content ""C:\temp\servers.txt"" +foreach ($computer in $computer) +{ +$a=[environment]::OSVersion.Version +If ($a -lt $expectedVersion) +{ + Write-Host ""$computer $a is NOT Patched"" -ForegroundColor Red +} +Else +{ + Write-Host ""$computer $a is Patched"" -ForegroundColor Green +}} + +``` + +which give me the following results: + +System-01 6.1.7601.65536 is Patched + +System-02 6.1.7601.65536 is Patched + +System-41 6.1.7601.65536 is Patched + +System-42 6.1.7601.65536 is Patched + +the issue I am having is that the resulting OS version is only of the local system and not the remote systems. + +I know this because it is being run from a Win 7 box against a long list of Server and only server OS which are different OS version numbers then what is showing up in the results. + +what am I missing here. can you all help me tweak this to make it work against remote systems? + +thanks",2017/09/01,"['https://Stackoverflow.com/questions/46006705', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1232402/']","(1) When you make a change to checkbox you need to check all checkboxes and update to textarea. + +(2) function `updateAllChecked` will handle all the check and update. + +(3) for check all, if it is checked, set all email checkboxes to checked and call `.change()` to trigger the change event. + +```js +$(""input[name=email]"").change(function() { + updateAllChecked(); +}); + +$(""input[name=addall]"").change(function() { + if (this.checked) { + $(""input[name=email]"").prop('checked', true).change(); + } else { + $(""input[name=email]"").prop('checked', false).change(); + } +}); + +function updateAllChecked() { + $('#recipients').text(''); + $(""input[name=email]"").each(function() { + if (this.checked) { + let old_text = $('#recipients').text() ? $('#recipients').text() + ', ' : ''; + $('#recipients').text(old_text + $(this).val()); + } + }) +} +``` + +```html + + +email_1
+email_2
+email_3
+email_4
+
+Add All Email
+ + +```","Hi guys here is my html and php, I retrieve recipients email from db: + +``` +here is my html with php, I retrieve recipients email from db.: +
+ + + + + + + + + + + +
Sl. No.Applicant's NameJob TitleApply DateCover Letter
email;?>"" name=""email"" id=""email"">custom_encryption->encrypt_data($row_applied_job->job_seeker_ID));?>"">first_name.' '.$row_applied_job->last_name;?>job_slug);?>"">job_title;?> applied_date, 'M d, Y');?>c_letter;?>
+
+
 No application received
+ + +``` + +here is another portion for textarea: + +``` + + +```" +14695580,"I have a solution with two projects in it. A portable areas project, and a web site that references the portable areas project, and Both reference MvcContrib. + +The problem I am have is with the embedded resources, they are giving me a 404 error when I try to get to them. It seems like it's trying to access a physical path not the dll. The partial view works fine. + +The file I'm trying to access looks like this inside my visual studio solution explorer + +AdHocReporting/Areas/AdHocReportBuilder/Content/adhoc.css (the build action is embedded) + +**Here is the routing for the portable area:** + +``` +using System.Web.Mvc; +using MvcContrib.PortableAreas; + +namespace AdHocReporting.Areas.AdHocReportBuilder +{ + public class AdHocReportBuilderAreaRegistration : PortableAreaRegistration + { + public override string AreaName + { + get { return ""AdHocReportBuilder""; } + } + + public override void RegisterArea(AreaRegistrationContext context, IApplicationBus bus) + { + RegisterRoutes(context); + RegisterAreaEmbeddedResources(); + + } + private void RegisterRoutes(AreaRegistrationContext context) + { + context.MapRoute( + AreaName + ""_content"", + base.AreaRoutePrefix + ""/Content/{resourceName}"", + new { controller = ""EmbeddedResource"", action = ""Index"", resourcePath = ""Content"" }, + new[] { ""MvcContrib.PortableAreas"" } + ); + + context.MapRoute( + AreaName + ""_default"", + base.AreaRoutePrefix + ""/{controller}/{action}/{id}"", + new { action = ""Index"", id = UrlParameter.Optional } + ); + } + } +} + +``` + +**Here is the Web sites Global.aspx that has the reference to the portable area** + +``` +namespace AdHocReportingSite +{ + public class MvcApplication : System.Web.HttpApplication + { + public static void RegisterGlobalFilters(GlobalFilterCollection filters) + { + filters.Add(new HandleErrorAttribute()); + } + + public static void RegisterRoutes(RouteCollection routes) + { + routes.IgnoreRoute(""{resource}.axd/{*pathInfo}""); + routes.MapRoute( + ""Default"", // Route name + ""{controller}/{action}/{id}"", // URL with parameters + new { controller = ""Home"", action = ""Index"", id = UrlParameter.Optional } // Parameter defaults + ); + + } + protected void Application_Start() + { + AreaRegistration.RegisterAllAreas(); + PortableAreaRegistration.RegisterEmbeddedViewEngine(); + FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); + RouteConfig.RegisterRoutes(RouteTable.Routes); + } + } +} + +``` + +**here is an image of what my solution explore looks like:** + +![Solution Explorer](https://i.stack.imgur.com/6P0TK.png)",2013/02/04,"['https://Stackoverflow.com/questions/14695580', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/937294/']","See below for my original answer - that pattern has worked well, but recently I've started using a different approach to Service/Activity communication: + +* Use a [bound service](https://developer.android.com/guide/components/bound-services.html) which enables the Activity to get a direct +reference to the Service, thus allowing direct calls on it, rather +than using Intents. +* Use RxJava to execute asynchronous operations. +* If the Service needs to continue background operations even when no +Activity is running, also start the service from the Application +class so that it does not get stopped when unbound. + +The advantages I have found in this approach compared to the startService()/LocalBroadcast technique are + +* No need for data objects to implement Parcelable - this is particularly important to me as I am now sharing code between Android and iOS (using RoboVM) +* RxJava provides canned (and cross-platform) scheduling, and easy composition of sequential asynchronous operations. +* This should be more efficient than using a LocalBroadcast, though the overhead of using RxJava may outweigh that. + +Some example code. First the service: + +``` +public class AndroidBmService extends Service implements BmService { + + private static final int PRESSURE_RATE = 500000; // microseconds between pressure updates + private SensorManager sensorManager; + private SensorEventListener pressureListener; + private ObservableEmitter pressureObserver; + private Observable pressureObservable; + + public class LocalBinder extends Binder { + public AndroidBmService getService() { + return AndroidBmService.this; + } + } + + private IBinder binder = new LocalBinder(); + + @Nullable + @Override + public IBinder onBind(Intent intent) { + logMsg(""Service bound""); + return binder; + } + + @Override + public int onStartCommand(Intent intent, int flags, int startId) { + return START_NOT_STICKY; + } + + @Override + public void onCreate() { + super.onCreate(); + + sensorManager = (SensorManager)getSystemService(SENSOR_SERVICE); + Sensor pressureSensor = sensorManager.getDefaultSensor(Sensor.TYPE_PRESSURE); + if(pressureSensor != null) + sensorManager.registerListener(pressureListener = new SensorEventListener() { + @Override + public void onSensorChanged(SensorEvent event) { + if(pressureObserver != null) { + float lastPressure = event.values[0]; + float lastPressureAltitude = (float)((1 - Math.pow(lastPressure / 1013.25, 0.190284)) * 145366.45); + pressureObserver.onNext(lastPressureAltitude); + } + } + + @Override + public void onAccuracyChanged(Sensor sensor, int accuracy) { + + } + }, pressureSensor, PRESSURE_RATE); + } + + @Override + public Observable observePressure() { + if(pressureObservable == null) { + pressureObservable = Observable.create(emitter -> pressureObserver = emitter); + pressureObservable = pressureObservable.share(); + } + return pressureObservable; + } + + @Override + public void onDestroy() { + if(pressureListener != null) + sensorManager.unregisterListener(pressureListener); + } +} + +``` + +And an Activity that binds to the service and receives pressure altitude updates: + +``` +public class TestActivity extends AppCompatActivity { + + private ContentTestBinding binding; + private ServiceConnection serviceConnection; + private AndroidBmService service; + private Disposable disposable; + + @Override + protected void onDestroy() { + if(disposable != null) + disposable.dispose(); + unbindService(serviceConnection); + super.onDestroy(); + } + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + binding = DataBindingUtil.setContentView(this, R.layout.content_test); + serviceConnection = new ServiceConnection() { + @Override + public void onServiceConnected(ComponentName componentName, IBinder iBinder) { + logMsg(""BlueMAX service bound""); + service = ((AndroidBmService.LocalBinder)iBinder).getService(); + disposable = service.observePressure() + .observeOn(AndroidSchedulers.mainThread()) + .subscribe(altitude -> + binding.altitude.setText( + String.format(Locale.US, + ""Pressure Altitude %d feet"", + altitude.intValue()))); + } + + @Override + public void onServiceDisconnected(ComponentName componentName) { + logMsg(""Service disconnected""); + } + }; + bindService(new Intent( + this, AndroidBmService.class), + serviceConnection, BIND_AUTO_CREATE); + } +} + +``` + +The layout for this Activity is: + +``` + + + + + + + + + +``` + +If the service needs to run in the background without a bound Activity it can be started from the Application class as well in `OnCreate()` using [`Context#startService()`](https://developer.android.com/reference/android/content/Context.html#startService(android.content.Intent)). + +--- + +**My Original Answer (from 2013):** + +**In your service:** (using COPA as service in example below). + +Use a LocalBroadCastManager. In your service's onCreate, set up the broadcaster: + +``` +broadcaster = LocalBroadcastManager.getInstance(this); + +``` + +When you want to notify the UI of something: + +``` +static final public String COPA_RESULT = ""com.controlj.copame.backend.COPAService.REQUEST_PROCESSED""; + +static final public String COPA_MESSAGE = ""com.controlj.copame.backend.COPAService.COPA_MSG""; + +public void sendResult(String message) { + Intent intent = new Intent(COPA_RESULT); + if(message != null) + intent.putExtra(COPA_MESSAGE, message); + broadcaster.sendBroadcast(intent); +} + +``` + +**In your Activity:** + +Create a listener on onCreate: + +``` +public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + super.setContentView(R.layout.copa); + receiver = new BroadcastReceiver() { + @Override + public void onReceive(Context context, Intent intent) { + String s = intent.getStringExtra(COPAService.COPA_MESSAGE); + // do something here. + } + }; +} + +``` + +and register it in onStart: + +``` +@Override +protected void onStart() { + super.onStart(); + LocalBroadcastManager.getInstance(this).registerReceiver((receiver), + new IntentFilter(COPAService.COPA_RESULT) + ); +} + +@Override +protected void onStop() { + LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver); + super.onStop(); +} + +```","My solution might not be the cleanest but it should work with no problems. +The logic is simply to create a static variable to store your data on the `Service` and update your view each second on your `Activity`. + +Let's say that you have a `String` on your `Service` that you want to send it to a `TextView` on your `Activity`. It should look like this + +Your Service: + +``` +public class TestService extends Service { + public static String myString = """"; + // Do some stuff with myString + +``` + +Your Activty: + +``` +public class TestActivity extends Activity { + TextView tv; + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + tv = new TextView(this); + setContentView(tv); + update(); + Thread t = new Thread() { + @Override + public void run() { + try { + while (!isInterrupted()) { + Thread.sleep(1000); + runOnUiThread(new Runnable() { + @Override + public void run() { + update(); + } + }); + } + } catch (InterruptedException ignored) {} + } + }; + t.start(); + startService(new Intent(this, TestService.class)); + } + private void update() { + // update your interface here + tv.setText(TestService.myString); + } +} + +```" +14695580,"I have a solution with two projects in it. A portable areas project, and a web site that references the portable areas project, and Both reference MvcContrib. + +The problem I am have is with the embedded resources, they are giving me a 404 error when I try to get to them. It seems like it's trying to access a physical path not the dll. The partial view works fine. + +The file I'm trying to access looks like this inside my visual studio solution explorer + +AdHocReporting/Areas/AdHocReportBuilder/Content/adhoc.css (the build action is embedded) + +**Here is the routing for the portable area:** + +``` +using System.Web.Mvc; +using MvcContrib.PortableAreas; + +namespace AdHocReporting.Areas.AdHocReportBuilder +{ + public class AdHocReportBuilderAreaRegistration : PortableAreaRegistration + { + public override string AreaName + { + get { return ""AdHocReportBuilder""; } + } + + public override void RegisterArea(AreaRegistrationContext context, IApplicationBus bus) + { + RegisterRoutes(context); + RegisterAreaEmbeddedResources(); + + } + private void RegisterRoutes(AreaRegistrationContext context) + { + context.MapRoute( + AreaName + ""_content"", + base.AreaRoutePrefix + ""/Content/{resourceName}"", + new { controller = ""EmbeddedResource"", action = ""Index"", resourcePath = ""Content"" }, + new[] { ""MvcContrib.PortableAreas"" } + ); + + context.MapRoute( + AreaName + ""_default"", + base.AreaRoutePrefix + ""/{controller}/{action}/{id}"", + new { action = ""Index"", id = UrlParameter.Optional } + ); + } + } +} + +``` + +**Here is the Web sites Global.aspx that has the reference to the portable area** + +``` +namespace AdHocReportingSite +{ + public class MvcApplication : System.Web.HttpApplication + { + public static void RegisterGlobalFilters(GlobalFilterCollection filters) + { + filters.Add(new HandleErrorAttribute()); + } + + public static void RegisterRoutes(RouteCollection routes) + { + routes.IgnoreRoute(""{resource}.axd/{*pathInfo}""); + routes.MapRoute( + ""Default"", // Route name + ""{controller}/{action}/{id}"", // URL with parameters + new { controller = ""Home"", action = ""Index"", id = UrlParameter.Optional } // Parameter defaults + ); + + } + protected void Application_Start() + { + AreaRegistration.RegisterAllAreas(); + PortableAreaRegistration.RegisterEmbeddedViewEngine(); + FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); + RouteConfig.RegisterRoutes(RouteTable.Routes); + } + } +} + +``` + +**here is an image of what my solution explore looks like:** + +![Solution Explorer](https://i.stack.imgur.com/6P0TK.png)",2013/02/04,"['https://Stackoverflow.com/questions/14695580', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/937294/']","See below for my original answer - that pattern has worked well, but recently I've started using a different approach to Service/Activity communication: + +* Use a [bound service](https://developer.android.com/guide/components/bound-services.html) which enables the Activity to get a direct +reference to the Service, thus allowing direct calls on it, rather +than using Intents. +* Use RxJava to execute asynchronous operations. +* If the Service needs to continue background operations even when no +Activity is running, also start the service from the Application +class so that it does not get stopped when unbound. + +The advantages I have found in this approach compared to the startService()/LocalBroadcast technique are + +* No need for data objects to implement Parcelable - this is particularly important to me as I am now sharing code between Android and iOS (using RoboVM) +* RxJava provides canned (and cross-platform) scheduling, and easy composition of sequential asynchronous operations. +* This should be more efficient than using a LocalBroadcast, though the overhead of using RxJava may outweigh that. + +Some example code. First the service: + +``` +public class AndroidBmService extends Service implements BmService { + + private static final int PRESSURE_RATE = 500000; // microseconds between pressure updates + private SensorManager sensorManager; + private SensorEventListener pressureListener; + private ObservableEmitter pressureObserver; + private Observable pressureObservable; + + public class LocalBinder extends Binder { + public AndroidBmService getService() { + return AndroidBmService.this; + } + } + + private IBinder binder = new LocalBinder(); + + @Nullable + @Override + public IBinder onBind(Intent intent) { + logMsg(""Service bound""); + return binder; + } + + @Override + public int onStartCommand(Intent intent, int flags, int startId) { + return START_NOT_STICKY; + } + + @Override + public void onCreate() { + super.onCreate(); + + sensorManager = (SensorManager)getSystemService(SENSOR_SERVICE); + Sensor pressureSensor = sensorManager.getDefaultSensor(Sensor.TYPE_PRESSURE); + if(pressureSensor != null) + sensorManager.registerListener(pressureListener = new SensorEventListener() { + @Override + public void onSensorChanged(SensorEvent event) { + if(pressureObserver != null) { + float lastPressure = event.values[0]; + float lastPressureAltitude = (float)((1 - Math.pow(lastPressure / 1013.25, 0.190284)) * 145366.45); + pressureObserver.onNext(lastPressureAltitude); + } + } + + @Override + public void onAccuracyChanged(Sensor sensor, int accuracy) { + + } + }, pressureSensor, PRESSURE_RATE); + } + + @Override + public Observable observePressure() { + if(pressureObservable == null) { + pressureObservable = Observable.create(emitter -> pressureObserver = emitter); + pressureObservable = pressureObservable.share(); + } + return pressureObservable; + } + + @Override + public void onDestroy() { + if(pressureListener != null) + sensorManager.unregisterListener(pressureListener); + } +} + +``` + +And an Activity that binds to the service and receives pressure altitude updates: + +``` +public class TestActivity extends AppCompatActivity { + + private ContentTestBinding binding; + private ServiceConnection serviceConnection; + private AndroidBmService service; + private Disposable disposable; + + @Override + protected void onDestroy() { + if(disposable != null) + disposable.dispose(); + unbindService(serviceConnection); + super.onDestroy(); + } + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + binding = DataBindingUtil.setContentView(this, R.layout.content_test); + serviceConnection = new ServiceConnection() { + @Override + public void onServiceConnected(ComponentName componentName, IBinder iBinder) { + logMsg(""BlueMAX service bound""); + service = ((AndroidBmService.LocalBinder)iBinder).getService(); + disposable = service.observePressure() + .observeOn(AndroidSchedulers.mainThread()) + .subscribe(altitude -> + binding.altitude.setText( + String.format(Locale.US, + ""Pressure Altitude %d feet"", + altitude.intValue()))); + } + + @Override + public void onServiceDisconnected(ComponentName componentName) { + logMsg(""Service disconnected""); + } + }; + bindService(new Intent( + this, AndroidBmService.class), + serviceConnection, BIND_AUTO_CREATE); + } +} + +``` + +The layout for this Activity is: + +``` + + + + + + + + + +``` + +If the service needs to run in the background without a bound Activity it can be started from the Application class as well in `OnCreate()` using [`Context#startService()`](https://developer.android.com/reference/android/content/Context.html#startService(android.content.Intent)). + +--- + +**My Original Answer (from 2013):** + +**In your service:** (using COPA as service in example below). + +Use a LocalBroadCastManager. In your service's onCreate, set up the broadcaster: + +``` +broadcaster = LocalBroadcastManager.getInstance(this); + +``` + +When you want to notify the UI of something: + +``` +static final public String COPA_RESULT = ""com.controlj.copame.backend.COPAService.REQUEST_PROCESSED""; + +static final public String COPA_MESSAGE = ""com.controlj.copame.backend.COPAService.COPA_MSG""; + +public void sendResult(String message) { + Intent intent = new Intent(COPA_RESULT); + if(message != null) + intent.putExtra(COPA_MESSAGE, message); + broadcaster.sendBroadcast(intent); +} + +``` + +**In your Activity:** + +Create a listener on onCreate: + +``` +public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + super.setContentView(R.layout.copa); + receiver = new BroadcastReceiver() { + @Override + public void onReceive(Context context, Intent intent) { + String s = intent.getStringExtra(COPAService.COPA_MESSAGE); + // do something here. + } + }; +} + +``` + +and register it in onStart: + +``` +@Override +protected void onStart() { + super.onStart(); + LocalBroadcastManager.getInstance(this).registerReceiver((receiver), + new IntentFilter(COPAService.COPA_RESULT) + ); +} + +@Override +protected void onStop() { + LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver); + super.onStop(); +} + +```","I would use a [bound service](http://developer.android.com/guide/components/bound-services.html) to do that and communicate with it by implementing a listener in my activity. So if your app implements myServiceListener, you can register it as a listener in your service after you have bound with it, call listener.onUpdateUI from your bound service and update your UI in there!" +14695580,"I have a solution with two projects in it. A portable areas project, and a web site that references the portable areas project, and Both reference MvcContrib. + +The problem I am have is with the embedded resources, they are giving me a 404 error when I try to get to them. It seems like it's trying to access a physical path not the dll. The partial view works fine. + +The file I'm trying to access looks like this inside my visual studio solution explorer + +AdHocReporting/Areas/AdHocReportBuilder/Content/adhoc.css (the build action is embedded) + +**Here is the routing for the portable area:** + +``` +using System.Web.Mvc; +using MvcContrib.PortableAreas; + +namespace AdHocReporting.Areas.AdHocReportBuilder +{ + public class AdHocReportBuilderAreaRegistration : PortableAreaRegistration + { + public override string AreaName + { + get { return ""AdHocReportBuilder""; } + } + + public override void RegisterArea(AreaRegistrationContext context, IApplicationBus bus) + { + RegisterRoutes(context); + RegisterAreaEmbeddedResources(); + + } + private void RegisterRoutes(AreaRegistrationContext context) + { + context.MapRoute( + AreaName + ""_content"", + base.AreaRoutePrefix + ""/Content/{resourceName}"", + new { controller = ""EmbeddedResource"", action = ""Index"", resourcePath = ""Content"" }, + new[] { ""MvcContrib.PortableAreas"" } + ); + + context.MapRoute( + AreaName + ""_default"", + base.AreaRoutePrefix + ""/{controller}/{action}/{id}"", + new { action = ""Index"", id = UrlParameter.Optional } + ); + } + } +} + +``` + +**Here is the Web sites Global.aspx that has the reference to the portable area** + +``` +namespace AdHocReportingSite +{ + public class MvcApplication : System.Web.HttpApplication + { + public static void RegisterGlobalFilters(GlobalFilterCollection filters) + { + filters.Add(new HandleErrorAttribute()); + } + + public static void RegisterRoutes(RouteCollection routes) + { + routes.IgnoreRoute(""{resource}.axd/{*pathInfo}""); + routes.MapRoute( + ""Default"", // Route name + ""{controller}/{action}/{id}"", // URL with parameters + new { controller = ""Home"", action = ""Index"", id = UrlParameter.Optional } // Parameter defaults + ); + + } + protected void Application_Start() + { + AreaRegistration.RegisterAllAreas(); + PortableAreaRegistration.RegisterEmbeddedViewEngine(); + FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); + RouteConfig.RegisterRoutes(RouteTable.Routes); + } + } +} + +``` + +**here is an image of what my solution explore looks like:** + +![Solution Explorer](https://i.stack.imgur.com/6P0TK.png)",2013/02/04,"['https://Stackoverflow.com/questions/14695580', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/937294/']","``` +Callback from service to activity to update UI. +ResultReceiver receiver = new ResultReceiver(new Handler()) { + protected void onReceiveResult(int resultCode, Bundle resultData) { + //process results or update UI + } +} + +Intent instructionServiceIntent = new Intent(context, InstructionService.class); +instructionServiceIntent.putExtra(""receiver"", receiver); +context.startService(instructionServiceIntent); + +```","My solution might not be the cleanest but it should work with no problems. +The logic is simply to create a static variable to store your data on the `Service` and update your view each second on your `Activity`. + +Let's say that you have a `String` on your `Service` that you want to send it to a `TextView` on your `Activity`. It should look like this + +Your Service: + +``` +public class TestService extends Service { + public static String myString = """"; + // Do some stuff with myString + +``` + +Your Activty: + +``` +public class TestActivity extends Activity { + TextView tv; + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + tv = new TextView(this); + setContentView(tv); + update(); + Thread t = new Thread() { + @Override + public void run() { + try { + while (!isInterrupted()) { + Thread.sleep(1000); + runOnUiThread(new Runnable() { + @Override + public void run() { + update(); + } + }); + } + } catch (InterruptedException ignored) {} + } + }; + t.start(); + startService(new Intent(this, TestService.class)); + } + private void update() { + // update your interface here + tv.setText(TestService.myString); + } +} + +```" +14695580,"I have a solution with two projects in it. A portable areas project, and a web site that references the portable areas project, and Both reference MvcContrib. + +The problem I am have is with the embedded resources, they are giving me a 404 error when I try to get to them. It seems like it's trying to access a physical path not the dll. The partial view works fine. + +The file I'm trying to access looks like this inside my visual studio solution explorer + +AdHocReporting/Areas/AdHocReportBuilder/Content/adhoc.css (the build action is embedded) + +**Here is the routing for the portable area:** + +``` +using System.Web.Mvc; +using MvcContrib.PortableAreas; + +namespace AdHocReporting.Areas.AdHocReportBuilder +{ + public class AdHocReportBuilderAreaRegistration : PortableAreaRegistration + { + public override string AreaName + { + get { return ""AdHocReportBuilder""; } + } + + public override void RegisterArea(AreaRegistrationContext context, IApplicationBus bus) + { + RegisterRoutes(context); + RegisterAreaEmbeddedResources(); + + } + private void RegisterRoutes(AreaRegistrationContext context) + { + context.MapRoute( + AreaName + ""_content"", + base.AreaRoutePrefix + ""/Content/{resourceName}"", + new { controller = ""EmbeddedResource"", action = ""Index"", resourcePath = ""Content"" }, + new[] { ""MvcContrib.PortableAreas"" } + ); + + context.MapRoute( + AreaName + ""_default"", + base.AreaRoutePrefix + ""/{controller}/{action}/{id}"", + new { action = ""Index"", id = UrlParameter.Optional } + ); + } + } +} + +``` + +**Here is the Web sites Global.aspx that has the reference to the portable area** + +``` +namespace AdHocReportingSite +{ + public class MvcApplication : System.Web.HttpApplication + { + public static void RegisterGlobalFilters(GlobalFilterCollection filters) + { + filters.Add(new HandleErrorAttribute()); + } + + public static void RegisterRoutes(RouteCollection routes) + { + routes.IgnoreRoute(""{resource}.axd/{*pathInfo}""); + routes.MapRoute( + ""Default"", // Route name + ""{controller}/{action}/{id}"", // URL with parameters + new { controller = ""Home"", action = ""Index"", id = UrlParameter.Optional } // Parameter defaults + ); + + } + protected void Application_Start() + { + AreaRegistration.RegisterAllAreas(); + PortableAreaRegistration.RegisterEmbeddedViewEngine(); + FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); + RouteConfig.RegisterRoutes(RouteTable.Routes); + } + } +} + +``` + +**here is an image of what my solution explore looks like:** + +![Solution Explorer](https://i.stack.imgur.com/6P0TK.png)",2013/02/04,"['https://Stackoverflow.com/questions/14695580', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/937294/']","for me the simplest solution was to send a broadcast, in the activity oncreate i registered and defined the broadcast like this (updateUIReciver is defined as a class instance) : + +``` + IntentFilter filter = new IntentFilter(); + + filter.addAction(""com.hello.action""); + + updateUIReciver = new BroadcastReceiver() { + + @Override + public void onReceive(Context context, Intent intent) { + //UI update here + + } + }; + registerReceiver(updateUIReciver,filter); + +``` + +And from the service you send the intent like this: + +``` +Intent local = new Intent(); + +local.setAction(""com.hello.action""); + +this.sendBroadcast(local); + +``` + +don't forget to unregister the recover in the activity on destroy : + +``` +unregisterReceiver(updateUIReciver); + +```","My solution might not be the cleanest but it should work with no problems. +The logic is simply to create a static variable to store your data on the `Service` and update your view each second on your `Activity`. + +Let's say that you have a `String` on your `Service` that you want to send it to a `TextView` on your `Activity`. It should look like this + +Your Service: + +``` +public class TestService extends Service { + public static String myString = """"; + // Do some stuff with myString + +``` + +Your Activty: + +``` +public class TestActivity extends Activity { + TextView tv; + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + tv = new TextView(this); + setContentView(tv); + update(); + Thread t = new Thread() { + @Override + public void run() { + try { + while (!isInterrupted()) { + Thread.sleep(1000); + runOnUiThread(new Runnable() { + @Override + public void run() { + update(); + } + }); + } + } catch (InterruptedException ignored) {} + } + }; + t.start(); + startService(new Intent(this, TestService.class)); + } + private void update() { + // update your interface here + tv.setText(TestService.myString); + } +} + +```" +14695580,"I have a solution with two projects in it. A portable areas project, and a web site that references the portable areas project, and Both reference MvcContrib. + +The problem I am have is with the embedded resources, they are giving me a 404 error when I try to get to them. It seems like it's trying to access a physical path not the dll. The partial view works fine. + +The file I'm trying to access looks like this inside my visual studio solution explorer + +AdHocReporting/Areas/AdHocReportBuilder/Content/adhoc.css (the build action is embedded) + +**Here is the routing for the portable area:** + +``` +using System.Web.Mvc; +using MvcContrib.PortableAreas; + +namespace AdHocReporting.Areas.AdHocReportBuilder +{ + public class AdHocReportBuilderAreaRegistration : PortableAreaRegistration + { + public override string AreaName + { + get { return ""AdHocReportBuilder""; } + } + + public override void RegisterArea(AreaRegistrationContext context, IApplicationBus bus) + { + RegisterRoutes(context); + RegisterAreaEmbeddedResources(); + + } + private void RegisterRoutes(AreaRegistrationContext context) + { + context.MapRoute( + AreaName + ""_content"", + base.AreaRoutePrefix + ""/Content/{resourceName}"", + new { controller = ""EmbeddedResource"", action = ""Index"", resourcePath = ""Content"" }, + new[] { ""MvcContrib.PortableAreas"" } + ); + + context.MapRoute( + AreaName + ""_default"", + base.AreaRoutePrefix + ""/{controller}/{action}/{id}"", + new { action = ""Index"", id = UrlParameter.Optional } + ); + } + } +} + +``` + +**Here is the Web sites Global.aspx that has the reference to the portable area** + +``` +namespace AdHocReportingSite +{ + public class MvcApplication : System.Web.HttpApplication + { + public static void RegisterGlobalFilters(GlobalFilterCollection filters) + { + filters.Add(new HandleErrorAttribute()); + } + + public static void RegisterRoutes(RouteCollection routes) + { + routes.IgnoreRoute(""{resource}.axd/{*pathInfo}""); + routes.MapRoute( + ""Default"", // Route name + ""{controller}/{action}/{id}"", // URL with parameters + new { controller = ""Home"", action = ""Index"", id = UrlParameter.Optional } // Parameter defaults + ); + + } + protected void Application_Start() + { + AreaRegistration.RegisterAllAreas(); + PortableAreaRegistration.RegisterEmbeddedViewEngine(); + FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); + RouteConfig.RegisterRoutes(RouteTable.Routes); + } + } +} + +``` + +**here is an image of what my solution explore looks like:** + +![Solution Explorer](https://i.stack.imgur.com/6P0TK.png)",2013/02/04,"['https://Stackoverflow.com/questions/14695580', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/937294/']","I would use a [bound service](http://developer.android.com/guide/components/bound-services.html) to do that and communicate with it by implementing a listener in my activity. So if your app implements myServiceListener, you can register it as a listener in your service after you have bound with it, call listener.onUpdateUI from your bound service and update your UI in there!","My solution might not be the cleanest but it should work with no problems. +The logic is simply to create a static variable to store your data on the `Service` and update your view each second on your `Activity`. + +Let's say that you have a `String` on your `Service` that you want to send it to a `TextView` on your `Activity`. It should look like this + +Your Service: + +``` +public class TestService extends Service { + public static String myString = """"; + // Do some stuff with myString + +``` + +Your Activty: + +``` +public class TestActivity extends Activity { + TextView tv; + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + tv = new TextView(this); + setContentView(tv); + update(); + Thread t = new Thread() { + @Override + public void run() { + try { + while (!isInterrupted()) { + Thread.sleep(1000); + runOnUiThread(new Runnable() { + @Override + public void run() { + update(); + } + }); + } + } catch (InterruptedException ignored) {} + } + }; + t.start(); + startService(new Intent(this, TestService.class)); + } + private void update() { + // update your interface here + tv.setText(TestService.myString); + } +} + +```" +14695580,"I have a solution with two projects in it. A portable areas project, and a web site that references the portable areas project, and Both reference MvcContrib. + +The problem I am have is with the embedded resources, they are giving me a 404 error when I try to get to them. It seems like it's trying to access a physical path not the dll. The partial view works fine. + +The file I'm trying to access looks like this inside my visual studio solution explorer + +AdHocReporting/Areas/AdHocReportBuilder/Content/adhoc.css (the build action is embedded) + +**Here is the routing for the portable area:** + +``` +using System.Web.Mvc; +using MvcContrib.PortableAreas; + +namespace AdHocReporting.Areas.AdHocReportBuilder +{ + public class AdHocReportBuilderAreaRegistration : PortableAreaRegistration + { + public override string AreaName + { + get { return ""AdHocReportBuilder""; } + } + + public override void RegisterArea(AreaRegistrationContext context, IApplicationBus bus) + { + RegisterRoutes(context); + RegisterAreaEmbeddedResources(); + + } + private void RegisterRoutes(AreaRegistrationContext context) + { + context.MapRoute( + AreaName + ""_content"", + base.AreaRoutePrefix + ""/Content/{resourceName}"", + new { controller = ""EmbeddedResource"", action = ""Index"", resourcePath = ""Content"" }, + new[] { ""MvcContrib.PortableAreas"" } + ); + + context.MapRoute( + AreaName + ""_default"", + base.AreaRoutePrefix + ""/{controller}/{action}/{id}"", + new { action = ""Index"", id = UrlParameter.Optional } + ); + } + } +} + +``` + +**Here is the Web sites Global.aspx that has the reference to the portable area** + +``` +namespace AdHocReportingSite +{ + public class MvcApplication : System.Web.HttpApplication + { + public static void RegisterGlobalFilters(GlobalFilterCollection filters) + { + filters.Add(new HandleErrorAttribute()); + } + + public static void RegisterRoutes(RouteCollection routes) + { + routes.IgnoreRoute(""{resource}.axd/{*pathInfo}""); + routes.MapRoute( + ""Default"", // Route name + ""{controller}/{action}/{id}"", // URL with parameters + new { controller = ""Home"", action = ""Index"", id = UrlParameter.Optional } // Parameter defaults + ); + + } + protected void Application_Start() + { + AreaRegistration.RegisterAllAreas(); + PortableAreaRegistration.RegisterEmbeddedViewEngine(); + FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); + RouteConfig.RegisterRoutes(RouteTable.Routes); + } + } +} + +``` + +**here is an image of what my solution explore looks like:** + +![Solution Explorer](https://i.stack.imgur.com/6P0TK.png)",2013/02/04,"['https://Stackoverflow.com/questions/14695580', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/937294/']","Clyde's solution works, but it is a broadcast, which I am pretty sure will be less efficient than calling a method directly. I could be mistaken, but I think the broadcasts are meant more for inter-application communication. + +I'm assuming you already know how to bind a service with an Activity. +I do something sort of like the code below to handle this kind of problem: + +``` +class MyService extends Service { + MyFragment mMyFragment = null; + MyFragment mMyOtherFragment = null; + + private void networkLoop() { + ... + + //received new data for list. + if(myFragment != null) + myFragment.updateList(); + } + + ... + + //received new data for textView + if(myFragment !=null) + myFragment.updateText(); + + ... + + //received new data for textView + if(myOtherFragment !=null) + myOtherFragment.updateSomething(); + + ... + } +} + +class MyFragment extends Fragment { + + public void onResume() { + super.onResume() + //Assuming your activity bound to your service + getActivity().mMyService.mMyFragment=this; + } + + public void onPause() { + super.onPause() + //Assuming your activity bound to your service + getActivity().mMyService.mMyFragment=null; + } + + public void updateList() { + runOnUiThread(new Runnable() { + public void run() { + //Update the list. + } + }); + } + + public void updateText() { + //as above + } +} + +class MyOtherFragment extends Fragment { + public void onResume() { + super.onResume() + //Assuming your activity bound to your service + getActivity().mMyService.mMyOtherFragment=this; + } + + public void onPause() { + super.onPause() + //Assuming your activity bound to your service + getActivity().mMyService.mMyOtherFragment=null; + } + + public void updateSomething() {//etc... } +} + +``` + +I left out bits for thread safety, which is essential. Make sure to use locks or something like that when checking and using or changing the fragment references on the service.","You could use android Jetpack's [LiveData](https://developer.android.com/topic/libraries/architecture/livedata) + +As per the documentation: + +> +> You can extend a `LiveData` object using the singleton pattern to wrap +> system services so that they can be shared in your app. The LiveData +> object connects to the system service once, and then any observer that +> needs the resource can just watch the LiveData object. For more +> information, see [Extend +> LiveData](https://developer.android.com/topic/libraries/architecture/livedata?hl=en#extend_livedata). +> +> +> + +Below is what I did for communication between Service and Activity and also Service and Fragment. + +In this example, I have: + +* a class `SyncLogLiveData` extending `LiveData` that contains a `SpannableStringBuilder` +* a service `SyncService` +* a fragment `SyncFragment` + +The Fragment ""observes"" the LiveData (ie SyncLogLiveData) and performs an action when the LiveData changes. + +The LiveData is updated by the Service. + +I could also update the LiveData from the Fragment in the same way but don't show it here. + +**class `SyncLogLiveData`** + +```java +public class SyncLogLiveData extends LiveData { + private static SyncLogLiveData sInstance; + private final static SpannableStringBuilder log = new SpannableStringBuilder(""""); + + @MainThread + public static SyncLogLiveData get() { + if (sInstance == null) { + sInstance = new SyncLogLiveData(); + } + return sInstance; + } + + private SyncLogLiveData() { + } + + public void appendLog(String text) { + log.append(text); + postValue(log); + } + + public void appendLog(Spanned text) { + log.append(text); + postValue(log); + } +} + +``` + +**in class `SyncService`** + +This line of code will update the content of the LiveData + +```java +SyncLogLiveData.get().appendLog(message); + +``` + +You could also make direct use of `setValue(...)` or `postValue(...)` methods of `LiveData` + +```java +SyncLogLiveData.get().setValue(message); + +``` + +**class SyncFragment** + +```java +public void onViewCreated(@NonNull View view, Bundle savedInstanceState) { + + //... + + // Create the observer which updates the UI. + final Observer ETAObserver = new Observer() { + @Override + public void onChanged(@Nullable final SpannableStringBuilder spannableLog) { + // Update the UI, in this case, a TextView. + getActivity().runOnUiThread(new Runnable() { + @Override + public void run() { + textViewLog.setText(spannableLog); + } + }); + } + }; + // Observe the LiveData, passing in this activity/fragment as the LifecycleOwner and the observer. + SyncLogLiveData.get().observe(getViewLifecycleOwner(), ETAObserver); + + //... +} + +``` + +From within an activity it works the same way, but for `.observe(...)`, you may use this instead + +```java +SyncLogLiveData.get().observe(this, ETAObserver); + +``` + +You could also fetch the current value of the LiveData this way at anytime in your code. + +```java +SyncLogLiveData.get().getValue(); + +``` + +Hopefully this will help someone. There wasn't any mention of LiveData in this answer yet." +14695580,"I have a solution with two projects in it. A portable areas project, and a web site that references the portable areas project, and Both reference MvcContrib. + +The problem I am have is with the embedded resources, they are giving me a 404 error when I try to get to them. It seems like it's trying to access a physical path not the dll. The partial view works fine. + +The file I'm trying to access looks like this inside my visual studio solution explorer + +AdHocReporting/Areas/AdHocReportBuilder/Content/adhoc.css (the build action is embedded) + +**Here is the routing for the portable area:** + +``` +using System.Web.Mvc; +using MvcContrib.PortableAreas; + +namespace AdHocReporting.Areas.AdHocReportBuilder +{ + public class AdHocReportBuilderAreaRegistration : PortableAreaRegistration + { + public override string AreaName + { + get { return ""AdHocReportBuilder""; } + } + + public override void RegisterArea(AreaRegistrationContext context, IApplicationBus bus) + { + RegisterRoutes(context); + RegisterAreaEmbeddedResources(); + + } + private void RegisterRoutes(AreaRegistrationContext context) + { + context.MapRoute( + AreaName + ""_content"", + base.AreaRoutePrefix + ""/Content/{resourceName}"", + new { controller = ""EmbeddedResource"", action = ""Index"", resourcePath = ""Content"" }, + new[] { ""MvcContrib.PortableAreas"" } + ); + + context.MapRoute( + AreaName + ""_default"", + base.AreaRoutePrefix + ""/{controller}/{action}/{id}"", + new { action = ""Index"", id = UrlParameter.Optional } + ); + } + } +} + +``` + +**Here is the Web sites Global.aspx that has the reference to the portable area** + +``` +namespace AdHocReportingSite +{ + public class MvcApplication : System.Web.HttpApplication + { + public static void RegisterGlobalFilters(GlobalFilterCollection filters) + { + filters.Add(new HandleErrorAttribute()); + } + + public static void RegisterRoutes(RouteCollection routes) + { + routes.IgnoreRoute(""{resource}.axd/{*pathInfo}""); + routes.MapRoute( + ""Default"", // Route name + ""{controller}/{action}/{id}"", // URL with parameters + new { controller = ""Home"", action = ""Index"", id = UrlParameter.Optional } // Parameter defaults + ); + + } + protected void Application_Start() + { + AreaRegistration.RegisterAllAreas(); + PortableAreaRegistration.RegisterEmbeddedViewEngine(); + FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); + RouteConfig.RegisterRoutes(RouteTable.Routes); + } + } +} + +``` + +**here is an image of what my solution explore looks like:** + +![Solution Explorer](https://i.stack.imgur.com/6P0TK.png)",2013/02/04,"['https://Stackoverflow.com/questions/14695580', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/937294/']","See below for my original answer - that pattern has worked well, but recently I've started using a different approach to Service/Activity communication: + +* Use a [bound service](https://developer.android.com/guide/components/bound-services.html) which enables the Activity to get a direct +reference to the Service, thus allowing direct calls on it, rather +than using Intents. +* Use RxJava to execute asynchronous operations. +* If the Service needs to continue background operations even when no +Activity is running, also start the service from the Application +class so that it does not get stopped when unbound. + +The advantages I have found in this approach compared to the startService()/LocalBroadcast technique are + +* No need for data objects to implement Parcelable - this is particularly important to me as I am now sharing code between Android and iOS (using RoboVM) +* RxJava provides canned (and cross-platform) scheduling, and easy composition of sequential asynchronous operations. +* This should be more efficient than using a LocalBroadcast, though the overhead of using RxJava may outweigh that. + +Some example code. First the service: + +``` +public class AndroidBmService extends Service implements BmService { + + private static final int PRESSURE_RATE = 500000; // microseconds between pressure updates + private SensorManager sensorManager; + private SensorEventListener pressureListener; + private ObservableEmitter pressureObserver; + private Observable pressureObservable; + + public class LocalBinder extends Binder { + public AndroidBmService getService() { + return AndroidBmService.this; + } + } + + private IBinder binder = new LocalBinder(); + + @Nullable + @Override + public IBinder onBind(Intent intent) { + logMsg(""Service bound""); + return binder; + } + + @Override + public int onStartCommand(Intent intent, int flags, int startId) { + return START_NOT_STICKY; + } + + @Override + public void onCreate() { + super.onCreate(); + + sensorManager = (SensorManager)getSystemService(SENSOR_SERVICE); + Sensor pressureSensor = sensorManager.getDefaultSensor(Sensor.TYPE_PRESSURE); + if(pressureSensor != null) + sensorManager.registerListener(pressureListener = new SensorEventListener() { + @Override + public void onSensorChanged(SensorEvent event) { + if(pressureObserver != null) { + float lastPressure = event.values[0]; + float lastPressureAltitude = (float)((1 - Math.pow(lastPressure / 1013.25, 0.190284)) * 145366.45); + pressureObserver.onNext(lastPressureAltitude); + } + } + + @Override + public void onAccuracyChanged(Sensor sensor, int accuracy) { + + } + }, pressureSensor, PRESSURE_RATE); + } + + @Override + public Observable observePressure() { + if(pressureObservable == null) { + pressureObservable = Observable.create(emitter -> pressureObserver = emitter); + pressureObservable = pressureObservable.share(); + } + return pressureObservable; + } + + @Override + public void onDestroy() { + if(pressureListener != null) + sensorManager.unregisterListener(pressureListener); + } +} + +``` + +And an Activity that binds to the service and receives pressure altitude updates: + +``` +public class TestActivity extends AppCompatActivity { + + private ContentTestBinding binding; + private ServiceConnection serviceConnection; + private AndroidBmService service; + private Disposable disposable; + + @Override + protected void onDestroy() { + if(disposable != null) + disposable.dispose(); + unbindService(serviceConnection); + super.onDestroy(); + } + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + binding = DataBindingUtil.setContentView(this, R.layout.content_test); + serviceConnection = new ServiceConnection() { + @Override + public void onServiceConnected(ComponentName componentName, IBinder iBinder) { + logMsg(""BlueMAX service bound""); + service = ((AndroidBmService.LocalBinder)iBinder).getService(); + disposable = service.observePressure() + .observeOn(AndroidSchedulers.mainThread()) + .subscribe(altitude -> + binding.altitude.setText( + String.format(Locale.US, + ""Pressure Altitude %d feet"", + altitude.intValue()))); + } + + @Override + public void onServiceDisconnected(ComponentName componentName) { + logMsg(""Service disconnected""); + } + }; + bindService(new Intent( + this, AndroidBmService.class), + serviceConnection, BIND_AUTO_CREATE); + } +} + +``` + +The layout for this Activity is: + +``` + + + + + + + + + +``` + +If the service needs to run in the background without a bound Activity it can be started from the Application class as well in `OnCreate()` using [`Context#startService()`](https://developer.android.com/reference/android/content/Context.html#startService(android.content.Intent)). + +--- + +**My Original Answer (from 2013):** + +**In your service:** (using COPA as service in example below). + +Use a LocalBroadCastManager. In your service's onCreate, set up the broadcaster: + +``` +broadcaster = LocalBroadcastManager.getInstance(this); + +``` + +When you want to notify the UI of something: + +``` +static final public String COPA_RESULT = ""com.controlj.copame.backend.COPAService.REQUEST_PROCESSED""; + +static final public String COPA_MESSAGE = ""com.controlj.copame.backend.COPAService.COPA_MSG""; + +public void sendResult(String message) { + Intent intent = new Intent(COPA_RESULT); + if(message != null) + intent.putExtra(COPA_MESSAGE, message); + broadcaster.sendBroadcast(intent); +} + +``` + +**In your Activity:** + +Create a listener on onCreate: + +``` +public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + super.setContentView(R.layout.copa); + receiver = new BroadcastReceiver() { + @Override + public void onReceive(Context context, Intent intent) { + String s = intent.getStringExtra(COPAService.COPA_MESSAGE); + // do something here. + } + }; +} + +``` + +and register it in onStart: + +``` +@Override +protected void onStart() { + super.onStart(); + LocalBroadcastManager.getInstance(this).registerReceiver((receiver), + new IntentFilter(COPAService.COPA_RESULT) + ); +} + +@Override +protected void onStop() { + LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver); + super.onStop(); +} + +```","You could use android Jetpack's [LiveData](https://developer.android.com/topic/libraries/architecture/livedata) + +As per the documentation: + +> +> You can extend a `LiveData` object using the singleton pattern to wrap +> system services so that they can be shared in your app. The LiveData +> object connects to the system service once, and then any observer that +> needs the resource can just watch the LiveData object. For more +> information, see [Extend +> LiveData](https://developer.android.com/topic/libraries/architecture/livedata?hl=en#extend_livedata). +> +> +> + +Below is what I did for communication between Service and Activity and also Service and Fragment. + +In this example, I have: + +* a class `SyncLogLiveData` extending `LiveData` that contains a `SpannableStringBuilder` +* a service `SyncService` +* a fragment `SyncFragment` + +The Fragment ""observes"" the LiveData (ie SyncLogLiveData) and performs an action when the LiveData changes. + +The LiveData is updated by the Service. + +I could also update the LiveData from the Fragment in the same way but don't show it here. + +**class `SyncLogLiveData`** + +```java +public class SyncLogLiveData extends LiveData { + private static SyncLogLiveData sInstance; + private final static SpannableStringBuilder log = new SpannableStringBuilder(""""); + + @MainThread + public static SyncLogLiveData get() { + if (sInstance == null) { + sInstance = new SyncLogLiveData(); + } + return sInstance; + } + + private SyncLogLiveData() { + } + + public void appendLog(String text) { + log.append(text); + postValue(log); + } + + public void appendLog(Spanned text) { + log.append(text); + postValue(log); + } +} + +``` + +**in class `SyncService`** + +This line of code will update the content of the LiveData + +```java +SyncLogLiveData.get().appendLog(message); + +``` + +You could also make direct use of `setValue(...)` or `postValue(...)` methods of `LiveData` + +```java +SyncLogLiveData.get().setValue(message); + +``` + +**class SyncFragment** + +```java +public void onViewCreated(@NonNull View view, Bundle savedInstanceState) { + + //... + + // Create the observer which updates the UI. + final Observer ETAObserver = new Observer() { + @Override + public void onChanged(@Nullable final SpannableStringBuilder spannableLog) { + // Update the UI, in this case, a TextView. + getActivity().runOnUiThread(new Runnable() { + @Override + public void run() { + textViewLog.setText(spannableLog); + } + }); + } + }; + // Observe the LiveData, passing in this activity/fragment as the LifecycleOwner and the observer. + SyncLogLiveData.get().observe(getViewLifecycleOwner(), ETAObserver); + + //... +} + +``` + +From within an activity it works the same way, but for `.observe(...)`, you may use this instead + +```java +SyncLogLiveData.get().observe(this, ETAObserver); + +``` + +You could also fetch the current value of the LiveData this way at anytime in your code. + +```java +SyncLogLiveData.get().getValue(); + +``` + +Hopefully this will help someone. There wasn't any mention of LiveData in this answer yet." +14695580,"I have a solution with two projects in it. A portable areas project, and a web site that references the portable areas project, and Both reference MvcContrib. + +The problem I am have is with the embedded resources, they are giving me a 404 error when I try to get to them. It seems like it's trying to access a physical path not the dll. The partial view works fine. + +The file I'm trying to access looks like this inside my visual studio solution explorer + +AdHocReporting/Areas/AdHocReportBuilder/Content/adhoc.css (the build action is embedded) + +**Here is the routing for the portable area:** + +``` +using System.Web.Mvc; +using MvcContrib.PortableAreas; + +namespace AdHocReporting.Areas.AdHocReportBuilder +{ + public class AdHocReportBuilderAreaRegistration : PortableAreaRegistration + { + public override string AreaName + { + get { return ""AdHocReportBuilder""; } + } + + public override void RegisterArea(AreaRegistrationContext context, IApplicationBus bus) + { + RegisterRoutes(context); + RegisterAreaEmbeddedResources(); + + } + private void RegisterRoutes(AreaRegistrationContext context) + { + context.MapRoute( + AreaName + ""_content"", + base.AreaRoutePrefix + ""/Content/{resourceName}"", + new { controller = ""EmbeddedResource"", action = ""Index"", resourcePath = ""Content"" }, + new[] { ""MvcContrib.PortableAreas"" } + ); + + context.MapRoute( + AreaName + ""_default"", + base.AreaRoutePrefix + ""/{controller}/{action}/{id}"", + new { action = ""Index"", id = UrlParameter.Optional } + ); + } + } +} + +``` + +**Here is the Web sites Global.aspx that has the reference to the portable area** + +``` +namespace AdHocReportingSite +{ + public class MvcApplication : System.Web.HttpApplication + { + public static void RegisterGlobalFilters(GlobalFilterCollection filters) + { + filters.Add(new HandleErrorAttribute()); + } + + public static void RegisterRoutes(RouteCollection routes) + { + routes.IgnoreRoute(""{resource}.axd/{*pathInfo}""); + routes.MapRoute( + ""Default"", // Route name + ""{controller}/{action}/{id}"", // URL with parameters + new { controller = ""Home"", action = ""Index"", id = UrlParameter.Optional } // Parameter defaults + ); + + } + protected void Application_Start() + { + AreaRegistration.RegisterAllAreas(); + PortableAreaRegistration.RegisterEmbeddedViewEngine(); + FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); + RouteConfig.RegisterRoutes(RouteTable.Routes); + } + } +} + +``` + +**here is an image of what my solution explore looks like:** + +![Solution Explorer](https://i.stack.imgur.com/6P0TK.png)",2013/02/04,"['https://Stackoverflow.com/questions/14695580', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/937294/']","I would use a [bound service](http://developer.android.com/guide/components/bound-services.html) to do that and communicate with it by implementing a listener in my activity. So if your app implements myServiceListener, you can register it as a listener in your service after you have bound with it, call listener.onUpdateUI from your bound service and update your UI in there!","You could use android Jetpack's [LiveData](https://developer.android.com/topic/libraries/architecture/livedata) + +As per the documentation: + +> +> You can extend a `LiveData` object using the singleton pattern to wrap +> system services so that they can be shared in your app. The LiveData +> object connects to the system service once, and then any observer that +> needs the resource can just watch the LiveData object. For more +> information, see [Extend +> LiveData](https://developer.android.com/topic/libraries/architecture/livedata?hl=en#extend_livedata). +> +> +> + +Below is what I did for communication between Service and Activity and also Service and Fragment. + +In this example, I have: + +* a class `SyncLogLiveData` extending `LiveData` that contains a `SpannableStringBuilder` +* a service `SyncService` +* a fragment `SyncFragment` + +The Fragment ""observes"" the LiveData (ie SyncLogLiveData) and performs an action when the LiveData changes. + +The LiveData is updated by the Service. + +I could also update the LiveData from the Fragment in the same way but don't show it here. + +**class `SyncLogLiveData`** + +```java +public class SyncLogLiveData extends LiveData { + private static SyncLogLiveData sInstance; + private final static SpannableStringBuilder log = new SpannableStringBuilder(""""); + + @MainThread + public static SyncLogLiveData get() { + if (sInstance == null) { + sInstance = new SyncLogLiveData(); + } + return sInstance; + } + + private SyncLogLiveData() { + } + + public void appendLog(String text) { + log.append(text); + postValue(log); + } + + public void appendLog(Spanned text) { + log.append(text); + postValue(log); + } +} + +``` + +**in class `SyncService`** + +This line of code will update the content of the LiveData + +```java +SyncLogLiveData.get().appendLog(message); + +``` + +You could also make direct use of `setValue(...)` or `postValue(...)` methods of `LiveData` + +```java +SyncLogLiveData.get().setValue(message); + +``` + +**class SyncFragment** + +```java +public void onViewCreated(@NonNull View view, Bundle savedInstanceState) { + + //... + + // Create the observer which updates the UI. + final Observer ETAObserver = new Observer() { + @Override + public void onChanged(@Nullable final SpannableStringBuilder spannableLog) { + // Update the UI, in this case, a TextView. + getActivity().runOnUiThread(new Runnable() { + @Override + public void run() { + textViewLog.setText(spannableLog); + } + }); + } + }; + // Observe the LiveData, passing in this activity/fragment as the LifecycleOwner and the observer. + SyncLogLiveData.get().observe(getViewLifecycleOwner(), ETAObserver); + + //... +} + +``` + +From within an activity it works the same way, but for `.observe(...)`, you may use this instead + +```java +SyncLogLiveData.get().observe(this, ETAObserver); + +``` + +You could also fetch the current value of the LiveData this way at anytime in your code. + +```java +SyncLogLiveData.get().getValue(); + +``` + +Hopefully this will help someone. There wasn't any mention of LiveData in this answer yet." +14695580,"I have a solution with two projects in it. A portable areas project, and a web site that references the portable areas project, and Both reference MvcContrib. + +The problem I am have is with the embedded resources, they are giving me a 404 error when I try to get to them. It seems like it's trying to access a physical path not the dll. The partial view works fine. + +The file I'm trying to access looks like this inside my visual studio solution explorer + +AdHocReporting/Areas/AdHocReportBuilder/Content/adhoc.css (the build action is embedded) + +**Here is the routing for the portable area:** + +``` +using System.Web.Mvc; +using MvcContrib.PortableAreas; + +namespace AdHocReporting.Areas.AdHocReportBuilder +{ + public class AdHocReportBuilderAreaRegistration : PortableAreaRegistration + { + public override string AreaName + { + get { return ""AdHocReportBuilder""; } + } + + public override void RegisterArea(AreaRegistrationContext context, IApplicationBus bus) + { + RegisterRoutes(context); + RegisterAreaEmbeddedResources(); + + } + private void RegisterRoutes(AreaRegistrationContext context) + { + context.MapRoute( + AreaName + ""_content"", + base.AreaRoutePrefix + ""/Content/{resourceName}"", + new { controller = ""EmbeddedResource"", action = ""Index"", resourcePath = ""Content"" }, + new[] { ""MvcContrib.PortableAreas"" } + ); + + context.MapRoute( + AreaName + ""_default"", + base.AreaRoutePrefix + ""/{controller}/{action}/{id}"", + new { action = ""Index"", id = UrlParameter.Optional } + ); + } + } +} + +``` + +**Here is the Web sites Global.aspx that has the reference to the portable area** + +``` +namespace AdHocReportingSite +{ + public class MvcApplication : System.Web.HttpApplication + { + public static void RegisterGlobalFilters(GlobalFilterCollection filters) + { + filters.Add(new HandleErrorAttribute()); + } + + public static void RegisterRoutes(RouteCollection routes) + { + routes.IgnoreRoute(""{resource}.axd/{*pathInfo}""); + routes.MapRoute( + ""Default"", // Route name + ""{controller}/{action}/{id}"", // URL with parameters + new { controller = ""Home"", action = ""Index"", id = UrlParameter.Optional } // Parameter defaults + ); + + } + protected void Application_Start() + { + AreaRegistration.RegisterAllAreas(); + PortableAreaRegistration.RegisterEmbeddedViewEngine(); + FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); + RouteConfig.RegisterRoutes(RouteTable.Routes); + } + } +} + +``` + +**here is an image of what my solution explore looks like:** + +![Solution Explorer](https://i.stack.imgur.com/6P0TK.png)",2013/02/04,"['https://Stackoverflow.com/questions/14695580', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/937294/']","See below for my original answer - that pattern has worked well, but recently I've started using a different approach to Service/Activity communication: + +* Use a [bound service](https://developer.android.com/guide/components/bound-services.html) which enables the Activity to get a direct +reference to the Service, thus allowing direct calls on it, rather +than using Intents. +* Use RxJava to execute asynchronous operations. +* If the Service needs to continue background operations even when no +Activity is running, also start the service from the Application +class so that it does not get stopped when unbound. + +The advantages I have found in this approach compared to the startService()/LocalBroadcast technique are + +* No need for data objects to implement Parcelable - this is particularly important to me as I am now sharing code between Android and iOS (using RoboVM) +* RxJava provides canned (and cross-platform) scheduling, and easy composition of sequential asynchronous operations. +* This should be more efficient than using a LocalBroadcast, though the overhead of using RxJava may outweigh that. + +Some example code. First the service: + +``` +public class AndroidBmService extends Service implements BmService { + + private static final int PRESSURE_RATE = 500000; // microseconds between pressure updates + private SensorManager sensorManager; + private SensorEventListener pressureListener; + private ObservableEmitter pressureObserver; + private Observable pressureObservable; + + public class LocalBinder extends Binder { + public AndroidBmService getService() { + return AndroidBmService.this; + } + } + + private IBinder binder = new LocalBinder(); + + @Nullable + @Override + public IBinder onBind(Intent intent) { + logMsg(""Service bound""); + return binder; + } + + @Override + public int onStartCommand(Intent intent, int flags, int startId) { + return START_NOT_STICKY; + } + + @Override + public void onCreate() { + super.onCreate(); + + sensorManager = (SensorManager)getSystemService(SENSOR_SERVICE); + Sensor pressureSensor = sensorManager.getDefaultSensor(Sensor.TYPE_PRESSURE); + if(pressureSensor != null) + sensorManager.registerListener(pressureListener = new SensorEventListener() { + @Override + public void onSensorChanged(SensorEvent event) { + if(pressureObserver != null) { + float lastPressure = event.values[0]; + float lastPressureAltitude = (float)((1 - Math.pow(lastPressure / 1013.25, 0.190284)) * 145366.45); + pressureObserver.onNext(lastPressureAltitude); + } + } + + @Override + public void onAccuracyChanged(Sensor sensor, int accuracy) { + + } + }, pressureSensor, PRESSURE_RATE); + } + + @Override + public Observable observePressure() { + if(pressureObservable == null) { + pressureObservable = Observable.create(emitter -> pressureObserver = emitter); + pressureObservable = pressureObservable.share(); + } + return pressureObservable; + } + + @Override + public void onDestroy() { + if(pressureListener != null) + sensorManager.unregisterListener(pressureListener); + } +} + +``` + +And an Activity that binds to the service and receives pressure altitude updates: + +``` +public class TestActivity extends AppCompatActivity { + + private ContentTestBinding binding; + private ServiceConnection serviceConnection; + private AndroidBmService service; + private Disposable disposable; + + @Override + protected void onDestroy() { + if(disposable != null) + disposable.dispose(); + unbindService(serviceConnection); + super.onDestroy(); + } + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + binding = DataBindingUtil.setContentView(this, R.layout.content_test); + serviceConnection = new ServiceConnection() { + @Override + public void onServiceConnected(ComponentName componentName, IBinder iBinder) { + logMsg(""BlueMAX service bound""); + service = ((AndroidBmService.LocalBinder)iBinder).getService(); + disposable = service.observePressure() + .observeOn(AndroidSchedulers.mainThread()) + .subscribe(altitude -> + binding.altitude.setText( + String.format(Locale.US, + ""Pressure Altitude %d feet"", + altitude.intValue()))); + } + + @Override + public void onServiceDisconnected(ComponentName componentName) { + logMsg(""Service disconnected""); + } + }; + bindService(new Intent( + this, AndroidBmService.class), + serviceConnection, BIND_AUTO_CREATE); + } +} + +``` + +The layout for this Activity is: + +``` + + + + + + + + + +``` + +If the service needs to run in the background without a bound Activity it can be started from the Application class as well in `OnCreate()` using [`Context#startService()`](https://developer.android.com/reference/android/content/Context.html#startService(android.content.Intent)). + +--- + +**My Original Answer (from 2013):** + +**In your service:** (using COPA as service in example below). + +Use a LocalBroadCastManager. In your service's onCreate, set up the broadcaster: + +``` +broadcaster = LocalBroadcastManager.getInstance(this); + +``` + +When you want to notify the UI of something: + +``` +static final public String COPA_RESULT = ""com.controlj.copame.backend.COPAService.REQUEST_PROCESSED""; + +static final public String COPA_MESSAGE = ""com.controlj.copame.backend.COPAService.COPA_MSG""; + +public void sendResult(String message) { + Intent intent = new Intent(COPA_RESULT); + if(message != null) + intent.putExtra(COPA_MESSAGE, message); + broadcaster.sendBroadcast(intent); +} + +``` + +**In your Activity:** + +Create a listener on onCreate: + +``` +public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + super.setContentView(R.layout.copa); + receiver = new BroadcastReceiver() { + @Override + public void onReceive(Context context, Intent intent) { + String s = intent.getStringExtra(COPAService.COPA_MESSAGE); + // do something here. + } + }; +} + +``` + +and register it in onStart: + +``` +@Override +protected void onStart() { + super.onStart(); + LocalBroadcastManager.getInstance(this).registerReceiver((receiver), + new IntentFilter(COPAService.COPA_RESULT) + ); +} + +@Override +protected void onStop() { + LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver); + super.onStop(); +} + +```","for me the simplest solution was to send a broadcast, in the activity oncreate i registered and defined the broadcast like this (updateUIReciver is defined as a class instance) : + +``` + IntentFilter filter = new IntentFilter(); + + filter.addAction(""com.hello.action""); + + updateUIReciver = new BroadcastReceiver() { + + @Override + public void onReceive(Context context, Intent intent) { + //UI update here + + } + }; + registerReceiver(updateUIReciver,filter); + +``` + +And from the service you send the intent like this: + +``` +Intent local = new Intent(); + +local.setAction(""com.hello.action""); + +this.sendBroadcast(local); + +``` + +don't forget to unregister the recover in the activity on destroy : + +``` +unregisterReceiver(updateUIReciver); + +```" +14695580,"I have a solution with two projects in it. A portable areas project, and a web site that references the portable areas project, and Both reference MvcContrib. + +The problem I am have is with the embedded resources, they are giving me a 404 error when I try to get to them. It seems like it's trying to access a physical path not the dll. The partial view works fine. + +The file I'm trying to access looks like this inside my visual studio solution explorer + +AdHocReporting/Areas/AdHocReportBuilder/Content/adhoc.css (the build action is embedded) + +**Here is the routing for the portable area:** + +``` +using System.Web.Mvc; +using MvcContrib.PortableAreas; + +namespace AdHocReporting.Areas.AdHocReportBuilder +{ + public class AdHocReportBuilderAreaRegistration : PortableAreaRegistration + { + public override string AreaName + { + get { return ""AdHocReportBuilder""; } + } + + public override void RegisterArea(AreaRegistrationContext context, IApplicationBus bus) + { + RegisterRoutes(context); + RegisterAreaEmbeddedResources(); + + } + private void RegisterRoutes(AreaRegistrationContext context) + { + context.MapRoute( + AreaName + ""_content"", + base.AreaRoutePrefix + ""/Content/{resourceName}"", + new { controller = ""EmbeddedResource"", action = ""Index"", resourcePath = ""Content"" }, + new[] { ""MvcContrib.PortableAreas"" } + ); + + context.MapRoute( + AreaName + ""_default"", + base.AreaRoutePrefix + ""/{controller}/{action}/{id}"", + new { action = ""Index"", id = UrlParameter.Optional } + ); + } + } +} + +``` + +**Here is the Web sites Global.aspx that has the reference to the portable area** + +``` +namespace AdHocReportingSite +{ + public class MvcApplication : System.Web.HttpApplication + { + public static void RegisterGlobalFilters(GlobalFilterCollection filters) + { + filters.Add(new HandleErrorAttribute()); + } + + public static void RegisterRoutes(RouteCollection routes) + { + routes.IgnoreRoute(""{resource}.axd/{*pathInfo}""); + routes.MapRoute( + ""Default"", // Route name + ""{controller}/{action}/{id}"", // URL with parameters + new { controller = ""Home"", action = ""Index"", id = UrlParameter.Optional } // Parameter defaults + ); + + } + protected void Application_Start() + { + AreaRegistration.RegisterAllAreas(); + PortableAreaRegistration.RegisterEmbeddedViewEngine(); + FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); + RouteConfig.RegisterRoutes(RouteTable.Routes); + } + } +} + +``` + +**here is an image of what my solution explore looks like:** + +![Solution Explorer](https://i.stack.imgur.com/6P0TK.png)",2013/02/04,"['https://Stackoverflow.com/questions/14695580', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/937294/']","for me the simplest solution was to send a broadcast, in the activity oncreate i registered and defined the broadcast like this (updateUIReciver is defined as a class instance) : + +``` + IntentFilter filter = new IntentFilter(); + + filter.addAction(""com.hello.action""); + + updateUIReciver = new BroadcastReceiver() { + + @Override + public void onReceive(Context context, Intent intent) { + //UI update here + + } + }; + registerReceiver(updateUIReciver,filter); + +``` + +And from the service you send the intent like this: + +``` +Intent local = new Intent(); + +local.setAction(""com.hello.action""); + +this.sendBroadcast(local); + +``` + +don't forget to unregister the recover in the activity on destroy : + +``` +unregisterReceiver(updateUIReciver); + +```","I would use a [bound service](http://developer.android.com/guide/components/bound-services.html) to do that and communicate with it by implementing a listener in my activity. So if your app implements myServiceListener, you can register it as a listener in your service after you have bound with it, call listener.onUpdateUI from your bound service and update your UI in there!" +57344515,"I am trying to get serialized data for the below model with foreign keys but in the output i am only getting the ids instead of the fields of the model associated with hyperlink. + +I have tried getting all the fields of the Skills model using the commented lines in the profile serializer but no luck + +models.py + +``` +class Profile(models.Model): + user = models.OneToOneField( + settings.AUTH_USER_MODEL, on_delete=models.CASCADE) + first_name = models.CharField(max_length=20, null=True) + last_name = models.CharField(max_length=20, null=True) + + def __str__(self): + return 'Profile for user {}'.format(self.user.username) + +class Skill(models.Model): + skill = models.CharField(max_length=20, null=True) + level = models.CharField(max_length=20, null=True) + user = models.ForeignKey(Profile, null=True, + on_delete=models.PROTECT, related_name='skills') + + def __str__(self): + return '%s: %s: %s' % (self.user, self.skill, self.level) + +``` + +serializer.py + +``` +class SkillSerializer(serializers.ModelSerializer): + + class Meta: + model = Skill + fields = ('user', 'skill', 'level') + +class ProfileSerializer(serializers.ModelSerializer): + + class Meta: + # skills = SkillSerializer(many=True, read_only=True) # serializes child model's data inside this model's data + # skills = serializers.HyperlinkedRelatedField(many=True, read_only=True, view_name='skill-detail') + # skills = serializers.StringRelatedField(many=True) + # skills = serializers.HyperlinkedIdentityField( view_name = ""skill-list"", lookup_field = ""user"") + url = HyperlinkedIdentityField( view_name=""profile-detail"", lookup_field = ""id"") + # user = serializers.ReadOnlyField(source='user.username') + # pdb.set_trace() + + model = Profile + fields = ['id', 'user', 'url', 'skills'] + +``` + +views.py + +``` +class ProfileList(generics.ListCreateAPIView): + queryset = Profile.objects.all() + serializer_class = ProfileSerializer + +class ProfileDetail(generics.RetrieveUpdateDestroyAPIView): + queryset = Profile.objects.all() + serializer_class = ProfileSerializer + +class SkillList(generics.ListCreateAPIView): + queryset = Skill.objects.all() + serializer_class = SkillSerializer + +class SkillDetail(generics.RetrieveUpdateDestroyAPIView): + queryset = Skill.objects.all() + serializer_class = SkillSerializer + +``` + +urls.py + +``` +path('profiles/', views.ProfileList.as_view(), name='profile-list'), +path('profiles//', views.ProfileDetail.as_view(), name='profile-detail'), +path('skills/', views.SkillList.as_view(), name='profile-list'), +path('skills//', views.SkillDetail.as_view(), name='skill-list'), + +``` + +Output: + +``` + [ ""id"": 6, + ""user"": 4, + ""url"": ""http://127.0.0.1:8000/authenticator/profiles/6/"", + ""skills"": [ + 57, + 55 + ], + ] + +``` + +Expected output: + +``` + [ ""id"": 6, + ""user"": 4, + ""url"": ""http://127.0.0.1:8000/authenticator/profiles/6/"", + ""skills"": [ + { + ""user"": 6, + ""skill"": ""ABC"", + ""level"": ""Beginner"" + }, + { + ""user"": 6, + ""skill"": ""DEF"", + ""level"": ""Intermediate"" + }, + ] + ] + +```",2019/08/04,"['https://Stackoverflow.com/questions/57344515', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11879807/']","This should normally work with the following in serializer.py: + +``` +class ProfileSerializer(serializers.ModelSerializer): + skills = SkillSerializer(many=True, read_only=True) # serializes child model's data inside this model's data + url = HyperlinkedIdentityField( view_name=""profile-detail"", lookup_field = ""id"") + + class Meta: + model = Profile + fields = ['id', 'user', 'url', 'skills'] + +``` + +So basically uncomment the line in which the ProfileSerializer is told to serialize the skills with your SkillsSerializers, such that the entire skill objects are included in the result instead of its IDs.","You can use the concept of nested serializer for the solution. + +Create two serializer `ProfileReadSerializer` and `ProfileWriteSerializer` + +serializers.py + +```py +class SkillSerializer(serializers.ModelSerializer): + class Meta: + model = Skill + fields = ('user', 'skill', 'level') + +class ProfileReadSerializer(serializers.ModelSerializer): + skills = SkillSerializer(many=True, read_only=True) + url = HyperlinkedIdentityField( view_name=""profile-detail"", lookup_field = ""id"") + + class Meta: + model = Profile + fields = ('id', 'user', 'url', 'skills') + +class ProfileWriteSerializer(serializers.ModelSerializer): + skills = SkillSerializer(many=True) + + class Meta: + model = Profile + fields = ('id', 'user', 'url', 'skills') + +``` + +In views you simply can use `ModelViewSet` to make things easy and use `get_serializer_class` + +views.py + +```py +from rest_framework.viewsets import ModelViewSet + +class ProfileVewSet(ModelViewSet): + queryset = Profile.objects.all() + + def get_serializer_class(self): + if self.request.method == 'POST' or self.request.method == 'PUT' or self.request.method == 'PATCH': + return ProfileWriteSerializer + else: + return ProfileReadSerializer + +``` + +And at last if you are using `ModelViewSet` you need to change the `urls.py` + +urls.py + +```py +from rest_framework.routers import DefaultRouter + +router = DefaultRouter() +router.register('profile', views.ProfileViewSet, base_name='profile') + +urlpatterns = [ + path('', include(router.urls)) +] + +``` + +I think this will solve your problem. Please have a look." +53660611,"I'm trying to chunk 100 lists from a nestled list. I have looked looked through multiple examples on Stack Overflow, but I still cannot get something working correctly. + +My primary list is named data\_to\_insert and it contains other lists. I would like to extract (chunk) 100 lists from the primary nestled list. + +How do I accomplish this? + +This is my current code, which doesn't work as needed. + +``` +def divide_chunks(l, n): + for i in range(0, len(l), n): + yield l[i:i + n] + +n = 100 +x = list(divide_chunks(data_to_insert, 100)) + +``` + +Nestled list example: + +``` +data_to_insert = [['item1','item2','item3','item4','item5','item6'], + ['item1','item2','item3','item4','item5','item6'], + ['item1','item2','item3','item4','item5','item6'], + ['item1','item2','item3','item4','item5','item6'], + ['item1','item2','item3','item4','item5','item6'], + ... + [thousands of others lists go here]] + +``` + +Desired output is another list (sliced\_data), which contains 100 lists from the nestled list (data\_to\_insert). + +``` +sliced_data = [['item1','item2','item3','item4','item5','item6'], + ['item1','item2','item3','item4','item5','item6'], + ... + [98 more lists go here]] + +``` + +I need to loop through the nestled list, data\_to\_insert until it's empty.",2018/12/06,"['https://Stackoverflow.com/questions/53660611', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6083423/']","You can use `random` to select `100` random nested lists from your given list. + +This will output `3` random nested list from original list, + +``` +import random + +l = [[1,2], [3,4], [1,1], [2,3], [3,5], [0,0]] +print(random.sample(l, 3)) + +# output, +[[3, 4], [1, 2], [2, 3]] + +``` + +If you do not want a list output then replace `print(random.sample(l, 3))` with `print(*random.sample(l, 3))`, + +``` +# output, +[1, 2] [2, 3] [1, 1] + +``` + +If you just want first `100` nested lists then do, + +``` +print(l[:100]) + +```","If i did understand your question correctly, you need first to flatten your list of list then create a chunks of it. Here is an example using `chain.from_iterable` from `itertools module` along with the code you've used to create chunks: + +``` +from itertools import chain + +def chunks(elm, length): + for k in range(0, len(elm), length): + yield elm[k: k + length] + +my_list = [['item{}'.format(j) for j in range(7)]] * 1000 +flattened = list(chain.from_iterable(my_list)) + +chunks = list(chunks(flattened, 100)) + +print(len(chunks[10])) + +``` + +Output: + +``` +100 + +```" +53660611,"I'm trying to chunk 100 lists from a nestled list. I have looked looked through multiple examples on Stack Overflow, but I still cannot get something working correctly. + +My primary list is named data\_to\_insert and it contains other lists. I would like to extract (chunk) 100 lists from the primary nestled list. + +How do I accomplish this? + +This is my current code, which doesn't work as needed. + +``` +def divide_chunks(l, n): + for i in range(0, len(l), n): + yield l[i:i + n] + +n = 100 +x = list(divide_chunks(data_to_insert, 100)) + +``` + +Nestled list example: + +``` +data_to_insert = [['item1','item2','item3','item4','item5','item6'], + ['item1','item2','item3','item4','item5','item6'], + ['item1','item2','item3','item4','item5','item6'], + ['item1','item2','item3','item4','item5','item6'], + ['item1','item2','item3','item4','item5','item6'], + ... + [thousands of others lists go here]] + +``` + +Desired output is another list (sliced\_data), which contains 100 lists from the nestled list (data\_to\_insert). + +``` +sliced_data = [['item1','item2','item3','item4','item5','item6'], + ['item1','item2','item3','item4','item5','item6'], + ... + [98 more lists go here]] + +``` + +I need to loop through the nestled list, data\_to\_insert until it's empty.",2018/12/06,"['https://Stackoverflow.com/questions/53660611', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6083423/']","You can use `random` to select `100` random nested lists from your given list. + +This will output `3` random nested list from original list, + +``` +import random + +l = [[1,2], [3,4], [1,1], [2,3], [3,5], [0,0]] +print(random.sample(l, 3)) + +# output, +[[3, 4], [1, 2], [2, 3]] + +``` + +If you do not want a list output then replace `print(random.sample(l, 3))` with `print(*random.sample(l, 3))`, + +``` +# output, +[1, 2] [2, 3] [1, 1] + +``` + +If you just want first `100` nested lists then do, + +``` +print(l[:100]) + +```","After some time-consuming research, I developed a solution that worked. The solution below loops through a list of lists and extract 100 lists. + +``` +# Verifies that the list data_to_insert isn't empty +if len(data_to_insert) > 0: + + # Obtains the length of the data to insert. + # The length is the number of sublists + # contained in the main nestled list. + data_length = len(data_to_insert) + + # A loop counter used in the + # data insert process. + i = 0 + + # The number of sublists to slice + # from the main nestled list in + # each loop. + n = 100 + + # This loop execute a set of statements + # as long as the condition below is true + while i < data_length: + + # Increments the loop counter + if len(data_to_insert) < 100: + i += len(data_to_insert) + else: + i += 100 + + # Slices 100 sublists from the main nestled list. + sliced_data = data_to_insert[:n] + + # Verifies that the list sliced_data isn't empty + if len(sliced_data) > 0: + + # Removes 1000 sublists from the main nestled list. + data_to_insert = data_to_insert[n:] + + ################################## + do something with the sliced_data + ################################## + + # Clears the list used to store the + # sliced_data in the insertion loop. + sliced_data.clear() + gc.collect() + + # Clears the list used to store the + # data elements inserted into the + # database. + data_to_insert.clear() + gc.collect() + +```" +53660611,"I'm trying to chunk 100 lists from a nestled list. I have looked looked through multiple examples on Stack Overflow, but I still cannot get something working correctly. + +My primary list is named data\_to\_insert and it contains other lists. I would like to extract (chunk) 100 lists from the primary nestled list. + +How do I accomplish this? + +This is my current code, which doesn't work as needed. + +``` +def divide_chunks(l, n): + for i in range(0, len(l), n): + yield l[i:i + n] + +n = 100 +x = list(divide_chunks(data_to_insert, 100)) + +``` + +Nestled list example: + +``` +data_to_insert = [['item1','item2','item3','item4','item5','item6'], + ['item1','item2','item3','item4','item5','item6'], + ['item1','item2','item3','item4','item5','item6'], + ['item1','item2','item3','item4','item5','item6'], + ['item1','item2','item3','item4','item5','item6'], + ... + [thousands of others lists go here]] + +``` + +Desired output is another list (sliced\_data), which contains 100 lists from the nestled list (data\_to\_insert). + +``` +sliced_data = [['item1','item2','item3','item4','item5','item6'], + ['item1','item2','item3','item4','item5','item6'], + ... + [98 more lists go here]] + +``` + +I need to loop through the nestled list, data\_to\_insert until it's empty.",2018/12/06,"['https://Stackoverflow.com/questions/53660611', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6083423/']","You can use `random` to select `100` random nested lists from your given list. + +This will output `3` random nested list from original list, + +``` +import random + +l = [[1,2], [3,4], [1,1], [2,3], [3,5], [0,0]] +print(random.sample(l, 3)) + +# output, +[[3, 4], [1, 2], [2, 3]] + +``` + +If you do not want a list output then replace `print(random.sample(l, 3))` with `print(*random.sample(l, 3))`, + +``` +# output, +[1, 2] [2, 3] [1, 1] + +``` + +If you just want first `100` nested lists then do, + +``` +print(l[:100]) + +```","I developed a second method to accomplish my objective, which is based on [Sufiyan Ghori](https://stackoverflow.com/users/1149423/sufiyan-ghori) suggestion of using `random.` + +``` +if len(my_nestled_list) > 0: + + # Obtains the length of the data to insert. + # The length is the number of sublists + # contained in the main nestled list. + data_length = len(my_nestled_list)) + + # A loop counter used in the + # data insert process. + i = 0 + + # The number of sublists to slice + # from the main nestled list in + # each loop. + n = 100 + + # This loop execute a set of statements + # as long as the condition below is true + while i < data_length: + + # Increments the loop counter + if len(my_nestled_list)) < 100: + i += len(my_nestled_list)) + else: + i += 100 + + # Uses list comprehension to randomly select 100 lists + # from the nestled list. + random_sample_of_100 = [my_nestled_list)[i] for i in sorted(random.sample(range(len(my_nestled_list))), n))] + + print (random_sample_of_100) + +```" +53660611,"I'm trying to chunk 100 lists from a nestled list. I have looked looked through multiple examples on Stack Overflow, but I still cannot get something working correctly. + +My primary list is named data\_to\_insert and it contains other lists. I would like to extract (chunk) 100 lists from the primary nestled list. + +How do I accomplish this? + +This is my current code, which doesn't work as needed. + +``` +def divide_chunks(l, n): + for i in range(0, len(l), n): + yield l[i:i + n] + +n = 100 +x = list(divide_chunks(data_to_insert, 100)) + +``` + +Nestled list example: + +``` +data_to_insert = [['item1','item2','item3','item4','item5','item6'], + ['item1','item2','item3','item4','item5','item6'], + ['item1','item2','item3','item4','item5','item6'], + ['item1','item2','item3','item4','item5','item6'], + ['item1','item2','item3','item4','item5','item6'], + ... + [thousands of others lists go here]] + +``` + +Desired output is another list (sliced\_data), which contains 100 lists from the nestled list (data\_to\_insert). + +``` +sliced_data = [['item1','item2','item3','item4','item5','item6'], + ['item1','item2','item3','item4','item5','item6'], + ... + [98 more lists go here]] + +``` + +I need to loop through the nestled list, data\_to\_insert until it's empty.",2018/12/06,"['https://Stackoverflow.com/questions/53660611', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6083423/']","If i did understand your question correctly, you need first to flatten your list of list then create a chunks of it. Here is an example using `chain.from_iterable` from `itertools module` along with the code you've used to create chunks: + +``` +from itertools import chain + +def chunks(elm, length): + for k in range(0, len(elm), length): + yield elm[k: k + length] + +my_list = [['item{}'.format(j) for j in range(7)]] * 1000 +flattened = list(chain.from_iterable(my_list)) + +chunks = list(chunks(flattened, 100)) + +print(len(chunks[10])) + +``` + +Output: + +``` +100 + +```","After some time-consuming research, I developed a solution that worked. The solution below loops through a list of lists and extract 100 lists. + +``` +# Verifies that the list data_to_insert isn't empty +if len(data_to_insert) > 0: + + # Obtains the length of the data to insert. + # The length is the number of sublists + # contained in the main nestled list. + data_length = len(data_to_insert) + + # A loop counter used in the + # data insert process. + i = 0 + + # The number of sublists to slice + # from the main nestled list in + # each loop. + n = 100 + + # This loop execute a set of statements + # as long as the condition below is true + while i < data_length: + + # Increments the loop counter + if len(data_to_insert) < 100: + i += len(data_to_insert) + else: + i += 100 + + # Slices 100 sublists from the main nestled list. + sliced_data = data_to_insert[:n] + + # Verifies that the list sliced_data isn't empty + if len(sliced_data) > 0: + + # Removes 1000 sublists from the main nestled list. + data_to_insert = data_to_insert[n:] + + ################################## + do something with the sliced_data + ################################## + + # Clears the list used to store the + # sliced_data in the insertion loop. + sliced_data.clear() + gc.collect() + + # Clears the list used to store the + # data elements inserted into the + # database. + data_to_insert.clear() + gc.collect() + +```" +53660611,"I'm trying to chunk 100 lists from a nestled list. I have looked looked through multiple examples on Stack Overflow, but I still cannot get something working correctly. + +My primary list is named data\_to\_insert and it contains other lists. I would like to extract (chunk) 100 lists from the primary nestled list. + +How do I accomplish this? + +This is my current code, which doesn't work as needed. + +``` +def divide_chunks(l, n): + for i in range(0, len(l), n): + yield l[i:i + n] + +n = 100 +x = list(divide_chunks(data_to_insert, 100)) + +``` + +Nestled list example: + +``` +data_to_insert = [['item1','item2','item3','item4','item5','item6'], + ['item1','item2','item3','item4','item5','item6'], + ['item1','item2','item3','item4','item5','item6'], + ['item1','item2','item3','item4','item5','item6'], + ['item1','item2','item3','item4','item5','item6'], + ... + [thousands of others lists go here]] + +``` + +Desired output is another list (sliced\_data), which contains 100 lists from the nestled list (data\_to\_insert). + +``` +sliced_data = [['item1','item2','item3','item4','item5','item6'], + ['item1','item2','item3','item4','item5','item6'], + ... + [98 more lists go here]] + +``` + +I need to loop through the nestled list, data\_to\_insert until it's empty.",2018/12/06,"['https://Stackoverflow.com/questions/53660611', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6083423/']","If i did understand your question correctly, you need first to flatten your list of list then create a chunks of it. Here is an example using `chain.from_iterable` from `itertools module` along with the code you've used to create chunks: + +``` +from itertools import chain + +def chunks(elm, length): + for k in range(0, len(elm), length): + yield elm[k: k + length] + +my_list = [['item{}'.format(j) for j in range(7)]] * 1000 +flattened = list(chain.from_iterable(my_list)) + +chunks = list(chunks(flattened, 100)) + +print(len(chunks[10])) + +``` + +Output: + +``` +100 + +```","I developed a second method to accomplish my objective, which is based on [Sufiyan Ghori](https://stackoverflow.com/users/1149423/sufiyan-ghori) suggestion of using `random.` + +``` +if len(my_nestled_list) > 0: + + # Obtains the length of the data to insert. + # The length is the number of sublists + # contained in the main nestled list. + data_length = len(my_nestled_list)) + + # A loop counter used in the + # data insert process. + i = 0 + + # The number of sublists to slice + # from the main nestled list in + # each loop. + n = 100 + + # This loop execute a set of statements + # as long as the condition below is true + while i < data_length: + + # Increments the loop counter + if len(my_nestled_list)) < 100: + i += len(my_nestled_list)) + else: + i += 100 + + # Uses list comprehension to randomly select 100 lists + # from the nestled list. + random_sample_of_100 = [my_nestled_list)[i] for i in sorted(random.sample(range(len(my_nestled_list))), n))] + + print (random_sample_of_100) + +```" +39947,"I noticed the phrase “What gives?” in the following lines of the article of Washington Post (August 29) article, titled “Is Ron Paul being ignored?” + +> +> “And yet talk to almost anyone in politics — Republicans or Democrats — and the idea of Ron Paul as a top-tier candidate for president is greeted with either a laugh or an eye roll (or both.) +> +> +> *What gives?* +> +> +> Paul appears to be suffering from the “once bitten, twice shy” tendency of the media.” +> +> +> + +It appears to me “What gives?” is a common and frequently-used phrase, but I don’t think I’ve seen this phrase so often in written English format like newspaper articles, much less in English textbooks we use. +Does it mean “for what (reason)?” or ""What is its implication?"" What is the spelt-out format of “What gives?”",2011/08/30,"['https://english.stackexchange.com/questions/39947', 'https://english.stackexchange.com', 'https://english.stackexchange.com/users/3119/']","*What gives?* [means](http://idioms.thefreedictionary.com/What+Gives%3f): + +> +> Inf. What happened?; What went wrong?; What's the problem? +> +> +> Bill: Hi, you guys. What gives? Bob: Nothing, just a little misunderstanding. Tom's a little angry. +> +> +> Bob: Where's my wallet? What gives? +> +> +> Tom: I think one of those roughnecks who just walked by us has borrowed it for a little while. +> +> +> + +According to this page on the [linguistics of the phrase](http://ling.ucsc.edu/Jorge/joseph.html), it is not short for anything. There are a few theories about how it arose: + +> +> Regarding the issue of why *what gives* is anomalous, the best that I can offer (speaking now as an historical linguist) is to suggest that we turn to the history of the construction, but even there, full enlightenment is not forthcoming (see Joseph 2000 for more detailed discussion). The construction seems clearly to have originated in American English; the first attestation for what gives comes in 1940, in John O'Hara's Pal Joey, according to Wentworth and Flexner (1960: 574, s.v. what gives) and the Oxford English Dictionary (1989 on-line second edition). +> +> +> Even with this late attestation, what gives makes for an interesting comparison with the German existential use of *geben* 'to give', in the impersonal form with an expletive subject, *es gibt*, as in *Es gibt keinen Gott* 'There is no god', itself anomalous from the point of view of the usual syntax and meaning of *geben*... +> +> +> Some scholars however see what gives as having arisen via language contact, as a calque from German, an origin for it which would eliminate a basis for a Proto-West-Germanic prototype, but might allow for a different explanation for the anomalies this expression shows; that is, under such a view, it would show an anomaly because it is a borrowing in the same way that an expression like It goes without saying, calqued from French *Ça va sans dire*, does, with its unusual passive-like voice semantics for an active form of say. In particular, it has been suggested (Chapman (1986: 463, s.v.); see also Wentworth and Flexner ibid.) that what gives is a loan translation from German or Yiddish was *gibt* 'What's going on?'. +> +> +> + +The site itself has an even more thorough explanation of the phrase. However, it is a phrase on its own, rather than an abbreviation of another phrase. It means ""What's happening?"" or ""What's up?"" It is usually informal, though, so you would not see this in formal writing. You can use it in conversation with others, and they will understand you. However, the tone is slightly negative, so be careful when you choose to use it.","I've been living in Germany for 17 years, and this morning the similarity of the phrase ""What gives?"" to the German ""Was gibt's?"" occurred to me, so I checked the net ... + +The article [""What Gives with What Gives?""](http://babel.ucsc.edu/Jorge/joseph.html) by Brian Joseph of Ohio State University - also cited above - seems to provide a well founded discussion of the syntax and origin of the phrase in American English. Joseph argues, however, that the German may not be suitable as the origin of the phrase: + +> +> … there is no German expression that is simply *was gibt!* Rather, colloquial German has *was gibt es?* 'What is the matter? What's up?', but this is not a suitable source for *what gives* since the putative calquing did not lead to a direct counterpart to the German subject pronoun es (thus, *what gives*, not \**what gives it* or \**what does it give*). +> +> +> + +--- + +For all us non-linguists out there, Wikipedia says: + +> +> In linguistics, a calque (/ˈkælk/) or loan translation is a word or +> phrase borrowed from another language by literal, word-for-word +> (Latin: verbum pro verbo) or root-for-root translation. +> +> +> + +--- + +I believe, however, that his dismissal of the German as a source is flawed, because Joseph is principally arguing from a syntax-of-language standpoint and thus comparing the (written) WORDS instead of the SPOKEN language. + +Clearly in a comparison of the SYNTAX of ""Was - gibt - es ?"" with the English ""What - gives ?"" the word ""it"" (=""es"") is missing in the English. However, back then even more so than today, language is primarily a SPOKEN organism! - and a comparison of the SPOKEN phrases provides a very solid argument for its origin from the German: + +In the spoken German phrase ""Was gibt es?"" the second and third word are slurred together (at least, based on modern-day speech), so that only the ""s"" of ""es"" is pronounced (sorry, phonetics here are my best guess): + +/vasɡiːpts/ and /vasɡɪpts/ (normally written out with an apostrophe: ""Was gibt's"") + +In comparison to the English ""What gives?"", we can see (or rather hear) that the transition from the German to English comprises the translation of ""Was"" to ""what"" and the minimal change in the consonant sounds /pts/ to /vz/. + +The final /s/ in the German becomes the third person inflection ""(it) give*s*"" in the English. In other words the word ""it"" IS implicitly present in the English, but as an inflection of the verb instead of as an extra word. + +--- + +Wikipedia to the rescue again! Wikipedia explains that: + +> +> Calquing is distinct from phono-semantic matching.[3] While calquing +> includes semantic translation, it does not consist of phonetic +> matching (i.e. retaining the approximate sound of the borrowed word +> through matching it with a similar-sounding pre-existent word or +> morpheme in the target language). +> +> +> + +and + +> +> Phono-semantic matching (PSM) is a linguistic term referring to camouflaged borrowing in which a foreign word is matched with a phonetically and semantically similar pre-existent native word/root. +> +> +> + +--- + +So, to summarize: + +I argue that the phrase ""what gives?"" likely originates from the German ""Was gibt's?"", and transitioned to English primarily due to the phono-semantic match of the two phrases, and that the transition can be described as a calque in so far as the ""it"" is implied in the presence of the third person singular inflection /s/. + +I would be gratified if a linguist would take my argument further, and reiterate it using the correct phonetics. + +---" +39947,"I noticed the phrase “What gives?” in the following lines of the article of Washington Post (August 29) article, titled “Is Ron Paul being ignored?” + +> +> “And yet talk to almost anyone in politics — Republicans or Democrats — and the idea of Ron Paul as a top-tier candidate for president is greeted with either a laugh or an eye roll (or both.) +> +> +> *What gives?* +> +> +> Paul appears to be suffering from the “once bitten, twice shy” tendency of the media.” +> +> +> + +It appears to me “What gives?” is a common and frequently-used phrase, but I don’t think I’ve seen this phrase so often in written English format like newspaper articles, much less in English textbooks we use. +Does it mean “for what (reason)?” or ""What is its implication?"" What is the spelt-out format of “What gives?”",2011/08/30,"['https://english.stackexchange.com/questions/39947', 'https://english.stackexchange.com', 'https://english.stackexchange.com/users/3119/']","*What gives?* [means](http://idioms.thefreedictionary.com/What+Gives%3f): + +> +> Inf. What happened?; What went wrong?; What's the problem? +> +> +> Bill: Hi, you guys. What gives? Bob: Nothing, just a little misunderstanding. Tom's a little angry. +> +> +> Bob: Where's my wallet? What gives? +> +> +> Tom: I think one of those roughnecks who just walked by us has borrowed it for a little while. +> +> +> + +According to this page on the [linguistics of the phrase](http://ling.ucsc.edu/Jorge/joseph.html), it is not short for anything. There are a few theories about how it arose: + +> +> Regarding the issue of why *what gives* is anomalous, the best that I can offer (speaking now as an historical linguist) is to suggest that we turn to the history of the construction, but even there, full enlightenment is not forthcoming (see Joseph 2000 for more detailed discussion). The construction seems clearly to have originated in American English; the first attestation for what gives comes in 1940, in John O'Hara's Pal Joey, according to Wentworth and Flexner (1960: 574, s.v. what gives) and the Oxford English Dictionary (1989 on-line second edition). +> +> +> Even with this late attestation, what gives makes for an interesting comparison with the German existential use of *geben* 'to give', in the impersonal form with an expletive subject, *es gibt*, as in *Es gibt keinen Gott* 'There is no god', itself anomalous from the point of view of the usual syntax and meaning of *geben*... +> +> +> Some scholars however see what gives as having arisen via language contact, as a calque from German, an origin for it which would eliminate a basis for a Proto-West-Germanic prototype, but might allow for a different explanation for the anomalies this expression shows; that is, under such a view, it would show an anomaly because it is a borrowing in the same way that an expression like It goes without saying, calqued from French *Ça va sans dire*, does, with its unusual passive-like voice semantics for an active form of say. In particular, it has been suggested (Chapman (1986: 463, s.v.); see also Wentworth and Flexner ibid.) that what gives is a loan translation from German or Yiddish was *gibt* 'What's going on?'. +> +> +> + +The site itself has an even more thorough explanation of the phrase. However, it is a phrase on its own, rather than an abbreviation of another phrase. It means ""What's happening?"" or ""What's up?"" It is usually informal, though, so you would not see this in formal writing. You can use it in conversation with others, and they will understand you. However, the tone is slightly negative, so be careful when you choose to use it.","[As already observed](https://english.stackexchange.com/a/178303/16833), *What gives?* may well be derived from German *Was gibt es* via the more common contracted form *Was gibt's?*. As a native speaker of German who has spent some years in English-speaking countries I consider this particularly convincing because contrary to first impressions the uses of *What gives?* and *Was gibt's?* do actually overlap, and the overlap is in a kind of situation in which German speakers would be particularly likely to take such shortcuts as leaving out the *it* in an English sentence because the verb already ends in *s*. + +In German, *Was gibt es? / Was gibt's* is a neutral way of asking: *What's going on? / What's up?* But it is *also* something a drunk person is likely to say when feeling slighted by someone and trying to start a fight without really knowing why. (Of course there are also alternatives, such as *Was ist los?*) In this situation the question may well be repeated several times, and invariably in the contracted form *Was gibt's* rather than the long form *Was gibt es?*. + +(By the way, in northern Germany people are less likely to use the contraction, but instead they are likely to say *wat* instead of *was*: *Wat gibt es?* This is intriguing, though I doubt that it played an important role.) + +So I imagine a drunk, agitated German speaker in the US. Under the circumstances he may be mixing up and simplifying German and English phonetics: + +""Was hast du gesagt? Whas did you say? ... Was gib's? Was gib's? Was gib's?"" + +I think it would be natural for a native English speaker addressed in this way to remember the mysterious question as *What gives?* Or indeed the German speaker may say *What gives?* himself in his attempt to speak English. + +(I think it would have been more proper to upvote [the other answer](https://english.stackexchange.com/a/178303/16833) and add a short comment to it than make this a separate answer, but apparently both actions require 'reputation'.)" +39947,"I noticed the phrase “What gives?” in the following lines of the article of Washington Post (August 29) article, titled “Is Ron Paul being ignored?” + +> +> “And yet talk to almost anyone in politics — Republicans or Democrats — and the idea of Ron Paul as a top-tier candidate for president is greeted with either a laugh or an eye roll (or both.) +> +> +> *What gives?* +> +> +> Paul appears to be suffering from the “once bitten, twice shy” tendency of the media.” +> +> +> + +It appears to me “What gives?” is a common and frequently-used phrase, but I don’t think I’ve seen this phrase so often in written English format like newspaper articles, much less in English textbooks we use. +Does it mean “for what (reason)?” or ""What is its implication?"" What is the spelt-out format of “What gives?”",2011/08/30,"['https://english.stackexchange.com/questions/39947', 'https://english.stackexchange.com', 'https://english.stackexchange.com/users/3119/']","*What gives?* [means](http://idioms.thefreedictionary.com/What+Gives%3f): + +> +> Inf. What happened?; What went wrong?; What's the problem? +> +> +> Bill: Hi, you guys. What gives? Bob: Nothing, just a little misunderstanding. Tom's a little angry. +> +> +> Bob: Where's my wallet? What gives? +> +> +> Tom: I think one of those roughnecks who just walked by us has borrowed it for a little while. +> +> +> + +According to this page on the [linguistics of the phrase](http://ling.ucsc.edu/Jorge/joseph.html), it is not short for anything. There are a few theories about how it arose: + +> +> Regarding the issue of why *what gives* is anomalous, the best that I can offer (speaking now as an historical linguist) is to suggest that we turn to the history of the construction, but even there, full enlightenment is not forthcoming (see Joseph 2000 for more detailed discussion). The construction seems clearly to have originated in American English; the first attestation for what gives comes in 1940, in John O'Hara's Pal Joey, according to Wentworth and Flexner (1960: 574, s.v. what gives) and the Oxford English Dictionary (1989 on-line second edition). +> +> +> Even with this late attestation, what gives makes for an interesting comparison with the German existential use of *geben* 'to give', in the impersonal form with an expletive subject, *es gibt*, as in *Es gibt keinen Gott* 'There is no god', itself anomalous from the point of view of the usual syntax and meaning of *geben*... +> +> +> Some scholars however see what gives as having arisen via language contact, as a calque from German, an origin for it which would eliminate a basis for a Proto-West-Germanic prototype, but might allow for a different explanation for the anomalies this expression shows; that is, under such a view, it would show an anomaly because it is a borrowing in the same way that an expression like It goes without saying, calqued from French *Ça va sans dire*, does, with its unusual passive-like voice semantics for an active form of say. In particular, it has been suggested (Chapman (1986: 463, s.v.); see also Wentworth and Flexner ibid.) that what gives is a loan translation from German or Yiddish was *gibt* 'What's going on?'. +> +> +> + +The site itself has an even more thorough explanation of the phrase. However, it is a phrase on its own, rather than an abbreviation of another phrase. It means ""What's happening?"" or ""What's up?"" It is usually informal, though, so you would not see this in formal writing. You can use it in conversation with others, and they will understand you. However, the tone is slightly negative, so be careful when you choose to use it.","Leo Rosten, *The Joys of Yinglish* (1989) claims ""What gives"" as a characteristic element of what he calls ""Yinglish"" (hybridized English/Yiddish or Yiddish-inflected English): + +> +> **What gives?** +> +> +> This is a stellar addition to the colloquial phrases of conversational Yinglish. From Yiddish: *Vi geyt's*?"" ""How goes it?"" Via German: *Was gibt*? +> +> +> 1. What's going on there? +> 2. What's new? +> 3. What's the matter? What's wrong? +> 4. Tell me the whole story. +> +> +> + +As the multiple definitions in Rosten's account indicate, people use ""What gives?"" can be used in a number of distinct senses. But the most common ones in my experience are ""What's going on?"" (asked curiously or querulously) and ""What's wrong?"" (asked sympathetically). + +According to Christine Ammer, *The American Heritage Dictionary of Idioms* (1997), ""what gives"" can also mean ""how are you"": + +> +> The last variant [of ""what's cooking""], **what gives**, may derive from the German equivalent, *Was gibt's?* Slang from about 1940, it is also used to mean, ""how are you,"" as in *Hello, Jack—what gives?* +> +> +> + +As simchona's answer indicates, Harold Wentworth & Stuart Flexner have a detailed entry for ""What gives?"" in *Dictionary of American Slang*, first edition (1960): + +> +> **What gives?** **1** A common greeting. **2** ""What's happening?"" ""What did I do to make you say or do that?"" [Cross reference omitted.] 3 = **What's new?** *Perhaps a lit. translation of the Ger. ""was ist los?""* **1939:** ""What gives, I asked her...."" O'Hara, *Pal Joey*, 43. **1949:** ""What gives?' he croaked in an annoyed tone."" Chandler, *Little Sister*, 21. +> +> +> + +The instance from John O'Hara's *Pal Joey* appeared under the title ""[Joey and the Calcutta Club](https://books.google.com/books?id=BzYdAQAAMAAJ&q=%22what+gives,+I+asked+her%22&dq=%22what+gives,+I+asked+her%22&hl=en&sa=X&ved=0ahUKEwjPlPHy2tDOAhVI9WMKHRMAC4gQ6AEIUjAJ)"" in *The New Yorker* (March 30, 1940) [combined snippets]: + +> +> So Quinn asked me to join them and I did and this mouse with them named Jean Benedict looks like 10000 other dames on the line of some Bway show except when she opens her trap she has an accent that is so British even Sir Nevile Chamberlin would not be able to understand her. I knew she was strictly U.S.A. by appearance but the accent is so good I think what is the angle. **What gives**, I asked her, altho not in so many words. I inquired how she happen to have the accent and she said a lot of people inquire of her the same thing and it is easily explained. She is half American and her father is British. +> +> +> + +And from Raymond Chandler's [*The Little Sister*](https://books.google.com/books?id=YaaU052RltUC&pg=PA244&dq=%22what+gives?+he+croaked%22&hl=en&sa=X&ved=0ahUKEwi0woKr3dDOAhVW92MKHaPADcQQ6AEIHjAA#v=onepage&q=%22what%20gives%3F%20he%20croaked%22&f=false) (1949): + +> +> He made a grab for the glass [of gin, freshly poured by Marlowe]. I put it on the table in front of him. He grasped it carefully in both hands and poured the gin into his face. Then he laughed heartily and threw the glass at me. I managed to catch it and up-end it on the table again. The man looked me over with a studied but unsuccessful attempt at sternness. +> +> +> ""**What gives**?"" he croaked in an annoyed tone. +> +> +> ""Manager?"" +> +> +> He nodded and almost fell off the couch. ""Must be I'm drunky,"" he said. ""Kind of a bit of a little bit drunky."" +> +> +> ""You're not bad,"" I said. ""You're still breathing."" +> +> +> + +Somewhat surprisingly, the earliest match that a separate Google Books search finds for the expression is from Elizabeth Kata, [*Be Ready with Bells & Drums*](https://books.google.com/books?id=lAAfAAAAMAAJ&q=%22what+gives%22&dq=%22what+gives%22&hl=en&sa=X&ved=0ahUKEwj7i6uA4NDOAhUU22MKHRTQDmo4ChDoAQgiMAI) (1961): + +> +> ""Is that you. Paul?"" Gordon asked. +> +> +> 'But of course. Excuse me for asking, Dad, but **what gives**? **What gives** out there with Orphan Annie, with little Eva. With your—friend—so I'm told. You care to tell me **what gives**, Dad? Honoured older brother, you mind telling me about this friend of yours?' +> +> +> ... +> +> +> 'It's nice to know you care. I'm glad you love me, Dad.' I heard them laughing together. It was fine to hear brothers laughing together. Paul went on speaking. +> +> +> 'You're evading the issue—I don't like any issue being evaded. **What gives** with li'l Eva? Who, what, when, where, and for Pete's sake, why? Why?' +> +> +> + +In this dialogue, ""Dad"" appears to be beatnik talk for ""friend"" or ""pal."" Kata was an Australian novelist, not an American; but the usage of ""what gives"" in this excerpt mirrors U.S. usage." +39947,"I noticed the phrase “What gives?” in the following lines of the article of Washington Post (August 29) article, titled “Is Ron Paul being ignored?” + +> +> “And yet talk to almost anyone in politics — Republicans or Democrats — and the idea of Ron Paul as a top-tier candidate for president is greeted with either a laugh or an eye roll (or both.) +> +> +> *What gives?* +> +> +> Paul appears to be suffering from the “once bitten, twice shy” tendency of the media.” +> +> +> + +It appears to me “What gives?” is a common and frequently-used phrase, but I don’t think I’ve seen this phrase so often in written English format like newspaper articles, much less in English textbooks we use. +Does it mean “for what (reason)?” or ""What is its implication?"" What is the spelt-out format of “What gives?”",2011/08/30,"['https://english.stackexchange.com/questions/39947', 'https://english.stackexchange.com', 'https://english.stackexchange.com/users/3119/']","I've been living in Germany for 17 years, and this morning the similarity of the phrase ""What gives?"" to the German ""Was gibt's?"" occurred to me, so I checked the net ... + +The article [""What Gives with What Gives?""](http://babel.ucsc.edu/Jorge/joseph.html) by Brian Joseph of Ohio State University - also cited above - seems to provide a well founded discussion of the syntax and origin of the phrase in American English. Joseph argues, however, that the German may not be suitable as the origin of the phrase: + +> +> … there is no German expression that is simply *was gibt!* Rather, colloquial German has *was gibt es?* 'What is the matter? What's up?', but this is not a suitable source for *what gives* since the putative calquing did not lead to a direct counterpart to the German subject pronoun es (thus, *what gives*, not \**what gives it* or \**what does it give*). +> +> +> + +--- + +For all us non-linguists out there, Wikipedia says: + +> +> In linguistics, a calque (/ˈkælk/) or loan translation is a word or +> phrase borrowed from another language by literal, word-for-word +> (Latin: verbum pro verbo) or root-for-root translation. +> +> +> + +--- + +I believe, however, that his dismissal of the German as a source is flawed, because Joseph is principally arguing from a syntax-of-language standpoint and thus comparing the (written) WORDS instead of the SPOKEN language. + +Clearly in a comparison of the SYNTAX of ""Was - gibt - es ?"" with the English ""What - gives ?"" the word ""it"" (=""es"") is missing in the English. However, back then even more so than today, language is primarily a SPOKEN organism! - and a comparison of the SPOKEN phrases provides a very solid argument for its origin from the German: + +In the spoken German phrase ""Was gibt es?"" the second and third word are slurred together (at least, based on modern-day speech), so that only the ""s"" of ""es"" is pronounced (sorry, phonetics here are my best guess): + +/vasɡiːpts/ and /vasɡɪpts/ (normally written out with an apostrophe: ""Was gibt's"") + +In comparison to the English ""What gives?"", we can see (or rather hear) that the transition from the German to English comprises the translation of ""Was"" to ""what"" and the minimal change in the consonant sounds /pts/ to /vz/. + +The final /s/ in the German becomes the third person inflection ""(it) give*s*"" in the English. In other words the word ""it"" IS implicitly present in the English, but as an inflection of the verb instead of as an extra word. + +--- + +Wikipedia to the rescue again! Wikipedia explains that: + +> +> Calquing is distinct from phono-semantic matching.[3] While calquing +> includes semantic translation, it does not consist of phonetic +> matching (i.e. retaining the approximate sound of the borrowed word +> through matching it with a similar-sounding pre-existent word or +> morpheme in the target language). +> +> +> + +and + +> +> Phono-semantic matching (PSM) is a linguistic term referring to camouflaged borrowing in which a foreign word is matched with a phonetically and semantically similar pre-existent native word/root. +> +> +> + +--- + +So, to summarize: + +I argue that the phrase ""what gives?"" likely originates from the German ""Was gibt's?"", and transitioned to English primarily due to the phono-semantic match of the two phrases, and that the transition can be described as a calque in so far as the ""it"" is implied in the presence of the third person singular inflection /s/. + +I would be gratified if a linguist would take my argument further, and reiterate it using the correct phonetics. + +---","Leo Rosten, *The Joys of Yinglish* (1989) claims ""What gives"" as a characteristic element of what he calls ""Yinglish"" (hybridized English/Yiddish or Yiddish-inflected English): + +> +> **What gives?** +> +> +> This is a stellar addition to the colloquial phrases of conversational Yinglish. From Yiddish: *Vi geyt's*?"" ""How goes it?"" Via German: *Was gibt*? +> +> +> 1. What's going on there? +> 2. What's new? +> 3. What's the matter? What's wrong? +> 4. Tell me the whole story. +> +> +> + +As the multiple definitions in Rosten's account indicate, people use ""What gives?"" can be used in a number of distinct senses. But the most common ones in my experience are ""What's going on?"" (asked curiously or querulously) and ""What's wrong?"" (asked sympathetically). + +According to Christine Ammer, *The American Heritage Dictionary of Idioms* (1997), ""what gives"" can also mean ""how are you"": + +> +> The last variant [of ""what's cooking""], **what gives**, may derive from the German equivalent, *Was gibt's?* Slang from about 1940, it is also used to mean, ""how are you,"" as in *Hello, Jack—what gives?* +> +> +> + +As simchona's answer indicates, Harold Wentworth & Stuart Flexner have a detailed entry for ""What gives?"" in *Dictionary of American Slang*, first edition (1960): + +> +> **What gives?** **1** A common greeting. **2** ""What's happening?"" ""What did I do to make you say or do that?"" [Cross reference omitted.] 3 = **What's new?** *Perhaps a lit. translation of the Ger. ""was ist los?""* **1939:** ""What gives, I asked her...."" O'Hara, *Pal Joey*, 43. **1949:** ""What gives?' he croaked in an annoyed tone."" Chandler, *Little Sister*, 21. +> +> +> + +The instance from John O'Hara's *Pal Joey* appeared under the title ""[Joey and the Calcutta Club](https://books.google.com/books?id=BzYdAQAAMAAJ&q=%22what+gives,+I+asked+her%22&dq=%22what+gives,+I+asked+her%22&hl=en&sa=X&ved=0ahUKEwjPlPHy2tDOAhVI9WMKHRMAC4gQ6AEIUjAJ)"" in *The New Yorker* (March 30, 1940) [combined snippets]: + +> +> So Quinn asked me to join them and I did and this mouse with them named Jean Benedict looks like 10000 other dames on the line of some Bway show except when she opens her trap she has an accent that is so British even Sir Nevile Chamberlin would not be able to understand her. I knew she was strictly U.S.A. by appearance but the accent is so good I think what is the angle. **What gives**, I asked her, altho not in so many words. I inquired how she happen to have the accent and she said a lot of people inquire of her the same thing and it is easily explained. She is half American and her father is British. +> +> +> + +And from Raymond Chandler's [*The Little Sister*](https://books.google.com/books?id=YaaU052RltUC&pg=PA244&dq=%22what+gives?+he+croaked%22&hl=en&sa=X&ved=0ahUKEwi0woKr3dDOAhVW92MKHaPADcQQ6AEIHjAA#v=onepage&q=%22what%20gives%3F%20he%20croaked%22&f=false) (1949): + +> +> He made a grab for the glass [of gin, freshly poured by Marlowe]. I put it on the table in front of him. He grasped it carefully in both hands and poured the gin into his face. Then he laughed heartily and threw the glass at me. I managed to catch it and up-end it on the table again. The man looked me over with a studied but unsuccessful attempt at sternness. +> +> +> ""**What gives**?"" he croaked in an annoyed tone. +> +> +> ""Manager?"" +> +> +> He nodded and almost fell off the couch. ""Must be I'm drunky,"" he said. ""Kind of a bit of a little bit drunky."" +> +> +> ""You're not bad,"" I said. ""You're still breathing."" +> +> +> + +Somewhat surprisingly, the earliest match that a separate Google Books search finds for the expression is from Elizabeth Kata, [*Be Ready with Bells & Drums*](https://books.google.com/books?id=lAAfAAAAMAAJ&q=%22what+gives%22&dq=%22what+gives%22&hl=en&sa=X&ved=0ahUKEwj7i6uA4NDOAhUU22MKHRTQDmo4ChDoAQgiMAI) (1961): + +> +> ""Is that you. Paul?"" Gordon asked. +> +> +> 'But of course. Excuse me for asking, Dad, but **what gives**? **What gives** out there with Orphan Annie, with little Eva. With your—friend—so I'm told. You care to tell me **what gives**, Dad? Honoured older brother, you mind telling me about this friend of yours?' +> +> +> ... +> +> +> 'It's nice to know you care. I'm glad you love me, Dad.' I heard them laughing together. It was fine to hear brothers laughing together. Paul went on speaking. +> +> +> 'You're evading the issue—I don't like any issue being evaded. **What gives** with li'l Eva? Who, what, when, where, and for Pete's sake, why? Why?' +> +> +> + +In this dialogue, ""Dad"" appears to be beatnik talk for ""friend"" or ""pal."" Kata was an Australian novelist, not an American; but the usage of ""what gives"" in this excerpt mirrors U.S. usage." +39947,"I noticed the phrase “What gives?” in the following lines of the article of Washington Post (August 29) article, titled “Is Ron Paul being ignored?” + +> +> “And yet talk to almost anyone in politics — Republicans or Democrats — and the idea of Ron Paul as a top-tier candidate for president is greeted with either a laugh or an eye roll (or both.) +> +> +> *What gives?* +> +> +> Paul appears to be suffering from the “once bitten, twice shy” tendency of the media.” +> +> +> + +It appears to me “What gives?” is a common and frequently-used phrase, but I don’t think I’ve seen this phrase so often in written English format like newspaper articles, much less in English textbooks we use. +Does it mean “for what (reason)?” or ""What is its implication?"" What is the spelt-out format of “What gives?”",2011/08/30,"['https://english.stackexchange.com/questions/39947', 'https://english.stackexchange.com', 'https://english.stackexchange.com/users/3119/']","[As already observed](https://english.stackexchange.com/a/178303/16833), *What gives?* may well be derived from German *Was gibt es* via the more common contracted form *Was gibt's?*. As a native speaker of German who has spent some years in English-speaking countries I consider this particularly convincing because contrary to first impressions the uses of *What gives?* and *Was gibt's?* do actually overlap, and the overlap is in a kind of situation in which German speakers would be particularly likely to take such shortcuts as leaving out the *it* in an English sentence because the verb already ends in *s*. + +In German, *Was gibt es? / Was gibt's* is a neutral way of asking: *What's going on? / What's up?* But it is *also* something a drunk person is likely to say when feeling slighted by someone and trying to start a fight without really knowing why. (Of course there are also alternatives, such as *Was ist los?*) In this situation the question may well be repeated several times, and invariably in the contracted form *Was gibt's* rather than the long form *Was gibt es?*. + +(By the way, in northern Germany people are less likely to use the contraction, but instead they are likely to say *wat* instead of *was*: *Wat gibt es?* This is intriguing, though I doubt that it played an important role.) + +So I imagine a drunk, agitated German speaker in the US. Under the circumstances he may be mixing up and simplifying German and English phonetics: + +""Was hast du gesagt? Whas did you say? ... Was gib's? Was gib's? Was gib's?"" + +I think it would be natural for a native English speaker addressed in this way to remember the mysterious question as *What gives?* Or indeed the German speaker may say *What gives?* himself in his attempt to speak English. + +(I think it would have been more proper to upvote [the other answer](https://english.stackexchange.com/a/178303/16833) and add a short comment to it than make this a separate answer, but apparently both actions require 'reputation'.)","Leo Rosten, *The Joys of Yinglish* (1989) claims ""What gives"" as a characteristic element of what he calls ""Yinglish"" (hybridized English/Yiddish or Yiddish-inflected English): + +> +> **What gives?** +> +> +> This is a stellar addition to the colloquial phrases of conversational Yinglish. From Yiddish: *Vi geyt's*?"" ""How goes it?"" Via German: *Was gibt*? +> +> +> 1. What's going on there? +> 2. What's new? +> 3. What's the matter? What's wrong? +> 4. Tell me the whole story. +> +> +> + +As the multiple definitions in Rosten's account indicate, people use ""What gives?"" can be used in a number of distinct senses. But the most common ones in my experience are ""What's going on?"" (asked curiously or querulously) and ""What's wrong?"" (asked sympathetically). + +According to Christine Ammer, *The American Heritage Dictionary of Idioms* (1997), ""what gives"" can also mean ""how are you"": + +> +> The last variant [of ""what's cooking""], **what gives**, may derive from the German equivalent, *Was gibt's?* Slang from about 1940, it is also used to mean, ""how are you,"" as in *Hello, Jack—what gives?* +> +> +> + +As simchona's answer indicates, Harold Wentworth & Stuart Flexner have a detailed entry for ""What gives?"" in *Dictionary of American Slang*, first edition (1960): + +> +> **What gives?** **1** A common greeting. **2** ""What's happening?"" ""What did I do to make you say or do that?"" [Cross reference omitted.] 3 = **What's new?** *Perhaps a lit. translation of the Ger. ""was ist los?""* **1939:** ""What gives, I asked her...."" O'Hara, *Pal Joey*, 43. **1949:** ""What gives?' he croaked in an annoyed tone."" Chandler, *Little Sister*, 21. +> +> +> + +The instance from John O'Hara's *Pal Joey* appeared under the title ""[Joey and the Calcutta Club](https://books.google.com/books?id=BzYdAQAAMAAJ&q=%22what+gives,+I+asked+her%22&dq=%22what+gives,+I+asked+her%22&hl=en&sa=X&ved=0ahUKEwjPlPHy2tDOAhVI9WMKHRMAC4gQ6AEIUjAJ)"" in *The New Yorker* (March 30, 1940) [combined snippets]: + +> +> So Quinn asked me to join them and I did and this mouse with them named Jean Benedict looks like 10000 other dames on the line of some Bway show except when she opens her trap she has an accent that is so British even Sir Nevile Chamberlin would not be able to understand her. I knew she was strictly U.S.A. by appearance but the accent is so good I think what is the angle. **What gives**, I asked her, altho not in so many words. I inquired how she happen to have the accent and she said a lot of people inquire of her the same thing and it is easily explained. She is half American and her father is British. +> +> +> + +And from Raymond Chandler's [*The Little Sister*](https://books.google.com/books?id=YaaU052RltUC&pg=PA244&dq=%22what+gives?+he+croaked%22&hl=en&sa=X&ved=0ahUKEwi0woKr3dDOAhVW92MKHaPADcQQ6AEIHjAA#v=onepage&q=%22what%20gives%3F%20he%20croaked%22&f=false) (1949): + +> +> He made a grab for the glass [of gin, freshly poured by Marlowe]. I put it on the table in front of him. He grasped it carefully in both hands and poured the gin into his face. Then he laughed heartily and threw the glass at me. I managed to catch it and up-end it on the table again. The man looked me over with a studied but unsuccessful attempt at sternness. +> +> +> ""**What gives**?"" he croaked in an annoyed tone. +> +> +> ""Manager?"" +> +> +> He nodded and almost fell off the couch. ""Must be I'm drunky,"" he said. ""Kind of a bit of a little bit drunky."" +> +> +> ""You're not bad,"" I said. ""You're still breathing."" +> +> +> + +Somewhat surprisingly, the earliest match that a separate Google Books search finds for the expression is from Elizabeth Kata, [*Be Ready with Bells & Drums*](https://books.google.com/books?id=lAAfAAAAMAAJ&q=%22what+gives%22&dq=%22what+gives%22&hl=en&sa=X&ved=0ahUKEwj7i6uA4NDOAhUU22MKHRTQDmo4ChDoAQgiMAI) (1961): + +> +> ""Is that you. Paul?"" Gordon asked. +> +> +> 'But of course. Excuse me for asking, Dad, but **what gives**? **What gives** out there with Orphan Annie, with little Eva. With your—friend—so I'm told. You care to tell me **what gives**, Dad? Honoured older brother, you mind telling me about this friend of yours?' +> +> +> ... +> +> +> 'It's nice to know you care. I'm glad you love me, Dad.' I heard them laughing together. It was fine to hear brothers laughing together. Paul went on speaking. +> +> +> 'You're evading the issue—I don't like any issue being evaded. **What gives** with li'l Eva? Who, what, when, where, and for Pete's sake, why? Why?' +> +> +> + +In this dialogue, ""Dad"" appears to be beatnik talk for ""friend"" or ""pal."" Kata was an Australian novelist, not an American; but the usage of ""what gives"" in this excerpt mirrors U.S. usage." +35937244,"I have an application where I want to filter a long list of products based on value from ""select"" containing product types. The filter works, but only after I select something. It initially sets the ""Show All"" option, but filters out everything. If I select something else, it works, and if I re-select ""Show All"" it works. But why doesn't the filter work initially? + +The model (looks something like this): + +``` +$scope.products = {[ + {name: 'productA',Type: 1}, + {name: 'productB',Type: 1}, + {name: 'productC',Type: 2}, + {name: 'productD',Type: 2}, +]}; + +$scope.productTypes = {[ + {Name: 'typeAlpha',Type: 1}, + {Name: 'typeBravo',Type: 2}, +]}; + +``` + +The HTML: + +``` + +

{{product.Name}}

+ +```",2016/03/11,"['https://Stackoverflow.com/questions/35937244', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4233688/']","I recommend using ng-options instead of ng-repeat over the options: + +``` + +

+ {{product.name}} +

+ +``` + +For ""show all"", the filter must return undefined ([ng-repeat filter ""show all"" items if no filter selected](https://stackoverflow.com/questions/28164580/ng-repeat-filter-show-all-items-if-no-filter-selected)) + +Also removed the {..} around the array and better use lower case for properties: + +``` + $scope.products = [ + {name: 'productA', type: 1}, + {name: 'productB', type: 1}, + {name: 'productC', type: 2}, + {name: 'productD', type: 2} + ]; + + $scope.productTypes = [ + {name: 'typeAlpha', type: 1}, + {name: 'typeBravo', type: 2} + ]; + +``` + +Here is a jsbin (based on Hiskinds) +","This is a working example based on code above: + +The Slava.N's comment is correct and you should not wrap productTypes and product in {} + +Also, JavaScript is a case-sensitive language, `product.Name` is always undefined, you should use `product.name` in your HTML instead." +35937244,"I have an application where I want to filter a long list of products based on value from ""select"" containing product types. The filter works, but only after I select something. It initially sets the ""Show All"" option, but filters out everything. If I select something else, it works, and if I re-select ""Show All"" it works. But why doesn't the filter work initially? + +The model (looks something like this): + +``` +$scope.products = {[ + {name: 'productA',Type: 1}, + {name: 'productB',Type: 1}, + {name: 'productC',Type: 2}, + {name: 'productD',Type: 2}, +]}; + +$scope.productTypes = {[ + {Name: 'typeAlpha',Type: 1}, + {Name: 'typeBravo',Type: 2}, +]}; + +``` + +The HTML: + +``` + +

{{product.Name}}

+ +```",2016/03/11,"['https://Stackoverflow.com/questions/35937244', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4233688/']","I recommend using ng-options instead of ng-repeat over the options: + +``` + +

+ {{product.name}} +

+ +``` + +For ""show all"", the filter must return undefined ([ng-repeat filter ""show all"" items if no filter selected](https://stackoverflow.com/questions/28164580/ng-repeat-filter-show-all-items-if-no-filter-selected)) + +Also removed the {..} around the array and better use lower case for properties: + +``` + $scope.products = [ + {name: 'productA', type: 1}, + {name: 'productB', type: 1}, + {name: 'productC', type: 2}, + {name: 'productD', type: 2} + ]; + + $scope.productTypes = [ + {name: 'typeAlpha', type: 1}, + {name: 'typeBravo', type: 2} + ]; + +``` + +Here is a jsbin (based on Hiskinds) +",Use product.Type instead ofType inside 2nd ng-repeat filter +35937244,"I have an application where I want to filter a long list of products based on value from ""select"" containing product types. The filter works, but only after I select something. It initially sets the ""Show All"" option, but filters out everything. If I select something else, it works, and if I re-select ""Show All"" it works. But why doesn't the filter work initially? + +The model (looks something like this): + +``` +$scope.products = {[ + {name: 'productA',Type: 1}, + {name: 'productB',Type: 1}, + {name: 'productC',Type: 2}, + {name: 'productD',Type: 2}, +]}; + +$scope.productTypes = {[ + {Name: 'typeAlpha',Type: 1}, + {Name: 'typeBravo',Type: 2}, +]}; + +``` + +The HTML: + +``` + +

{{product.Name}}

+ +```",2016/03/11,"['https://Stackoverflow.com/questions/35937244', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4233688/']","I recommend using ng-options instead of ng-repeat over the options: + +``` + +

+ {{product.name}} +

+ +``` + +For ""show all"", the filter must return undefined ([ng-repeat filter ""show all"" items if no filter selected](https://stackoverflow.com/questions/28164580/ng-repeat-filter-show-all-items-if-no-filter-selected)) + +Also removed the {..} around the array and better use lower case for properties: + +``` + $scope.products = [ + {name: 'productA', type: 1}, + {name: 'productB', type: 1}, + {name: 'productC', type: 2}, + {name: 'productD', type: 2} + ]; + + $scope.productTypes = [ + {name: 'typeAlpha', type: 1}, + {name: 'typeBravo', type: 2} + ]; + +``` + +Here is a jsbin (based on Hiskinds) +","you set $scope.productFilter = ''. +so its return by default value blank at filter." +4701114,Is there a way to tell the split command to save the resultant files in a particular location?,2011/01/15,"['https://Stackoverflow.com/questions/4701114', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/50329/']","How about: + +``` +$ split -b 10 input.txt xxx/split-file + +``` + +or + +``` +$ split -b 10 input.txt /tmp/split-file + +``` + +Just include the output directory in the prefix specification. Keep in mind that the directory must be created beforehand.","This is the MacOS X (BSD) version of split, and includes some features of `csplit`: + +> +> split [-a suffix\_length] [-b byte\_count[k|m]] [-l line\_count] [-p pattern] [file [name]] +> +> +> + +The `name` specifies the prefix to the file name - the default is `x`, effectively `./x`. + +So, you do: + +``` + split bigfile /lots/of/little/files/here + +``` + +### POSIX + +The POSIX definition of [`split`](http://pubs.opengroup.org/onlinepubs/9699919799/utilities/split.html) gives the synopses: + +> +> +> ``` +> split [-l line_count] [-a suffix_length] [file [name]] +> +> split -b n[k|m] [-a suffix_length] [file [name]] +> +> ``` +> +> + +(The web site has a repeated typo - no space between `file` and `[name]`.)" +4427,"Motivated by these questions: + +[Case Study: First Answer Bias](https://academia.meta.stackexchange.com/q/4414/19607) and [Are upvotes skewed towards the first answer to a question?](https://academia.meta.stackexchange.com/q/3826/19607) + +I propose a biased (biased towards people who use the meta site) study of AcademiaSE users to see how much of an upvote biases the first answer to a question gets (the ""fastest gun in the west"" problem) from ""non-random"" Academia users. To wit, + +> +> For questions you read which have multiple answers, do you typically vote on an answer before reading other answers? (Answer by up-voting answers below. At least for this question, please read the answers first and upvote at least one.) +> +> +>",2019/02/10,"['https://academia.meta.stackexchange.com/questions/4427', 'https://academia.meta.stackexchange.com', 'https://academia.meta.stackexchange.com/users/19607/']",I typically vote on answers I like right after reading them but usually read several of the answers.,I typically read most answers before voting. +4427,"Motivated by these questions: + +[Case Study: First Answer Bias](https://academia.meta.stackexchange.com/q/4414/19607) and [Are upvotes skewed towards the first answer to a question?](https://academia.meta.stackexchange.com/q/3826/19607) + +I propose a biased (biased towards people who use the meta site) study of AcademiaSE users to see how much of an upvote biases the first answer to a question gets (the ""fastest gun in the west"" problem) from ""non-random"" Academia users. To wit, + +> +> For questions you read which have multiple answers, do you typically vote on an answer before reading other answers? (Answer by up-voting answers below. At least for this question, please read the answers first and upvote at least one.) +> +> +>",2019/02/10,"['https://academia.meta.stackexchange.com/questions/4427', 'https://academia.meta.stackexchange.com', 'https://academia.meta.stackexchange.com/users/19607/']",I typically read most answers before voting.,I typically vote on answers I like right after reading them and often don't read further answers. +4427,"Motivated by these questions: + +[Case Study: First Answer Bias](https://academia.meta.stackexchange.com/q/4414/19607) and [Are upvotes skewed towards the first answer to a question?](https://academia.meta.stackexchange.com/q/3826/19607) + +I propose a biased (biased towards people who use the meta site) study of AcademiaSE users to see how much of an upvote biases the first answer to a question gets (the ""fastest gun in the west"" problem) from ""non-random"" Academia users. To wit, + +> +> For questions you read which have multiple answers, do you typically vote on an answer before reading other answers? (Answer by up-voting answers below. At least for this question, please read the answers first and upvote at least one.) +> +> +>",2019/02/10,"['https://academia.meta.stackexchange.com/questions/4427', 'https://academia.meta.stackexchange.com', 'https://academia.meta.stackexchange.com/users/19607/']",I typically read most answers before voting.,"**Other** (vote before reading, never vote, ...) + +Please explain in comments." +4427,"Motivated by these questions: + +[Case Study: First Answer Bias](https://academia.meta.stackexchange.com/q/4414/19607) and [Are upvotes skewed towards the first answer to a question?](https://academia.meta.stackexchange.com/q/3826/19607) + +I propose a biased (biased towards people who use the meta site) study of AcademiaSE users to see how much of an upvote biases the first answer to a question gets (the ""fastest gun in the west"" problem) from ""non-random"" Academia users. To wit, + +> +> For questions you read which have multiple answers, do you typically vote on an answer before reading other answers? (Answer by up-voting answers below. At least for this question, please read the answers first and upvote at least one.) +> +> +>",2019/02/10,"['https://academia.meta.stackexchange.com/questions/4427', 'https://academia.meta.stackexchange.com', 'https://academia.meta.stackexchange.com/users/19607/']",I typically vote on answers I like right after reading them but usually read several of the answers.,I typically vote on answers I like right after reading them and often don't read further answers. +4427,"Motivated by these questions: + +[Case Study: First Answer Bias](https://academia.meta.stackexchange.com/q/4414/19607) and [Are upvotes skewed towards the first answer to a question?](https://academia.meta.stackexchange.com/q/3826/19607) + +I propose a biased (biased towards people who use the meta site) study of AcademiaSE users to see how much of an upvote biases the first answer to a question gets (the ""fastest gun in the west"" problem) from ""non-random"" Academia users. To wit, + +> +> For questions you read which have multiple answers, do you typically vote on an answer before reading other answers? (Answer by up-voting answers below. At least for this question, please read the answers first and upvote at least one.) +> +> +>",2019/02/10,"['https://academia.meta.stackexchange.com/questions/4427', 'https://academia.meta.stackexchange.com', 'https://academia.meta.stackexchange.com/users/19607/']",I typically vote on answers I like right after reading them but usually read several of the answers.,"**Other** (vote before reading, never vote, ...) + +Please explain in comments." +4427,"Motivated by these questions: + +[Case Study: First Answer Bias](https://academia.meta.stackexchange.com/q/4414/19607) and [Are upvotes skewed towards the first answer to a question?](https://academia.meta.stackexchange.com/q/3826/19607) + +I propose a biased (biased towards people who use the meta site) study of AcademiaSE users to see how much of an upvote biases the first answer to a question gets (the ""fastest gun in the west"" problem) from ""non-random"" Academia users. To wit, + +> +> For questions you read which have multiple answers, do you typically vote on an answer before reading other answers? (Answer by up-voting answers below. At least for this question, please read the answers first and upvote at least one.) +> +> +>",2019/02/10,"['https://academia.meta.stackexchange.com/questions/4427', 'https://academia.meta.stackexchange.com', 'https://academia.meta.stackexchange.com/users/19607/']","**Other** (vote before reading, never vote, ...) + +Please explain in comments.",I typically vote on answers I like right after reading them and often don't read further answers. +40375015,"My scenario is like this : I have some texts and image inside the Container. Both of them display correctly with different screen sizes. + +However, it doesn't display to my expected result when I view it in Desktop. + +[![enter image description here](https://i.stack.imgur.com/kPGhO.jpg)](https://i.stack.imgur.com/kPGhO.jpg) + +**What I want to achieve is something similar to screenshot(Responsive). Anyone know how to do that?** + +``` + + + + Bootstrap Example + + + + + + + + + + +
+

A solid border.A solid border.A solid border.A solid border.A solid border.A solid border.A solid border.A solid border.A solid border.A solid border.A solid border.A solid border.A solid border.A solid border.A solid border.A solid border.

+ +

+
+ + + + +```",2016/11/02,"['https://Stackoverflow.com/questions/40375015', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6521417/']","You appear to be running on a corporate network that is **sending web traffic through a proxy** (`pfSense proxy`). + +The error is showing a **private IP address** (`192.168.0.46`), which means the request never made it to the Internet. + +You should chat with your network administrators and determine why it is listed in a group called `Bloack_Sites` (presumably, 'Blocked sites'?).","Since the address is address: 192.168.0.46 +and the client name is address: 192.168.0.46 +Then the target group is undefined: Bloack\_Sites not recognized. +Target group: Block\_Sites" +78924,"As the title suggests, I can't figure out a way to share a folder outside my home folder using Ubuntu One. When browsing to my work partition using Nautilus, every folder has the ""Share"" option grayed out.",2011/11/13,"['https://askubuntu.com/questions/78924', 'https://askubuntu.com', 'https://askubuntu.com/users/39959/']","I just did a test, created a new folder */new* and gave it permissions 777. When right clicking on it, Ubuntu One options were greyed out. Also tried creating a shortcut in ~/ dir, but no luck either. + +In short: No, you can't +=======================","There are unsupported ways which will work. Think mount points under ~/ + +Using a bind mount as described above to a folder under ~/ you can sync any folder on your computer with Ubuntu One. + +I sync folders on a separate partition with Ubuntu One this way. + +Like I said, this is not really supported, but it does work" +78924,"As the title suggests, I can't figure out a way to share a folder outside my home folder using Ubuntu One. When browsing to my work partition using Nautilus, every folder has the ""Share"" option grayed out.",2011/11/13,"['https://askubuntu.com/questions/78924', 'https://askubuntu.com', 'https://askubuntu.com/users/39959/']","You could try using a `mount --bind command`. Something like + +``` +mount --bind /path/to/folder /home/username/folder_to_sync + +``` + +This should make the contents of `/path/to/folder` available in both places. + +Ubuntu-one doesn't support symlinks, but it might support binding mounts. If it does work, you can add a line to `/etc/fstab` + +``` +/path/to/folder /home/username/folder_to_sync none bind 0 0 + +``` + +That way it will always mount on boot.","I just did a test, created a new folder */new* and gave it permissions 777. When right clicking on it, Ubuntu One options were greyed out. Also tried creating a shortcut in ~/ dir, but no luck either. + +In short: No, you can't +=======================" +78924,"As the title suggests, I can't figure out a way to share a folder outside my home folder using Ubuntu One. When browsing to my work partition using Nautilus, every folder has the ""Share"" option grayed out.",2011/11/13,"['https://askubuntu.com/questions/78924', 'https://askubuntu.com', 'https://askubuntu.com/users/39959/']","You could try using a `mount --bind command`. Something like + +``` +mount --bind /path/to/folder /home/username/folder_to_sync + +``` + +This should make the contents of `/path/to/folder` available in both places. + +Ubuntu-one doesn't support symlinks, but it might support binding mounts. If it does work, you can add a line to `/etc/fstab` + +``` +/path/to/folder /home/username/folder_to_sync none bind 0 0 + +``` + +That way it will always mount on boot.","There are unsupported ways which will work. Think mount points under ~/ + +Using a bind mount as described above to a folder under ~/ you can sync any folder on your computer with Ubuntu One. + +I sync folders on a separate partition with Ubuntu One this way. + +Like I said, this is not really supported, but it does work" +70277178,"How to take an number input from user and split it's digits and use each digit separately + +*For example* +If user enters '''4568''' +The code should split 4568 into 4,5,6,8",2021/12/08,"['https://Stackoverflow.com/questions/70277178', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/17627014/']","Use a list comprehension over the user input. + +```py +values = [int(i) for i in input()] + +``` + +Note that this code doesn't handles cases where user puts non-digits characters in his input. To deal with this case, you would prefer to write : + +```py +values = [int(i) for i in input() if i.isdigit()] + +```","Convert it to string, iterate to string and get each character as an integer. + +``` +# Input from the user +inp = input() +digits=[] +for c in str(inp): + try: + digit=int(c) + # Populate the list with the last digit obtained + digits.append(digit) + except: + # I'm assuming you don't need to worry about any other non integer character + pass + +``` + +Or in one line, **BUT pay attention that if any non integer character is present into the input, the map fails**: + +``` +inp = 1234 +digits = list(map(int, list(str(inp))) + +``` + +Where `list(str(inp))` splits the string-converted input in the list of its characters, `map` applies the transformation to integer to each element of the latter list, eventually the conversion to list return your desired array + +EDIT: I was writing the code while the comment were being written. I've now integrated the direct `int` suggestion to map function + +EDIT2: a nitpicky edit to allow for an actual user input instead of a test variable. This does not change the substance at all." +70277178,"How to take an number input from user and split it's digits and use each digit separately + +*For example* +If user enters '''4568''' +The code should split 4568 into 4,5,6,8",2021/12/08,"['https://Stackoverflow.com/questions/70277178', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/17627014/']","You could `map` it to `int`, and convert the `map` to `list`. + +``` +digits = list(map(int, input())) + +``` + +If you want to make sure only numbers are accepted add a `filter` to the `input` + +``` +digits = list(map(int, filter(lambda c: c.isdigit(), input()))) + +```","Convert it to string, iterate to string and get each character as an integer. + +``` +# Input from the user +inp = input() +digits=[] +for c in str(inp): + try: + digit=int(c) + # Populate the list with the last digit obtained + digits.append(digit) + except: + # I'm assuming you don't need to worry about any other non integer character + pass + +``` + +Or in one line, **BUT pay attention that if any non integer character is present into the input, the map fails**: + +``` +inp = 1234 +digits = list(map(int, list(str(inp))) + +``` + +Where `list(str(inp))` splits the string-converted input in the list of its characters, `map` applies the transformation to integer to each element of the latter list, eventually the conversion to list return your desired array + +EDIT: I was writing the code while the comment were being written. I've now integrated the direct `int` suggestion to map function + +EDIT2: a nitpicky edit to allow for an actual user input instead of a test variable. This does not change the substance at all." +1116,"In English and other Germanic languages, noun compounds are formed simply by “appending” the nouns in a certain order. For example, phrases like this are very common: + +> +> electricity price comparison service +> +> +> + +In Portuguese, Spanish and probably other Romance languages, this kind of compounding has to be done with the aid of prepositions. The translation of the phrase above to Portuguese is: + +> +> serviço *de* comparação *de* preços *de* eletricidade +> +> +> + +What determines how noun compounds are formed in a language? Is there something like a parameter (as in the principles and parameters theory) that explains this? + +I'm focusing only on ""open"" compounds (not idiomatic ones) formed exclusively by nouns. As Molly mentioned, this might be related to the Adj/N word order in the language. This hypothesis is quite reasonable, since in the Germanic languages the head in these compounds comes at the end, whereas in Romance languages, they come at the beginning, matching the Adj/N word order. + +But even if this correlation does hold cross-linguistically, how does it relate to the need for prepositions? Maybe prepositions help avoiding ambiguities when the adjectives are postnominal? Could it be related to processing preferences?",2011/12/06,"['https://linguistics.stackexchange.com/questions/1116', 'https://linguistics.stackexchange.com', 'https://linguistics.stackexchange.com/users/22/']","Compound words are really complex, even if we limit it to noun-noun compounds. + +It looks like you're concerned with ""open"" compound nouns, not ""closed"" or hyphenated or [idiomatic](http://www.sciencedirect.com/science/article/pii/0024384168900521) compound nouns [like these](http://www.rickwalton.com/curricul/compound.htm) (what a list! right? corpus alert!). So - + +The syntactic definition of a compound noun is when the rule N -> N N can be recursively applied. Anything with more than two nouns is ambiguous in structure. ((coffee mug) holder) vs. (coffee (mug holder)) or whatever. + +Most languages are more predictable than English when it comes to ""headedness"" or left/right branching of closed noun compounds; Downing's conclusion to [""On the Creation and Use of English Compound Nouns""](http://www.jstor.org/pss/412913) is basically that the relationship is unpredictable from the semantics of the two words. + +My instinct (very scientific!) is that the concatenation vs. use of prepositions for noun-noun compounds is predictable by typology. My guess is that the form of compound nouns is correlated to [the Adj/N word order](http://wals.info/chapter/87) tendency of a language. Of course, this isn't really an answer, but I think the answer you're looking for is too big. It's sort of like asking why a language is SVO or SOV.","Just thinking out aloud, but might it be related to the case systems in Germanic vs. Romance languages? + +> +> electricity price comparison service +> +> +> + +...is a shortened form of: + +> +> service for the comparison of prices for electricity +> +> +> + +This is the same as your Portuguese translation, where the prepositions act as case licensors. However, in Germanic languages, the case system is/was richer and the prepositions disappear (because they're redundant). In particular, ""of"" can be seen as a genitive licensor: + +> +> (service for the comparison) of (prices for electricity) +> +> +> (prices for electricity)'s (service for the[ir] comparison) +> +> +> + +Similarly, ""for"" is a dative licensor: + +> +> (electricity prices)'s (comparison service) +> +> +> + +Dropping the genitive ""'s"" morpheme doesn't seem like a huge stretch of the imagination and serves brevity: + +> +> electricity price comparison service +> +> +>" +9458285,"I've been actively using the revealing module pattern for years but there's a few things I'd like to understand deeper. From what I understand potential benefits of self-executing functions are anoymimty & self-execution, both of which don't seem necessary/utilised in this particular pattern. The other thing I don't understand is, what in the below scenario makes its possible to wrap function Init inside the SocialMedia function(), i.e an embedded function, self-executing functions seem to be a very a unique construct in JS, isn't it strange that we can just assign a properties values to a self-executing code block? + +``` +var myObj = { + prop1, ""prop1value"", + SocialMedia: (function () { + function Init() { + + } + return { + Init: Init + } + })() +} + +```",2012/02/26,"['https://Stackoverflow.com/questions/9458285', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/314963/']","> +> Why do we use self-executing functions in the revealing module pattern? +> +> +> + +JavaScript has first-class functions and lacks block-scoping, so functions are used to introduce new scopes. + +> +> what in the below scenario makes its possible to wrap function Init inside the SocialMedia function(), i.e an embedded function +> ... isn't it strange that we can just assign a properties values to a self-executing code block? +> +> +> + +In JavaScript, a function is just an object that responds to the `()` and `new` operators. + +Like other objects, you can use it when you define it, or store it in a variable or property for later use. + +> +> self-executing functions seem to be a very a unique construct in JS +> +> +> + +This isn't unique to JavaScript. All languages that have [first class functions](http://en.wikipedia.org/wiki/First-class_function) have this property, for example: + +* Lisp, +* OCaml, +* Scala, +* Go, +* C# (via delegates), +* C (via fn ptrs), +* Python, +* Perl (via `&`), +* Ruby, +* Lua + +In recent language development, first-class functions are the norm rather than the rule. Un-statically-typed languages just make it easier because there's no overhead in the type system syntax and no [variance](http://en.wikipedia.org/wiki/Variance_%28computer_science%29#Need_for_covariant_argument_types.3F) issues. + +Even Java might be jumping on the bandwagon with [Lambdas slated for Java 8](http://openjdk.java.net/projects/lambda/). + +In many of those other languages, immediately called functions aren't that useful though. Most other languages are [block-scoped](http://en.wikipedia.org/wiki/Scope_%28computer_science%29#Block_scope_within_a_function) so if you want to keep your variables separate, you just use a `{...}` block. In JavaScript though, `var` is scoped to the smallest containing `function` or Program, so `function`s are the easiest way to introduce a new scope. + +[Ruby](http://www.robertsosinski.com/2008/12/21/understanding-ruby-blocks-procs-and-lambdas/) makes very little distinction between blocks and functions so could be considered similar to JS in this respect.","Self-executing functions are used to introduce new scopes, see also Mike Samuels answer. + +There are two reasons for that: + +* avoid polluting the global scope +* use of closures, i.e. ""exporting"" a function from an extra scope + +Of course you can stack scopes, but usually you won't create that big modules where you have to avoid polluting your local module scope :-) + +Also, the self-executing function in your example is useless, as it's totally equivalent to + +``` +var myObj = { + prop1: ""prop1value"", + SocialMedia: { + Init: function Init() { + + } + } +} + +```" +15773588,"I'm trying to write text in `Canvas`. As I need to show the soft keyboard to write text, I added an `EditText` to my Activity with 0 width. I also implemented a TextWatcher to get the text entered into the `EditText`. With this trick, I can show the soft keyboard whenever I like with this code : + +``` +InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); +imm.showSoftInput(myEditText, InputMethodManager.SHOW_IMPLICIT); + +``` + +Like this I'm able to know what the user is writing and to write the text inside my `Canvas`. + +Now... this becomes tricky when the user would like to stop writing (or let say, anchor the text in the canvas definitely). What I thought is that he could press 'Enter'. So I tried to implement some way to catch the key events. Without any success so far. + +Here is my actual code. This method is called when I would like to start writing. 'edit' is an `EditText`. + +``` +public void handleUp(final Paint myPaint) { + edit.setFocusable(true); + edit.setFocusableInTouchMode(true); + edit.requestFocus(); + edit.addTextChangedListener(new Watcher()); + edit.setImeOptions(EditorInfo.IME_ACTION_GO); + edit.setOnEditorActionListener(new OnEditorActionListener() { + public boolean onEditorAction(TextView arg0, int arg1, KeyEvent arg2) { + Log.d(""MyApp"", ""key pressed""); + Paint localPaint = new Paint(); + mCanvas.drawText(edit.getText().toString(), mX, mY, localPaint); + return false; + } + }); + edit.setOnKeyListener(new OnKeyListener() { + public boolean onKey(View v, int keyCode, KeyEvent event) { + + Log.d(""MyApp"", ""key pressed""); + if (keyCode == KeyEvent.ACTION_DOWN) { + Paint localPaint = new Paint(); + mCanvas.drawText(edit.getText().toString(), mX, mY, localPaint); + return true; + } + return false; + } + }); + InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); + imm.showSoftInput(edit, InputMethodManager.SHOW_IMPLICIT); + + } + +``` + +When I debug my app I never reach check points that I have put on my `Log()` and can't see any message in my Logs neither. I have seen many posts on StackOverFlow where this kind of implementation is used by I can't figure out why it fails here. + +Thank you",2013/04/02,"['https://Stackoverflow.com/questions/15773588', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1685143/']","Taken from the documentation: + +``` +public void setOnKeyListener (View.OnKeyListener l) +Added in API level 1 +Register a callback to be invoked when a hardware key is pressed in this view. Key presses in software input methods will generally not trigger the methods of this listener. + +``` + +So you should look for another listener. + +My best guess would be to use this: + +``` +public void setOnEditorActionListener (TextView.OnEditorActionListener l) +Added in API level 3 +Set a special listener to be called when an action is performed on the text view. This will be called when the enter key is pressed, or when an action supplied to the IME is selected by the user. Setting this means that the normal hard key event will not insert a newline into the text view, even if it is multi-line; holding down the ALT modifier will, however, allow the user to insert a newline character. + +``` + +But none of the methods I could see in the documentation mentioned anything about soft key input.","Okay so finally the reason nothing worked was because my `EditText` had a width of 0. When I put width and height to 1. Setting visibility to `View.INVISIBLE` doesn't work in this case. + +By the way, the three Listener (OnEditorActionListener, OnKeyListener and Overriding dispatchKeyEvent) get the callbacks. But I'll use `OnEditorActionListener` because it's the only one getting only one callback. The two others get several callbacks which is problematic." +15773588,"I'm trying to write text in `Canvas`. As I need to show the soft keyboard to write text, I added an `EditText` to my Activity with 0 width. I also implemented a TextWatcher to get the text entered into the `EditText`. With this trick, I can show the soft keyboard whenever I like with this code : + +``` +InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); +imm.showSoftInput(myEditText, InputMethodManager.SHOW_IMPLICIT); + +``` + +Like this I'm able to know what the user is writing and to write the text inside my `Canvas`. + +Now... this becomes tricky when the user would like to stop writing (or let say, anchor the text in the canvas definitely). What I thought is that he could press 'Enter'. So I tried to implement some way to catch the key events. Without any success so far. + +Here is my actual code. This method is called when I would like to start writing. 'edit' is an `EditText`. + +``` +public void handleUp(final Paint myPaint) { + edit.setFocusable(true); + edit.setFocusableInTouchMode(true); + edit.requestFocus(); + edit.addTextChangedListener(new Watcher()); + edit.setImeOptions(EditorInfo.IME_ACTION_GO); + edit.setOnEditorActionListener(new OnEditorActionListener() { + public boolean onEditorAction(TextView arg0, int arg1, KeyEvent arg2) { + Log.d(""MyApp"", ""key pressed""); + Paint localPaint = new Paint(); + mCanvas.drawText(edit.getText().toString(), mX, mY, localPaint); + return false; + } + }); + edit.setOnKeyListener(new OnKeyListener() { + public boolean onKey(View v, int keyCode, KeyEvent event) { + + Log.d(""MyApp"", ""key pressed""); + if (keyCode == KeyEvent.ACTION_DOWN) { + Paint localPaint = new Paint(); + mCanvas.drawText(edit.getText().toString(), mX, mY, localPaint); + return true; + } + return false; + } + }); + InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); + imm.showSoftInput(edit, InputMethodManager.SHOW_IMPLICIT); + + } + +``` + +When I debug my app I never reach check points that I have put on my `Log()` and can't see any message in my Logs neither. I have seen many posts on StackOverFlow where this kind of implementation is used by I can't figure out why it fails here. + +Thank you",2013/04/02,"['https://Stackoverflow.com/questions/15773588', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1685143/']","You override the dispatchKeyEvent to get the Enter key + +``` +@Override +public boolean dispatchKeyEvent(KeyEvent event) +{ + if (event.getKeyCode() == KeyEvent.KEYCODE_ENTER) + { + // Do whatever you want + } + + return super.dispatchKeyEvent(event); +} + +```","Okay so finally the reason nothing worked was because my `EditText` had a width of 0. When I put width and height to 1. Setting visibility to `View.INVISIBLE` doesn't work in this case. + +By the way, the three Listener (OnEditorActionListener, OnKeyListener and Overriding dispatchKeyEvent) get the callbacks. But I'll use `OnEditorActionListener` because it's the only one getting only one callback. The two others get several callbacks which is problematic." +1992827,"I am creating a poll in php. I have a table with an id column. + +When a user submits a choice, I want the php to first query the database and check whether the table ""id"" has the id of the current user. + +I am pretty new at mysql, can someone help me with the query?",2010/01/02,"['https://Stackoverflow.com/questions/1992827', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/107922/']",Give the empty element a different class (say `someHiddenElement`) when you are generating the content. Then add `someHiddenElement { display: none }` to your style sheet.,"At the point where you populate the optional `div`, if there is no text to put in it, try changing the CSS `display` property to `none.` According to [this source](http://webdesign.about.com/od/css/f/blfaqhidden.htm) (and others), `display: none` removes the element completely from the document. It does not take up any space, even though the HTML for it is still in the source code." +1992827,"I am creating a poll in php. I have a table with an id column. + +When a user submits a choice, I want the php to first query the database and check whether the table ""id"" has the id of the current user. + +I am pretty new at mysql, can someone help me with the query?",2010/01/02,"['https://Stackoverflow.com/questions/1992827', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/107922/']","You can do the trick with the CSS3 pseudo-class :empty + +``` +.someElement +{ + // your standard style +} +.someElement:empty +{ + display:none; +} + +``` + +Sadly Internet explorer doesn't support that feauture yet. For all the other browsers it shall do just fine...","I can't think of a CSS only way to do that. + +I would try to decide whether the element is rendered at the time I know whether there will be any content in it. That is probably the cleanest solution." +1992827,"I am creating a poll in php. I have a table with an id column. + +When a user submits a choice, I want the php to first query the database and check whether the table ""id"" has the id of the current user. + +I am pretty new at mysql, can someone help me with the query?",2010/01/02,"['https://Stackoverflow.com/questions/1992827', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/107922/']","You can do the trick with the CSS3 pseudo-class :empty + +``` +.someElement +{ + // your standard style +} +.someElement:empty +{ + display:none; +} + +``` + +Sadly Internet explorer doesn't support that feauture yet. For all the other browsers it shall do just fine...","``` + +
With padded content
+
+ +``` + +Adding display:table; should do the trick." +1992827,"I am creating a poll in php. I have a table with an id column. + +When a user submits a choice, I want the php to first query the database and check whether the table ""id"" has the id of the current user. + +I am pretty new at mysql, can someone help me with the query?",2010/01/02,"['https://Stackoverflow.com/questions/1992827', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/107922/']","Give the element an `id` attribute. You can then use Javascript to check it's innerHTML property once the page has loaded. If innerHTML has a length of zero, then you can set it's display property to none. [This page](http://www.tizag.com/javascriptT/javascript-innerHTML.php) might help if you don't know your javascript. + +This is still a mucky way to play. If you know the element shouldn't be rendered before you serve the page it would be better to omit it altogether. If you don't want to omit the element, just hide it, then force it into hiding; `style=""display: none""`","Don't use padding on container, use margin on content. Than when there is no content, container remains invisible." +1992827,"I am creating a poll in php. I have a table with an id column. + +When a user submits a choice, I want the php to first query the database and check whether the table ""id"" has the id of the current user. + +I am pretty new at mysql, can someone help me with the query?",2010/01/02,"['https://Stackoverflow.com/questions/1992827', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/107922/']","If it's *necessary* to have the `div.someElement` in the HTML, the best CSS/HTML way to do that would be to add an extra `div` around the added content that has the padding property + +``` +.someElement > div{padding-top:5px;} + +
Content
+ +``` + +Otherwise, do as Pekka says, or take a look at having javascript do it for you.","At the point where you populate the optional `div`, if there is no text to put in it, try changing the CSS `display` property to `none.` According to [this source](http://webdesign.about.com/od/css/f/blfaqhidden.htm) (and others), `display: none` removes the element completely from the document. It does not take up any space, even though the HTML for it is still in the source code." +1992827,"I am creating a poll in php. I have a table with an id column. + +When a user submits a choice, I want the php to first query the database and check whether the table ""id"" has the id of the current user. + +I am pretty new at mysql, can someone help me with the query?",2010/01/02,"['https://Stackoverflow.com/questions/1992827', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/107922/']","If it's *necessary* to have the `div.someElement` in the HTML, the best CSS/HTML way to do that would be to add an extra `div` around the added content that has the padding property + +``` +.someElement > div{padding-top:5px;} + +
Content
+ +``` + +Otherwise, do as Pekka says, or take a look at having javascript do it for you.","Don't use padding on container, use margin on content. Than when there is no content, container remains invisible." +1992827,"I am creating a poll in php. I have a table with an id column. + +When a user submits a choice, I want the php to first query the database and check whether the table ""id"" has the id of the current user. + +I am pretty new at mysql, can someone help me with the query?",2010/01/02,"['https://Stackoverflow.com/questions/1992827', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/107922/']","You can do the trick with the CSS3 pseudo-class :empty + +``` +.someElement +{ + // your standard style +} +.someElement:empty +{ + display:none; +} + +``` + +Sadly Internet explorer doesn't support that feauture yet. For all the other browsers it shall do just fine...",Give the empty element a different class (say `someHiddenElement`) when you are generating the content. Then add `someHiddenElement { display: none }` to your style sheet. +1992827,"I am creating a poll in php. I have a table with an id column. + +When a user submits a choice, I want the php to first query the database and check whether the table ""id"" has the id of the current user. + +I am pretty new at mysql, can someone help me with the query?",2010/01/02,"['https://Stackoverflow.com/questions/1992827', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/107922/']","``` + +
With padded content
+
+ +``` + +Adding display:table; should do the trick.","I can't think of a CSS only way to do that. + +I would try to decide whether the element is rendered at the time I know whether there will be any content in it. That is probably the cleanest solution." +1992827,"I am creating a poll in php. I have a table with an id column. + +When a user submits a choice, I want the php to first query the database and check whether the table ""id"" has the id of the current user. + +I am pretty new at mysql, can someone help me with the query?",2010/01/02,"['https://Stackoverflow.com/questions/1992827', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/107922/']","``` + +
With padded content
+
+ +``` + +Adding display:table; should do the trick.","Don't use padding on container, use margin on content. Than when there is no content, container remains invisible." +1992827,"I am creating a poll in php. I have a table with an id column. + +When a user submits a choice, I want the php to first query the database and check whether the table ""id"" has the id of the current user. + +I am pretty new at mysql, can someone help me with the query?",2010/01/02,"['https://Stackoverflow.com/questions/1992827', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/107922/']","I can't think of a CSS only way to do that. + +I would try to decide whether the element is rendered at the time I know whether there will be any content in it. That is probably the cleanest solution.","At the point where you populate the optional `div`, if there is no text to put in it, try changing the CSS `display` property to `none.` According to [this source](http://webdesign.about.com/od/css/f/blfaqhidden.htm) (and others), `display: none` removes the element completely from the document. It does not take up any space, even though the HTML for it is still in the source code." +20354862,"Even If I choose only one branch in git extensions it still shows me something like this. Why are there additional vertical lines? As I found out, red one is branch in my local repo, why is there a separate blue line with tags, why aren't they on red line? + +Edit: and what are these circles and rectangles mean? + +![enter image description here](https://i.stack.imgur.com/qUCLM.png)",2013/12/03,"['https://Stackoverflow.com/questions/20354862', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/260894/']","A git branch is basically a name that points to a commit, but the commit it points to is updated whenever a new commit is added to the branch. + +Git is an acyclic directed graph. Each git commit has a) an optional [tree object](http://www.gitguys.com/topics/git-object-tree/), b) an optional parent commit (or two or more parents if it's a merge commit), and c) Commit metadata (committer name, email, commit message, etc.). This means that a branch, which in implementation is just a special auto-updated pointer to a commit, represents the entire subgraph accessible by traversing from that commit along its parents, and their parents, etc. In a history with no merges you will get what you expect; a single straight line of commits. In a history with merges you will see what you have here, multiple paths expanding outward (and merging inwards when a commit started two separate branches which were later merged together.","And for your edit: +The circles represent revisions in the history. +The squares represent a revision which is referenced by one ore more branches." +19142,"I have a new LCD for my HTC phone, but unfortunately it's not press-fit or screw on like some older phones. I have to re-glue it back. What domestic glues (not superglue as I've heard it cracks when dry) could I use to put my LCD screen back onto my phone please? I was thinking a more glutenous glue like vinyl repair or heated glue? Thanks",2018/09/05,"['https://lifehacks.stackexchange.com/questions/19142', 'https://lifehacks.stackexchange.com', 'https://lifehacks.stackexchange.com/users/25469/']","Replacement screens, event rebuilds, may come with an adhesive strip already attached. This is also how these screens were mounted in the first place. + +If that is not the case we may use double-sided adhesive tape (AKA double-sided sticky tape, mounting tape, carpet tape) that we cut into the desired dimensions. + +Before we attach the replacement we have to carfully remove **all** remnants of the original tape.","If you're mounting a screen assembly (protective glass/touch sensitive digitiser/LCD display) onto a phone chassis, a double sided sticky foam as Takkat recommends - surprised it didn't come with the display/wasn't already attached but may be available separately, computer cut for your exact phone dimensions + +If you mean glueing a protective glass onto a digitiser or digitiser onto an LCD (depending how your phone screen stack is constructed) there's a specific glue for it, referred to as LOCA, optically clear (and indeed forms a vital part of the vibrancy of the display) - it is set using UV light after being applied + +Both these items are available on the likes of amazon and eBay. Your local mobile phone repair place should also be able to advise and supply" +15594289,"I am trying to display some images in a ListView and have not been successful. I am using WPF MVVM and the ListView is a holdover from simply displaying suits and rank data. (See my previous post: [MVVM in WPF - How to alert ViewModel of changes in Model... or should I?](https://stackoverflow.com/questions/15439841/mvvm-in-wpf-how-to-alert-viewmodel-of-changes-in-model-or-should-i) if you are interested!) That is, I could use something other than ListView (if that is the advice) but I would still like to know how to do it with ListView, assuming it's doable. My property I'm binding to in the ViewModel is: + +``` +public ObservableCollection PlayerCardImages{ + get{ + ObservableCollection results = new ObservableCollection(); + foreach (CardModel card in PlayerCards) + { + Image img = new Image(); + BitmapImage bi3 = new BitmapImage(); + bi3.BeginInit(); + // TODO: Pick card based on suit/rank. Just get 1 image working now + bi3.UriSource = new Uri(""diamond-1.png"", UriKind.Relative); + bi3.EndInit(); + img.Stretch = Stretch.Fill; + img.Source = bi3; + results.Add(img); + } + return results; + } +} + +``` + +In my **XAML** code I'm using: + +``` + + + + + + + + + + + +``` + +This idea was shamelessly stolen from: [WPF - bind images horizontally to ListView](https://stackoverflow.com/questions/10457872/wpf-bind-images-horizontally-to-listview) However, it doesn't even appear to databind as evidenced by my breakpoint in PlayerCardImages not being hit. + +I also tried the following XAML with somewhat better luck: + +``` + + + + + + + + + + + + + + + + + + +``` + +this code definitely goes through databinding - my breakpoint is hit at the beginning of the program and whenever items are added to the collection. But no images is displayed. Rather than torture you with more XAML that does not work, perhaps I could ask someone to point me to some code/examples/docs that show how to bind a list of Images to a ListView (or another control if you really feel that ListView is inappropriate). Notice that my collection is the stuff I'm binding to. I notice that with many examples, they are binding to a subproperty. I.e. they may have a collection of albums and for each album they bind to it's property image (see: [Showing items as images in a WPF ListView](https://stackoverflow.com/questions/2570568/showing-items-as-images-in-a-wpf-listview)). + +Any ideas or help would be much appreciated. + +-Dave + +**Additional info.** + +Based on suggestions by Clemens, I now have this code for PlayerCardImages: + +``` +public ObservableCollection PlayerCardImages + { + get + { + var results = new ObservableCollection(); + + //if (PlayerCards.Count == 0) + // return results; + //else + //{ + // results.Add(new BitmapImage(new Uri(@""Images\\"" + ""diamond-1.png"", UriKind.Relative))); + //} + foreach (var card in PlayerCards) + { + results.Add(new BitmapImage(new Uri(@""Images\\"" + GetCardFileName(card), UriKind.Relative))); + + } + return results; + + } + +``` + +I used the exact XAML he suggested. It almost works. I say ""almost"" because I noticed strange behavior whereby sometimes 1 card would show and sometimes not (I never got 2 cards). All the getting cards from files and binding seems to be working and I tracked down what I think is key to the last remaining bug (and it's BIZARRE). If in the debugger, I examine results, and further open up results[0] in the debugger, I get that card displayed! I actually have to open up [0] (you see info about height, width, etc.) for this to work. Furthermore if I open up [1], I get that card displayed instead. Why would opening up the debugger info have any effect? For those of you who might ask, what happens if you open up both cards in the debugger... that doesn't work. I get a operation timed out exception. I will say that perhaps my image files are big. 10Kbytes to 30 Kbytes. Is that the problem? I'm guessing not, and that it's a subtle problem with reading in the images or binding. What is going on? Thanks, Dave",2013/03/24,"['https://Stackoverflow.com/questions/15594289', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/286641/']","First, you should not use Image controls in your ViewModel. You already have an Image control in the DateTemplate of your view. You want to bind the `Source` property of this Image conntrol, and the source property of this binding can't be another Image. + +Instead your ViewModel would either use [`ImageSource`](http://msdn.microsoft.com/en-us/library/system.windows.media.imagesource.aspx) (or a derived class like [`BitmapImage`](http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.bitmapimage.aspx)) as image type, like this: + +``` +public ObservableCollection PlayerCardImages +{ + get + { + var results = new ObservableCollection(); + foreach (var card in PlayerCards) + { + results.Add(new BitmapImage(new Uri(card.ImageUrl))); + } + return results; + } +} + +``` + +Or simply the image URIs or paths, as there is an automatic conversion from `string` to `ImageSource` built into WPF: + +``` +public ObservableCollection PlayerCardImages +{ + get + { + var results = new ObservableCollection(); + foreach (var card in PlayerCards) + { + results.Add(card.ImageUrl); + } + return results; + } +} + +``` + +You would now bind your Listbox's `ItemsSource` property to the `PlayerCardGames` collection, and in the DataTemplate you bind directly to the collection item. The ListView's DataContext has to be set to an instance of the object that defines the `PlayerCardGames` property. + +``` + + + + + + + + + + +``` + +--- + +UPDATE: As there seems to be a problem with loading the image files, you may try the following method. It loads images synchronously and you are able to step through with the debugger. + +``` +public static ImageSource LoadImage(string fileName) +{ + var image = new BitmapImage(); + + using (var stream = new FileStream(fileName, FileMode.Open)) + { + image.BeginInit(); + image.CacheOption = BitmapCacheOption.OnLoad; + image.StreamSource = stream; + image.EndInit(); + } + + return image; +} + +``` + +You can use this method in your `PlayerCardGames` property getter like this: + +``` +foreach (var card in PlayerCards) +{ + results.Add(LoadImage(@""Images\\"" + GetCardFileName(card))); +} + +```","I didn't really try to reproduce your problem, but I will if this is not solving it: + +In your first xaml block, I think you mixed up the bindings. This would be how I expect it, ItemsSource to the ObservableCollection of Images, Image source to the Image. + +``` + + + +``` + +In your second block, you omitted the Source binding altogether: + +``` + + +```" +14950314,"UPDATE 1 +======== + +I did some more debugging and found that the constructor is run from the main UI thread but the handleMessage(Message) method is run on the Thread I created, which completely contradicts my understanding of Handlers. + +Problem +======= + +I've been working on Android for a while now and I've run into an issue that doesn't seem to be documented. I'm not doing anything special with my code. I can't seem to get my application to create any UI elements such as Alert Dialogs and Toast messages from a Handler's handleMessage method. + +Additionally, I get a ""Thread has not called Looper.prepare()"" exception. However, I believe that I shouldn't even need to call Looper.prepare() since I'm not creating a Handler inside of the Thread object. I'm calling the constructor in the main UI thread and then passing it to the new Thread's constructor. + +What I Expect +------------- + +I should see a Toast message as well as an Alert Dialog. + +What Actually Happens +--------------------- + +Nothing. I've run the debugger on the application and I find that the JVM does launch the Thread. The run method is called and the message is dispatched. The handler handles the method and I run through all the methods of creating the AlertDialog as well as the Toast message but nothing ever shows up. + +I've run this application on my Emulator running 4.2, my friend's Samsung Galaxy S3 running 4.0.4, and my own Droid X2 running 2.3.5. + +Flow of the Program +=================== + +1. I create a Handler on the UI thread. +2. I create and start a Thread that will dispatch a message to the Handler. +3. The handler will handle the message + +Source Code +=========== + + + +``` +package com.nguyenmp.ErrorTest; + +import android.app.Activity; +import android.app.AlertDialog; +import android.app.Dialog; +import android.content.Context; +import android.os.Bundle; +import android.os.Handler; +import android.os.Looper; +import android.os.Message; +import android.view.View; +import android.widget.Button; +import android.widget.Toast; + +public class MyActivity extends Activity { + + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + //Init the UI + setContentView(R.layout.main); + + //Create a new handler, passing it the current activity context + final Handler handler = new MyHandler(MyActivity.this); + + //Bind a listener to the button on the UI + View view = findViewById(R.id.button); + view.setOnClickListener(new View.OnClickListener() { + + @Override + public void onClick(View v) { + //Start a new thread that will send a message to that handler + new MyThread(handler).start(); + } + + }); + } + + private class MyThread extends Thread { + private final Handler mHandler; + + MyThread(Handler handler) { + mHandler = handler; + } + + @Override + public void run() { + //Dispatch message to UI thread asynchronously + Looper.prepare(); + mHandler.dispatchMessage(mHandler.obtainMessage()); + } + } + + private class MyHandler extends Handler { + private final Context mContext; + + MyHandler(Context context) { + mContext = context; + } + + @Override + public void handleMessage(Message msg) { + //Show that we got the message + AlertDialog.Builder builder = new AlertDialog.Builder(mContext); + builder.setTitle(""HelloWorld""); + builder.setMessage(""It worked!""); + builder.show(); + + //Another variant of showing that we got the message + Toast.makeText(mContext, ""Message Received"", Toast.LENGTH_SHORT).show(); + + System.out.println(""Yeah""); + } + } +} + +```",2013/02/19,"['https://Stackoverflow.com/questions/14950314', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/783338/']","You should use +to send the message that will be later processed by handleMessage.",The problem was that I was calling dispatchMessage(Message) which is executed imediately on the current thread. I should have been using sendMessage(Message) which would enqueue the given Message to the original thread's message queue that created the Handler in the first place. +63394559,"I have POJO attribute as below, + +``` + @Column(name = ""timeStamp"") + private LocalDateTime timeStamp; + +``` + +This attribute coming from a service, and need to retain the format. I am streaming input from Kafka and need to store in Cassandra. + +I'm creating table using datastax API, + +``` + +CreateTable createTable = SchemaBuilder.createTable(""sample31"", ""contactNew"") + .ifNotExists() + .withColumn(""timeStamp"", DataTypes.TIMESTAMP); + +``` + +When my job execution, am facing the below exception, + +``` +Codec not found for requested operation: [timestamp <-> java.time.LocalDateTime] + +``` + +I tried with different data type such as `DataTypes.DURATION` , `DataTypes.DATE` not working.",2020/08/13,"['https://Stackoverflow.com/questions/63394559', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2182920/']","For Java driver 3.x you need to use a separate package - so-called ""Optional codecs"" by including an additional dependency: + +```xml + + com.datastax.cassandra + cassandra-driver-extras + driver-version + + +``` + +For `LocalDateTime` from Java 8 there is a `LocalDateTimeCodec` ([doc](https://docs.datastax.com/en/developer/java-driver/3.8/manual/custom_codecs/extras/#jdk-8)) that should be registered when you created a cluster object, like this: + +```java +import com.datastax.driver.extras.codecs.jdk8.LocalDateTimeCodec; + +cluster.getConfiguration().getCodecRegistry() + .register(LocalDateTimeCodec.instance); + +``` + +There is similar codecs for Java driver 4.x, starting with driver 4.8. Also just register necessary codec as [described in documentation](https://docs.datastax.com/en/developer/java-driver/4.8/manual/core/custom_codecs/#mapping-cql-timestamps-to-local-date-time). But the easiest way is to register all necessary codecs at the session build time with something like this: + +```java +CqlSession session = CqlSession.builder().addTypeCodecs()....build(); + +```","Just convert it to Instant and it will be mapped automatically: + +``` +message.getLocalDateTime().toInstant(ZoneOffset.UTC) + +```" +48798101,"What I want to do is save one y dataframe for each file in the loop below.Right now, I only have the last one. + +``` +temp = list.files(pattern=""*.csv"") +myfiles = lapply(temp, read.csv) + +for (file in myfiles){ + y <- some code +} + +``` + +y has 26 observations of 2 variables. + +Sorry if this is not a working example. My data is too big even if taking samples. Any help is much appreciated.",2018/02/14,"['https://Stackoverflow.com/questions/48798101', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7747528/']","`df <- do.call(""rbind"",lapply(list.files(pattern = ""*.csv""),read.csv, header = TRUE))` + +Here is an [example](https://stat.ethz.ch/pipermail/r-help/2003-April/032077.html).","If I understand well, you want to save `y` as a `csv`? You could do something like this: + +``` +temp = list.files(pattern=""*.csv"") +myfiles = lapply(temp, read.csv) +## Adding a counter to be incremented in the loop +counter <- 1 + +for (file in myfiles){ + y <- some code + ## writing the csv + write.csv(y, file = paste0(""my_csv_"", counter, "".csv"") + ## Increment the counter + counter <- counter + 1 +} + +``` + +Or do you want to save `y` as a variable containing all your data.frames? In this case, you can do something like this: + +``` +temp = list.files(pattern=""*.csv"") +myfiles = lapply(temp, read.csv) +## Adding a counter to be incremented in the loop +counter <- 1 +## Create an empty list y + +for (file in myfiles){ + y[[counter]] <- some code + ## Increment the counter + counter <- counter + 1 +} + +```" +25582291,"I am trying to call a stored procedure using entity framework 6. I get an error on the output message. + +> +> A first chance exception of type 'System.Data.Entity.Core.EntityCommandExecutionException' occurred in EntityFramework.SqlServer.dll +> +> +> + +``` + using (var context = new PartnerPortalEntities2()) + { + var outputParameter = new ObjectParameter(""result"", typeof(string)); + var spresults = context.assignRoles_CreateAccountAndContacts(user.Id, role, user.AccountId, user.AccountName, user.ContactId, user.FirstName, user.LastName, outputParameter); + // Control never comes after the above line + if(spresults.Equals(""1"")) + { + //Do something + } + else + { + // Do something + } + + } + +``` + +When i do a debug, The control goes to line where the stored procedure is called after which we get the above error on the output window and the debugger stops, it never gets into the if statements. + +I have run the stored procedure on SQLserver and it works fine there. Any thoughts what could be the error. I have built the context by generating the code from database.",2014/08/30,"['https://Stackoverflow.com/questions/25582291', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/193247/']","As suggested by @Shoe, i had embeded the call to stored procedure with in a try catch block which caught the exception and showed the exact error. + +It turned out to be that i was not passing the exact variable as the output parameter. Changed result to results as the variable defined in stored procedure was results + +``` +var outputParameter = new ObjectParameter(""result"", typeof(string)); + +```","I just had the same error and I managed to fix it! + +This error could be a result of other reasons, but the reason for this error was that the SQL server was not configured to accept transport from my debugging station- I had to configure the IP of my computer in the Sql server settings and then it worked perfectly. + +Hope it helps." +19600123,"I have created a timeline card with a custom menu item. I would like to get a callback when the user has selected that menu item. + +``` +// Create a menu item for the card +var mnuActivate = new MenuItem() { + Action = ""CUSTOM"", + RemoveWhenSelected = new bool?(true), + Id = ACCEPT_ID, + Values = new List() { + new MenuValue() { + State=""DEFAULT"", + DisplayName=""Activate"", + }, + new MenuValue() { + State=""PENDING"", + DisplayName=""Activating..."" + }, + new MenuValue() { + State=""CONFIRMED"", + DisplayName=""Activated"" + } + } +} + +// Create a new card for the user's timeline +var item = new TimelineItem() { + Html = html, + Notification = new NotificationConfig() { Level = ""DEFAULT"" }, + MenuItems = new List() { mnuActivate } +}; + +var card = this._service.Timeline.Insert(item).Fetch(); + +``` + +I then subscribe to all timeline events and provide an https callback URL +``` + // Create a new subscription +var subscription = new Subscription() +{ + Collection = ""timeline"", + Operation = new List(), + CallbackUrl = """" +}; +this._service.Subscriptions.Insert(subscription).Fetch(); +// Retrieve a list of subscriptions to make sure it is there. +var mySubcriptions = this._service.Subscriptions.List().Fetch(); +if (mySubcriptions != null && mySubcriptions.Items != null && mySubcriptions.Items.Count == 1) +{ + Console.WriteLine(""Subscription created successfully.""); +} +``` + +So the subscription is created without any issues as far as I can tell. But after interacting with the card, I never get a callback. What am I missing? + +Things I have tried: + +1. Populating Ids on the subscription obj, timeline card, and menuItem +2. Subscribing before creating the card instead of after +3. Adding the userId as the UserToken on the subscription object +4. Calling my callback URL directly to ensure that it is listening + +JSON Response from GET /mirror/v1/subscriptions: + +``` +{ + ""kind"": ""mirror#subscriptionsList"", + ""items"": [ + { + ""kind"": ""mirror#subscription"", + ""id"": ""timeline"", + ""updated"": ""2013-10-28T15:19:19.404Z"", + ""collection"": ""timeline"", + ""callbackUrl"": ""https://mypubliclyavailableserver.com/notify"" + } + ] +} + +```",2013/10/25,"['https://Stackoverflow.com/questions/19600123', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/281336/']","The main thing you need to keep in mind is [endianness](http://en.wikipedia.org/wiki/Endianness). That is, the order the bytes are interpreted in is different on different platforms. + +For example, your Intel CPU might interpret the byte string `0x01 0x00` to be the number 1, but someone else's PowerPC would interpret that string of bytes to be the number 256. + +When building a network protocol, it's important to keep issues like this in mind. (you might look at something like [Google Protocol Buffers](https://code.google.com/p/protobuf/), which was designed to address this concern) + +Since you're only talking about two bytes, you should also take a look at the `htons()` macro. This converts a 2-byte value from *host order* to *network order*. (network order is *big endian*, whereas host order is often *little endian*, but on big endian platforms `htons()` can simply be defined as a no-op.) If you want to send 4-byte (32-bit) values, you should also take a look at the `htonl()` macro. `htons` stands for *host to network short*, and will convert your 16-byte value to an equivalent *network order* 16-bit value (if you are on an Intel CPU, that means it will return a version of the 16-bit integer with the bytes swapped). When you have incoming bytes, your code should use the `ntohs` (and `ntohl`, for 32-bit values) macro to convert the incoming data from network byte order back to host order.","Also, you'd obviously want to send both bytes using a single socket write operation. Don't write one byte and then write the other using two writes as that could end up being very inefficient over the wire. That is, don't write uint8\_t[0] followed by uint8\_t[1]. Writing &uint16\_t will avoid that situation." +41422231,"I am developing an app with input field, and for pattern using angular js ui-mask. + +**HTML** + +``` + + +``` + +1. With `type=""text""` the code works fine. +2. But when we use `type=""password""`, on `focus` of the field, the **spaces** in `pattern` is also masked. + +Only when the user types, it has to mask the characters. + +Is there any way to achieve it? + +Ref: ",2017/01/02,"['https://Stackoverflow.com/questions/41422231', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2979319/']","You can use conditional aggregation for this: + +``` +SELECT column1, + column2 +FROM your_table t +GROUP BY column1, + column2 +HAVING COUNT(CASE WHEN source = 'a' THEN 1 END) = 0; + +```","You can achieve the desired result using below query: + +SELECT DISTINCT COLUMN1, COLUMN2 +FROM TABLE1 +WHERE Source <> 'a'" +36939625,"I'm looking for a way to evaluate price expressions stored in database in Postgres 9.1+ + +I tried code below from answer in +[How to evaluate expression in select statement in Postgres](https://stackoverflow.com/questions/26063328/how-to-evaluate-expression-in-select-statement-in-postgres) + +but got error + +``` +ERROR: missing FROM-clause entry for table ""product"" +LINE 1: select product.price*0.95 + +``` + +how to fix ? + +Maybe it is possible to pass customer and product current row as eval parameters and to use them in eval expresion ? + +``` +create or replace function eval( sql text ) returns text as $$ +declare + as_txt text; +begin + execute 'select ' || sql into as_txt ; + return as_txt ; +end; +$$ language plpgsql; + +create table customer +( id int primary key, + priceexpression text ); +insert into customer values (1, 'product.price*0.95'),(2,'cost+12.0' ); + +create table product +( id char(20) primary key, + price numeric(12,4), + cost numeric(12,4) ); +insert into product values ('PRODUCT1', 120, 80),('PRODUCT2', 310.5, 290); + +select + customer.id as customer, + product.id as product, + eval(priceexpression) as price + from customer,product + +```",2016/04/29,"['https://Stackoverflow.com/questions/36939625', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/742402/']","*Serg* is basically right. **Your *dyna-SQL* is executed ""on its own""** so it needs to be a valid SQL statement (**having ""to know"" all involved tables**). I [updated my answer in the referred thread](https://stackoverflow.com/a/36909941/1915920) to reflect this. + +But to properly cite it in here your example should be something like (actually you should **use the 2nd `eval( sql text, keys text[], vals text[] )` variant!**): + +``` +eval( + 'select '||c.price_expression||' from product where id=:pid', + '{""{cost}"",:pid}', + array[ p.cost, p.id ] +) as cust_cost + +``` + +This should be more straight forward, robust and modular than *Serg*s suggestions.","Just add the table name somwhere. May be + +``` +insert into customer values (1, 'product.price*0.95 FROM product'),(2,'cost+12.0 FROM product' ); + +``` + +or may be + +``` + execute 'select ' || sql || ' FROM product' into as_txt ; + +``` + +at your choice. + +Hope this `priceexpression` is not exposed to users but only to restricted number of admins, because it's dangerous sql injection security hole." +14249367,"below is a terminal session illustrating the problem: + +``` +$ pip install scrappy --user +Requirement already satisfied (use --upgrade to upgrade): scrappy in /home/louist/Documents/Python/Scrappy +Downloading/unpacking guessit (from scrappy) + Downloading guessit-0.5.3.tar.gz (45Kb): 45Kb downloaded + Running setup.py egg_info for package guessit + +Downloading/unpacking tvdb-api (from scrappy) + Downloading tvdb_api-1.8.2.tar.gz + Running setup.py egg_info for package tvdb-api + +Downloading/unpacking hachoir-metadata (from scrappy) + Downloading hachoir-metadata-1.3.3.tar.gz (52Kb): 52Kb downloaded + Running setup.py egg_info for package hachoir-metadata + Warning: unable to recompile dialog.ui to dialog_ui.py using pyuic4 + (use command ""-c egg_info --egg-base pip-egg-info --disable-qt"" to disable this warning) + +Downloading/unpacking hachoir-core (from scrappy) + Downloading hachoir-core-1.3.3.tar.gz (91Kb): 91Kb downloaded + Running setup.py egg_info for package hachoir-core + +Downloading/unpacking hachoir-parser (from scrappy) + Downloading hachoir-parser-1.3.4.tar.gz (359Kb): 359Kb downloaded + Running setup.py egg_info for package hachoir-parser + + warning: no files found matching 'metadata_csv.py' +Installing collected packages: guessit, tvdb-api, hachoir-metadata, hachoir-core, hachoir-parser + Running setup.py install for guessit + + Running setup.py install for tvdb-api + + Running setup.py install for hachoir-metadata + Warning: unable to recompile dialog.ui to dialog_ui.py using pyuic4 + (use command ""-c install --single-version-externally-managed --record /tmp/pip-3OxvBD-record/install-record.txt --install-headers /home/louist/.virtualenvs/test/include/site/python2.7 --user --disable-qt"" to disable this warning) + + changing mode of build/scripts-2.7/hachoir-metadata from 664 to 775 + changing mode of build/scripts-2.7/hachoir-metadata-gtk from 664 to 775 + changing mode of build/scripts-2.7/hachoir-metadata-qt from 664 to 775 + deleting hachoir_metadata.egg-info/requires.txt + + changing mode of /home/louist/.local/bin/hachoir-metadata to 775 + changing mode of /home/louist/.local/bin/hachoir-metadata-gtk to 775 + changing mode of /home/louist/.local/bin/hachoir-metadata-qt to 775 + Running setup.py install for hachoir-core + + Running setup.py install for hachoir-parser + deleting hachoir_parser.egg-info/requires.txt + + warning: no files found matching 'metadata_csv.py' +Successfully installed guessit tvdb-api hachoir-metadata hachoir-core hachoir-parser +Cleaning up... +(test)louist@ltpc:~/Documents/Python/Scrappy$ python +Python 2.7.3 (default, Sep 26 2012, 21:51:14) +[GCC 4.7.2] on linux2 +Type ""help"", ""copyright"", ""credits"" or ""license"" for more information. +>>> import scrappy.core as scrappy +Traceback (most recent call last): + File """", line 1, in + File ""scrappy/core.py"", line 10, in + import guessit +ImportError: No module named guessit + +``` + +In a nutshell, I did the following: + +1. start a virtualenv with `mkvirtualenv test` +2. try to install the package i'm developing via `pip install scrappy --user` +3. start python terminal and then try to import `scrappy.core` + +Here is my setup.py file: + +``` +#!/usr/bin/env python +from setuptools import setup + +setup( + name='Scrappy', + version=""0.2.7 alpha"", + author='Louis Thibault', + author_email='louist87@gmail.com', + packages=['scrappy'], + include_package_data=True, + install_requires=['guessit', 'tvdb_api', 'hachoir-metadata', 'hachoir-core', 'hachoir-parser'], + url='https://github.com/louist87/scrappy', + license='GPL 3.0', + description='Rename video files based on information scraped from thetvdb.com', + keywords=[""TVDB"", ""thetvdb"", ""rename"", ""broadcatching"", ""media""], + long_description=open('README.rst').read() +) + +``` + +Any ideas as to what's going on?",2013/01/10,"['https://Stackoverflow.com/questions/14249367', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1156707/']","By default new virtualenv doesn't include packages installed outside of it (created without `--system-site-packages` option). Therefore your `test` virtualenv doesn't see packages installed to `~/.local` (due to `--user` option). + +Either create virtualenv with --system-site-packages option or don't use --user while installing within activated virtualenv.","I had a similar issue, it was a distros problem +When i installed using the following - + +``` +sudo apt-get install python-scrapy + +``` + +from command line it work. Do make sure you update your repository before hitting the above command to get a current version" +444376,"**Duplicate of: [In Python, how do I get the path and name of the file that is currently executing?](https://stackoverflow.com/questions/50499/in-python-how-do-i-get-the-path-and-name-of-the-file-that-is-currently-executing)** + +I would like to find out the path to the currently executing script. +I have tried os.getcwd() but that only returns the directory I ran the script from not the actual directory the script is stored.",2009/01/14,"['https://Stackoverflow.com/questions/444376', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/32933/']","In Python, `__file__` identifies the current Python file. Thus: + +``` +print ""I'm inside Python file %s"" % __file__ + +``` + +will print the current Python file. Note that this works in imported Python modules, as well as scripts.","How about using sys.path[0] + +You can do something like + +'print os.path.join(sys.path[0], sys.argv[0])' + +" +19517707,"I'd like to sort a `List` on element *counts* of `IGrouping`s. + +And that's it, the list should ideally be the same. I would compromise with a new list, but then the elements should be the very same original objects, not copies (however shallow) and definitely not anonymous objects. + +**Specifically:** We have an entity with many properties, and a list of objects of this type. We'd like to **(1)** group the objects by certain properties (name, address, ...) then **(2)** count the number of elements in each group. Finally we'd like to **(3)** reorder the list based on these counts by placing the elements that are part of the larger groups first. + +**Note:** Our main issue is that we can't seem to find a way to keep a reference to the original objects in the elements of the groups. Indeed all we can select in the Linq query is the grouping key (or properties of the key) and nothing else is exposed by `IGrouping`. We can't figure out how to associate a group element with an element of the list either, short of looking at the data (and even then, we'd need the primary key, which we can't add to the grouping key or it would defeat the purpose of the grouping to begin with).",2013/10/22,"['https://Stackoverflow.com/questions/19517707', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2266481/']","Almost no operation in .NET clones an object. Neither deeply nor shallowly. LINQ also does not clone the elements it processes. Therefore, a simple LINQ query will work: + +``` +var oldList = ...; +var newList = (from x in oldList + group x by something into g + orderby g.Count() + from x in g //flatten the groups + select x).ToList(); + +``` + +This code copies *references* to the original objects. If you believe otherwise, you are probably misinterpreting what you are seeing.","Well, this is embarrassing. + +My mistake was indeed based on a misunderstanding: + +``` +class Item +{ + internal string Value { get; set; } + internal string Qux { get; set; } + internal string Quux { get; set; } +} + +var query = from i in list + group i by new { i.Value, i.Qux } into g // Note: no Quux, no primary key, just what's necessary + orderby g.Count() descending, g.Key.Value + select new { // [1] + Value = g.Key.Value, + Qux = g.Key.Qux, + // Quux? + } + +``` + +My bad assumption was that the selection at [1] was acting on individual records, much like SQL. Well, hopefully I can save someone who had the same assumption: it is not. + +It seems obvious now, but the selection acts on individual groups, and hence here a new object would be created for each group, not for each element. + +My second mistake was in focusing on the key, wondering how one would ""pass"" other properties without using it. I was also worried that we seemed to be required to make shallow copies of our objects. Again this is based on the fact that we were clueless as to how the `IGrouping` is behaving: since we didn't know we were selecting on the groups, we couldn't even create new objects for each element from the select. + +The solution is definitely not impressive: + +``` +var query = from i in list + group i by new { i.Value, i.Qux } into g + orderby g.Count() descending, g.Key.Value + select g; + +foreach (var group in query) +{ + foreach (var item in group) + Console.WriteLine(""{0} {1} {2} [Original object? {3}]"", + item.Value, + item.Qux, + item.Quux, + list.Contains(item)); + + Console.WriteLine(""-""); +} + +``` + +Output: + +``` +AAA Foo ... [Original object? True] +AAA Foo ... [Original object? True] +AAA Foo ... [Original object? True] +- +BBB Foo ... [Original object? True] +BBB Foo ... [Original object? True] +- +AAA Bar ... [Original object? True] +- +CCC Foo ... [Original object? True] +- +DDD Foo ... [Original object? True] +- +DDD Bar ... [Original object? True] +- +EEE Foo ... [Original object? True] + +``` + +Indeed the `IGrouping` elements are the original elements. From there we can create a new list without any issue. + +**Update:** I flatten the result set outside of the query mainly to be able to write the group separator to the console for demonstration purposes, but see Tim's and usr's answers to flatten inside the query using `SelectMany` (and equivalent Linq syntax). + +Needless to say, this was another classic case of ""we're in too much of a hurry, let's read some examples here and there and that'll be it"", where the proper approach would have been to spend a little bit of time learning the fundamentals. Linq is not SQL. + +My apologies for the time you may have wasted trying to clear the confusion. Hopefully someone else in a hurry might benefit from these mistakes now." +19517707,"I'd like to sort a `List` on element *counts* of `IGrouping`s. + +And that's it, the list should ideally be the same. I would compromise with a new list, but then the elements should be the very same original objects, not copies (however shallow) and definitely not anonymous objects. + +**Specifically:** We have an entity with many properties, and a list of objects of this type. We'd like to **(1)** group the objects by certain properties (name, address, ...) then **(2)** count the number of elements in each group. Finally we'd like to **(3)** reorder the list based on these counts by placing the elements that are part of the larger groups first. + +**Note:** Our main issue is that we can't seem to find a way to keep a reference to the original objects in the elements of the groups. Indeed all we can select in the Linq query is the grouping key (or properties of the key) and nothing else is exposed by `IGrouping`. We can't figure out how to associate a group element with an element of the list either, short of looking at the data (and even then, we'd need the primary key, which we can't add to the grouping key or it would defeat the purpose of the grouping to begin with).",2013/10/22,"['https://Stackoverflow.com/questions/19517707', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2266481/']","``` +var mySortedList = myList.GroupBy(x => x.Name).OrderByDescending(g => g.Count()) + .SelectMany(x => x).ToList(); + +```","Almost no operation in .NET clones an object. Neither deeply nor shallowly. LINQ also does not clone the elements it processes. Therefore, a simple LINQ query will work: + +``` +var oldList = ...; +var newList = (from x in oldList + group x by something into g + orderby g.Count() + from x in g //flatten the groups + select x).ToList(); + +``` + +This code copies *references* to the original objects. If you believe otherwise, you are probably misinterpreting what you are seeing." +19517707,"I'd like to sort a `List` on element *counts* of `IGrouping`s. + +And that's it, the list should ideally be the same. I would compromise with a new list, but then the elements should be the very same original objects, not copies (however shallow) and definitely not anonymous objects. + +**Specifically:** We have an entity with many properties, and a list of objects of this type. We'd like to **(1)** group the objects by certain properties (name, address, ...) then **(2)** count the number of elements in each group. Finally we'd like to **(3)** reorder the list based on these counts by placing the elements that are part of the larger groups first. + +**Note:** Our main issue is that we can't seem to find a way to keep a reference to the original objects in the elements of the groups. Indeed all we can select in the Linq query is the grouping key (or properties of the key) and nothing else is exposed by `IGrouping`. We can't figure out how to associate a group element with an element of the list either, short of looking at the data (and even then, we'd need the primary key, which we can't add to the grouping key or it would defeat the purpose of the grouping to begin with).",2013/10/22,"['https://Stackoverflow.com/questions/19517707', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2266481/']","``` +var mySortedList = myList.GroupBy(x => x.Name).OrderByDescending(g => g.Count()) + .SelectMany(x => x).ToList(); + +```","Well, this is embarrassing. + +My mistake was indeed based on a misunderstanding: + +``` +class Item +{ + internal string Value { get; set; } + internal string Qux { get; set; } + internal string Quux { get; set; } +} + +var query = from i in list + group i by new { i.Value, i.Qux } into g // Note: no Quux, no primary key, just what's necessary + orderby g.Count() descending, g.Key.Value + select new { // [1] + Value = g.Key.Value, + Qux = g.Key.Qux, + // Quux? + } + +``` + +My bad assumption was that the selection at [1] was acting on individual records, much like SQL. Well, hopefully I can save someone who had the same assumption: it is not. + +It seems obvious now, but the selection acts on individual groups, and hence here a new object would be created for each group, not for each element. + +My second mistake was in focusing on the key, wondering how one would ""pass"" other properties without using it. I was also worried that we seemed to be required to make shallow copies of our objects. Again this is based on the fact that we were clueless as to how the `IGrouping` is behaving: since we didn't know we were selecting on the groups, we couldn't even create new objects for each element from the select. + +The solution is definitely not impressive: + +``` +var query = from i in list + group i by new { i.Value, i.Qux } into g + orderby g.Count() descending, g.Key.Value + select g; + +foreach (var group in query) +{ + foreach (var item in group) + Console.WriteLine(""{0} {1} {2} [Original object? {3}]"", + item.Value, + item.Qux, + item.Quux, + list.Contains(item)); + + Console.WriteLine(""-""); +} + +``` + +Output: + +``` +AAA Foo ... [Original object? True] +AAA Foo ... [Original object? True] +AAA Foo ... [Original object? True] +- +BBB Foo ... [Original object? True] +BBB Foo ... [Original object? True] +- +AAA Bar ... [Original object? True] +- +CCC Foo ... [Original object? True] +- +DDD Foo ... [Original object? True] +- +DDD Bar ... [Original object? True] +- +EEE Foo ... [Original object? True] + +``` + +Indeed the `IGrouping` elements are the original elements. From there we can create a new list without any issue. + +**Update:** I flatten the result set outside of the query mainly to be able to write the group separator to the console for demonstration purposes, but see Tim's and usr's answers to flatten inside the query using `SelectMany` (and equivalent Linq syntax). + +Needless to say, this was another classic case of ""we're in too much of a hurry, let's read some examples here and there and that'll be it"", where the proper approach would have been to spend a little bit of time learning the fundamentals. Linq is not SQL. + +My apologies for the time you may have wasted trying to clear the confusion. Hopefully someone else in a hurry might benefit from these mistakes now." +806400,"We have a project with several applications including web applications, web services, windows services and windows applications. We also have prerequisites like SQL Server Express, .NET 2.0 and others. We don't have much user interaction during the setup but we want to add more intelligence to it. + +We are currently using Visual Studio to generate the integrated setup for all this. But we continuously struggle with it to make it work like we want. + +We want to change our setup tool into something simpler and flexible enough. + +We are also looking for a better solution for the upgrader, that must run upgrade sql scripts on the deployed system. Maybe this could be integrated with the setup. + +We are thinking about using InstallShield, but some say that it brings a lot of complexity. What do you think is the best tool for this job? + +Thanks!",2009/04/30,"['https://Stackoverflow.com/questions/806400', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/44547/']","I have used [Installshield](http://www.acresso.com/products/is/installshield-overview.htm), [NSIS](http://nsis.sourceforge.net/), Visual Studio and [WiX](http://wix.sourceforge.net/). Installshield always produced a bloated installer for me and costs alot. Visual Studio can be limited in some of the things that it can do, but overall it is pretty good. NSIS is definately a nice little install system since I have use it for a few products (one that has been downloaded and installed about 750k times) but when I was using it it did not follow the MSI rules. WiX is great and provides you with alot of functionality as well but is script based but there are GUIs for it now too. + +Of course it looks like you have decided to use Advanced Installer. Good luck.","We have chosen WiX too. Mind you that you will still need to know all about Windows Installer mechanisms. WiX is version control friendly and very transparent + +If you need custom actions and would like to write that in a .NET language then go for the CustomActionAttribute approach. You can write setup dialogs using WinForms. + +This site is also a very good source [InstallSite.org](http://www.installsite.org/)" +806400,"We have a project with several applications including web applications, web services, windows services and windows applications. We also have prerequisites like SQL Server Express, .NET 2.0 and others. We don't have much user interaction during the setup but we want to add more intelligence to it. + +We are currently using Visual Studio to generate the integrated setup for all this. But we continuously struggle with it to make it work like we want. + +We want to change our setup tool into something simpler and flexible enough. + +We are also looking for a better solution for the upgrader, that must run upgrade sql scripts on the deployed system. Maybe this could be integrated with the setup. + +We are thinking about using InstallShield, but some say that it brings a lot of complexity. What do you think is the best tool for this job? + +Thanks!",2009/04/30,"['https://Stackoverflow.com/questions/806400', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/44547/']","I have used [Installshield](http://www.acresso.com/products/is/installshield-overview.htm), [NSIS](http://nsis.sourceforge.net/), Visual Studio and [WiX](http://wix.sourceforge.net/). Installshield always produced a bloated installer for me and costs alot. Visual Studio can be limited in some of the things that it can do, but overall it is pretty good. NSIS is definately a nice little install system since I have use it for a few products (one that has been downloaded and installed about 750k times) but when I was using it it did not follow the MSI rules. WiX is great and provides you with alot of functionality as well but is script based but there are GUIs for it now too. + +Of course it looks like you have decided to use Advanced Installer. Good luck.","Since you mention Visual Studio and .net, I'm assuming you are deploying to Windows based servers, but even still you might want to take a look at [fabric](http://www.nongnu.org/fab/). It is a python based deployment tool. You can write and launch scripts to deploy and setup your servers, web services, etc.. The only thing is I'm not sure how well it plays with Windows as the target server." +806400,"We have a project with several applications including web applications, web services, windows services and windows applications. We also have prerequisites like SQL Server Express, .NET 2.0 and others. We don't have much user interaction during the setup but we want to add more intelligence to it. + +We are currently using Visual Studio to generate the integrated setup for all this. But we continuously struggle with it to make it work like we want. + +We want to change our setup tool into something simpler and flexible enough. + +We are also looking for a better solution for the upgrader, that must run upgrade sql scripts on the deployed system. Maybe this could be integrated with the setup. + +We are thinking about using InstallShield, but some say that it brings a lot of complexity. What do you think is the best tool for this job? + +Thanks!",2009/04/30,"['https://Stackoverflow.com/questions/806400', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/44547/']","WiX is your friend here. + + + +WiX is an incredibly flexible setup technology, xml driven and with a lot of tools and knowledge out there. + +There are a number of blogs that are relevant to WiX out there. Check out: + + + +","There are three things I don't like about InstallShield: + +1. It seems overly complex +2. There is no way (to my knowledge) of generating from the command line, you always have to use the GUI, which is a hindrance for automated builds. +3. It seems to add an excessive amount of overhead. + +I've used [NSIS](http://nsis.sourceforge.net/) a fair bit, which is open source. Whereas InstallShield has almost a too high level a view of things, NSIS is almost a too low level. You have to write the code to poke the registry entries in for uninstalling via Add/Remove programs for instance. You will be able to get the job done, and have full control of exactly what it will do, though, and it will package into a very compact single executable. + +I have no experience with [InnoSetup](http://www.jrsoftware.org/isinfo.php) or [WiX](http://wix.sourceforge.net/) - either of them may steer a course between the two extremes of InstallShield and NSIS. Both are freely available and worth a look as well." +806400,"We have a project with several applications including web applications, web services, windows services and windows applications. We also have prerequisites like SQL Server Express, .NET 2.0 and others. We don't have much user interaction during the setup but we want to add more intelligence to it. + +We are currently using Visual Studio to generate the integrated setup for all this. But we continuously struggle with it to make it work like we want. + +We want to change our setup tool into something simpler and flexible enough. + +We are also looking for a better solution for the upgrader, that must run upgrade sql scripts on the deployed system. Maybe this could be integrated with the setup. + +We are thinking about using InstallShield, but some say that it brings a lot of complexity. What do you think is the best tool for this job? + +Thanks!",2009/04/30,"['https://Stackoverflow.com/questions/806400', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/44547/']","After reading these answers we ended up deciding to use Advanced Installer, it has the advantage of adhering to the MSI standards and also of being quite simple to use.","WiX is your friend here. + + + +WiX is an incredibly flexible setup technology, xml driven and with a lot of tools and knowledge out there. + +There are a number of blogs that are relevant to WiX out there. Check out: + + + +" +806400,"We have a project with several applications including web applications, web services, windows services and windows applications. We also have prerequisites like SQL Server Express, .NET 2.0 and others. We don't have much user interaction during the setup but we want to add more intelligence to it. + +We are currently using Visual Studio to generate the integrated setup for all this. But we continuously struggle with it to make it work like we want. + +We want to change our setup tool into something simpler and flexible enough. + +We are also looking for a better solution for the upgrader, that must run upgrade sql scripts on the deployed system. Maybe this could be integrated with the setup. + +We are thinking about using InstallShield, but some say that it brings a lot of complexity. What do you think is the best tool for this job? + +Thanks!",2009/04/30,"['https://Stackoverflow.com/questions/806400', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/44547/']","I have used [Installshield](http://www.acresso.com/products/is/installshield-overview.htm), [NSIS](http://nsis.sourceforge.net/), Visual Studio and [WiX](http://wix.sourceforge.net/). Installshield always produced a bloated installer for me and costs alot. Visual Studio can be limited in some of the things that it can do, but overall it is pretty good. NSIS is definately a nice little install system since I have use it for a few products (one that has been downloaded and installed about 750k times) but when I was using it it did not follow the MSI rules. WiX is great and provides you with alot of functionality as well but is script based but there are GUIs for it now too. + +Of course it looks like you have decided to use Advanced Installer. Good luck.","There are three things I don't like about InstallShield: + +1. It seems overly complex +2. There is no way (to my knowledge) of generating from the command line, you always have to use the GUI, which is a hindrance for automated builds. +3. It seems to add an excessive amount of overhead. + +I've used [NSIS](http://nsis.sourceforge.net/) a fair bit, which is open source. Whereas InstallShield has almost a too high level a view of things, NSIS is almost a too low level. You have to write the code to poke the registry entries in for uninstalling via Add/Remove programs for instance. You will be able to get the job done, and have full control of exactly what it will do, though, and it will package into a very compact single executable. + +I have no experience with [InnoSetup](http://www.jrsoftware.org/isinfo.php) or [WiX](http://wix.sourceforge.net/) - either of them may steer a course between the two extremes of InstallShield and NSIS. Both are freely available and worth a look as well." +806400,"We have a project with several applications including web applications, web services, windows services and windows applications. We also have prerequisites like SQL Server Express, .NET 2.0 and others. We don't have much user interaction during the setup but we want to add more intelligence to it. + +We are currently using Visual Studio to generate the integrated setup for all this. But we continuously struggle with it to make it work like we want. + +We want to change our setup tool into something simpler and flexible enough. + +We are also looking for a better solution for the upgrader, that must run upgrade sql scripts on the deployed system. Maybe this could be integrated with the setup. + +We are thinking about using InstallShield, but some say that it brings a lot of complexity. What do you think is the best tool for this job? + +Thanks!",2009/04/30,"['https://Stackoverflow.com/questions/806400', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/44547/']","After reading these answers we ended up deciding to use Advanced Installer, it has the advantage of adhering to the MSI standards and also of being quite simple to use.","I have used [Installshield](http://www.acresso.com/products/is/installshield-overview.htm), [NSIS](http://nsis.sourceforge.net/), Visual Studio and [WiX](http://wix.sourceforge.net/). Installshield always produced a bloated installer for me and costs alot. Visual Studio can be limited in some of the things that it can do, but overall it is pretty good. NSIS is definately a nice little install system since I have use it for a few products (one that has been downloaded and installed about 750k times) but when I was using it it did not follow the MSI rules. WiX is great and provides you with alot of functionality as well but is script based but there are GUIs for it now too. + +Of course it looks like you have decided to use Advanced Installer. Good luck." +806400,"We have a project with several applications including web applications, web services, windows services and windows applications. We also have prerequisites like SQL Server Express, .NET 2.0 and others. We don't have much user interaction during the setup but we want to add more intelligence to it. + +We are currently using Visual Studio to generate the integrated setup for all this. But we continuously struggle with it to make it work like we want. + +We want to change our setup tool into something simpler and flexible enough. + +We are also looking for a better solution for the upgrader, that must run upgrade sql scripts on the deployed system. Maybe this could be integrated with the setup. + +We are thinking about using InstallShield, but some say that it brings a lot of complexity. What do you think is the best tool for this job? + +Thanks!",2009/04/30,"['https://Stackoverflow.com/questions/806400', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/44547/']","After reading these answers we ended up deciding to use Advanced Installer, it has the advantage of adhering to the MSI standards and also of being quite simple to use.","If you want to or have to adhere to the MSI standard installs for the Windows platform, I'd second Martin Peck's recommendation for WiX. It's basically the same technology the VS-setup projects and Installshield use - with all its pros and cons. + +If you do **not** need to be on the MSI train, you could also look at simpler alternatives - my favourite here would be [InnoSetup](http://www.jrsoftware.org/isinfo.php). It's free, it's totally easy to use, it's open source (Pascal/Delphi), it can install your apps in a fraction of a second, it JUST WORKS! :) + +Marc" +806400,"We have a project with several applications including web applications, web services, windows services and windows applications. We also have prerequisites like SQL Server Express, .NET 2.0 and others. We don't have much user interaction during the setup but we want to add more intelligence to it. + +We are currently using Visual Studio to generate the integrated setup for all this. But we continuously struggle with it to make it work like we want. + +We want to change our setup tool into something simpler and flexible enough. + +We are also looking for a better solution for the upgrader, that must run upgrade sql scripts on the deployed system. Maybe this could be integrated with the setup. + +We are thinking about using InstallShield, but some say that it brings a lot of complexity. What do you think is the best tool for this job? + +Thanks!",2009/04/30,"['https://Stackoverflow.com/questions/806400', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/44547/']","After reading these answers we ended up deciding to use Advanced Installer, it has the advantage of adhering to the MSI standards and also of being quite simple to use.","We have chosen WiX too. Mind you that you will still need to know all about Windows Installer mechanisms. WiX is version control friendly and very transparent + +If you need custom actions and would like to write that in a .NET language then go for the CustomActionAttribute approach. You can write setup dialogs using WinForms. + +This site is also a very good source [InstallSite.org](http://www.installsite.org/)" +806400,"We have a project with several applications including web applications, web services, windows services and windows applications. We also have prerequisites like SQL Server Express, .NET 2.0 and others. We don't have much user interaction during the setup but we want to add more intelligence to it. + +We are currently using Visual Studio to generate the integrated setup for all this. But we continuously struggle with it to make it work like we want. + +We want to change our setup tool into something simpler and flexible enough. + +We are also looking for a better solution for the upgrader, that must run upgrade sql scripts on the deployed system. Maybe this could be integrated with the setup. + +We are thinking about using InstallShield, but some say that it brings a lot of complexity. What do you think is the best tool for this job? + +Thanks!",2009/04/30,"['https://Stackoverflow.com/questions/806400', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/44547/']","After reading these answers we ended up deciding to use Advanced Installer, it has the advantage of adhering to the MSI standards and also of being quite simple to use.","Since you mention Visual Studio and .net, I'm assuming you are deploying to Windows based servers, but even still you might want to take a look at [fabric](http://www.nongnu.org/fab/). It is a python based deployment tool. You can write and launch scripts to deploy and setup your servers, web services, etc.. The only thing is I'm not sure how well it plays with Windows as the target server." +806400,"We have a project with several applications including web applications, web services, windows services and windows applications. We also have prerequisites like SQL Server Express, .NET 2.0 and others. We don't have much user interaction during the setup but we want to add more intelligence to it. + +We are currently using Visual Studio to generate the integrated setup for all this. But we continuously struggle with it to make it work like we want. + +We want to change our setup tool into something simpler and flexible enough. + +We are also looking for a better solution for the upgrader, that must run upgrade sql scripts on the deployed system. Maybe this could be integrated with the setup. + +We are thinking about using InstallShield, but some say that it brings a lot of complexity. What do you think is the best tool for this job? + +Thanks!",2009/04/30,"['https://Stackoverflow.com/questions/806400', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/44547/']","WiX is your friend here. + + + +WiX is an incredibly flexible setup technology, xml driven and with a lot of tools and knowledge out there. + +There are a number of blogs that are relevant to WiX out there. Check out: + + + +","If you want to or have to adhere to the MSI standard installs for the Windows platform, I'd second Martin Peck's recommendation for WiX. It's basically the same technology the VS-setup projects and Installshield use - with all its pros and cons. + +If you do **not** need to be on the MSI train, you could also look at simpler alternatives - my favourite here would be [InnoSetup](http://www.jrsoftware.org/isinfo.php). It's free, it's totally easy to use, it's open source (Pascal/Delphi), it can install your apps in a fraction of a second, it JUST WORKS! :) + +Marc" +56685913,"I am pulling data out of a SQL server using pyodbc. The issue is I need to pull data from a certain date frame, however; the date comes across in both an incorrect data type and format. Float64 and 90502(5/02/09 is what I would like.) I am very new to python and far from really even being very good at this and would appreciate any help. + +I have tried converting to string, and then strptime but it tells me that the data is in the wrong format. I have also tried the included code, however it does not seem to do what I would like for it to do, as the data still reads as float64, and does not output as desired. + +``` +import pandas.io.sql as psql +from datetime import datetime +import xlwt +import numpy +date = datetime.strftime(datetime.now(), '%m.%d.%Y') + +cnxn = pyodbc.connect( + driver='{SQL Server}', + Server='atlmktsql06', + Database='Repository', + trusted_connection='yes') +cursor = cnxn.cursor() +sql = (""""""select * FROM dbo.tblAS400_Vcresrv WHERE VRRESV='CCVNQ'"""""") +df = psql.read_sql_query(sql, cnxn) +cnxn.close() +psql.to_datetime(psql.Series(['VRIN']).astype(str), infer_datetime_format=True, errors='coerce') +a = df.head(60) +print(a) +print(df.dtypes) +df.to_excel(r'C:\PythonCode\Testing.xls') + +``` + +The end result as stated above would be for the data to convert to date, and also read appropriately so I can use the sql statement in python to pull by timeframe. Currently, VRIN = Float64 and reads as 90502 and I want VRIN = Date 5/02/09. Thank you again!",2019/06/20,"['https://Stackoverflow.com/questions/56685913', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8112192/']","One option is to use the base R function `setNames` + +``` +aggregate_mtcars <- mtcars_copy[, setNames(.(sum(carb)), new_col)] + +``` + +Or you could use `data.table::setnames` + +``` +aggregate_mtcars <- setnames(mtcars_copy[, .(sum(carb))], new_col) + +```","I think what you want is to simply make a copy when doing case 1. + +``` +aggregate_mtcars <- copy(mtcars_copy)[, eval(new_col) := sum(carb)] + +``` + +That retains `mtcars_copy` as a separate dataset to the new `aggregate_metcars`, without the new columns." +56685913,"I am pulling data out of a SQL server using pyodbc. The issue is I need to pull data from a certain date frame, however; the date comes across in both an incorrect data type and format. Float64 and 90502(5/02/09 is what I would like.) I am very new to python and far from really even being very good at this and would appreciate any help. + +I have tried converting to string, and then strptime but it tells me that the data is in the wrong format. I have also tried the included code, however it does not seem to do what I would like for it to do, as the data still reads as float64, and does not output as desired. + +``` +import pandas.io.sql as psql +from datetime import datetime +import xlwt +import numpy +date = datetime.strftime(datetime.now(), '%m.%d.%Y') + +cnxn = pyodbc.connect( + driver='{SQL Server}', + Server='atlmktsql06', + Database='Repository', + trusted_connection='yes') +cursor = cnxn.cursor() +sql = (""""""select * FROM dbo.tblAS400_Vcresrv WHERE VRRESV='CCVNQ'"""""") +df = psql.read_sql_query(sql, cnxn) +cnxn.close() +psql.to_datetime(psql.Series(['VRIN']).astype(str), infer_datetime_format=True, errors='coerce') +a = df.head(60) +print(a) +print(df.dtypes) +df.to_excel(r'C:\PythonCode\Testing.xls') + +``` + +The end result as stated above would be for the data to convert to date, and also read appropriately so I can use the sql statement in python to pull by timeframe. Currently, VRIN = Float64 and reads as 90502 and I want VRIN = Date 5/02/09. Thank you again!",2019/06/20,"['https://Stackoverflow.com/questions/56685913', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8112192/']","I think what you want is to simply make a copy when doing case 1. + +``` +aggregate_mtcars <- copy(mtcars_copy)[, eval(new_col) := sum(carb)] + +``` + +That retains `mtcars_copy` as a separate dataset to the new `aggregate_metcars`, without the new columns.","The reason is because case 2 uses `data.frame` way to create column in a data frame (as a new list). +There is hidden parameter in data.table : `with` that handles the way the object is returned. It can be a data.table or a vector. + +> +> ?data.table : +> +> By default with=TRUE and j is evaluated within the frame of x; column names can be used as variables. In case of overlapping variables names inside dataset and in parent scope you can use double dot prefix ..cols to explicitly refer to 'cols variable parent scope and not from your dataset. +> +> +> When j is a character vector of column names, a numeric vector of column positions to select or of the form startcol:endcol, and the value returned is always a data.table. with=FALSE is not necessary anymore to select columns dynamically. Note that x[, cols] is equivalent to x[, ..cols] and to x[, cols, with=FALSE] and to x[, .SD, .SDcols=cols]. +> +> +> + +```r +# Case 2 : +aggregate_mtcars<-mtcars_copy[,(get(new_col)=sum(carb))] # error +aggregate_mtcars<-mtcars_copy[,eval(new_col)=sum(carb))] # error +aggregate_mtcars<-mtcars_copy[,c(eval(new_col)=sum(carb))] # Error + +mtcars_copy[, new_col, with = FALSE ] # gives a data.table +mtcars_copy[, eval(new_col), with = FALSE ] # this works and create a data.table +mtcars_copy[, eval(new_col), with = TRUE ] # the default that is used here with error +mtcars_copy[, get(new_col), with = TRUE ] # works and gives a vector + +# Case 2 solution : affecting values the data.frame way +mtcars_copy[, eval(new_col) ] <- sum(mtcars_copy$carb) # or any vector +mtcars_copy[[eval(new_col)]] <- sum(mtcars_copy$carb) # or any vector + +```" +56685913,"I am pulling data out of a SQL server using pyodbc. The issue is I need to pull data from a certain date frame, however; the date comes across in both an incorrect data type and format. Float64 and 90502(5/02/09 is what I would like.) I am very new to python and far from really even being very good at this and would appreciate any help. + +I have tried converting to string, and then strptime but it tells me that the data is in the wrong format. I have also tried the included code, however it does not seem to do what I would like for it to do, as the data still reads as float64, and does not output as desired. + +``` +import pandas.io.sql as psql +from datetime import datetime +import xlwt +import numpy +date = datetime.strftime(datetime.now(), '%m.%d.%Y') + +cnxn = pyodbc.connect( + driver='{SQL Server}', + Server='atlmktsql06', + Database='Repository', + trusted_connection='yes') +cursor = cnxn.cursor() +sql = (""""""select * FROM dbo.tblAS400_Vcresrv WHERE VRRESV='CCVNQ'"""""") +df = psql.read_sql_query(sql, cnxn) +cnxn.close() +psql.to_datetime(psql.Series(['VRIN']).astype(str), infer_datetime_format=True, errors='coerce') +a = df.head(60) +print(a) +print(df.dtypes) +df.to_excel(r'C:\PythonCode\Testing.xls') + +``` + +The end result as stated above would be for the data to convert to date, and also read appropriately so I can use the sql statement in python to pull by timeframe. Currently, VRIN = Float64 and reads as 90502 and I want VRIN = Date 5/02/09. Thank you again!",2019/06/20,"['https://Stackoverflow.com/questions/56685913', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8112192/']","One option is to use the base R function `setNames` + +``` +aggregate_mtcars <- mtcars_copy[, setNames(.(sum(carb)), new_col)] + +``` + +Or you could use `data.table::setnames` + +``` +aggregate_mtcars <- setnames(mtcars_copy[, .(sum(carb))], new_col) + +```","The reason is because case 2 uses `data.frame` way to create column in a data frame (as a new list). +There is hidden parameter in data.table : `with` that handles the way the object is returned. It can be a data.table or a vector. + +> +> ?data.table : +> +> By default with=TRUE and j is evaluated within the frame of x; column names can be used as variables. In case of overlapping variables names inside dataset and in parent scope you can use double dot prefix ..cols to explicitly refer to 'cols variable parent scope and not from your dataset. +> +> +> When j is a character vector of column names, a numeric vector of column positions to select or of the form startcol:endcol, and the value returned is always a data.table. with=FALSE is not necessary anymore to select columns dynamically. Note that x[, cols] is equivalent to x[, ..cols] and to x[, cols, with=FALSE] and to x[, .SD, .SDcols=cols]. +> +> +> + +```r +# Case 2 : +aggregate_mtcars<-mtcars_copy[,(get(new_col)=sum(carb))] # error +aggregate_mtcars<-mtcars_copy[,eval(new_col)=sum(carb))] # error +aggregate_mtcars<-mtcars_copy[,c(eval(new_col)=sum(carb))] # Error + +mtcars_copy[, new_col, with = FALSE ] # gives a data.table +mtcars_copy[, eval(new_col), with = FALSE ] # this works and create a data.table +mtcars_copy[, eval(new_col), with = TRUE ] # the default that is used here with error +mtcars_copy[, get(new_col), with = TRUE ] # works and gives a vector + +# Case 2 solution : affecting values the data.frame way +mtcars_copy[, eval(new_col) ] <- sum(mtcars_copy$carb) # or any vector +mtcars_copy[[eval(new_col)]] <- sum(mtcars_copy$carb) # or any vector + +```" +26974838,"I want to run Python on 3Dsmax 2014. I saw the website and know 3Dsmax 2014 can use the Python script . But when I try with example from the website, it does not work. Maybe lack of some software or anything else. + +I used this code in ""MAXscript Listener"": + +``` +python.Execute ""print 'hello'"" + +``` + +And result was: + +``` +-- Unknown property: ""execute"" in undefined + +``` + +So , someone can guide me how to use the Execute ? +Thanks everyone !",2014/11/17,"['https://Stackoverflow.com/questions/26974838', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4261541/']",You would need the Extension 1 (Subscription Advantage Pack) to be able to run python scripts like that.,"You need to load python first. Try this: + +``` +python.init() +python.execute ""print 'Hello World'"" + +```" +6824604,"How to get the default HTTP USER AGENT and its default settings from the android device? + +thanks + +Nohsib",2011/07/26,"['https://Stackoverflow.com/questions/6824604', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/530993/']","as Varundroid mentioned in his answer, + +``` +String userAgent = System.getProperty(""http.agent""); + +``` + +is better way to do it for Android 2.1 and above. + +==================== + +From android source code. + +``` +public static String getDefaultUserAgent() { + StringBuilder result = new StringBuilder(64); + result.append(""Dalvik/""); + result.append(System.getProperty(""java.vm.version"")); // such as 1.1.0 + result.append("" (Linux; U; Android ""); + + String version = Build.VERSION.RELEASE; // ""1.0"" or ""3.4b5"" + result.append(version.length() > 0 ? version : ""1.0""); + + // add the model for the release build + if (""REL"".equals(Build.VERSION.CODENAME)) { + String model = Build.MODEL; + if (model.length() > 0) { + result.append(""; ""); + result.append(model); + } + } + String id = Build.ID; // ""MASTER"" or ""M4-rc20"" + if (id.length() > 0) { + result.append("" Build/""); + result.append(id); + } + result.append("")""); + return result.toString(); +} + +```","**Edit: See Prakash's answer, which is better for 2.1+.** + +Try + +Note that this User Agent will only apply for the embedded WebKit browser that's used by default in Android. Unfortunately, you'll need to create a new WebView object to get the user agent. Fortunately, the user agent doesn't change often, so you should only need to run this code once in your application lifetime (unless don't care about performance). Just do: + +``` +String userAgent = new WebView(this).getSettings().getUserAgentString(); + +``` + +Alternatively, you can use the JavaScript method `navigator.getUserAgent()`." +6824604,"How to get the default HTTP USER AGENT and its default settings from the android device? + +thanks + +Nohsib",2011/07/26,"['https://Stackoverflow.com/questions/6824604', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/530993/']","**Edit: See Prakash's answer, which is better for 2.1+.** + +Try + +Note that this User Agent will only apply for the embedded WebKit browser that's used by default in Android. Unfortunately, you'll need to create a new WebView object to get the user agent. Fortunately, the user agent doesn't change often, so you should only need to run this code once in your application lifetime (unless don't care about performance). Just do: + +``` +String userAgent = new WebView(this).getSettings().getUserAgentString(); + +``` + +Alternatively, you can use the JavaScript method `navigator.getUserAgent()`.","When you use web view to access the user-agent, make sure you run the + +`new WebView(this).getSettings().getUserAgentString();` + +on the UI thread. + +If you want access the user agent on background thread. +use + +`System.getProperty(""http.agent"")` + +To check whether a user-agent is valid or not use this +" +6824604,"How to get the default HTTP USER AGENT and its default settings from the android device? + +thanks + +Nohsib",2011/07/26,"['https://Stackoverflow.com/questions/6824604', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/530993/']","**Edit: See Prakash's answer, which is better for 2.1+.** + +Try + +Note that this User Agent will only apply for the embedded WebKit browser that's used by default in Android. Unfortunately, you'll need to create a new WebView object to get the user agent. Fortunately, the user agent doesn't change often, so you should only need to run this code once in your application lifetime (unless don't care about performance). Just do: + +``` +String userAgent = new WebView(this).getSettings().getUserAgentString(); + +``` + +Alternatively, you can use the JavaScript method `navigator.getUserAgent()`.","An alternative + +``` +if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1) { + String userAgent = WebSettings.getDefaultUserAgent(context); +} + +```" +6824604,"How to get the default HTTP USER AGENT and its default settings from the android device? + +thanks + +Nohsib",2011/07/26,"['https://Stackoverflow.com/questions/6824604', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/530993/']","as Varundroid mentioned in his answer, + +``` +String userAgent = System.getProperty(""http.agent""); + +``` + +is better way to do it for Android 2.1 and above. + +==================== + +From android source code. + +``` +public static String getDefaultUserAgent() { + StringBuilder result = new StringBuilder(64); + result.append(""Dalvik/""); + result.append(System.getProperty(""java.vm.version"")); // such as 1.1.0 + result.append("" (Linux; U; Android ""); + + String version = Build.VERSION.RELEASE; // ""1.0"" or ""3.4b5"" + result.append(version.length() > 0 ? version : ""1.0""); + + // add the model for the release build + if (""REL"".equals(Build.VERSION.CODENAME)) { + String model = Build.MODEL; + if (model.length() > 0) { + result.append(""; ""); + result.append(model); + } + } + String id = Build.ID; // ""MASTER"" or ""M4-rc20"" + if (id.length() > 0) { + result.append("" Build/""); + result.append(id); + } + result.append("")""); + return result.toString(); +} + +```","When you use web view to access the user-agent, make sure you run the + +`new WebView(this).getSettings().getUserAgentString();` + +on the UI thread. + +If you want access the user agent on background thread. +use + +`System.getProperty(""http.agent"")` + +To check whether a user-agent is valid or not use this +" +6824604,"How to get the default HTTP USER AGENT and its default settings from the android device? + +thanks + +Nohsib",2011/07/26,"['https://Stackoverflow.com/questions/6824604', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/530993/']","as Varundroid mentioned in his answer, + +``` +String userAgent = System.getProperty(""http.agent""); + +``` + +is better way to do it for Android 2.1 and above. + +==================== + +From android source code. + +``` +public static String getDefaultUserAgent() { + StringBuilder result = new StringBuilder(64); + result.append(""Dalvik/""); + result.append(System.getProperty(""java.vm.version"")); // such as 1.1.0 + result.append("" (Linux; U; Android ""); + + String version = Build.VERSION.RELEASE; // ""1.0"" or ""3.4b5"" + result.append(version.length() > 0 ? version : ""1.0""); + + // add the model for the release build + if (""REL"".equals(Build.VERSION.CODENAME)) { + String model = Build.MODEL; + if (model.length() > 0) { + result.append(""; ""); + result.append(model); + } + } + String id = Build.ID; // ""MASTER"" or ""M4-rc20"" + if (id.length() > 0) { + result.append("" Build/""); + result.append(id); + } + result.append("")""); + return result.toString(); +} + +```","An alternative + +``` +if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1) { + String userAgent = WebSettings.getDefaultUserAgent(context); +} + +```" +6824604,"How to get the default HTTP USER AGENT and its default settings from the android device? + +thanks + +Nohsib",2011/07/26,"['https://Stackoverflow.com/questions/6824604', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/530993/']","When you use web view to access the user-agent, make sure you run the + +`new WebView(this).getSettings().getUserAgentString();` + +on the UI thread. + +If you want access the user agent on background thread. +use + +`System.getProperty(""http.agent"")` + +To check whether a user-agent is valid or not use this +","An alternative + +``` +if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1) { + String userAgent = WebSettings.getDefaultUserAgent(context); +} + +```" +19532982,"I tried to give `@Column(name = ""message"")` only for the field, but it didn't work. + +I have a Bean class, that contains 10 fields but i want to insert only 2 fields using HIBERNATE ANNOTATION..? +How can i omit rest of the fields?? + +I am getting full Query: + +``` +insert into message (circle, day, destNumber, encryptedBody, hour, interfaceType, location, message) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + +``` + +Instead i want only: + insert into message (message,msgId) values(?,?)",2013/10/23,"['https://Stackoverflow.com/questions/19532982', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2888996/']","According to the [documentation](http://docs.jboss.org/hibernate/orm/4.3/manual/en-US/html/ch05.html#mapping-declaration-property), you need to annotate the properties that you **don't** want to be persisted as `@Transient`: + +``` +@Entity +public class Message implements Serializable { + + Long id; + int circle; + int day; + String message + //... + + @Id + public Long getId() { return id; } + public void setId(Long id) { this.id = id; } + + // Will not be persisted + @Transient + public int getCircle() { return circle; } + public void setCircle(int circle) { this.circle = circle; } + + // Will not be persisted + @Transient + public int getDay() { return day; } + public void setDay(int day) { this.day = day; } + + // Will be persisted + public string getMessage() { return message; } + public void setMessage(String message) { this.message = message; } + + //... +} + +``` + +If you need the `Id` to be auto-generated, you should annotate it with [`@GeneratedValue`](http://docs.jboss.org/hibernate/orm/4.3/manual/en-US/html/ch05.html#mapping-declaration-id-generator): + +``` + @Id + @GeneratedValue + @Column(name = ""msgId"") + public Long getId() { return id; } + public void setId(Long id) { this.id = id; } + +``` + +The `@GeneratedValue` annotation has many parameters that help you define how the identifier should be generated. For example, if it will be generated by the database (identity column) you should use `@GeneratedValue(strategy=GenerationType.IDENTITY)`. [This](http://docs.jboss.org/hibernate/orm/4.3/manual/en-US/html/ch05.html#d5e2487) section of the documentation lists all of the generation strategies. + +Please read the documentation carefully. You'll find the answer to almost all of your questions in the documentation. Refer to the links that I've provided.","For the MsgId issue + +1.Make sure that your MsgId field is set to Primary key and auto increment + +2.add these annotations for MsgId + +> +> @Id +> +> +> @GeneratedValue(strategy=GenerationType.AUTO) +> +> +> public Long getMsgId() { +> +> +> return id; +> +> +> } +> +> +>" +19532982,"I tried to give `@Column(name = ""message"")` only for the field, but it didn't work. + +I have a Bean class, that contains 10 fields but i want to insert only 2 fields using HIBERNATE ANNOTATION..? +How can i omit rest of the fields?? + +I am getting full Query: + +``` +insert into message (circle, day, destNumber, encryptedBody, hour, interfaceType, location, message) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + +``` + +Instead i want only: + insert into message (message,msgId) values(?,?)",2013/10/23,"['https://Stackoverflow.com/questions/19532982', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2888996/']","> +> Use Dynamic insert or dynamic-update +> +> +> + +The dynamic-insert attribute tells Hibernate whether to include null properties in the SQL INSERT statement. + +To update only modified values Use dynamic-update option + +If dynamic-update set to true, then hibernate excludes unmodified properties in the Hibernate’s SQL update statement. + +> +> @Entity +> +> +> @Table(name = ""table"") +> +> +> @org.hibernate.annotations.Entity( +> dynamicUpdate = true) +> +> +> public class Sample implements java.io.Serializable { // } +> +> +> + +[Example for dynamic insert](http://www.mkyong.com/hibernate/hibernate-dynamic-insert-attribute-example/) + +[Example for dynamic update](http://www.mkyong.com/hibernate/hibernate-dynamic-update-attribute-example/)","For the MsgId issue + +1.Make sure that your MsgId field is set to Primary key and auto increment + +2.add these annotations for MsgId + +> +> @Id +> +> +> @GeneratedValue(strategy=GenerationType.AUTO) +> +> +> public Long getMsgId() { +> +> +> return id; +> +> +> } +> +> +>" +47113078,"I have a matrix `A` of size 13472x1537. This matrix contains values smaller than 1. In my case I seek for a solution to satisfy the following condition: +If a column contains a value smaller than 1, replace all other values in the same column with `NaN`. + +I was able to implement a code that could replace these values (smaller than 1) with the previous value (or any value). However, I am looking for a solution that changes every value in the column to `NaN` no matter whether later (or previous) values are greater than 1. + +I have `i=1537`; `t=13472` + +``` +for i = 1:size(A,2) + I = A(1,i); + for t= 2:size(A,1) + if A(t,i) <= 1 + A(t,i) = I; + else + I = A(t,i); + end + end +end + +```",2017/11/04,"['https://Stackoverflow.com/questions/47113078', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7758301/']","A version, which gets rid of the loop would look like this: + +``` +A = randn(5)+2; % Random example +[row,col] = find(A<1); +A(:,col) = NaN; + +``` + +If you would want to keep the values smaller than 1 in the matrix a solution could look something like this: + +``` +A = randn(5)+2; % Random example +[row,col,ind] = find(A<1); +b = A(ind) +A(:,col) = NaN; +A(ind) = b; + +```","That would be like the following + +``` +for i = 1:size(A,2) + if ~isempty(find(A(:,i) <= 1)) + A(:,i)=nan(size(A,1),1); + end +end + +```" +14108373,"I am developing an application in swing which has 5 tabs with following 5 operations on an image :No Operation ,Color Convert ,Affine Transform ,Convolve and Look Up. + +Here is the code : + +``` +import java.awt.color.ColorSpace; +import java.awt.geom.AffineTransform; +import java.awt.image.AffineTransformOp; +import java.awt.image.BufferedImage; +import java.awt.image.ColorConvertOp; +import java.awt.image.ConvolveOp; +import java.awt.image.Kernel; +import java.awt.image.LookupOp; +import java.awt.image.LookupTable; +import java.awt.image.ShortLookupTable; +import java.io.File; +import java.io.IOException; + +import javax.imageio.ImageIO; +import javax.swing.ImageIcon; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JTabbedPane; +import javax.swing.SwingUtilities; +import javax.swing.UIManager; + +public class ImageProcessing extends JFrame{ +BufferedImage source; +public static void main(String args[]) +{ + try { + UIManager.setLookAndFeel(""javax.swing.plaf.nimbus.NimbusLookAndFeel""); + } catch (Exception e1){e1.printStackTrace();} + SwingUtilities.invokeLater(new Runnable(){public void run(){new ImageProcessing();}}); +} + +public ImageProcessing() { + // TODO Auto-generated constructor stub + super(""Image Processing""); + setSize(600,400); + setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + + try + { + source=ImageIO.read(new File(""src/abc.jpg"")); + }catch(IOException e){System.out.println(""Exception Here :""+e);} + + JTabbedPane jtp=new JTabbedPane(); + buildNoOpTab(jtp); + buildAffineTransformOpTab(jtp); + buildColorConvertOpTab(jtp); + buildConvolveOpTab(jtp); + buildLookUpOpTab(jtp); + //buildRescaleOpTab(jtp); + + add(jtp); + setVisible(true); + +} +private void buildNoOpTab(JTabbedPane jtp) +{ + jtp.add(""No Op"",new JLabel(new ImageIcon(source))); +} +private void buildAffineTransformOpTab(JTabbedPane jtp) +{ + BufferedImage dst; + AffineTransform transform=AffineTransform.getScaleInstance(0.5, 0.5); + AffineTransformOp op=new AffineTransformOp(transform, AffineTransformOp.TYPE_BILINEAR); + dst=op.filter(source, null); + jtp.add(""AffineTransform"",new JLabel(new ImageIcon(dst))); +} +private void buildColorConvertOpTab(JTabbedPane jtp) +{ + BufferedImage dst = null; + ColorSpace clr=ColorSpace.getInstance(ColorSpace.CS_GRAY); + ColorConvertOp op=new ColorConvertOp(clr,null); + dst=op.filter(source,dst); + jtp.add(""Color Convert"",new JLabel(new ImageIcon(dst))); +} + private void buildConvolveOpTab(JTabbedPane jtp) { + BufferedImage dst = null; + float sharpen[] = new float[] { + 0.0f, -1.0f, 0.0f, + -1.0f, 5.0f, -1.0f, + 0.0f, -1.0f, 0.0f + }; + Kernel kernel = new Kernel(3, 3, sharpen); + ConvolveOp op = new ConvolveOp(kernel); + dst = op.filter(source, null); + + jtp.add(""Convolve"", new JLabel(new ImageIcon(dst))); + } + private void buildLookUpOpTab(JTabbedPane jtp) + { + BufferedImage dst=null; + short[] data=new short[256]; + for(int i=0;i<256;i++) + data[i]=(short)(255-i); + LookupTable lkp=new ShortLookupTable(0,data); + LookupOp op=new LookupOp(lkp,null); + dst=op.filter(source, null); + jtp.add(""Look Up"",new JLabel(new ImageIcon(dst))); +} + +} + +``` + +There is some problem in the buildLookUpOpTab as removing this method application works fine. + +Here is the exception which I am getting: + +``` +Exception in thread ""AWT-EventQueue-0"" java.lang.IllegalArgumentException: + Number of color/alpha components should be 3 but length of bits array is 1 + at java.awt.image.ColorModel.(ColorModel.java:336) + at java.awt.image.ComponentColorModel.(ComponentColorModel.java:273) + at java.awt.image.LookupOp.createCompatibleDestImage(LookupOp.java:413) + at java.awt.image.LookupOp.filter(LookupOp.java:153) + at ImageProcessing.buildLookUpOpTab(ImageProcessing.java:108) + at ImageProcessing.(ImageProcessing.java:49) + at ImageProcessing$1.run(ImageProcessing.java:30) + at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:251) + at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:701) + at java.awt.EventQueue.access$000(EventQueue.java:102) + at java.awt.EventQueue$3.run(EventQueue.java:662) + at java.awt.EventQueue$3.run(EventQueue.java:660) + at java.security.AccessController.doPrivileged(Native Method) + at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76) + at java.awt.EventQueue.dispatchEvent(EventQueue.java:671) + at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:244) + at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:163) + at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:151) + at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:147) + at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:139) + at java.awt.EventDispatchThread.run(EventDispatchThread.java:97) + +``` + +Can anyone tell me what is the problem in that method?",2013/01/01,"['https://Stackoverflow.com/questions/14108373', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1460665/']","The `LookupOp.filter` method says that: + +*Performs a lookup operation on a BufferedImage. If the color model in the source image is not the same as that in the destination image, the pixels will be converted in the destination. If the destination image is null, a BufferedImage will be created with an appropriate ColorModel. **An IllegalArgumentException might be thrown if the number of arrays in the LookupTable does not meet the restrictions stated in the class comment above, or if the source image has an IndexColorModel.*** + +Since you are filtering a `BufferedImage` created from using `ImageIO.read`, the color model that the image will have will definitely not be IndexColorModel, since `JPEGImageReader` (which actually created the BufferdImage from the file) does not support `IndexColorModel` - in the olden days, JPEGs used the `DirectColorModel` + +Have a look at the answer on this thread on how to read a JPEG file and use a different color model: +[Unable to read JPEG image using ImageIO.read(File file)](https://stackoverflow.com/questions/2408613/problem-reading-jpeg-image-using-imageio-readfile-file)","You need to remove alpha channel from your image before using any filter on it. To make your code working, change: + +``` +try + { + source=ImageIO.read(new File(""src/abc.jpg"")); + } catch(IOException e){System.out.println(""Exception Here :""+e);} + +``` + +with this: + +``` + try + { + BufferedImage src = ImageIO.read(new File(""abc.jpg"")); + int w = src.getWidth(); + int h = src.getHeight(); + source = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); + Raster raster = src.getRaster().createChild(0, 0, w, h, 0, 0, + new int[] {0, 1, 2}); + source.setData(raster); + }catch(IOException e){System.out.println(""Exception Here :""+e);} + +``` + +The above code creates a new buffered image in `RGB` mode and set the `RGB` data of original image to new buffered image ignoring the `alpha` values. But in case your original image contains completely transparent spots then it will become black spots in new buffered image." +17284128,"It just occured to me I do not know how to best handle cases like these were I am retrieving an object from the disk, in this case I know it only is supposed to be of type `NSDictionary`. But it´s not good coding practice to make assumptions so... is the norm to do a check on which class it is and then convert it to Dictionary? + +If so, would I first retrieve the file in an `NSData` class and then ask if it is a `NSDictionary` class? + +``` + NSString *destinationString = [NSString stringWithFormat:@""%@/%@"",dataPath,filename]; + + NSDictionary *file = [[NSDictionary alloc]initWithContentsOfFile:destinationString]; + if (file) { + return YES; + } + return NO; +} + +```",2013/06/24,"['https://Stackoverflow.com/questions/17284128', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1526334/']","You don't know how `initWithContentsOfFile` is implemented. Chances are that it checks the start of the file to see if it matches a dictionary and bails early if it doesn't (returning `nil`). It might be much more efficient than getting the data first. + +As per the docs for `initWithContentsOfFile`, the method checks the type of data contained in the file and won't return a 'bad' or 'wrong' object to you so you can be sure that a non-nil object is good. + +Whether your code needs to try creating an array and then a dictionary is a different matter.","Implementing persistence in the way you describe is quite fragile. Any little change can break your persistence solution and introduce unexpected errors. If you need light weight persistence, you may take a look at [Mantle from Github](https://github.com/github/Mantle). Mantle allows you to build a typed serializable model that you can easily save into a file and read it back. Additionally, it supports versioning that is utmost important if you have to evolve your model over time." +17284128,"It just occured to me I do not know how to best handle cases like these were I am retrieving an object from the disk, in this case I know it only is supposed to be of type `NSDictionary`. But it´s not good coding practice to make assumptions so... is the norm to do a check on which class it is and then convert it to Dictionary? + +If so, would I first retrieve the file in an `NSData` class and then ask if it is a `NSDictionary` class? + +``` + NSString *destinationString = [NSString stringWithFormat:@""%@/%@"",dataPath,filename]; + + NSDictionary *file = [[NSDictionary alloc]initWithContentsOfFile:destinationString]; + if (file) { + return YES; + } + return NO; +} + +```",2013/06/24,"['https://Stackoverflow.com/questions/17284128', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1526334/']","You don't know how `initWithContentsOfFile` is implemented. Chances are that it checks the start of the file to see if it matches a dictionary and bails early if it doesn't (returning `nil`). It might be much more efficient than getting the data first. + +As per the docs for `initWithContentsOfFile`, the method checks the type of data contained in the file and won't return a 'bad' or 'wrong' object to you so you can be sure that a non-nil object is good. + +Whether your code needs to try creating an array and then a dictionary is a different matter.","Persist first class models that make sense to your application. Implement `NSCoding`and use `NSKeyedArchiver` and `NSKeyedUnarchiver`. Or as @allprog suggests, go with Mantle, this is effectively what they're doing, they just make it less boilerplate code for you." +7603,"If my interpretation is correct, Kant argued in the Critique of pure reason and Prolegomena that: + +> +> The existence of an external world guarantees that we can intuit, conceive, etc internally. +> +> +> + +This argument bears that ""transcendental"" essence in it. + +Now my question is: +Does the Brain-in-a-Vat thought experiment undermines Kant's transcendental argument above? in what way? + +I have read [this entry in the SEP](http://plato.stanford.edu/entries/realism-sem-challenge/), but it doesn't get me any further for the question I had.",2013/07/18,"['https://philosophy.stackexchange.com/questions/7603', 'https://philosophy.stackexchange.com', 'https://philosophy.stackexchange.com/users/1671/']","> +> The existence of an external world guarantees that we can intuit, +> conceive, etc internally. Does the Brain-in-a-Vat thought experiment +> undermines Kant's transcendental argument above? +> +> +> + +I think your central question is “Does external exist, and we conceive internally, if we are a brain in the vat? +Answer: If we apply the Occam's razor the question is pointless.The maps are not the territory. + +Suppose a Bizarre Brain, BB, that is, the computer of the ""brain in the vat"" skepticism, the brain of the Descartes' devil that deceives us, a permanently dreaming brain, or the solipsistic brain that create the ""universe"" for itself or for us. If the BB makes her mind the object of scientific study, it will find that it behaves with the same complexity as the universe described by a Common Sense Brain, CSB. Thus what CSB calls ""the universe"", the BB calls ""one's own mind."" Understood this way, the distinction between CSB and BB collapses and amounts to different ways of describing the same thing: a massively complex process that causes all the BB's experiences. Presumably having made the case that the BB scientist is actually a CSB scientist, the BB applies Occam's Razor, and suggests to the BB scientist to prefer the CSB's standard external “reality” over something like a BB's ""reality"". This is because the standard ""reality"" fits all the data available to the scientist, and on the skeptic's hypothesis is impossible to find differences, rendering superfluous the other more complicated possibilities. + +Unobservables such as atomic particles, the force of gravity, and the quantum physics, are useful representation models. ""The brain in the Vat"" skepticism and the solipsism are interpretations or models too. Any language which provide a practical way of thinking and make sense about natural laws, a common mind-independent world, must provide a way of expressing common true inductive inferences about this world, or a description that relates representation to prediction. What varies are the models and interpretations, but if they are to be true, what they predict does not change. There is no more an objective basis for choosing one theory/representation over another than there is for preferring the Fahrenheit to the Celsius scale for temperature ascriptions. In an interpretation, it is prediction that remains invariant between different, but equally adequate, theories or representations. + +If too many of speakers utterances are false, then the link between what speakers say and the world is severed; and the enterprise of interpretation each other halts. Too much error in statements about the world is not an option if speakers are going to translate each other. Therefore prediction is objective in the sense that most of what speakers say about the world are truths about the world. This is an assumption an translator makes because the only path into the world speakers share are the events in the world that cause them to hold those sentences true. Models translation need essentially inter-subjectivity.The maps are not the territory. It is pointless to say ""the mountain is disobeying the map"". + +Central ideas of David Deutsch and David Davidson","Kant was reacting to two positions - the wholly idealistic philosophy of Berkeley - which is a very rough equivalent to the 'brain in a vat' thought experiment which is more akin to classical solipsism - in which everything is mind and objective reality disappears, and the radical scepticism of Hume which totally undermined the basis for empirical science - essentially the idea of causality. + +The phenomenal world as we know it and sense it immediately is structured by the the intuition giving it space & time to be presented to the intellectual & reasoning faculties of the mind - the understanding. (Think of a photograph, it is actually flat, but the mind projects an illusion of space; think of reading a novel, we give the illusion of time to the protagonists in it, a (narrative) time that is entirely separate from the flow of time we are as we are reading it). + +The world in-itself (noumena) is never accessible - but it exists - otherwise we won't see its representation as phenomena. + +So Kant finds a middle ground where mind & intuition meet reality and each is immanent in the other. This allows science to happen, as it must; and leaves solipsism still fighting a lost battle." +29314841,"I want to use Raspberry PI's system command `raspistill`to take images in a c program, the program line is: `system(""raspistill -q 5 -vf -hf -o pic1.jpg -t 1 -th 0:0:0"");` + +However, when I run the program sometimes error occurs, +it shows that: + +> +> mmal\_vc\_component\_enable- failed to enable component- ENOSPC +> mmal- camera component couldn't be enabled +> mmal- main- Failed to create camera component +> mmal- Failed to run camera app. Please check for firmware updatesckquote +> +> +> + +And I have tried to add some parameters into /boot/config.txt: + +> +> gpu\_mem=128 start\_file=start\_x.elf fixup\_file=fixup\_x.dat +> +> disable\_camera\_led=1 cam\_lwm=16 cam\_hwm=32 cam\_offline\_start=16 +> +> +> + +However the error still always occurs sometimes (sometimes ok). I really want to solve this problem in order to continue my project. What should I do?",2015/03/28,"['https://Stackoverflow.com/questions/29314841', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4407689/']","In my case I ran the following on a Pi 4 model B + +``` +vcgencmd get_camera +supported=1 detected=1 + +raspistill -w 3280 -h 2464 -n -t 2000 -o test.png +mmal: mmal_vc_component_enable: failed to enable component: ENOSPC +mmal: camera component couldn't be enabled +mmal: main: Failed to create camera component +mmal: Failed to run camera app. Please check for firmware updates + +make: *** [makefile:27: raspistill] Error 70 + +``` + +It turned out to be the camera. The standard camera works!","This error occurs when you use I/O during camera recording operation. +I faced the same issue on using used I/O while recording. +So you can either add before recording or after not in between." +29314841,"I want to use Raspberry PI's system command `raspistill`to take images in a c program, the program line is: `system(""raspistill -q 5 -vf -hf -o pic1.jpg -t 1 -th 0:0:0"");` + +However, when I run the program sometimes error occurs, +it shows that: + +> +> mmal\_vc\_component\_enable- failed to enable component- ENOSPC +> mmal- camera component couldn't be enabled +> mmal- main- Failed to create camera component +> mmal- Failed to run camera app. Please check for firmware updatesckquote +> +> +> + +And I have tried to add some parameters into /boot/config.txt: + +> +> gpu\_mem=128 start\_file=start\_x.elf fixup\_file=fixup\_x.dat +> +> disable\_camera\_led=1 cam\_lwm=16 cam\_hwm=32 cam\_offline\_start=16 +> +> +> + +However the error still always occurs sometimes (sometimes ok). I really want to solve this problem in order to continue my project. What should I do?",2015/03/28,"['https://Stackoverflow.com/questions/29314841', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4407689/']","This error will appear when the RPi Camera is ""On"" and is streaming. The component: ENOSPC cannot start unless the RPi Camera is not streaming or being used by another process. +One solution is to try to stop the Camera stream before the Snapshot and then restart it after.","This error occurs when you use I/O during camera recording operation. +I faced the same issue on using used I/O while recording. +So you can either add before recording or after not in between." +29314841,"I want to use Raspberry PI's system command `raspistill`to take images in a c program, the program line is: `system(""raspistill -q 5 -vf -hf -o pic1.jpg -t 1 -th 0:0:0"");` + +However, when I run the program sometimes error occurs, +it shows that: + +> +> mmal\_vc\_component\_enable- failed to enable component- ENOSPC +> mmal- camera component couldn't be enabled +> mmal- main- Failed to create camera component +> mmal- Failed to run camera app. Please check for firmware updatesckquote +> +> +> + +And I have tried to add some parameters into /boot/config.txt: + +> +> gpu\_mem=128 start\_file=start\_x.elf fixup\_file=fixup\_x.dat +> +> disable\_camera\_led=1 cam\_lwm=16 cam\_hwm=32 cam\_offline\_start=16 +> +> +> + +However the error still always occurs sometimes (sometimes ok). I really want to solve this problem in order to continue my project. What should I do?",2015/03/28,"['https://Stackoverflow.com/questions/29314841', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4407689/']","Stop any other processes using the camera (e.g.raspimjpeg) + +``` +$ ps -aux + +``` + +// locate the process pid and kill it using the pid number (e.g. 764) + +``` +$ sudo kill 764 + +``` + +Note: You might have more than one process running so be sure to kill them all before trying again.","I use a Raspberry Pi 4 Model B and I had faced the same issue. +My solution was to **set the GPU Memory from 128 to 256** in the Raspberry Pi Configuration." +29314841,"I want to use Raspberry PI's system command `raspistill`to take images in a c program, the program line is: `system(""raspistill -q 5 -vf -hf -o pic1.jpg -t 1 -th 0:0:0"");` + +However, when I run the program sometimes error occurs, +it shows that: + +> +> mmal\_vc\_component\_enable- failed to enable component- ENOSPC +> mmal- camera component couldn't be enabled +> mmal- main- Failed to create camera component +> mmal- Failed to run camera app. Please check for firmware updatesckquote +> +> +> + +And I have tried to add some parameters into /boot/config.txt: + +> +> gpu\_mem=128 start\_file=start\_x.elf fixup\_file=fixup\_x.dat +> +> disable\_camera\_led=1 cam\_lwm=16 cam\_hwm=32 cam\_offline\_start=16 +> +> +> + +However the error still always occurs sometimes (sometimes ok). I really want to solve this problem in order to continue my project. What should I do?",2015/03/28,"['https://Stackoverflow.com/questions/29314841', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4407689/']","Stop any other processes using the camera (e.g.raspimjpeg) + +``` +$ ps -aux + +``` + +// locate the process pid and kill it using the pid number (e.g. 764) + +``` +$ sudo kill 764 + +``` + +Note: You might have more than one process running so be sure to kill them all before trying again.","This error occurs when you use I/O during camera recording operation. +I faced the same issue on using used I/O while recording. +So you can either add before recording or after not in between." +29314841,"I want to use Raspberry PI's system command `raspistill`to take images in a c program, the program line is: `system(""raspistill -q 5 -vf -hf -o pic1.jpg -t 1 -th 0:0:0"");` + +However, when I run the program sometimes error occurs, +it shows that: + +> +> mmal\_vc\_component\_enable- failed to enable component- ENOSPC +> mmal- camera component couldn't be enabled +> mmal- main- Failed to create camera component +> mmal- Failed to run camera app. Please check for firmware updatesckquote +> +> +> + +And I have tried to add some parameters into /boot/config.txt: + +> +> gpu\_mem=128 start\_file=start\_x.elf fixup\_file=fixup\_x.dat +> +> disable\_camera\_led=1 cam\_lwm=16 cam\_hwm=32 cam\_offline\_start=16 +> +> +> + +However the error still always occurs sometimes (sometimes ok). I really want to solve this problem in order to continue my project. What should I do?",2015/03/28,"['https://Stackoverflow.com/questions/29314841', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4407689/']","finally i can solve this problem after a lot of hours troubleshooting. + +I already share it in my YouTube () + +This problem only occur in camera raspberry pi V2.1 (IMX219) from **Element14**. But in camera raspberry pi V2.1 from **OKdo**, i don't get this error + +So, the solution when error +""mmal: mmal\_vc\_component\_enable: failed to enable component: ENOSPC +mmal: camera component couldn't be enabled +mmal: main: Failed to create camera component +mmal: Failed to run camera app. Please check for firmware updates"" + +You **need some initialization** with a works camera (me camera from **OKdo**). +So, the step is + +1. Plug your works camera to Raspberry Pi (me using Raspberry Pi 4B) +2. Turn on your Raspberry Pi +3. check ""vcgencmd get\_camera"" to make sure your hardware is detected the camera +4. capture image using ""raspistill -v"" and camera will capture the image +5. Then replace the works camera with ENOSPC Error Camera (from **Element14**) +6. then try to capture the image ""raspistill -v"" and the ENOSPC Error will not occur + +**Notes:** + +* But, after the ENOSPC Error Camera works, and then you restart/shutdown the raspberry pi, the error will occur again :( + +OS Raspberry Pi 4 Model B (4GB) + +* Linux raspberrypi 5.10.60-v7l+ #1449 SMP Wed Aug 25 15:00:44 BST 2021 armv7l GNU/Linux","This error occurs when you use I/O during camera recording operation. +I faced the same issue on using used I/O while recording. +So you can either add before recording or after not in between." +29314841,"I want to use Raspberry PI's system command `raspistill`to take images in a c program, the program line is: `system(""raspistill -q 5 -vf -hf -o pic1.jpg -t 1 -th 0:0:0"");` + +However, when I run the program sometimes error occurs, +it shows that: + +> +> mmal\_vc\_component\_enable- failed to enable component- ENOSPC +> mmal- camera component couldn't be enabled +> mmal- main- Failed to create camera component +> mmal- Failed to run camera app. Please check for firmware updatesckquote +> +> +> + +And I have tried to add some parameters into /boot/config.txt: + +> +> gpu\_mem=128 start\_file=start\_x.elf fixup\_file=fixup\_x.dat +> +> disable\_camera\_led=1 cam\_lwm=16 cam\_hwm=32 cam\_offline\_start=16 +> +> +> + +However the error still always occurs sometimes (sometimes ok). I really want to solve this problem in order to continue my project. What should I do?",2015/03/28,"['https://Stackoverflow.com/questions/29314841', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4407689/']","Stop any other processes using the camera (e.g.raspimjpeg) + +``` +$ ps -aux + +``` + +// locate the process pid and kill it using the pid number (e.g. 764) + +``` +$ sudo kill 764 + +``` + +Note: You might have more than one process running so be sure to kill them all before trying again.","finally i can solve this problem after a lot of hours troubleshooting. + +I already share it in my YouTube () + +This problem only occur in camera raspberry pi V2.1 (IMX219) from **Element14**. But in camera raspberry pi V2.1 from **OKdo**, i don't get this error + +So, the solution when error +""mmal: mmal\_vc\_component\_enable: failed to enable component: ENOSPC +mmal: camera component couldn't be enabled +mmal: main: Failed to create camera component +mmal: Failed to run camera app. Please check for firmware updates"" + +You **need some initialization** with a works camera (me camera from **OKdo**). +So, the step is + +1. Plug your works camera to Raspberry Pi (me using Raspberry Pi 4B) +2. Turn on your Raspberry Pi +3. check ""vcgencmd get\_camera"" to make sure your hardware is detected the camera +4. capture image using ""raspistill -v"" and camera will capture the image +5. Then replace the works camera with ENOSPC Error Camera (from **Element14**) +6. then try to capture the image ""raspistill -v"" and the ENOSPC Error will not occur + +**Notes:** + +* But, after the ENOSPC Error Camera works, and then you restart/shutdown the raspberry pi, the error will occur again :( + +OS Raspberry Pi 4 Model B (4GB) + +* Linux raspberrypi 5.10.60-v7l+ #1449 SMP Wed Aug 25 15:00:44 BST 2021 armv7l GNU/Linux" +29314841,"I want to use Raspberry PI's system command `raspistill`to take images in a c program, the program line is: `system(""raspistill -q 5 -vf -hf -o pic1.jpg -t 1 -th 0:0:0"");` + +However, when I run the program sometimes error occurs, +it shows that: + +> +> mmal\_vc\_component\_enable- failed to enable component- ENOSPC +> mmal- camera component couldn't be enabled +> mmal- main- Failed to create camera component +> mmal- Failed to run camera app. Please check for firmware updatesckquote +> +> +> + +And I have tried to add some parameters into /boot/config.txt: + +> +> gpu\_mem=128 start\_file=start\_x.elf fixup\_file=fixup\_x.dat +> +> disable\_camera\_led=1 cam\_lwm=16 cam\_hwm=32 cam\_offline\_start=16 +> +> +> + +However the error still always occurs sometimes (sometimes ok). I really want to solve this problem in order to continue my project. What should I do?",2015/03/28,"['https://Stackoverflow.com/questions/29314841', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4407689/']","In my case I ran the following on a Pi 4 model B + +``` +vcgencmd get_camera +supported=1 detected=1 + +raspistill -w 3280 -h 2464 -n -t 2000 -o test.png +mmal: mmal_vc_component_enable: failed to enable component: ENOSPC +mmal: camera component couldn't be enabled +mmal: main: Failed to create camera component +mmal: Failed to run camera app. Please check for firmware updates + +make: *** [makefile:27: raspistill] Error 70 + +``` + +It turned out to be the camera. The standard camera works!","I use a Raspberry Pi 4 Model B and I had faced the same issue. +My solution was to **set the GPU Memory from 128 to 256** in the Raspberry Pi Configuration." +29314841,"I want to use Raspberry PI's system command `raspistill`to take images in a c program, the program line is: `system(""raspistill -q 5 -vf -hf -o pic1.jpg -t 1 -th 0:0:0"");` + +However, when I run the program sometimes error occurs, +it shows that: + +> +> mmal\_vc\_component\_enable- failed to enable component- ENOSPC +> mmal- camera component couldn't be enabled +> mmal- main- Failed to create camera component +> mmal- Failed to run camera app. Please check for firmware updatesckquote +> +> +> + +And I have tried to add some parameters into /boot/config.txt: + +> +> gpu\_mem=128 start\_file=start\_x.elf fixup\_file=fixup\_x.dat +> +> disable\_camera\_led=1 cam\_lwm=16 cam\_hwm=32 cam\_offline\_start=16 +> +> +> + +However the error still always occurs sometimes (sometimes ok). I really want to solve this problem in order to continue my project. What should I do?",2015/03/28,"['https://Stackoverflow.com/questions/29314841', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4407689/']","This error will appear when the RPi Camera is ""On"" and is streaming. The component: ENOSPC cannot start unless the RPi Camera is not streaming or being used by another process. +One solution is to try to stop the Camera stream before the Snapshot and then restart it after.","I use a Raspberry Pi 4 Model B and I had faced the same issue. +My solution was to **set the GPU Memory from 128 to 256** in the Raspberry Pi Configuration." +29314841,"I want to use Raspberry PI's system command `raspistill`to take images in a c program, the program line is: `system(""raspistill -q 5 -vf -hf -o pic1.jpg -t 1 -th 0:0:0"");` + +However, when I run the program sometimes error occurs, +it shows that: + +> +> mmal\_vc\_component\_enable- failed to enable component- ENOSPC +> mmal- camera component couldn't be enabled +> mmal- main- Failed to create camera component +> mmal- Failed to run camera app. Please check for firmware updatesckquote +> +> +> + +And I have tried to add some parameters into /boot/config.txt: + +> +> gpu\_mem=128 start\_file=start\_x.elf fixup\_file=fixup\_x.dat +> +> disable\_camera\_led=1 cam\_lwm=16 cam\_hwm=32 cam\_offline\_start=16 +> +> +> + +However the error still always occurs sometimes (sometimes ok). I really want to solve this problem in order to continue my project. What should I do?",2015/03/28,"['https://Stackoverflow.com/questions/29314841', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4407689/']","Stop any other processes using the camera (e.g.raspimjpeg) + +``` +$ ps -aux + +``` + +// locate the process pid and kill it using the pid number (e.g. 764) + +``` +$ sudo kill 764 + +``` + +Note: You might have more than one process running so be sure to kill them all before trying again.","This error will appear when the RPi Camera is ""On"" and is streaming. The component: ENOSPC cannot start unless the RPi Camera is not streaming or being used by another process. +One solution is to try to stop the Camera stream before the Snapshot and then restart it after." +29314841,"I want to use Raspberry PI's system command `raspistill`to take images in a c program, the program line is: `system(""raspistill -q 5 -vf -hf -o pic1.jpg -t 1 -th 0:0:0"");` + +However, when I run the program sometimes error occurs, +it shows that: + +> +> mmal\_vc\_component\_enable- failed to enable component- ENOSPC +> mmal- camera component couldn't be enabled +> mmal- main- Failed to create camera component +> mmal- Failed to run camera app. Please check for firmware updatesckquote +> +> +> + +And I have tried to add some parameters into /boot/config.txt: + +> +> gpu\_mem=128 start\_file=start\_x.elf fixup\_file=fixup\_x.dat +> +> disable\_camera\_led=1 cam\_lwm=16 cam\_hwm=32 cam\_offline\_start=16 +> +> +> + +However the error still always occurs sometimes (sometimes ok). I really want to solve this problem in order to continue my project. What should I do?",2015/03/28,"['https://Stackoverflow.com/questions/29314841', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4407689/']","In my case I ran the following on a Pi 4 model B + +``` +vcgencmd get_camera +supported=1 detected=1 + +raspistill -w 3280 -h 2464 -n -t 2000 -o test.png +mmal: mmal_vc_component_enable: failed to enable component: ENOSPC +mmal: camera component couldn't be enabled +mmal: main: Failed to create camera component +mmal: Failed to run camera app. Please check for firmware updates + +make: *** [makefile:27: raspistill] Error 70 + +``` + +It turned out to be the camera. The standard camera works!","This error will appear when the RPi Camera is ""On"" and is streaming. The component: ENOSPC cannot start unless the RPi Camera is not streaming or being used by another process. +One solution is to try to stop the Camera stream before the Snapshot and then restart it after." +35521868,"I cannot change the color of this SVG Image: + +Here's the SVG's code: + +``` + + + + + +``` + +I want the color to be white using the following but it doesn't change anything: + +``` + + + + + +``` + +What's the problem? + +I am editing the SVG's code using this site: ",2016/02/20,"['https://Stackoverflow.com/questions/35521868', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']","Try using this: + +``` + let selectedTube = ""circle"" + let headers = [""cache-control"": ""no-cache"",] + +let request = NSMutableURLRequest(URL: NSURL(string: ""https://api.tfl.gov.uk/Line/\(selectedTube)/Arrivals?app_id=6573044a&app_key=7a97df35339dc68625384077a5e07304"")!, + cachePolicy: .UseProtocolCachePolicy, + timeoutInterval: 10.0) + request.HTTPMethod = ""GET"" + request.allHTTPHeaderFields = headers + + let session = NSURLSession.sharedSession() + let dataTask = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in + if (error != nil) { + print(error) + } else { + let httpResponse = response as? NSHTTPURLResponse + print(httpResponse) + } + }) + + dataTask.resume() + +```","I'm not quite sure what your problem is. The following code works just fine in a playground. I would suspect the problem lies within your custom `JSON` function: + +``` +import Foundation + +let selectedTube = ""Circle"" +let url = NSURL(string: ""https://api.tfl.gov.uk/Line/\(selectedTube)/Arrivals?app_id=6573044a&app_key=7a97df35339dc68625384077a5e07304"") +if let jsonData = NSData(contentsOfURL: url!) { + let readableJSON = try NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers) + NSLog(""the URL: \(readableJSON)"") +} else { + print(""Cannot read data."") +} + +```" +394610,"I accidentally add a locale, e.g. sudo locale-gen zh\_TW + +e.g. locale -a + +``` +zh_TW + +``` + +But how to remove it?",2012/06/01,"['https://serverfault.com/questions/394610', 'https://serverfault.com', 'https://serverfault.com/users/50774/']",I think you can do this by editing `/var/lib/locales/supported.d/local` and removing that locale. Then run `locale-gen` to regenerate the compiled locales.,You can also reconfigure the locales package using `dpkg-reconfigure locales`. +394610,"I accidentally add a locale, e.g. sudo locale-gen zh\_TW + +e.g. locale -a + +``` +zh_TW + +``` + +But how to remove it?",2012/06/01,"['https://serverfault.com/questions/394610', 'https://serverfault.com', 'https://serverfault.com/users/50774/']",I think you can do this by editing `/var/lib/locales/supported.d/local` and removing that locale. Then run `locale-gen` to regenerate the compiled locales.,"**Which locales are installed on my machine?** + +You can check which locales are generated and configured on your system using the locale command: + +* **`locale`** ... list the current locale configuration +* **`locale -a`** ... lists all all locales that were generated on your system +* **`locale -a -v`** ... list all locales and show useful additional information (such as +directory names that contain the locale information data files) + +The last command from above makes you see that all generated locales are located in **`/usr/lib/locale/`**, and you may remove any of them if unneeded. Each pack of locale information is a directory containing text files and other directories. + +- + +**Supported locales** + +All locales that you want your system to support are listed in the text files in **`/var/lib/locales/supported.d/`**. These files have two columns, language tag and character map. + +I want my system to know US-English only, so I have only one file there, called **`en`**, which contains just a single line: + +``` +en_US UTF-8 + +``` + +- + +**Error messages** + +If error messages are displayed when issuing the locale command, e.g. + +``` +locale: Cannot set LC_ALL to default locale: No such file or directory + +``` + +make sure the file **`/etc/default/locale`** exists and has proper content, such as: + +``` +LANG=""en_US"" +LANGUAGE=""en_US:en"" + +``` + +- + +**Get rid of unneeded locale data - Step by step** + +Now we know all the necessary details to get started with cleaning up our system's locale information: + +1. Edit the locale file(s) in **`/var/lib/locales/supported.d/`**, and remove all unneeded locales (one locale per line) +2. Create and edit **`/etc/default/locale`** (see above for an example) +3. Delete all generated locale data: **`rm -rfv /usr/lib/locale/*`** +4. Re-generate new locales: **`locale-gen`** + +That's all! Reboot your machine to make your changes take effect. Then run one or more of the locale command examples from above to ensure yourself that the result is as expected. + +- + +**Reference:** + +" +394610,"I accidentally add a locale, e.g. sudo locale-gen zh\_TW + +e.g. locale -a + +``` +zh_TW + +``` + +But how to remove it?",2012/06/01,"['https://serverfault.com/questions/394610', 'https://serverfault.com', 'https://serverfault.com/users/50774/']",I think you can do this by editing `/var/lib/locales/supported.d/local` and removing that locale. Then run `locale-gen` to regenerate the compiled locales.,"**Note:** Some of the commands below require root privileges, consider the use of `sudo`. + +### Basic info + +According to [`man locale-gen`](http://manpages.ubuntu.com/manpages/jammy/man8/locale-gen.8.html), locales are set in several files. + +> +> `/etc/locale.gen` +> +> +> The main configuration file, which has a simple format: every line that is not empty and does not begin with a # is treated as a locale definition that is to be built. +> +> +> `/var/lib/locales/supported.d/` +> +> +> A directory containing locale.gen snippets provided by language-pack packages. Do not edit these manually, they will be overwritten on package upgrades. +> +> +> + +Locales are compiled (generated) into a single file. + +> +> `/usr/lib/locale/locale-archive` +> +> +> Usual default locale archive location. +> +> +> + +Comprehensive details on locales at the [Arch Wiki](https://wiki.archlinux.org/index.php/locale). + +### Checking locales and the locale + +To list available (known) locales, run any of the following commands (with minor output differences). + +```bash +locale -a +localectl list-locales + +``` + +To check the (already) generated locales, run the following command. + +```bash +localedef --list-archive + +``` + +To check the currently used locale, run any of the following commands (with minor output differences). + +```bash +locale +localectl + +``` + +### Setting and generating (new) locales + +Locales are typically set by uncommenting lines in `/etc/locale.gen`, after which running `locale-gen` is required. + +```bash +nano /etc/locale.gen # uncomment desired lines (locales) +locale-gen + +``` + +This will compile (generate) locales into `/usr/lib/locale/locale-archive` for each uncommented line in `/etc/locale.gen` and under `/var/lib/locales/supported.d/`, whether they were previously compiled or not. + +Alternatively, the command + +```bash +locale-gen + +``` + +will uncomment the corresponding line in `locale-gen` while generating the desired locale and only this one. + +Note: The implementation of `locale-gen` is distro dependent. For instance, the command above is valid in Ubuntu/Debian but not in ArchLinux. + +### Removing locales + +When issuing `locale-gen`, the compiled archive is erased and all locales in `/etc/locale.gen` and under `/usr/lib/locale/locale-archive` are regenerated anew. The command `locale-gen --purge ` doesn't do what the modifier suggests but the opposite: It removes all compiled locales except those indicated. To make sure only specific locales are generated when `locale-gen` is issued or and update is performed both `/etc/locale.gen` and `/usr/lib/locale/locale-archive` must be considered. + +To remove locales in `/etc/locale.gen`, simply comment the desired lines and regenerate the locales using `locale-gen`. + +To remove locales under `/var/lib/locales/supported.d/` is trickier. Since any file `/var/lib/locales/supported.d/` depends on the package `language-pack--base`, any change on the former will be restored when the latter is updated. To solve this, simply hold the packages that update files under `/var/lib/locales/supported.d/`. The command that achieves this in Ubuntu/Debian is the following. + +```bash +apt-mark language-pack--base + +``` + +To update a held package, you must [unmark](https://manpages.ubuntu.com/manpages/jammy/man8/apt-mark.8.html) it or simply [`--ignore-hold`](https://manpages.ubuntu.com/manpages/jammy/man8/apt-get.8.html). + +**Workaround.** A more intrusive but general solution that prevents changes under `/var/lib/locales/supported.d/` is to set files in it with the [""immutable (i)"" attribute](http://manpages.ubuntu.com/manpages/jammy/man1/chattr.1.html). So instead of removing files, empty them. For instance: + +```bash +cd /var/lib/locales/supported.d/ +rm && touch # has been emptied +lsattr # regular attributes +chattr +i # adding (+) immutable +lsattr # checking attributes + +``` + +### Setting the locale + +Setting and generating locales does not set the system locale. Any of the following commands achieves this. + +```bash +echo LANG= | sudo tee /etc/locale.conf # reboot (might be ignored in Ubuntu) +localectl set-locale LANG= + +```" +394610,"I accidentally add a locale, e.g. sudo locale-gen zh\_TW + +e.g. locale -a + +``` +zh_TW + +``` + +But how to remove it?",2012/06/01,"['https://serverfault.com/questions/394610', 'https://serverfault.com', 'https://serverfault.com/users/50774/']",I think you can do this by editing `/var/lib/locales/supported.d/local` and removing that locale. Then run `locale-gen` to regenerate the compiled locales.,"I am unsure why the most Distributions and Users are unaware from [localepurge](https://manpages.ubuntu.com/manpages/kinetic/en/man8/localepurge.8.html) + +For Debian based Systems, should it be available by + +```bash +apt-get install localepurge + +``` + +From the Manpage: + +> +> localepurge is a small script to recover disk space wasted for unneeded locale files and localized man pages. It will be automagically invoked by dpkg upon completion of any apt installation run. +> +> +> + +> +> You have to define the locale diretory names you want to keep from +> removal after each apt installation run in the /etc/locale.nopurge configuration file. Unless localepurge has been adequately configured, the system's localization files won't be touched at all. +> +> +> + +> +> The contents of following directories will be affected from removals: +> +> +> + +``` + - /usr/share/doc/kde/HTML + - /usr/share/gnome/help + - /usr/share/locale + - /usr/share/man + - /usr/share/omf + - /usr/share/tcltk + - /usr/share/cups/{templates,locale,doc-root} + - /usr/share/calendar + - /usr/share/aptitude + - /usr/share/help//HELP_CONTENT(files&dirs) + - /usr/share/vim/vim*/lang + +``` + +> +> The localization files you actually need and which you want to be preserved on your system can be easily configured by running the following command: +> +> +> + +``` +dpkg-reconfigure localepurge + +``` + +Conclusion: +This Script will take care of any unwanted locales at the moment and in the future." +394610,"I accidentally add a locale, e.g. sudo locale-gen zh\_TW + +e.g. locale -a + +``` +zh_TW + +``` + +But how to remove it?",2012/06/01,"['https://serverfault.com/questions/394610', 'https://serverfault.com', 'https://serverfault.com/users/50774/']",You can also reconfigure the locales package using `dpkg-reconfigure locales`.,"**Note:** Some of the commands below require root privileges, consider the use of `sudo`. + +### Basic info + +According to [`man locale-gen`](http://manpages.ubuntu.com/manpages/jammy/man8/locale-gen.8.html), locales are set in several files. + +> +> `/etc/locale.gen` +> +> +> The main configuration file, which has a simple format: every line that is not empty and does not begin with a # is treated as a locale definition that is to be built. +> +> +> `/var/lib/locales/supported.d/` +> +> +> A directory containing locale.gen snippets provided by language-pack packages. Do not edit these manually, they will be overwritten on package upgrades. +> +> +> + +Locales are compiled (generated) into a single file. + +> +> `/usr/lib/locale/locale-archive` +> +> +> Usual default locale archive location. +> +> +> + +Comprehensive details on locales at the [Arch Wiki](https://wiki.archlinux.org/index.php/locale). + +### Checking locales and the locale + +To list available (known) locales, run any of the following commands (with minor output differences). + +```bash +locale -a +localectl list-locales + +``` + +To check the (already) generated locales, run the following command. + +```bash +localedef --list-archive + +``` + +To check the currently used locale, run any of the following commands (with minor output differences). + +```bash +locale +localectl + +``` + +### Setting and generating (new) locales + +Locales are typically set by uncommenting lines in `/etc/locale.gen`, after which running `locale-gen` is required. + +```bash +nano /etc/locale.gen # uncomment desired lines (locales) +locale-gen + +``` + +This will compile (generate) locales into `/usr/lib/locale/locale-archive` for each uncommented line in `/etc/locale.gen` and under `/var/lib/locales/supported.d/`, whether they were previously compiled or not. + +Alternatively, the command + +```bash +locale-gen + +``` + +will uncomment the corresponding line in `locale-gen` while generating the desired locale and only this one. + +Note: The implementation of `locale-gen` is distro dependent. For instance, the command above is valid in Ubuntu/Debian but not in ArchLinux. + +### Removing locales + +When issuing `locale-gen`, the compiled archive is erased and all locales in `/etc/locale.gen` and under `/usr/lib/locale/locale-archive` are regenerated anew. The command `locale-gen --purge ` doesn't do what the modifier suggests but the opposite: It removes all compiled locales except those indicated. To make sure only specific locales are generated when `locale-gen` is issued or and update is performed both `/etc/locale.gen` and `/usr/lib/locale/locale-archive` must be considered. + +To remove locales in `/etc/locale.gen`, simply comment the desired lines and regenerate the locales using `locale-gen`. + +To remove locales under `/var/lib/locales/supported.d/` is trickier. Since any file `/var/lib/locales/supported.d/` depends on the package `language-pack--base`, any change on the former will be restored when the latter is updated. To solve this, simply hold the packages that update files under `/var/lib/locales/supported.d/`. The command that achieves this in Ubuntu/Debian is the following. + +```bash +apt-mark language-pack--base + +``` + +To update a held package, you must [unmark](https://manpages.ubuntu.com/manpages/jammy/man8/apt-mark.8.html) it or simply [`--ignore-hold`](https://manpages.ubuntu.com/manpages/jammy/man8/apt-get.8.html). + +**Workaround.** A more intrusive but general solution that prevents changes under `/var/lib/locales/supported.d/` is to set files in it with the [""immutable (i)"" attribute](http://manpages.ubuntu.com/manpages/jammy/man1/chattr.1.html). So instead of removing files, empty them. For instance: + +```bash +cd /var/lib/locales/supported.d/ +rm && touch # has been emptied +lsattr # regular attributes +chattr +i # adding (+) immutable +lsattr # checking attributes + +``` + +### Setting the locale + +Setting and generating locales does not set the system locale. Any of the following commands achieves this. + +```bash +echo LANG= | sudo tee /etc/locale.conf # reboot (might be ignored in Ubuntu) +localectl set-locale LANG= + +```" +394610,"I accidentally add a locale, e.g. sudo locale-gen zh\_TW + +e.g. locale -a + +``` +zh_TW + +``` + +But how to remove it?",2012/06/01,"['https://serverfault.com/questions/394610', 'https://serverfault.com', 'https://serverfault.com/users/50774/']",You can also reconfigure the locales package using `dpkg-reconfigure locales`.,"I am unsure why the most Distributions and Users are unaware from [localepurge](https://manpages.ubuntu.com/manpages/kinetic/en/man8/localepurge.8.html) + +For Debian based Systems, should it be available by + +```bash +apt-get install localepurge + +``` + +From the Manpage: + +> +> localepurge is a small script to recover disk space wasted for unneeded locale files and localized man pages. It will be automagically invoked by dpkg upon completion of any apt installation run. +> +> +> + +> +> You have to define the locale diretory names you want to keep from +> removal after each apt installation run in the /etc/locale.nopurge configuration file. Unless localepurge has been adequately configured, the system's localization files won't be touched at all. +> +> +> + +> +> The contents of following directories will be affected from removals: +> +> +> + +``` + - /usr/share/doc/kde/HTML + - /usr/share/gnome/help + - /usr/share/locale + - /usr/share/man + - /usr/share/omf + - /usr/share/tcltk + - /usr/share/cups/{templates,locale,doc-root} + - /usr/share/calendar + - /usr/share/aptitude + - /usr/share/help//HELP_CONTENT(files&dirs) + - /usr/share/vim/vim*/lang + +``` + +> +> The localization files you actually need and which you want to be preserved on your system can be easily configured by running the following command: +> +> +> + +``` +dpkg-reconfigure localepurge + +``` + +Conclusion: +This Script will take care of any unwanted locales at the moment and in the future." +394610,"I accidentally add a locale, e.g. sudo locale-gen zh\_TW + +e.g. locale -a + +``` +zh_TW + +``` + +But how to remove it?",2012/06/01,"['https://serverfault.com/questions/394610', 'https://serverfault.com', 'https://serverfault.com/users/50774/']","**Which locales are installed on my machine?** + +You can check which locales are generated and configured on your system using the locale command: + +* **`locale`** ... list the current locale configuration +* **`locale -a`** ... lists all all locales that were generated on your system +* **`locale -a -v`** ... list all locales and show useful additional information (such as +directory names that contain the locale information data files) + +The last command from above makes you see that all generated locales are located in **`/usr/lib/locale/`**, and you may remove any of them if unneeded. Each pack of locale information is a directory containing text files and other directories. + +- + +**Supported locales** + +All locales that you want your system to support are listed in the text files in **`/var/lib/locales/supported.d/`**. These files have two columns, language tag and character map. + +I want my system to know US-English only, so I have only one file there, called **`en`**, which contains just a single line: + +``` +en_US UTF-8 + +``` + +- + +**Error messages** + +If error messages are displayed when issuing the locale command, e.g. + +``` +locale: Cannot set LC_ALL to default locale: No such file or directory + +``` + +make sure the file **`/etc/default/locale`** exists and has proper content, such as: + +``` +LANG=""en_US"" +LANGUAGE=""en_US:en"" + +``` + +- + +**Get rid of unneeded locale data - Step by step** + +Now we know all the necessary details to get started with cleaning up our system's locale information: + +1. Edit the locale file(s) in **`/var/lib/locales/supported.d/`**, and remove all unneeded locales (one locale per line) +2. Create and edit **`/etc/default/locale`** (see above for an example) +3. Delete all generated locale data: **`rm -rfv /usr/lib/locale/*`** +4. Re-generate new locales: **`locale-gen`** + +That's all! Reboot your machine to make your changes take effect. Then run one or more of the locale command examples from above to ensure yourself that the result is as expected. + +- + +**Reference:** + +","**Note:** Some of the commands below require root privileges, consider the use of `sudo`. + +### Basic info + +According to [`man locale-gen`](http://manpages.ubuntu.com/manpages/jammy/man8/locale-gen.8.html), locales are set in several files. + +> +> `/etc/locale.gen` +> +> +> The main configuration file, which has a simple format: every line that is not empty and does not begin with a # is treated as a locale definition that is to be built. +> +> +> `/var/lib/locales/supported.d/` +> +> +> A directory containing locale.gen snippets provided by language-pack packages. Do not edit these manually, they will be overwritten on package upgrades. +> +> +> + +Locales are compiled (generated) into a single file. + +> +> `/usr/lib/locale/locale-archive` +> +> +> Usual default locale archive location. +> +> +> + +Comprehensive details on locales at the [Arch Wiki](https://wiki.archlinux.org/index.php/locale). + +### Checking locales and the locale + +To list available (known) locales, run any of the following commands (with minor output differences). + +```bash +locale -a +localectl list-locales + +``` + +To check the (already) generated locales, run the following command. + +```bash +localedef --list-archive + +``` + +To check the currently used locale, run any of the following commands (with minor output differences). + +```bash +locale +localectl + +``` + +### Setting and generating (new) locales + +Locales are typically set by uncommenting lines in `/etc/locale.gen`, after which running `locale-gen` is required. + +```bash +nano /etc/locale.gen # uncomment desired lines (locales) +locale-gen + +``` + +This will compile (generate) locales into `/usr/lib/locale/locale-archive` for each uncommented line in `/etc/locale.gen` and under `/var/lib/locales/supported.d/`, whether they were previously compiled or not. + +Alternatively, the command + +```bash +locale-gen + +``` + +will uncomment the corresponding line in `locale-gen` while generating the desired locale and only this one. + +Note: The implementation of `locale-gen` is distro dependent. For instance, the command above is valid in Ubuntu/Debian but not in ArchLinux. + +### Removing locales + +When issuing `locale-gen`, the compiled archive is erased and all locales in `/etc/locale.gen` and under `/usr/lib/locale/locale-archive` are regenerated anew. The command `locale-gen --purge ` doesn't do what the modifier suggests but the opposite: It removes all compiled locales except those indicated. To make sure only specific locales are generated when `locale-gen` is issued or and update is performed both `/etc/locale.gen` and `/usr/lib/locale/locale-archive` must be considered. + +To remove locales in `/etc/locale.gen`, simply comment the desired lines and regenerate the locales using `locale-gen`. + +To remove locales under `/var/lib/locales/supported.d/` is trickier. Since any file `/var/lib/locales/supported.d/` depends on the package `language-pack--base`, any change on the former will be restored when the latter is updated. To solve this, simply hold the packages that update files under `/var/lib/locales/supported.d/`. The command that achieves this in Ubuntu/Debian is the following. + +```bash +apt-mark language-pack--base + +``` + +To update a held package, you must [unmark](https://manpages.ubuntu.com/manpages/jammy/man8/apt-mark.8.html) it or simply [`--ignore-hold`](https://manpages.ubuntu.com/manpages/jammy/man8/apt-get.8.html). + +**Workaround.** A more intrusive but general solution that prevents changes under `/var/lib/locales/supported.d/` is to set files in it with the [""immutable (i)"" attribute](http://manpages.ubuntu.com/manpages/jammy/man1/chattr.1.html). So instead of removing files, empty them. For instance: + +```bash +cd /var/lib/locales/supported.d/ +rm && touch # has been emptied +lsattr # regular attributes +chattr +i # adding (+) immutable +lsattr # checking attributes + +``` + +### Setting the locale + +Setting and generating locales does not set the system locale. Any of the following commands achieves this. + +```bash +echo LANG= | sudo tee /etc/locale.conf # reboot (might be ignored in Ubuntu) +localectl set-locale LANG= + +```" +394610,"I accidentally add a locale, e.g. sudo locale-gen zh\_TW + +e.g. locale -a + +``` +zh_TW + +``` + +But how to remove it?",2012/06/01,"['https://serverfault.com/questions/394610', 'https://serverfault.com', 'https://serverfault.com/users/50774/']","**Which locales are installed on my machine?** + +You can check which locales are generated and configured on your system using the locale command: + +* **`locale`** ... list the current locale configuration +* **`locale -a`** ... lists all all locales that were generated on your system +* **`locale -a -v`** ... list all locales and show useful additional information (such as +directory names that contain the locale information data files) + +The last command from above makes you see that all generated locales are located in **`/usr/lib/locale/`**, and you may remove any of them if unneeded. Each pack of locale information is a directory containing text files and other directories. + +- + +**Supported locales** + +All locales that you want your system to support are listed in the text files in **`/var/lib/locales/supported.d/`**. These files have two columns, language tag and character map. + +I want my system to know US-English only, so I have only one file there, called **`en`**, which contains just a single line: + +``` +en_US UTF-8 + +``` + +- + +**Error messages** + +If error messages are displayed when issuing the locale command, e.g. + +``` +locale: Cannot set LC_ALL to default locale: No such file or directory + +``` + +make sure the file **`/etc/default/locale`** exists and has proper content, such as: + +``` +LANG=""en_US"" +LANGUAGE=""en_US:en"" + +``` + +- + +**Get rid of unneeded locale data - Step by step** + +Now we know all the necessary details to get started with cleaning up our system's locale information: + +1. Edit the locale file(s) in **`/var/lib/locales/supported.d/`**, and remove all unneeded locales (one locale per line) +2. Create and edit **`/etc/default/locale`** (see above for an example) +3. Delete all generated locale data: **`rm -rfv /usr/lib/locale/*`** +4. Re-generate new locales: **`locale-gen`** + +That's all! Reboot your machine to make your changes take effect. Then run one or more of the locale command examples from above to ensure yourself that the result is as expected. + +- + +**Reference:** + +","I am unsure why the most Distributions and Users are unaware from [localepurge](https://manpages.ubuntu.com/manpages/kinetic/en/man8/localepurge.8.html) + +For Debian based Systems, should it be available by + +```bash +apt-get install localepurge + +``` + +From the Manpage: + +> +> localepurge is a small script to recover disk space wasted for unneeded locale files and localized man pages. It will be automagically invoked by dpkg upon completion of any apt installation run. +> +> +> + +> +> You have to define the locale diretory names you want to keep from +> removal after each apt installation run in the /etc/locale.nopurge configuration file. Unless localepurge has been adequately configured, the system's localization files won't be touched at all. +> +> +> + +> +> The contents of following directories will be affected from removals: +> +> +> + +``` + - /usr/share/doc/kde/HTML + - /usr/share/gnome/help + - /usr/share/locale + - /usr/share/man + - /usr/share/omf + - /usr/share/tcltk + - /usr/share/cups/{templates,locale,doc-root} + - /usr/share/calendar + - /usr/share/aptitude + - /usr/share/help//HELP_CONTENT(files&dirs) + - /usr/share/vim/vim*/lang + +``` + +> +> The localization files you actually need and which you want to be preserved on your system can be easily configured by running the following command: +> +> +> + +``` +dpkg-reconfigure localepurge + +``` + +Conclusion: +This Script will take care of any unwanted locales at the moment and in the future." +394610,"I accidentally add a locale, e.g. sudo locale-gen zh\_TW + +e.g. locale -a + +``` +zh_TW + +``` + +But how to remove it?",2012/06/01,"['https://serverfault.com/questions/394610', 'https://serverfault.com', 'https://serverfault.com/users/50774/']","**Note:** Some of the commands below require root privileges, consider the use of `sudo`. + +### Basic info + +According to [`man locale-gen`](http://manpages.ubuntu.com/manpages/jammy/man8/locale-gen.8.html), locales are set in several files. + +> +> `/etc/locale.gen` +> +> +> The main configuration file, which has a simple format: every line that is not empty and does not begin with a # is treated as a locale definition that is to be built. +> +> +> `/var/lib/locales/supported.d/` +> +> +> A directory containing locale.gen snippets provided by language-pack packages. Do not edit these manually, they will be overwritten on package upgrades. +> +> +> + +Locales are compiled (generated) into a single file. + +> +> `/usr/lib/locale/locale-archive` +> +> +> Usual default locale archive location. +> +> +> + +Comprehensive details on locales at the [Arch Wiki](https://wiki.archlinux.org/index.php/locale). + +### Checking locales and the locale + +To list available (known) locales, run any of the following commands (with minor output differences). + +```bash +locale -a +localectl list-locales + +``` + +To check the (already) generated locales, run the following command. + +```bash +localedef --list-archive + +``` + +To check the currently used locale, run any of the following commands (with minor output differences). + +```bash +locale +localectl + +``` + +### Setting and generating (new) locales + +Locales are typically set by uncommenting lines in `/etc/locale.gen`, after which running `locale-gen` is required. + +```bash +nano /etc/locale.gen # uncomment desired lines (locales) +locale-gen + +``` + +This will compile (generate) locales into `/usr/lib/locale/locale-archive` for each uncommented line in `/etc/locale.gen` and under `/var/lib/locales/supported.d/`, whether they were previously compiled or not. + +Alternatively, the command + +```bash +locale-gen + +``` + +will uncomment the corresponding line in `locale-gen` while generating the desired locale and only this one. + +Note: The implementation of `locale-gen` is distro dependent. For instance, the command above is valid in Ubuntu/Debian but not in ArchLinux. + +### Removing locales + +When issuing `locale-gen`, the compiled archive is erased and all locales in `/etc/locale.gen` and under `/usr/lib/locale/locale-archive` are regenerated anew. The command `locale-gen --purge ` doesn't do what the modifier suggests but the opposite: It removes all compiled locales except those indicated. To make sure only specific locales are generated when `locale-gen` is issued or and update is performed both `/etc/locale.gen` and `/usr/lib/locale/locale-archive` must be considered. + +To remove locales in `/etc/locale.gen`, simply comment the desired lines and regenerate the locales using `locale-gen`. + +To remove locales under `/var/lib/locales/supported.d/` is trickier. Since any file `/var/lib/locales/supported.d/` depends on the package `language-pack--base`, any change on the former will be restored when the latter is updated. To solve this, simply hold the packages that update files under `/var/lib/locales/supported.d/`. The command that achieves this in Ubuntu/Debian is the following. + +```bash +apt-mark language-pack--base + +``` + +To update a held package, you must [unmark](https://manpages.ubuntu.com/manpages/jammy/man8/apt-mark.8.html) it or simply [`--ignore-hold`](https://manpages.ubuntu.com/manpages/jammy/man8/apt-get.8.html). + +**Workaround.** A more intrusive but general solution that prevents changes under `/var/lib/locales/supported.d/` is to set files in it with the [""immutable (i)"" attribute](http://manpages.ubuntu.com/manpages/jammy/man1/chattr.1.html). So instead of removing files, empty them. For instance: + +```bash +cd /var/lib/locales/supported.d/ +rm && touch # has been emptied +lsattr # regular attributes +chattr +i # adding (+) immutable +lsattr # checking attributes + +``` + +### Setting the locale + +Setting and generating locales does not set the system locale. Any of the following commands achieves this. + +```bash +echo LANG= | sudo tee /etc/locale.conf # reboot (might be ignored in Ubuntu) +localectl set-locale LANG= + +```","I am unsure why the most Distributions and Users are unaware from [localepurge](https://manpages.ubuntu.com/manpages/kinetic/en/man8/localepurge.8.html) + +For Debian based Systems, should it be available by + +```bash +apt-get install localepurge + +``` + +From the Manpage: + +> +> localepurge is a small script to recover disk space wasted for unneeded locale files and localized man pages. It will be automagically invoked by dpkg upon completion of any apt installation run. +> +> +> + +> +> You have to define the locale diretory names you want to keep from +> removal after each apt installation run in the /etc/locale.nopurge configuration file. Unless localepurge has been adequately configured, the system's localization files won't be touched at all. +> +> +> + +> +> The contents of following directories will be affected from removals: +> +> +> + +``` + - /usr/share/doc/kde/HTML + - /usr/share/gnome/help + - /usr/share/locale + - /usr/share/man + - /usr/share/omf + - /usr/share/tcltk + - /usr/share/cups/{templates,locale,doc-root} + - /usr/share/calendar + - /usr/share/aptitude + - /usr/share/help//HELP_CONTENT(files&dirs) + - /usr/share/vim/vim*/lang + +``` + +> +> The localization files you actually need and which you want to be preserved on your system can be easily configured by running the following command: +> +> +> + +``` +dpkg-reconfigure localepurge + +``` + +Conclusion: +This Script will take care of any unwanted locales at the moment and in the future." +70755860,"I have done until now to create a button and inside a tag button I have created another div with class background to give same property for animation effects when click on button. +But I am not sure if in this way is regular syntax for HTML to put another div into tag button in my case? +I AM SHARING MY CODE: + +```css + button { + height: 73px; + min-width: 198px; + border-radius: 5px; + background-color: $gold; + border-color: $gold; + position: relative; + overflow: hidden; + display: inline-block; + font-size: 1.313rem; + color: black; + z-index: 2; + line-height: 30.24px; + font-weight: bold; + text-transform: uppercase; + } + + .background { + width: 0; + height: 0; + position: absolute; + top: 50%; + left: 50%; + transform: translate(-50%, -50%); + background-image: linear-gradient(#000000, #000000); + transition: .5s; + z-index: -1; + border-radius: 50%; + } + + button:hover { + color: $gold; + } + + button:hover .background { + width: 500%; + height: 500%; + } +``` + +```html + +``` + +But when I Click on button we want background color display as circle and not as eclipse in the center on button. Exactly by the Figma[enter link description here](https://www.figma.com/proto/kwnH9NnM6eZO9eGAjEpEaG/Passport-Site-(Copy)?node-id=10%3A185&scaling=min-zoom&page-id=0%3A1&starting-point-node-id=10%3A185) + +or code pene: [enter link description here](https://codepen.io/liamj/pen/vvdRdR)",2022/01/18,"['https://Stackoverflow.com/questions/70755860', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/15796964/']","The issue in your approach is that you are setting the background `width` and `height` to 1:1 proportions. This would make circle for a square button. For you to create circle you need to make it proportional to the width and height of your button. For example: + +```css +button { + height: 73px; + min-width: 198px; + border-radius: 5px; + background-color: $gold; + border-color: $gold; + position: relative; + overflow: hidden; + display: inline-block; + font-size: 1.313rem; + color: black; + z-index: 2; + line-height: 30.24px; + font-weight: bold; + text-transform: uppercase; + } + + .background { + width: 0; + height: 0; + position: absolute; + top: 50%; + left: 50%; + transform: translate(-50%, -50%); + background-image: linear-gradient(#000000, #000000); + transition: .5s; + z-index: -1; + border-radius: 50%; + } + + button:hover { + color: $gold; + } + + button:hover .background { + width: 150%; + height: 406%; + } + +``` + +```html + +``` + +To get the proportional width you can use in your case (198/73)\*height. So if you choose for your height to be 130% you should have width of 353%. The higher % the faster your animation will be, so keep that in mind.","``` +button:hover .background { + width: 120%; + height: 300%; +} + +```" +33325137,"**Problem** + +I would like to use the [MailGun](https://documentation.mailgun.com/quickstart-sending.html#how-to-start-sending-email) service to send emails from a pure Swift app. + +**Research So Far** + +As I understand it, [there are two methods to send an email](https://documentation.mailgun.com/quickstart-sending.html#send-via-smtp) via MailGun. One is to email MailGun with the emails, and MailGun will redirect it (See *Send via SMTP*). That will, as I understand it, not work, as iOS cannot programatically automatically send mail, and must use [methods that require user intervention](http://www.ioscreator.com/tutorials/send-email-tutorial-ios8-swift). As such, I should use the API directly. As I understand it, I need to open a URL to do this, and so I should use some form of `NSURLSession`, as per [this SO answer](https://stackoverflow.com/questions/24016142/how-to-make-an-http-request-in-swift) + +**Code** + +MailGun provides documentation for Python, which is as follows: + +``` +def send_simple_message(): +return requests.post( + ""https://api.mailgun.net/v3/sandbox(Personal info).mailgun.org/messages"", + auth=(""api"", ""key-(Personal info)""), + data={""from"": ""Excited User <(Personal info)>"", + ""to"": [""bar@example.com"", ""(Personal info)""], + ""subject"": ""Hello"", + ""text"": ""Testing some Mailgun awesomness!""}) + +``` + +with (Personal info) being substituted for keys/information/emails. + +**Question** + +How do I do that in Swift? + +Thanks!",2015/10/25,"['https://Stackoverflow.com/questions/33325137', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3892545/']","In python, the `auth` is being passed in the header. + +You have to do a http post request, passing both the header and the body. + +This is a working code: + +``` +func test() { + let session = NSURLSession.sharedSession() + let request = NSMutableURLRequest(URL: NSURL(string: ""https://api.mailgun.net/v3/sandbox(Personal info).mailgun.org/messages"")!) + request.HTTPMethod = ""POST"" + let data = ""from: Excited User <(Personal info)>&to: [bar@example.com,(Personal info)]&subject:Hello&text:Testinggsome Mailgun awesomness!"" + request.HTTPBody = data.dataUsingEncoding(NSASCIIStringEncoding) + request.setValue(""key-(Personal info)"", forHTTPHeaderField: ""api"") + let task = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in + + if let error = error { + print(error) + } + if let response = response { + print(""url = \(response.URL!)"") + print(""response = \(response)"") + let httpResponse = response as! NSHTTPURLResponse + print(""response code = \(httpResponse.statusCode)"") + } + + }) + task.resume() + } + +```","[`requests.post`](http://docs.python-requests.org/en/latest/user/quickstart/#more-complicated-post-requests) sends an HTTP POST request, encoding key/value pairs as `application/x-www-form-urlencoded`. You need to do the same. + +* convert the set of key-value pairs into `application/x-www-form-urlencoded` as per [How to escape the HTTP params in Swift](https://stackoverflow.com/questions/27148100/how-to-escape-the-http-params-in-swift) +* compose the request using the resulting string for data & send it as per [iOS : http Post using swift](https://stackoverflow.com/questions/30596114/ios-http-post-using-swift)" +33325137,"**Problem** + +I would like to use the [MailGun](https://documentation.mailgun.com/quickstart-sending.html#how-to-start-sending-email) service to send emails from a pure Swift app. + +**Research So Far** + +As I understand it, [there are two methods to send an email](https://documentation.mailgun.com/quickstart-sending.html#send-via-smtp) via MailGun. One is to email MailGun with the emails, and MailGun will redirect it (See *Send via SMTP*). That will, as I understand it, not work, as iOS cannot programatically automatically send mail, and must use [methods that require user intervention](http://www.ioscreator.com/tutorials/send-email-tutorial-ios8-swift). As such, I should use the API directly. As I understand it, I need to open a URL to do this, and so I should use some form of `NSURLSession`, as per [this SO answer](https://stackoverflow.com/questions/24016142/how-to-make-an-http-request-in-swift) + +**Code** + +MailGun provides documentation for Python, which is as follows: + +``` +def send_simple_message(): +return requests.post( + ""https://api.mailgun.net/v3/sandbox(Personal info).mailgun.org/messages"", + auth=(""api"", ""key-(Personal info)""), + data={""from"": ""Excited User <(Personal info)>"", + ""to"": [""bar@example.com"", ""(Personal info)""], + ""subject"": ""Hello"", + ""text"": ""Testing some Mailgun awesomness!""}) + +``` + +with (Personal info) being substituted for keys/information/emails. + +**Question** + +How do I do that in Swift? + +Thanks!",2015/10/25,"['https://Stackoverflow.com/questions/33325137', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3892545/']","people are getting 400 or 401 errors because none of the other answers construct the url correctly. here is some code that works in swift 5 and iOS15: + +``` +func sendEmail() { + // variablize our https path with API key, recipient and message text + let mailgunAPIPath = ""https://api:YOUR_API_KEY@api.mailgun.net/v3/YOUR_DOMAIN/messages?"" + let emailRecipient = ""RECIPIENT@EMAIL.COM"" + let emailMessage = ""Testing%20email%20sender%20variables"" + // Create a session and fill it with our request + let session = URLSession.shared + let request = NSMutableURLRequest(url: NSURL(string: mailgunAPIPath + ""from=USER@YOUR_DOMAIN&to=\(emailRecipient)&subject=A%20New%20Test%21&text=\(emailMessage)"")! as URL) + + // POST and report back with any errors and response codes + request.httpMethod = ""POST"" + let task = session.dataTask(with: request as URLRequest, completionHandler: {(data, response, error) in + if let error = error { + print(error) + } + + if let response = response { + print(""url = \(response.url!)"") + print(""response = \(response)"") + let httpResponse = response as! HTTPURLResponse + print(""response code = \(httpResponse.statusCode)"") + } + }) + task.resume() +} + +```","[`requests.post`](http://docs.python-requests.org/en/latest/user/quickstart/#more-complicated-post-requests) sends an HTTP POST request, encoding key/value pairs as `application/x-www-form-urlencoded`. You need to do the same. + +* convert the set of key-value pairs into `application/x-www-form-urlencoded` as per [How to escape the HTTP params in Swift](https://stackoverflow.com/questions/27148100/how-to-escape-the-http-params-in-swift) +* compose the request using the resulting string for data & send it as per [iOS : http Post using swift](https://stackoverflow.com/questions/30596114/ios-http-post-using-swift)" +33325137,"**Problem** + +I would like to use the [MailGun](https://documentation.mailgun.com/quickstart-sending.html#how-to-start-sending-email) service to send emails from a pure Swift app. + +**Research So Far** + +As I understand it, [there are two methods to send an email](https://documentation.mailgun.com/quickstart-sending.html#send-via-smtp) via MailGun. One is to email MailGun with the emails, and MailGun will redirect it (See *Send via SMTP*). That will, as I understand it, not work, as iOS cannot programatically automatically send mail, and must use [methods that require user intervention](http://www.ioscreator.com/tutorials/send-email-tutorial-ios8-swift). As such, I should use the API directly. As I understand it, I need to open a URL to do this, and so I should use some form of `NSURLSession`, as per [this SO answer](https://stackoverflow.com/questions/24016142/how-to-make-an-http-request-in-swift) + +**Code** + +MailGun provides documentation for Python, which is as follows: + +``` +def send_simple_message(): +return requests.post( + ""https://api.mailgun.net/v3/sandbox(Personal info).mailgun.org/messages"", + auth=(""api"", ""key-(Personal info)""), + data={""from"": ""Excited User <(Personal info)>"", + ""to"": [""bar@example.com"", ""(Personal info)""], + ""subject"": ""Hello"", + ""text"": ""Testing some Mailgun awesomness!""}) + +``` + +with (Personal info) being substituted for keys/information/emails. + +**Question** + +How do I do that in Swift? + +Thanks!",2015/10/25,"['https://Stackoverflow.com/questions/33325137', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3892545/']","In python, the `auth` is being passed in the header. + +You have to do a http post request, passing both the header and the body. + +This is a working code: + +``` +func test() { + let session = NSURLSession.sharedSession() + let request = NSMutableURLRequest(URL: NSURL(string: ""https://api.mailgun.net/v3/sandbox(Personal info).mailgun.org/messages"")!) + request.HTTPMethod = ""POST"" + let data = ""from: Excited User <(Personal info)>&to: [bar@example.com,(Personal info)]&subject:Hello&text:Testinggsome Mailgun awesomness!"" + request.HTTPBody = data.dataUsingEncoding(NSASCIIStringEncoding) + request.setValue(""key-(Personal info)"", forHTTPHeaderField: ""api"") + let task = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in + + if let error = error { + print(error) + } + if let response = response { + print(""url = \(response.URL!)"") + print(""response = \(response)"") + let httpResponse = response as! NSHTTPURLResponse + print(""response code = \(httpResponse.statusCode)"") + } + + }) + task.resume() + } + +```","I spent hours trying to get the selected answer working, but to no avail. + +Although I was finally able to get this working properly with a large HTTP response. I put the full path into Keys.plist so that I can upload my code to github and broke out some of the arguments into variables so I can have them programmatically set later down the road. + +``` +// Email the FBO with desired information +// Parse our Keys.plist so we can use our path +var keys: NSDictionary? + +if let path = NSBundle.mainBundle().pathForResource(""Keys"", ofType: ""plist"") { + keys = NSDictionary(contentsOfFile: path) +} + +if let dict = keys { + // variablize our https path with API key, recipient and message text + let mailgunAPIPath = dict[""mailgunAPIPath""] as? String + let emailRecipient = ""bar@foo.com"" + let emailMessage = ""Testing%20email%20sender%20variables"" + + // Create a session and fill it with our request + let session = NSURLSession.sharedSession() + let request = NSMutableURLRequest(URL: NSURL(string: mailgunAPIPath! + ""from=FBOGo%20Reservation%20%3Cscheduler@.com%3E&to=reservations@.com&to=\(emailRecipient)&subject=A%20New%20Reservation%21&text=\(emailMessage)"")!) + + // POST and report back with any errors and response codes + request.HTTPMethod = ""POST"" + let task = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in + if let error = error { + print(error) + } + + if let response = response { + print(""url = \(response.URL!)"") + print(""response = \(response)"") + let httpResponse = response as! NSHTTPURLResponse + print(""response code = \(httpResponse.statusCode)"") + } + }) + task.resume() +} + +``` + +The Mailgun Path is in Keys.plist as a string called mailgunAPIPath with the value: + +``` +https://API:key-@api.mailgun.net/v3/.com/messages? + +``` + +Hope this offers a solution to anyone else having issues with MailGun and wanting to avoid a 3rd party solution!" +33325137,"**Problem** + +I would like to use the [MailGun](https://documentation.mailgun.com/quickstart-sending.html#how-to-start-sending-email) service to send emails from a pure Swift app. + +**Research So Far** + +As I understand it, [there are two methods to send an email](https://documentation.mailgun.com/quickstart-sending.html#send-via-smtp) via MailGun. One is to email MailGun with the emails, and MailGun will redirect it (See *Send via SMTP*). That will, as I understand it, not work, as iOS cannot programatically automatically send mail, and must use [methods that require user intervention](http://www.ioscreator.com/tutorials/send-email-tutorial-ios8-swift). As such, I should use the API directly. As I understand it, I need to open a URL to do this, and so I should use some form of `NSURLSession`, as per [this SO answer](https://stackoverflow.com/questions/24016142/how-to-make-an-http-request-in-swift) + +**Code** + +MailGun provides documentation for Python, which is as follows: + +``` +def send_simple_message(): +return requests.post( + ""https://api.mailgun.net/v3/sandbox(Personal info).mailgun.org/messages"", + auth=(""api"", ""key-(Personal info)""), + data={""from"": ""Excited User <(Personal info)>"", + ""to"": [""bar@example.com"", ""(Personal info)""], + ""subject"": ""Hello"", + ""text"": ""Testing some Mailgun awesomness!""}) + +``` + +with (Personal info) being substituted for keys/information/emails. + +**Question** + +How do I do that in Swift? + +Thanks!",2015/10/25,"['https://Stackoverflow.com/questions/33325137', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3892545/']","In python, the `auth` is being passed in the header. + +You have to do a http post request, passing both the header and the body. + +This is a working code: + +``` +func test() { + let session = NSURLSession.sharedSession() + let request = NSMutableURLRequest(URL: NSURL(string: ""https://api.mailgun.net/v3/sandbox(Personal info).mailgun.org/messages"")!) + request.HTTPMethod = ""POST"" + let data = ""from: Excited User <(Personal info)>&to: [bar@example.com,(Personal info)]&subject:Hello&text:Testinggsome Mailgun awesomness!"" + request.HTTPBody = data.dataUsingEncoding(NSASCIIStringEncoding) + request.setValue(""key-(Personal info)"", forHTTPHeaderField: ""api"") + let task = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in + + if let error = error { + print(error) + } + if let response = response { + print(""url = \(response.URL!)"") + print(""response = \(response)"") + let httpResponse = response as! NSHTTPURLResponse + print(""response code = \(httpResponse.statusCode)"") + } + + }) + task.resume() + } + +```","Swift 3 answer: + +``` + func test() { + let session = URLSession.shared + var request = URLRequest(url: URL(string: ""https://api.mailgun.net/v3/sandbox(Personal info).mailgun.org/messages"")!) + request.httpMethod = ""POST"" + let data = ""from: Excited User <(Personal info)>&to: [bar@example.com,(Personal info)]&subject:Hello&text:Testinggsome Mailgun awesomness!"" + request.httpBody = data.data(using: .ascii) + request.setValue(""key-(Personal info)"", forHTTPHeaderField: ""api"") + let task = session.dataTask(with: request, completionHandler: {(data, response, error) in + + if let error = error { + print(error) + } + if let response = response { + print(""url = \(response.url!)"") + print(""response = \(response)"") + let httpResponse = response as! HTTPURLResponse + print(""response code = \(httpResponse.statusCode)"") + } + + }) + task.resume() + } + +```" +33325137,"**Problem** + +I would like to use the [MailGun](https://documentation.mailgun.com/quickstart-sending.html#how-to-start-sending-email) service to send emails from a pure Swift app. + +**Research So Far** + +As I understand it, [there are two methods to send an email](https://documentation.mailgun.com/quickstart-sending.html#send-via-smtp) via MailGun. One is to email MailGun with the emails, and MailGun will redirect it (See *Send via SMTP*). That will, as I understand it, not work, as iOS cannot programatically automatically send mail, and must use [methods that require user intervention](http://www.ioscreator.com/tutorials/send-email-tutorial-ios8-swift). As such, I should use the API directly. As I understand it, I need to open a URL to do this, and so I should use some form of `NSURLSession`, as per [this SO answer](https://stackoverflow.com/questions/24016142/how-to-make-an-http-request-in-swift) + +**Code** + +MailGun provides documentation for Python, which is as follows: + +``` +def send_simple_message(): +return requests.post( + ""https://api.mailgun.net/v3/sandbox(Personal info).mailgun.org/messages"", + auth=(""api"", ""key-(Personal info)""), + data={""from"": ""Excited User <(Personal info)>"", + ""to"": [""bar@example.com"", ""(Personal info)""], + ""subject"": ""Hello"", + ""text"": ""Testing some Mailgun awesomness!""}) + +``` + +with (Personal info) being substituted for keys/information/emails. + +**Question** + +How do I do that in Swift? + +Thanks!",2015/10/25,"['https://Stackoverflow.com/questions/33325137', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3892545/']","In python, the `auth` is being passed in the header. + +You have to do a http post request, passing both the header and the body. + +This is a working code: + +``` +func test() { + let session = NSURLSession.sharedSession() + let request = NSMutableURLRequest(URL: NSURL(string: ""https://api.mailgun.net/v3/sandbox(Personal info).mailgun.org/messages"")!) + request.HTTPMethod = ""POST"" + let data = ""from: Excited User <(Personal info)>&to: [bar@example.com,(Personal info)]&subject:Hello&text:Testinggsome Mailgun awesomness!"" + request.HTTPBody = data.dataUsingEncoding(NSASCIIStringEncoding) + request.setValue(""key-(Personal info)"", forHTTPHeaderField: ""api"") + let task = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in + + if let error = error { + print(error) + } + if let response = response { + print(""url = \(response.URL!)"") + print(""response = \(response)"") + let httpResponse = response as! NSHTTPURLResponse + print(""response code = \(httpResponse.statusCode)"") + } + + }) + task.resume() + } + +```","people are getting 400 or 401 errors because none of the other answers construct the url correctly. here is some code that works in swift 5 and iOS15: + +``` +func sendEmail() { + // variablize our https path with API key, recipient and message text + let mailgunAPIPath = ""https://api:YOUR_API_KEY@api.mailgun.net/v3/YOUR_DOMAIN/messages?"" + let emailRecipient = ""RECIPIENT@EMAIL.COM"" + let emailMessage = ""Testing%20email%20sender%20variables"" + // Create a session and fill it with our request + let session = URLSession.shared + let request = NSMutableURLRequest(url: NSURL(string: mailgunAPIPath + ""from=USER@YOUR_DOMAIN&to=\(emailRecipient)&subject=A%20New%20Test%21&text=\(emailMessage)"")! as URL) + + // POST and report back with any errors and response codes + request.httpMethod = ""POST"" + let task = session.dataTask(with: request as URLRequest, completionHandler: {(data, response, error) in + if let error = error { + print(error) + } + + if let response = response { + print(""url = \(response.url!)"") + print(""response = \(response)"") + let httpResponse = response as! HTTPURLResponse + print(""response code = \(httpResponse.statusCode)"") + } + }) + task.resume() +} + +```" +33325137,"**Problem** + +I would like to use the [MailGun](https://documentation.mailgun.com/quickstart-sending.html#how-to-start-sending-email) service to send emails from a pure Swift app. + +**Research So Far** + +As I understand it, [there are two methods to send an email](https://documentation.mailgun.com/quickstart-sending.html#send-via-smtp) via MailGun. One is to email MailGun with the emails, and MailGun will redirect it (See *Send via SMTP*). That will, as I understand it, not work, as iOS cannot programatically automatically send mail, and must use [methods that require user intervention](http://www.ioscreator.com/tutorials/send-email-tutorial-ios8-swift). As such, I should use the API directly. As I understand it, I need to open a URL to do this, and so I should use some form of `NSURLSession`, as per [this SO answer](https://stackoverflow.com/questions/24016142/how-to-make-an-http-request-in-swift) + +**Code** + +MailGun provides documentation for Python, which is as follows: + +``` +def send_simple_message(): +return requests.post( + ""https://api.mailgun.net/v3/sandbox(Personal info).mailgun.org/messages"", + auth=(""api"", ""key-(Personal info)""), + data={""from"": ""Excited User <(Personal info)>"", + ""to"": [""bar@example.com"", ""(Personal info)""], + ""subject"": ""Hello"", + ""text"": ""Testing some Mailgun awesomness!""}) + +``` + +with (Personal info) being substituted for keys/information/emails. + +**Question** + +How do I do that in Swift? + +Thanks!",2015/10/25,"['https://Stackoverflow.com/questions/33325137', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3892545/']","people are getting 400 or 401 errors because none of the other answers construct the url correctly. here is some code that works in swift 5 and iOS15: + +``` +func sendEmail() { + // variablize our https path with API key, recipient and message text + let mailgunAPIPath = ""https://api:YOUR_API_KEY@api.mailgun.net/v3/YOUR_DOMAIN/messages?"" + let emailRecipient = ""RECIPIENT@EMAIL.COM"" + let emailMessage = ""Testing%20email%20sender%20variables"" + // Create a session and fill it with our request + let session = URLSession.shared + let request = NSMutableURLRequest(url: NSURL(string: mailgunAPIPath + ""from=USER@YOUR_DOMAIN&to=\(emailRecipient)&subject=A%20New%20Test%21&text=\(emailMessage)"")! as URL) + + // POST and report back with any errors and response codes + request.httpMethod = ""POST"" + let task = session.dataTask(with: request as URLRequest, completionHandler: {(data, response, error) in + if let error = error { + print(error) + } + + if let response = response { + print(""url = \(response.url!)"") + print(""response = \(response)"") + let httpResponse = response as! HTTPURLResponse + print(""response code = \(httpResponse.statusCode)"") + } + }) + task.resume() +} + +```","I spent hours trying to get the selected answer working, but to no avail. + +Although I was finally able to get this working properly with a large HTTP response. I put the full path into Keys.plist so that I can upload my code to github and broke out some of the arguments into variables so I can have them programmatically set later down the road. + +``` +// Email the FBO with desired information +// Parse our Keys.plist so we can use our path +var keys: NSDictionary? + +if let path = NSBundle.mainBundle().pathForResource(""Keys"", ofType: ""plist"") { + keys = NSDictionary(contentsOfFile: path) +} + +if let dict = keys { + // variablize our https path with API key, recipient and message text + let mailgunAPIPath = dict[""mailgunAPIPath""] as? String + let emailRecipient = ""bar@foo.com"" + let emailMessage = ""Testing%20email%20sender%20variables"" + + // Create a session and fill it with our request + let session = NSURLSession.sharedSession() + let request = NSMutableURLRequest(URL: NSURL(string: mailgunAPIPath! + ""from=FBOGo%20Reservation%20%3Cscheduler@.com%3E&to=reservations@.com&to=\(emailRecipient)&subject=A%20New%20Reservation%21&text=\(emailMessage)"")!) + + // POST and report back with any errors and response codes + request.HTTPMethod = ""POST"" + let task = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in + if let error = error { + print(error) + } + + if let response = response { + print(""url = \(response.URL!)"") + print(""response = \(response)"") + let httpResponse = response as! NSHTTPURLResponse + print(""response code = \(httpResponse.statusCode)"") + } + }) + task.resume() +} + +``` + +The Mailgun Path is in Keys.plist as a string called mailgunAPIPath with the value: + +``` +https://API:key-@api.mailgun.net/v3/.com/messages? + +``` + +Hope this offers a solution to anyone else having issues with MailGun and wanting to avoid a 3rd party solution!" +33325137,"**Problem** + +I would like to use the [MailGun](https://documentation.mailgun.com/quickstart-sending.html#how-to-start-sending-email) service to send emails from a pure Swift app. + +**Research So Far** + +As I understand it, [there are two methods to send an email](https://documentation.mailgun.com/quickstart-sending.html#send-via-smtp) via MailGun. One is to email MailGun with the emails, and MailGun will redirect it (See *Send via SMTP*). That will, as I understand it, not work, as iOS cannot programatically automatically send mail, and must use [methods that require user intervention](http://www.ioscreator.com/tutorials/send-email-tutorial-ios8-swift). As such, I should use the API directly. As I understand it, I need to open a URL to do this, and so I should use some form of `NSURLSession`, as per [this SO answer](https://stackoverflow.com/questions/24016142/how-to-make-an-http-request-in-swift) + +**Code** + +MailGun provides documentation for Python, which is as follows: + +``` +def send_simple_message(): +return requests.post( + ""https://api.mailgun.net/v3/sandbox(Personal info).mailgun.org/messages"", + auth=(""api"", ""key-(Personal info)""), + data={""from"": ""Excited User <(Personal info)>"", + ""to"": [""bar@example.com"", ""(Personal info)""], + ""subject"": ""Hello"", + ""text"": ""Testing some Mailgun awesomness!""}) + +``` + +with (Personal info) being substituted for keys/information/emails. + +**Question** + +How do I do that in Swift? + +Thanks!",2015/10/25,"['https://Stackoverflow.com/questions/33325137', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3892545/']","people are getting 400 or 401 errors because none of the other answers construct the url correctly. here is some code that works in swift 5 and iOS15: + +``` +func sendEmail() { + // variablize our https path with API key, recipient and message text + let mailgunAPIPath = ""https://api:YOUR_API_KEY@api.mailgun.net/v3/YOUR_DOMAIN/messages?"" + let emailRecipient = ""RECIPIENT@EMAIL.COM"" + let emailMessage = ""Testing%20email%20sender%20variables"" + // Create a session and fill it with our request + let session = URLSession.shared + let request = NSMutableURLRequest(url: NSURL(string: mailgunAPIPath + ""from=USER@YOUR_DOMAIN&to=\(emailRecipient)&subject=A%20New%20Test%21&text=\(emailMessage)"")! as URL) + + // POST and report back with any errors and response codes + request.httpMethod = ""POST"" + let task = session.dataTask(with: request as URLRequest, completionHandler: {(data, response, error) in + if let error = error { + print(error) + } + + if let response = response { + print(""url = \(response.url!)"") + print(""response = \(response)"") + let httpResponse = response as! HTTPURLResponse + print(""response code = \(httpResponse.statusCode)"") + } + }) + task.resume() +} + +```","Swift 3 answer: + +``` + func test() { + let session = URLSession.shared + var request = URLRequest(url: URL(string: ""https://api.mailgun.net/v3/sandbox(Personal info).mailgun.org/messages"")!) + request.httpMethod = ""POST"" + let data = ""from: Excited User <(Personal info)>&to: [bar@example.com,(Personal info)]&subject:Hello&text:Testinggsome Mailgun awesomness!"" + request.httpBody = data.data(using: .ascii) + request.setValue(""key-(Personal info)"", forHTTPHeaderField: ""api"") + let task = session.dataTask(with: request, completionHandler: {(data, response, error) in + + if let error = error { + print(error) + } + if let response = response { + print(""url = \(response.url!)"") + print(""response = \(response)"") + let httpResponse = response as! HTTPURLResponse + print(""response code = \(httpResponse.statusCode)"") + } + + }) + task.resume() + } + +```" +2428907,"$$\lim\_{x\to0}\frac{\sin^2(3x)}{x^2\cos x}=\lim\_{u\to0}\frac{\sin^2(u)}{\left(\dfrac u3\right)^2}=9\left(\lim\_{u\to0}\frac{\sin u}u\right)^2.$$ + +> +> A bit of confusion on the little steps that are missing. 1. Why does $\sin(x)$ go away. It is because $\cos(0)=1$? 2. How does the change of variable work, completely lost? +> +> +>",2017/09/14,"['https://math.stackexchange.com/questions/2428907', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/418493/']","Hint:$$\quad{\lim\_{x\to0}\frac{\sin^2(3x)}{x^2\cos x}=\\\lim\_{x\to0}\frac{\sin(3x)}{x}.\lim\_{x\to0}\frac{\sin(3x)}{x}.\lim\_{x\to0}\frac{1}{\cos x}=\\ +\lim\_{x\to0}\color{red} {3}\frac{\sin(3x)}{\color{red} {3}x}.\lim\_{x\to0}\color{red} {3}\frac{\sin(3x)}{\color{red} {3}x}.\lim\_{x\to0}\frac{1}{\cos x}=\\ +\color{red} {9}\underbrace{\lim\_{x\to0}\frac{\sin(3x)}{\color{red} {3}x}}\_{1}.\underbrace{\lim\_{x\to0}\frac{\sin(3x)}{\color{red} {3}x}}\_{1}.\lim\_{x\to0}\frac{1}{\cos x}=\\9.1.1.\lim\_{x\to0}\frac{1}{\cos x}=9.1.1.1}$$",$$\lim\_{x\to0}\frac{\sin^2(3x)}{x^2\cos x}=3^2\left(\lim\_{x\to0}\dfrac{\sin3x}{3x}\right)^2\cdot\dfrac1{\lim\_{x\to0}\cos x}=?$$ +846695,"Is $\delta \_{mn}=1$ when $m\neq n$, and $\delta \_{mm}=0$? + +I am not very good at Math. So would you give me the answer and explanation please?",2014/06/25,"['https://math.stackexchange.com/questions/846695', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/135962/']","You got it. [For example, this.](http://www.wolframalpha.com/input/?i=sin%20300) What is your worry?","$$\cos^2\theta + \sin^2\theta = 1^2$$ +$$r^2(\cos^2\theta + \sin^2\theta) = r^2(1^2)$$ +$$(r\cos\theta)^2 + (r\sin\theta)^2 = r^2$$ + +$$x^2+y^2 = r^2$$ + +Draw a circle of radius 2. For what values of $\theta$ would the y-coordinate of the circle $x^2+y^2=2^2$ intersect the line $y = -\sqrt{3}$? + +![enter image description here](https://i.stack.imgur.com/j0ivq.png) + +Hint #2 + +What does $x$ equal? What is the distance between $(-x, -\sqrt{3})$ and $(x,-\sqrt{3})$?" +26900359,"Currently i am designing WPF application using MahApps.Metro style UI. +Tile control which provided by MahApps can not showing icon in center of tile + +I saw example in MahApps website where it could show image as tile background, but I couldn't figure out how to show icon instead of image (icon such as IE logo, people logo, maps logo, etc) + +I appreciated if someone can show me how to do this + +Thank you",2014/11/13,"['https://Stackoverflow.com/questions/26900359', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3540114/']","i figure it out + +use icons.xaml as resource, and add rectangle control inside tile, here is the example on how to show character inside tile control + +``` + + + + + + + + +``` + +thank you if anyone notice about this, hope can help to contribute","You can use [FontAwesome.Wpf](https://github.com/charri/Font-Awesome-WPF/blob/master/README-WPF.md) which has more icons and requires less code. + +``` + + + + + + +``` + +Don't forget to call the namespace + +``` +xmlns:fa=""http://schemas.fontawesome.io/icons/"" + +```" +95202,"I have a Gateway laptop that originally came with Vista, and I upgraded to Vista Ultimate. I have always been able to change the brightness settings by using Func+Up or Func+Down but a few days ago it stopped working and is always at MAX bright! + +Anybody knows why is that happening and how to fix it? It is very annoying not being able to dim the screen when in battery mode, since it can make quite a difference in battery life. + +Thanks!",2010/01/13,"['https://superuser.com/questions/95202', 'https://superuser.com', 'https://superuser.com/users/15180/']","The screen brightness can be changed in the power options section of Control Panel (or by clicking the little battery icon in the system tray, though i'm unsure if that's new to Win 7 or works in vista). + +As for the Fn keys stopping working, it's likely that there will be an app you can install from the Gateway website for your machine that will re-enable them. I've had this issue before too (though not on a Gateway), and had to reinstall the program from my manufacturers website to get proper Fn key functionality back.","Ensure you have the latest video driver, downloaded from the website of the card's manufacturer. + +If you have installed ""Dox Optimised Forceware"", then uninstall it first." +20402662,"Can anyone explain to me why I can write 'ECHO Y|' in the Powershell command line but not if I implement it in a script? + +These variables are taken from a .csv file. When I used the command line I did not use the variables. + +``` +ECHO Y|cacls $_.""Serverdisc"" /G ADMINISTRATORS:F + cacls $_.""Serverdisc"" /G $_.""Username"":C /T /E + cacls $_.""Serverdisc"" /G SYSTEM:F /T /E + +```",2013/12/05,"['https://Stackoverflow.com/questions/20402662', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2564636/']","I am guessing you are trying to pass ""Y(es)"" to any possible prompts? +CMD shell and PowerShell are two different shells. What you are trying to do is use the CMD shell syntax for Powershell and therefore running into trouble + +$\_ is used when you are iterating through an array coming from pipeline, so there must be something other than what you have shared here. I will give you an example. + +Assume I have 2 files in c:\temp\: + +``` +c:\temp\a.txt +c:\temp\b.txt + +``` + +and I want to grant them permissions and not to be prompted. + +``` +""c:\temp\a.txt"",""c:\temp\b.txt"" | foreach-object { +ECHO Y|cacls $_ /G ADMINISTRATORS:F +echo Y|cacls $_ /G SYSTEM:F /T /E +} + +``` + +This is equivalent to the following + +``` +ECHO Y|cacls c:\temp\a.txt /G ADMINISTRATORS:F +echo Y|cacls c:\temp\a.txt /G SYSTEM:F /T /E +ECHO Y|cacls c:\temp\b.txt /G ADMINISTRATORS:F +echo Y|cacls c:\temp\b.txt /G SYSTEM:F /T /E + +``` + +$\_ is being replaced withing foreach-object by what is coming down from pipeline, which is pretty much imitating CMD shell command that would work.","It's probably because the pipeline function of powershell is different from the cmd prompt + +If you use `cmd /c echo Y| cacls ....` +it will work." +20402662,"Can anyone explain to me why I can write 'ECHO Y|' in the Powershell command line but not if I implement it in a script? + +These variables are taken from a .csv file. When I used the command line I did not use the variables. + +``` +ECHO Y|cacls $_.""Serverdisc"" /G ADMINISTRATORS:F + cacls $_.""Serverdisc"" /G $_.""Username"":C /T /E + cacls $_.""Serverdisc"" /G SYSTEM:F /T /E + +```",2013/12/05,"['https://Stackoverflow.com/questions/20402662', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2564636/']","I will add to Adil H.'s comments and say that using cacls is depreciated. You should instead be using **icacls**. icacls has a parameter /Q (Quiet) which will suppress all the confirmation messages for you, and you will not have to use `ECHO Y|` in your code. + +(assuming you have the rest of your script in order(see Adil H.'s post)) Your script block would change to this: + +``` +icacls $_.""Serverdisc"" /Q /Grant ADMINISTRATORS:F +icacls $_.""Serverdisc"" /Q /Grant $_.""Username"":C /T +icacls $_.""Serverdisc"" /Q /Grant SYSTEM:F /T + +```","It's probably because the pipeline function of powershell is different from the cmd prompt + +If you use `cmd /c echo Y| cacls ....` +it will work." +50815061,"I am building REST API which stores name, salary and expenses of people. How can I POST data of multiple people at the same time, like an array? + +This is my serializers.py file + +``` +from rest_framework import serializers +from .models import Bucketlist + +class BucketlistSerializer(serializers.ModelSerializer): + class Meta: + model = Bucketlist + fields = ('id','name', 'date_created', 'salary','Expenditure') + read_only_fields = ('date_created',) + +``` + +This is my views.py file + +![screenshot of views.py](https://i.stack.imgur.com/T4yAw.png)",2018/06/12,"['https://Stackoverflow.com/questions/50815061', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9929677/']","As you are on your tabbed page already you can literally just do the following + +``` +public partial class MyTabbedPage : TabbedPage +{ + public MyTabbedPage() + { + InitializeComponent(); + CurrentPageChanged += CurrentPageHasChanged; + } + + private void CurrentPageHasChanged(object sender, EventArgs e) => Title = CurrentPage.Title; +} + +``` + +if you want to use the sender you can do the following + +``` +public partial class MyTabbedPage : TabbedPage +{ + public MyTabbedPage() + { + InitializeComponent(); + CurrentPageChanged += CurrentPageHasChanged; + } + + private void CurrentPageHasChanged(object sender, EventArgs e) + { + var tabbedPage = (TabbedPage) sender; + Title = tabbedPage.CurrentPage.Title; + } +} + +``` + +Or if you can elaborate on what you are trying to do exactly I can give a better answer as I do not know what it is that you are trying to do exactly","I don't think you can achieve what you want to do, at least not like this. The event behaves the way it does and as described: it is fired whenever the current page changes, also for children. + +That being said, I think you should focus on implementing the functionality you want with the tools we have. I can't really deduce from your code what you are trying to do, but it looks like you want to change the title? When a tab is changed? Why not just make some kind of condition to only do it for certain pages? For example when the page is contained in the `Children` collection?" +23284601,"I have an input form- + +``` +"" /> + +``` + +The variable `$email` is a decrypted one, & it holds the value `psb@***.com` (when echoed in the same page). + +I'm retrieving the value in my action page like- `$_POST['unsubscribe_email']`. + +Instead of getting `***@***.com`, the variable is getting appended. + +This is what I get + +`psb@***.com�����������������` + +I'm clueless as to why this is happening. + +Here's the actual code- +HTML- + +``` +
+"" /> + +
+ +``` + +PHP- + +``` +$email = $_POST['unsubscribe_email']; +echo $email; //gives me this- psb@*.com����������������� + +``` + +EDIT: The decrypt method that I'm using is appending ""\u000"" to the original string. + +Any leads on how to deal with ""\u000""? + +Thanks in advance, folks!",2014/04/25,"['https://Stackoverflow.com/questions/23284601', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3523750/']","Assign your context variable before using, like this + +``` +context = getApplicationContext(); + +```","Its because your context is null. Instead of context, you could use your activity like `NextActivity.this`" +39618765,"I need to write a test `PartitionMapperTest` for my Java class `PartitionMapper`. This class has private fields with `@Inject` annotations but it has only a no-param constructor. + +For the test, I want to create a `partitionMapper` before any test and inject values into its private fields. Then, tester tests the mapper's method `mapPartitions` and assert values. However, I don't know how to inject these values into `partitionMapper`. + +PartitionMapper.java + +``` +@Named +public class PartitionMapper implements javax.batch.api.partition.PartitionMapper { + + @Inject + private JobContext jobContext; + + @Inject + @BatchProperty + private String fetchSize; + + @Inject + @BatchProperty + private String rowsPerPartition; + + // other batch properties ... + + @PersistenceUnit(unitName = ""h2"") + private EntityManagerFactory emf; + + @Override + public PartitionPlan mapPartitions() throws Exception { + // ... + } +} + +``` + +PartitionMapperTest.java + +``` +public class PartitionMapperTest { + + private PartitionMapper partitionMapper; + + @Before + public void setUp() { + // Prepare JobContext, batch properties to inject ... + + // Instantiation + partitionMapper = new PartitionMapper(); + + // TODO How to inject these objects into partitionMapper? + } + + @Test + public void testMapPartitions() throws Exception { + PartitionPlan partitionPlan = partitionMapper.mapPartitions(); + for (Properties p : partitionPlan.getPartitionProperties()) { + // Assertions here ... + } + } + + // ... +} + +``` + +I actually did implement a real `PartitionMapperTest` based on Mockito and PowerMock, which can be seen on my [GitHub](https://github.com/mincong-h/gsoc-hsearch/blob/217d560424171e83864dfe55f6d08d955baeb763/core/src/test/java/org/hibernate/search/jsr352/PartitionMapperTest.java). The problem is there're so many assumptions that it leads to very poor code for user-understanding. I'm looking for another solution for refactoring it.",2016/09/21,"['https://Stackoverflow.com/questions/39618765', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4381330/']","Is there any reason to only have a no args constructor? + +I would recommand you to use constructor injection instead of field injection. That would solve you problem. + +For example instead of: + +``` +public class Foo { + @Inject + private Bar bar; +} + +``` + +do this: + +``` +public class Foo { + private Bar bar; + + public Foo(@Inject Bar bar) { + this.bar = bar; + } +} + +``` + +If you define your injection points this way you have a clean API and your class can be used in non-cdi environments (like unit-tests). + +There are many resources about ""constructor injection VS field injection""... Also on stackoverflow, e.g. .","Use protected fields instead of private to be able to mock fields in unit test: + +``` +@Named +public class PartitionMapper implements javax.batch.api.partition.PartitionMapper { + + @Inject + JobContext jobContext; + + @Inject + @BatchProperty + String fetchSize; + + @Inject + @BatchProperty + String rowsPerPartition; + + // other batch properties ... + + @PersistenceUnit(unitName = ""h2"") + EntityManagerFactory emf; + + @Override + public PartitionPlan mapPartitions() throws Exception { + // ... + } +} + +```" +73225372,"What's the logic behind `if n < i*i: return True`? + +``` +def isPrime(n, i = 2): + + # Base cases + if (n <= 2): + return True if(n == 2) else False + if (n % i == 0): + return False + if (n < i*i): + return True + + # Check for the next divisor + return isPrime(n, i + 1) + +```",2022/08/03,"['https://Stackoverflow.com/questions/73225372', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/19583160/']","For each factor `f`, there is a complement `n/f`. If the factor is less than `sqrt(n)`, the complement is bigger, and vice versa. So, if we checked all factors up to and including `sqrt(n)`, and found none, it is sufficient to say that there are no other factors.","At each iteration, we establish that `n` is not divisible by an integer less than or equal to `i`. If `n` were not a prime, then by definition `n = x * y` where `x` and `y` are positive integers. Both `x` and `y` must be greater than `i` as mentioned earlier. It follows that `n = x * y` must be greater than `i * i` for it to possibly be a prime." +32922,"I've noticed on my team the developers are very busy toward the beginning of the sprint with the QA people having little to do, while the opposite is true toward the end of the sprint. + +This seems inefficient... is there any way to smooth it out?",2021/07/29,"['https://pm.stackexchange.com/questions/32922', 'https://pm.stackexchange.com', 'https://pm.stackexchange.com/users/597/']","It sounds like you are doing something very common in teams - a 2-week waterfall project. Things likely move from some requirements conversations before the sprint or in the early days of it to coding, then QA at the end. There are a few things you can do to change this up which will also have the impact of smoothing out workload: + +1. Smaller pieces of work. Break things down into small features that can be designed, coded, and tested in 2 - 3 days. Lessons learned many decades ago from Lean: small batches lead to better flow. +2. Test-first development. Using techniques like TDD and BDD (as examples) can bring a lot of the testing early in the process instead of later. (this doesn't completely eliminate exploratory testing btw). This also really helps with... +3. Invest in test automation. Unit tests, integration tests, automated acceptance tests. This is all part of the build it process. Also, this requires both the coders and testers to work together. The testers are good at knowing what to test and the developers can help automate them and build the application to be more easily testable. This also gives you a large suite of regression tests that make it easier and safer to do #1.","I'm using a lot of Scrum terms here, but other agile methods are not that different. + +Let me make one thing clear first: test cases are not things developers or QA people make up as they go. Test cases are defined alongside the requirements. They need to be there when the implementation starts. Maybe not as automated tests, but at least as a description what should happen when on a piece of paper or in the ticket or as a reference to some electronic document. + +Writing those testcases is a lot of work and can be done by QA people whenever they have nothing to do. However, that still leaves QA with one type of work at the start of the sprint and another type at the end of the sprint and the work at the start of a sprint is not even calculated into any kind of velocity because it's not measured as getting a ticket to ""done"". + +The best way I have seen so far is to actually *not* have dedicated QA in the team. It doesn't make sense and wastes a lot of time. Maybe have a single one that can assist all others to become better at testing but can develop little features on their own if no assistance is neccessary. + +Normal testing is done by the developers (preferably not the same developer that actually implemented the feature). They make sure a story works. They go by the test cases that are already listed with the story. + +The team delivers *potentially releasable* software increments each sprint. The chance that you *actually* want to release that increment are slim. ""Agile"" lives from the ability to change things until the product owner is truly happy with them. Constantly realeasing a trickle of changes that might later be unchanged or changed in a different way is costly to everybody involved. You cannot run a marketing campaign every sprint. You cannot have ads for every little thing you finish. You cannot have 10 words translated (well, you can, but it might cost just as much as waiting until you have 100). And yes, you cannot have every feature thouroughly QA'd if it doesn't make it into a production release in the end. That's waste. + +So your QA team needs to do their job not on every increment, but only on those increments that are to be released. The same as the marketing department, sales, whoever is involved in releasing a new version. + +I know a team is supposed to be able to finish a product on their own, but that only goes for the actual implementation. There are no marketers, ad salesmen or translators on your team either. So don't make QA a part of the team. It's neither fun nor a good use of money to QA a feature over and over and over every time the product owner changes it. + +Please note that I am talking about QA here. QA is making sure a product is working as it should be. I'm not talking about simple testing. Testing should be done by the developers, how else would they be able to say ""I'm done""." +32922,"I've noticed on my team the developers are very busy toward the beginning of the sprint with the QA people having little to do, while the opposite is true toward the end of the sprint. + +This seems inefficient... is there any way to smooth it out?",2021/07/29,"['https://pm.stackexchange.com/questions/32922', 'https://pm.stackexchange.com', 'https://pm.stackexchange.com/users/597/']","Switch to Kanban so that you can balance the flow of work without the cold-start at the beginning of every sprint. + +Once you start optimizing for delivery, look at how developers can help with the QA to finish the work instead of starting new items. + +Over time, this might reveal team imbalance and drive some staffing decisions and/or tooling improvements.","I'm using a lot of Scrum terms here, but other agile methods are not that different. + +Let me make one thing clear first: test cases are not things developers or QA people make up as they go. Test cases are defined alongside the requirements. They need to be there when the implementation starts. Maybe not as automated tests, but at least as a description what should happen when on a piece of paper or in the ticket or as a reference to some electronic document. + +Writing those testcases is a lot of work and can be done by QA people whenever they have nothing to do. However, that still leaves QA with one type of work at the start of the sprint and another type at the end of the sprint and the work at the start of a sprint is not even calculated into any kind of velocity because it's not measured as getting a ticket to ""done"". + +The best way I have seen so far is to actually *not* have dedicated QA in the team. It doesn't make sense and wastes a lot of time. Maybe have a single one that can assist all others to become better at testing but can develop little features on their own if no assistance is neccessary. + +Normal testing is done by the developers (preferably not the same developer that actually implemented the feature). They make sure a story works. They go by the test cases that are already listed with the story. + +The team delivers *potentially releasable* software increments each sprint. The chance that you *actually* want to release that increment are slim. ""Agile"" lives from the ability to change things until the product owner is truly happy with them. Constantly realeasing a trickle of changes that might later be unchanged or changed in a different way is costly to everybody involved. You cannot run a marketing campaign every sprint. You cannot have ads for every little thing you finish. You cannot have 10 words translated (well, you can, but it might cost just as much as waiting until you have 100). And yes, you cannot have every feature thouroughly QA'd if it doesn't make it into a production release in the end. That's waste. + +So your QA team needs to do their job not on every increment, but only on those increments that are to be released. The same as the marketing department, sales, whoever is involved in releasing a new version. + +I know a team is supposed to be able to finish a product on their own, but that only goes for the actual implementation. There are no marketers, ad salesmen or translators on your team either. So don't make QA a part of the team. It's neither fun nor a good use of money to QA a feature over and over and over every time the product owner changes it. + +Please note that I am talking about QA here. QA is making sure a product is working as it should be. I'm not talking about simple testing. Testing should be done by the developers, how else would they be able to say ""I'm done""." +32922,"I've noticed on my team the developers are very busy toward the beginning of the sprint with the QA people having little to do, while the opposite is true toward the end of the sprint. + +This seems inefficient... is there any way to smooth it out?",2021/07/29,"['https://pm.stackexchange.com/questions/32922', 'https://pm.stackexchange.com', 'https://pm.stackexchange.com/users/597/']","One key is cross-training to reduce the skill gap between QA and SW engineers. That is, train developers to do some low-level testing, and testers some low-level development work. In fact, a big-data presentation I saw all the way back in 2014 at Agile World showed the best-performing teams did not have separate disciplines. + +This echoes some of the other answers, but the process that has worked well for my teams includes these generic tasks for each development user story: + +1. Write the test case, if one doesn't exist (QA, or dev in easier +cases). +2. Develop (Dev) || Automate new test case, or conduct break/UX testing of existing code (QA). +3. Unit test (Dev). +4. ""Second set of eyes"" testing (QA, or different Dev from step 3's). +5. Acceptance test (Customer or Product Owner). + +Good luck--Jim","I'm using a lot of Scrum terms here, but other agile methods are not that different. + +Let me make one thing clear first: test cases are not things developers or QA people make up as they go. Test cases are defined alongside the requirements. They need to be there when the implementation starts. Maybe not as automated tests, but at least as a description what should happen when on a piece of paper or in the ticket or as a reference to some electronic document. + +Writing those testcases is a lot of work and can be done by QA people whenever they have nothing to do. However, that still leaves QA with one type of work at the start of the sprint and another type at the end of the sprint and the work at the start of a sprint is not even calculated into any kind of velocity because it's not measured as getting a ticket to ""done"". + +The best way I have seen so far is to actually *not* have dedicated QA in the team. It doesn't make sense and wastes a lot of time. Maybe have a single one that can assist all others to become better at testing but can develop little features on their own if no assistance is neccessary. + +Normal testing is done by the developers (preferably not the same developer that actually implemented the feature). They make sure a story works. They go by the test cases that are already listed with the story. + +The team delivers *potentially releasable* software increments each sprint. The chance that you *actually* want to release that increment are slim. ""Agile"" lives from the ability to change things until the product owner is truly happy with them. Constantly realeasing a trickle of changes that might later be unchanged or changed in a different way is costly to everybody involved. You cannot run a marketing campaign every sprint. You cannot have ads for every little thing you finish. You cannot have 10 words translated (well, you can, but it might cost just as much as waiting until you have 100). And yes, you cannot have every feature thouroughly QA'd if it doesn't make it into a production release in the end. That's waste. + +So your QA team needs to do their job not on every increment, but only on those increments that are to be released. The same as the marketing department, sales, whoever is involved in releasing a new version. + +I know a team is supposed to be able to finish a product on their own, but that only goes for the actual implementation. There are no marketers, ad salesmen or translators on your team either. So don't make QA a part of the team. It's neither fun nor a good use of money to QA a feature over and over and over every time the product owner changes it. + +Please note that I am talking about QA here. QA is making sure a product is working as it should be. I'm not talking about simple testing. Testing should be done by the developers, how else would they be able to say ""I'm done""." +32922,"I've noticed on my team the developers are very busy toward the beginning of the sprint with the QA people having little to do, while the opposite is true toward the end of the sprint. + +This seems inefficient... is there any way to smooth it out?",2021/07/29,"['https://pm.stackexchange.com/questions/32922', 'https://pm.stackexchange.com', 'https://pm.stackexchange.com/users/597/']","It sounds like you are doing something very common in teams - a 2-week waterfall project. Things likely move from some requirements conversations before the sprint or in the early days of it to coding, then QA at the end. There are a few things you can do to change this up which will also have the impact of smoothing out workload: + +1. Smaller pieces of work. Break things down into small features that can be designed, coded, and tested in 2 - 3 days. Lessons learned many decades ago from Lean: small batches lead to better flow. +2. Test-first development. Using techniques like TDD and BDD (as examples) can bring a lot of the testing early in the process instead of later. (this doesn't completely eliminate exploratory testing btw). This also really helps with... +3. Invest in test automation. Unit tests, integration tests, automated acceptance tests. This is all part of the build it process. Also, this requires both the coders and testers to work together. The testers are good at knowing what to test and the developers can help automate them and build the application to be more easily testable. This also gives you a large suite of regression tests that make it easier and safer to do #1.","Switch to Kanban so that you can balance the flow of work without the cold-start at the beginning of every sprint. + +Once you start optimizing for delivery, look at how developers can help with the QA to finish the work instead of starting new items. + +Over time, this might reveal team imbalance and drive some staffing decisions and/or tooling improvements." +32922,"I've noticed on my team the developers are very busy toward the beginning of the sprint with the QA people having little to do, while the opposite is true toward the end of the sprint. + +This seems inefficient... is there any way to smooth it out?",2021/07/29,"['https://pm.stackexchange.com/questions/32922', 'https://pm.stackexchange.com', 'https://pm.stackexchange.com/users/597/']","It sounds like you are doing something very common in teams - a 2-week waterfall project. Things likely move from some requirements conversations before the sprint or in the early days of it to coding, then QA at the end. There are a few things you can do to change this up which will also have the impact of smoothing out workload: + +1. Smaller pieces of work. Break things down into small features that can be designed, coded, and tested in 2 - 3 days. Lessons learned many decades ago from Lean: small batches lead to better flow. +2. Test-first development. Using techniques like TDD and BDD (as examples) can bring a lot of the testing early in the process instead of later. (this doesn't completely eliminate exploratory testing btw). This also really helps with... +3. Invest in test automation. Unit tests, integration tests, automated acceptance tests. This is all part of the build it process. Also, this requires both the coders and testers to work together. The testers are good at knowing what to test and the developers can help automate them and build the application to be more easily testable. This also gives you a large suite of regression tests that make it easier and safer to do #1.","One key is cross-training to reduce the skill gap between QA and SW engineers. That is, train developers to do some low-level testing, and testers some low-level development work. In fact, a big-data presentation I saw all the way back in 2014 at Agile World showed the best-performing teams did not have separate disciplines. + +This echoes some of the other answers, but the process that has worked well for my teams includes these generic tasks for each development user story: + +1. Write the test case, if one doesn't exist (QA, or dev in easier +cases). +2. Develop (Dev) || Automate new test case, or conduct break/UX testing of existing code (QA). +3. Unit test (Dev). +4. ""Second set of eyes"" testing (QA, or different Dev from step 3's). +5. Acceptance test (Customer or Product Owner). + +Good luck--Jim" +41196,"I am having problem understanding why **negative frequencies are showing up to the right of positive frequencies** in discrete complex FFT. + +I am not sure how to apply aliasing concept to explain such phenomenon even after reading about modulo-2pi angular frequency concept at [MIT OCW signal processing course](https://ocw.mit.edu/courses/mechanical-engineering/2-161-signal-processing-continuous-and-discrete-fall-2008/lecture-notes/lecture_10.pdf). + +Anyone ? + +[![enter image description here](https://i.stack.imgur.com/QfcWd.png)](https://i.stack.imgur.com/QfcWd.png)",2017/05/24,"['https://dsp.stackexchange.com/questions/41196', 'https://dsp.stackexchange.com', 'https://dsp.stackexchange.com/users/22522/']","The Fourier transform $X(e^{j\Omega})$ of a sequence $x[n]$ is by definition periodic of period $2\pi$ in $\Omega$. The $N$-point discrete Fourier transform (DFT) of $x[n]$ is simply defined as a sampled version of the Fourier transform $X(e^{j\Omega})$, that is +$$X[k] = X(e^{j\frac{2k\pi}{N}}).$$ +The periodicity of $2\pi$ in $\Omega$ for the Fourier transform becomes a periodicity of $N$ in $k$ for the DFT +$$X[k+N] = X[k].$$ +The negative frequencies showing up to the right of the positive frequencies is simply a consequence of this periodicity. Or if you prefer, you get $X[k]$ for $k \in [0, N-1]$ instead of $k \in [-\frac{N-1}{2}, \frac{N-1}{2}]$. If you want the vector to contain first negative frequencies, then the DC and finally the positive frequencies instead, you can for example use MATLAB `fftshift`. + +Those negative frequencies are not shown for the ""real"" DFT because if $x[n]$ is real, then $X[k] = X^\*[-k]$ (conjugate symmetry). Hence, you only need $X[k]$ for $k \in [0, N/2]$.","I will try to give a more intuitive answer here. Have you ever seen [this effect](http://www.youtube.com/watch?v=jHS9JGkEOmA)? It is related to your question. + +For simplicity, I will take easy numbers. The camera rate (fs) is, lets say, 1 frames per second: every second it takes a snapshot of the wheel. Now, assume that the wheel is spinning also at 1 turn per second (fw). Result? you see a static wheel, the car is going fast (the landscape is passing by...), but the wheels just seem not to spin at all, but you know they are moving. In this case, $fw = fs$, and you see how $2 \cdot \pi$ [rads] maps to $0 \cdot \pi$ [rads], you lose information in the sampling process. + +Now, if $fw$ is 0.9 ([Hz]), the wheels seem to spin counterclockwise very slowly. But the question is, did it turn counterclockwise slowly or clockwise but much faster?. We have two options: + +1. Assume they are always spinning clockwise (or counterclockwise), i.e. it spun at 0.9 Hz clockwise. So possible frequencies span [0, N) samples or [0, 1) Hz. +2. Assume that wheels reached that state through the shortest pat, i.e. it spun counterclockwise at 0.1 Hz. So possible frequencies span [-N/2,N/2) samples or [-0.5, 0.5) Hz. + +In the signal domain, a wheel spinning clockwise would be sine and a counterclockwise spinning wheel would be a negative sine ($sin(- \omega \cdot t) = -sin(\omega \cdot t)$), and so on for cosine. Since negative sine is common we better go with the second approach. + +In short, negative frequencies equal higher positive frequencies, in the digital domain you can not tell the difference." +129650,"Let's say I have many-to-many relationship (using the ActiveRecord attribute HasAndBelongsToMany) between Posts and Tags (domain object names changed to protect the innocent), and I wanted a method like +``` +FindAllPostByTags(IList tags) +``` + that returns all Posts that have all (not just some of) the Tags in the parameter. Any way I could accomplish this either with NHibernate Expressions or HQL? I've searched through the HQL documentation and couldn't find anything that suited my needs. I hope I'm just missing something obvious!",2008/09/24,"['https://Stackoverflow.com/questions/129650', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14064/']","You could also just use an `IN` statement + +``` +DetachedCriteria query = DetachedCriteria.For(); +query.CreateCriteria(""Post"").Add(Expression.In(""TagName"", string.Join("","",tags.ToArray()) ); + +``` + +I haven't compiled that so it could have errors","I don't have a system at hand with a Castle install right now, so I didn't test or compile this, but the code below should about do what you want. + +``` +Junction c = Expression.Conjunction(); +foreach(Tag t in tags) + c = c.Add( Expression.Eq(""Tag"", t); + +return sess.CreateCriteria(typeof(Post)).Add(c).List(); + +```" +129650,"Let's say I have many-to-many relationship (using the ActiveRecord attribute HasAndBelongsToMany) between Posts and Tags (domain object names changed to protect the innocent), and I wanted a method like +``` +FindAllPostByTags(IList tags) +``` + that returns all Posts that have all (not just some of) the Tags in the parameter. Any way I could accomplish this either with NHibernate Expressions or HQL? I've searched through the HQL documentation and couldn't find anything that suited my needs. I hope I'm just missing something obvious!",2008/09/24,"['https://Stackoverflow.com/questions/129650', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14064/']","You could also just use an `IN` statement + +``` +DetachedCriteria query = DetachedCriteria.For(); +query.CreateCriteria(""Post"").Add(Expression.In(""TagName"", string.Join("","",tags.ToArray()) ); + +``` + +I haven't compiled that so it could have errors","I just had the same problem and tried to read the HQL-documentation, however some of the features doesn't seem to be implemented in NHibernate (with-keyword for example) + +I ended up with this sort of solution: + +``` + +select p +FROM Post p +JOIN p.Tags tag1 +JOIN p.Tags tag2 +WHERE + tag1.Id = 1 + tag2.Id = 2 + +``` + +Meaning, dynamically build the HQL using join for each tag, then make the selection in your WHERE clause. This worked for me. I tried doing the same thing with a DetachedCriteria but ran into trouble when trying to join the table multiple times." +71368718,"I am trying to build an application where user can search for various items. now my question is how can I send efficiently user search request to the server ? + +example , user will type something (say 15 characters). For every 1 character he is sending one request to the server (using axios). now he is typing so fast, within 3 seconds he has sent 15 request to the server.. due to 15 parallel requests, my app is showing the actual result lately (or sometime failing). please help me how can i solve it.. I am using react native with axios. + +example: + +``` +async searchLocation(text) { + + if (text.length > 3) { + this.setState({searching: true, searchResultWindow: true}); + var getSearchResult = await searchPlace(text); /// Here I am making axios call to our server + this.setState({searching: false, searchResults: getSearchResult.message}); + } + } + +```",2022/03/06,"['https://Stackoverflow.com/questions/71368718', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/911423/']","You can use `setTimeout` to handle that case + +``` +let timer //the global variable to track the timer +async searchLocation(text) { + + if (text.length > 3) { + //remove the API trigger within 3 seconds + clearTimeout(timer) + //assign new timer for the API call + timer = setTimeout(() => { + this.setState({searching: true, searchResultWindow: true}); + var getSearchResult = await searchPlace(text); /// Here I am making axios call to our server + this.setState({searching: false, searchResults: getSearchResult.message}); + }, 3000) //the API only triggers once users stop typing after 3 seconds + } + } + +``` + +If you want to have deeper understanding, you can read this article + +","I think you can divide the issue into two steps + +* At the first you must find a word that the user wants to type for search (**not result of search**) +in this step, you can just use a dictionary +* The second step is finding user search results after pressing **Enter key** or Click to the search button" +11671135,"Consider this list of POSIXct dates: + +``` +times <- list(as.POSIXct(c(""2012-07-26 00:30"", ""2012-07-26 6:20"", + ""2012-07-26 10:40"", ""2012-07-26 15:50"")), + as.POSIXct(c(""2012-07-26 01:15"", ""2012-07-26 10:10"", + ""2012-07-26 15:15"", ""2012-07-26 18:50"")), + as.POSIXct(c(""2012-07-26 00:35"", ""2012-07-26 15:05"", + ""2012-07-26 19:36"", ""2012-07-26 22:32"")), + as.POSIXct(c(""2012-07-26 03:34"", ""2012-07-26 16:43"", + ""2012-07-26 21:44"", ""2012-07-26 23:45""))) + +``` + +If I do: + +``` +range(times[[1]]) + +``` + +I correctly get: + +``` +[1] ""2012-07-26 00:30:00 CEST"" ""2012-07-26 15:50:00 CEST"" + +``` + +Now, if I do: + +``` +range(times[c(1,3)]) + +``` + +for whatever reason R decides to convert the POSIXct objects into timestamps and gives me + +``` +[1] 1343255400 1343334720 + +``` + +I then try to reconvert them to POSIXct by doing: + +``` +as.POSIXct(range(times[c(1,3)]), origin=""1970-01-01 00:00"") + +``` + +And, strangely, I get the range with 1 hour of advance: + +``` +[1] ""2012-07-25 23:30:00 CEST"" ""2012-07-26 21:32:00 CEST"" + +``` + +So I have to do: + +``` +as.POSIXct(range(times[c(1,3)]), origin=""1970-01-01 01:00"") + +``` + +To get the correct range of: + +``` +[1] ""2012-07-26 00:30:00 CEST"" ""2012-07-26 22:32:00 CEST"" + +``` + +Am I missing something or is there a bug somewhere?",2012/07/26,"['https://Stackoverflow.com/questions/11671135', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/176923/']","`times[[1]]` is a vector, while `times[c(1,3)]` is a list. Convert the latter to a vector before calling `range` and all is well. + +You don't want to use `unlist` though, since it will only return an atomic vector (`range` must be doing something like that internally), but you can use `do.call`: + +``` +range(do.call(c,times[c(1,3)])) + +``` + +The differences you get from using `as.POSIXct` are likely due to timezone issues.","As Joshua said, the hour is because of timezones. Try, for example: + +``` +times <- list(as.POSIXct(c(""2012-07-26 00:30"", ""2012-07-26 6:20"", + ""2012-07-26 10:40"", ""2012-07-26 15:50""), ""GMT""), + as.POSIXct(c(""2012-07-26 01:15"", ""2012-07-26 10:10"", + ""2012-07-26 15:15"", ""2012-07-26 18:50""), ""GMT""), + as.POSIXct(c(""2012-07-26 00:35"", ""2012-07-26 15:05"", + ""2012-07-26 19:36"", ""2012-07-26 22:32""), ""GMT""), + as.POSIXct(c(""2012-07-26 03:34"", ""2012-07-26 16:43"", + ""2012-07-26 21:44"", ""2012-07-26 23:45""), ""GMT"")) +as.POSIXct(range(times[c(1,3)]), origin=""1970-01-01 00:00"", ""GMT"") + +```" +1064367,"Title pretty much says it all. `lspci -v` finds a sound card, but neither `aplay -l` not `pacmd list-cards` don't. Problem first surfaced when updating ubuntu to 18.04, which was a hail-mary attempt to fix an another probably unrelated issue with my login screen. I'm not sure whether or not my sound was working before the ubuntu update either, since the login screen issue arose when I got my machine back from warranty repair. + +Alsa self diagnose: + + +lspci -v: + + +aplay -l: +aplay: device\_list:270: no soundcards found... + +pacmd list-cards: +0 card(s) available. + +Things to note: + +* My boot time lasts a bit longer than I remember it lasting, maybe some kernel module thing fails? +* My pulseaudio daemon doesn't start on boot. Maybe unrelated but I think you should know. +* I'm running the newest ubuntu (18.04). + +Have tried: + +* Reinstalling many things, some probably multiple times. +* Robooting with various changes +* Deleting the local pulseaudio config in `~/.config/pulse` +* reseting default.pa (might have picked the wrong one to reset to) +* Adding myself to audio group + +**EDIT:** `inxi -a` sees the card and states that it's using the snd\_hda\_intel driver.",2018/08/11,"['https://askubuntu.com/questions/1064367', 'https://askubuntu.com', 'https://askubuntu.com/users/527308/']","Typically, `dconf` schemas translate nicely into `gsettings` schemas by replacing slashes with dots and vice versa. + +In your example, `org.mate.peripherals-mouse` is the closest matching for what I'd expect to be a static schema. + +However, not all `gsettings` schemas translate nicely. There's something known as [relocatable schemas](https://blog.gtk.org/2017/05/01/first-steps-with-gsettings/): + +> +> A relocatable schema is what you need when you need multiple instances of the same configuration, stored separately. A typical example for this is accounts: your application allows to create more than one, and each of them has the same kind of configuration information associated with it. +> +> +> + +For such cases, schema also requires a particular path added to it. [For example](https://askubuntu.com/a/290160/295286), + +``` +gsettings set org.compiz.unityshell:/org/compiz/profiles/unity/plugins/unityshell/ dash-blur-experimental 1 + +``` + +Here's another example from one of Budgie desktop schemas: + +``` +$ dconf write /com/solus-project/budgie-panel/panels/{5f6251f2-9d09-11e8-be4b-d053493d53fd}/size 52 +$ gsettings set com.solus-project.budgie-panel.panel:/com/solus-project/budgie-panel/panels/{5f6251f2-9d09-11e8-be4b-d053493d53fd}/ size 52 + +``` + +Typically paths for relocatable `gsettings` schemas are the same as for `dconf`, but [it's not guaranteed](https://stackoverflow.com/q/30687792/3701431) from what I understand. Manual way would be to run `dconf watch /` and use GUI buttons/sliders/preferences menus to figure out which schemas are controlled by those.","To further clarify the relation between GSettings and DConf: + +First of all, they are part of the *same* system. To be more precise, GSettings *uses* DConf as its ***storage backend***. + +And that's what DConf is: a **storage** system. That's why it only speaks in terms of *paths*: it stores keys and values in a given path. Those paths, keys and values are then stored in a binary *source*. Think of `dconf` as a ZIP archive: it contains ""files"" (keys) with values, structured in directories and subdirectories. + +For dconf that data has no *semantics*. Yes, its values are strongly typed (String, Integer, List, Boolean and so on). But they have no *meaning*. It doesn't care (or even *know*) about *schemas*. + +Now comes GSettings. It organizes data in a *logical* way, with *schemas* declaring all settings an application uses, their description and summary. A Schema is the ""blueprint"" of a collection of settings, and has a unique ID. So an application, say Gnome Terminal, installs the schema `org.gnome.Terminal.Legacy.Settings`. The schema is saying ""my (legacy) settings have this *format*"". + +GSettings (actually GLib) takes care of *where* and *how* such settings will be saved, so you don't have to. It could theoretically use an SQLite or MySQL database. Or INI files. Or JSON. It uses DConf, and so by default it saves that schema at dconf's path `/org/gnome/terminal/legacy/settings/`. + +So is there a 1:1 mapping between GSettings schemas and DConf paths? For *non-relocatable* schemas (more on that later), yes. But you cannot derive a path from a schema name: even if *most* schemas are stored in a path resembling the schema, such as Gnome Terminal example above, that is not always the case: `org.gnome.Vino`, for example, is stored at `/org/gnome/desktop/remote-access/`. To get the paths where schemas are stored, use: + +``` +gsettings list-schemas --print-paths + +``` + +And to infer the schemas from the paths... don't. You can get away with *""replace `/` with `.`""* only for the most basic cases. It won't work for: + +* Schemas with`Mixed.case.Names`, such as Gnome Terminal +* Schemas in non-standard paths, such as Vino +* Non-relocatable schemas + +***Relocatable***? Yes, when the same Schema is used in *multiple instances*. For example, Gnome Terminal allows you to create several named *profiles*, which is a subset of the application's settings. Since all profiles have the same *format*, they all share the same ""blueprint"", the Gsettings schema `org.gnome.Terminal.Legacy.Profile`. The data for each profile is saved in a distinct dconf *path*, and so that schema is a **relocatable** one. + +That's why for relocatable schemas the application (and you) must specify **both** the schema *and* path when using `gsettings`. If accessing `dconf` directly, as it doesn't know about schemas, you use just the path. But there isn't a 1:1 mapping, as relocatable schemas have a 1:N relation with paths. + +--- + +To answer your question: none of the mouse-related schemas you listed is a relocatable schema (those would be listed with `gsettings list-relocatable-schemas`), so you *can* for this particular case get their DConf paths with + +``` +gsettings list-schemas --print-paths | grep -i mouse + +``` + +As for ""which one should I use""? Well, that depends on what setting you want to change. Several applications might have mouse-related settings. Gnome Desktop has one, Mate has another for its desktop (I presume) and a mouse-related plugin in its ""settings daemon"", whatever that is. What behavior in your system each setting controls is application-dependent, but that would be outside the scope of the question." +46061388,"I am trying to change the background color and text color of a link inside a button that I created, but only the background color changes. The text remains it's default color and refuses to change regardless of !important tags. + +Here is my code: + +```css +button, +input, +select, +textarea { + font-size: 100%; + /* Corrects font size not being inherited in all browsers */ + margin: 0; + /* Addresses margins set differently in IE6/7, F3/4, S5, Chrome */ + vertical-align: baseline; + /* Improves appearance and consistency in all browsers */ + padding: 15px; +} + +button, +.button, +input[type=""button""], +input[type=""reset""], +input[type=""submit""] { + font-size: 12px; + padding: 12px 30px; + margin-bottom: 10px; + width: 200px; + border: 1px solid #007af4; + color: #007af4; + text-transform: uppercase; + letter-spacing: 4px; + background-color: transparent; + -webkit-transition: all 0.3s; + transition: all 0.3s; + cursor: pointer; + /* Improves usability and consistency of cursor style between image-type 'input' and others */ + -webkit-appearance: button; + /* Corrects inability to style clickable 'input' types in iOS */ +} + +.button { + -webkit-appearance: none; +} + +input[type=""submit""] { + margin-top: 5px; +} + +button:hover, +.button:hover, +input[type=""button""]:hover, +input[type=""reset""]:hover, +input[type=""submit""]:hover { + background-color: #007af4; + text-decoration: none; + color: #FFFFFF; +} +``` + +```html + +``` + +I've already looked at these two threads: + +[a:hover color is not working](https://stackoverflow.com/questions/16967118/ahover-color-is-not-working) + +[a: hover, color is not changing](https://stackoverflow.com/questions/35241294/a-hover-color-is-not-changing) + +Neither of the answers given on those threads helped with my problem (Unless I've overlooked something), so any help is greatly appreciated!",2017/09/05,"['https://Stackoverflow.com/questions/46061388', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8565234/']","Your CSS doesn't actually have any `a:hover` rules. + +Why do you expect something to happen? + +CSS will only do what you tell it to.","When you are changing a links colour on hover you need to make sure to apply it to the `a` tag directly. So in your case you want a style similar to the following: + +``` +a:hover { + color: white; +} + +```" +46061388,"I am trying to change the background color and text color of a link inside a button that I created, but only the background color changes. The text remains it's default color and refuses to change regardless of !important tags. + +Here is my code: + +```css +button, +input, +select, +textarea { + font-size: 100%; + /* Corrects font size not being inherited in all browsers */ + margin: 0; + /* Addresses margins set differently in IE6/7, F3/4, S5, Chrome */ + vertical-align: baseline; + /* Improves appearance and consistency in all browsers */ + padding: 15px; +} + +button, +.button, +input[type=""button""], +input[type=""reset""], +input[type=""submit""] { + font-size: 12px; + padding: 12px 30px; + margin-bottom: 10px; + width: 200px; + border: 1px solid #007af4; + color: #007af4; + text-transform: uppercase; + letter-spacing: 4px; + background-color: transparent; + -webkit-transition: all 0.3s; + transition: all 0.3s; + cursor: pointer; + /* Improves usability and consistency of cursor style between image-type 'input' and others */ + -webkit-appearance: button; + /* Corrects inability to style clickable 'input' types in iOS */ +} + +.button { + -webkit-appearance: none; +} + +input[type=""submit""] { + margin-top: 5px; +} + +button:hover, +.button:hover, +input[type=""button""]:hover, +input[type=""reset""]:hover, +input[type=""submit""]:hover { + background-color: #007af4; + text-decoration: none; + color: #FFFFFF; +} +``` + +```html + +``` + +I've already looked at these two threads: + +[a:hover color is not working](https://stackoverflow.com/questions/16967118/ahover-color-is-not-working) + +[a: hover, color is not changing](https://stackoverflow.com/questions/35241294/a-hover-color-is-not-changing) + +Neither of the answers given on those threads helped with my problem (Unless I've overlooked something), so any help is greatly appreciated!",2017/09/05,"['https://Stackoverflow.com/questions/46061388', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8565234/']","If you want to change the `` text color when hovering over the enclosing `.button` you can do this: + +``` +.button:hover a { + color: #FFFFFF +} + +``` + +This has the advantage of not needing to hover over the actual link -- when you hover over any part of the button, the link color will change and stay readable. + +```css +button, +input, +select, +textarea { + font-size: 100%; + /* Corrects font size not being inherited in all browsers */ + margin: 0; + /* Addresses margins set differently in IE6/7, F3/4, S5, Chrome */ + vertical-align: baseline; + /* Improves appearance and consistency in all browsers */ + padding: 15px; +} + +button, +.button, +input[type=""button""], +input[type=""reset""], +input[type=""submit""] { + font-size: 12px; + padding: 12px 30px; + margin-bottom: 10px; + width: 200px; + border: 1px solid #007af4; + color: #007af4; + text-transform: uppercase; + letter-spacing: 4px; + background-color: transparent; + -webkit-transition: all 0.3s; + transition: all 0.3s; + cursor: pointer; + /* Improves usability and consistency of cursor style between image-type 'input' and others */ + -webkit-appearance: button; + /* Corrects inability to style clickable 'input' types in iOS */ +} +.button:hover a { +color: #FFFFFF +} +.button { + -webkit-appearance: none; +} + +input[type=""submit""] { + margin-top: 5px; +} + +button:hover, +.button:hover, +input[type=""button""]:hover, +input[type=""reset""]:hover, +input[type=""submit""]:hover { + background-color: #007af4; + text-decoration: none; + color: #FFFFFF; +} +``` + +```html + +```","Your CSS doesn't actually have any `a:hover` rules. + +Why do you expect something to happen? + +CSS will only do what you tell it to." +46061388,"I am trying to change the background color and text color of a link inside a button that I created, but only the background color changes. The text remains it's default color and refuses to change regardless of !important tags. + +Here is my code: + +```css +button, +input, +select, +textarea { + font-size: 100%; + /* Corrects font size not being inherited in all browsers */ + margin: 0; + /* Addresses margins set differently in IE6/7, F3/4, S5, Chrome */ + vertical-align: baseline; + /* Improves appearance and consistency in all browsers */ + padding: 15px; +} + +button, +.button, +input[type=""button""], +input[type=""reset""], +input[type=""submit""] { + font-size: 12px; + padding: 12px 30px; + margin-bottom: 10px; + width: 200px; + border: 1px solid #007af4; + color: #007af4; + text-transform: uppercase; + letter-spacing: 4px; + background-color: transparent; + -webkit-transition: all 0.3s; + transition: all 0.3s; + cursor: pointer; + /* Improves usability and consistency of cursor style between image-type 'input' and others */ + -webkit-appearance: button; + /* Corrects inability to style clickable 'input' types in iOS */ +} + +.button { + -webkit-appearance: none; +} + +input[type=""submit""] { + margin-top: 5px; +} + +button:hover, +.button:hover, +input[type=""button""]:hover, +input[type=""reset""]:hover, +input[type=""submit""]:hover { + background-color: #007af4; + text-decoration: none; + color: #FFFFFF; +} +``` + +```html + +``` + +I've already looked at these two threads: + +[a:hover color is not working](https://stackoverflow.com/questions/16967118/ahover-color-is-not-working) + +[a: hover, color is not changing](https://stackoverflow.com/questions/35241294/a-hover-color-is-not-changing) + +Neither of the answers given on those threads helped with my problem (Unless I've overlooked something), so any help is greatly appreciated!",2017/09/05,"['https://Stackoverflow.com/questions/46061388', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8565234/']","Your CSS doesn't actually have any `a:hover` rules. + +Why do you expect something to happen? + +CSS will only do what you tell it to.","A link already has an predefined style. You need to remove that style first to apply your style. Try this in your link + +``` +text-decoration: none + +``` + +Try hover after that." +46061388,"I am trying to change the background color and text color of a link inside a button that I created, but only the background color changes. The text remains it's default color and refuses to change regardless of !important tags. + +Here is my code: + +```css +button, +input, +select, +textarea { + font-size: 100%; + /* Corrects font size not being inherited in all browsers */ + margin: 0; + /* Addresses margins set differently in IE6/7, F3/4, S5, Chrome */ + vertical-align: baseline; + /* Improves appearance and consistency in all browsers */ + padding: 15px; +} + +button, +.button, +input[type=""button""], +input[type=""reset""], +input[type=""submit""] { + font-size: 12px; + padding: 12px 30px; + margin-bottom: 10px; + width: 200px; + border: 1px solid #007af4; + color: #007af4; + text-transform: uppercase; + letter-spacing: 4px; + background-color: transparent; + -webkit-transition: all 0.3s; + transition: all 0.3s; + cursor: pointer; + /* Improves usability and consistency of cursor style between image-type 'input' and others */ + -webkit-appearance: button; + /* Corrects inability to style clickable 'input' types in iOS */ +} + +.button { + -webkit-appearance: none; +} + +input[type=""submit""] { + margin-top: 5px; +} + +button:hover, +.button:hover, +input[type=""button""]:hover, +input[type=""reset""]:hover, +input[type=""submit""]:hover { + background-color: #007af4; + text-decoration: none; + color: #FFFFFF; +} +``` + +```html + +``` + +I've already looked at these two threads: + +[a:hover color is not working](https://stackoverflow.com/questions/16967118/ahover-color-is-not-working) + +[a: hover, color is not changing](https://stackoverflow.com/questions/35241294/a-hover-color-is-not-changing) + +Neither of the answers given on those threads helped with my problem (Unless I've overlooked something), so any help is greatly appreciated!",2017/09/05,"['https://Stackoverflow.com/questions/46061388', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8565234/']","If you want to change the `` text color when hovering over the enclosing `.button` you can do this: + +``` +.button:hover a { + color: #FFFFFF +} + +``` + +This has the advantage of not needing to hover over the actual link -- when you hover over any part of the button, the link color will change and stay readable. + +```css +button, +input, +select, +textarea { + font-size: 100%; + /* Corrects font size not being inherited in all browsers */ + margin: 0; + /* Addresses margins set differently in IE6/7, F3/4, S5, Chrome */ + vertical-align: baseline; + /* Improves appearance and consistency in all browsers */ + padding: 15px; +} + +button, +.button, +input[type=""button""], +input[type=""reset""], +input[type=""submit""] { + font-size: 12px; + padding: 12px 30px; + margin-bottom: 10px; + width: 200px; + border: 1px solid #007af4; + color: #007af4; + text-transform: uppercase; + letter-spacing: 4px; + background-color: transparent; + -webkit-transition: all 0.3s; + transition: all 0.3s; + cursor: pointer; + /* Improves usability and consistency of cursor style between image-type 'input' and others */ + -webkit-appearance: button; + /* Corrects inability to style clickable 'input' types in iOS */ +} +.button:hover a { +color: #FFFFFF +} +.button { + -webkit-appearance: none; +} + +input[type=""submit""] { + margin-top: 5px; +} + +button:hover, +.button:hover, +input[type=""button""]:hover, +input[type=""reset""]:hover, +input[type=""submit""]:hover { + background-color: #007af4; + text-decoration: none; + color: #FFFFFF; +} +``` + +```html + +```","When you are changing a links colour on hover you need to make sure to apply it to the `a` tag directly. So in your case you want a style similar to the following: + +``` +a:hover { + color: white; +} + +```" +46061388,"I am trying to change the background color and text color of a link inside a button that I created, but only the background color changes. The text remains it's default color and refuses to change regardless of !important tags. + +Here is my code: + +```css +button, +input, +select, +textarea { + font-size: 100%; + /* Corrects font size not being inherited in all browsers */ + margin: 0; + /* Addresses margins set differently in IE6/7, F3/4, S5, Chrome */ + vertical-align: baseline; + /* Improves appearance and consistency in all browsers */ + padding: 15px; +} + +button, +.button, +input[type=""button""], +input[type=""reset""], +input[type=""submit""] { + font-size: 12px; + padding: 12px 30px; + margin-bottom: 10px; + width: 200px; + border: 1px solid #007af4; + color: #007af4; + text-transform: uppercase; + letter-spacing: 4px; + background-color: transparent; + -webkit-transition: all 0.3s; + transition: all 0.3s; + cursor: pointer; + /* Improves usability and consistency of cursor style between image-type 'input' and others */ + -webkit-appearance: button; + /* Corrects inability to style clickable 'input' types in iOS */ +} + +.button { + -webkit-appearance: none; +} + +input[type=""submit""] { + margin-top: 5px; +} + +button:hover, +.button:hover, +input[type=""button""]:hover, +input[type=""reset""]:hover, +input[type=""submit""]:hover { + background-color: #007af4; + text-decoration: none; + color: #FFFFFF; +} +``` + +```html + +``` + +I've already looked at these two threads: + +[a:hover color is not working](https://stackoverflow.com/questions/16967118/ahover-color-is-not-working) + +[a: hover, color is not changing](https://stackoverflow.com/questions/35241294/a-hover-color-is-not-changing) + +Neither of the answers given on those threads helped with my problem (Unless I've overlooked something), so any help is greatly appreciated!",2017/09/05,"['https://Stackoverflow.com/questions/46061388', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8565234/']","When you are changing a links colour on hover you need to make sure to apply it to the `a` tag directly. So in your case you want a style similar to the following: + +``` +a:hover { + color: white; +} + +```","A link already has an predefined style. You need to remove that style first to apply your style. Try this in your link + +``` +text-decoration: none + +``` + +Try hover after that." +46061388,"I am trying to change the background color and text color of a link inside a button that I created, but only the background color changes. The text remains it's default color and refuses to change regardless of !important tags. + +Here is my code: + +```css +button, +input, +select, +textarea { + font-size: 100%; + /* Corrects font size not being inherited in all browsers */ + margin: 0; + /* Addresses margins set differently in IE6/7, F3/4, S5, Chrome */ + vertical-align: baseline; + /* Improves appearance and consistency in all browsers */ + padding: 15px; +} + +button, +.button, +input[type=""button""], +input[type=""reset""], +input[type=""submit""] { + font-size: 12px; + padding: 12px 30px; + margin-bottom: 10px; + width: 200px; + border: 1px solid #007af4; + color: #007af4; + text-transform: uppercase; + letter-spacing: 4px; + background-color: transparent; + -webkit-transition: all 0.3s; + transition: all 0.3s; + cursor: pointer; + /* Improves usability and consistency of cursor style between image-type 'input' and others */ + -webkit-appearance: button; + /* Corrects inability to style clickable 'input' types in iOS */ +} + +.button { + -webkit-appearance: none; +} + +input[type=""submit""] { + margin-top: 5px; +} + +button:hover, +.button:hover, +input[type=""button""]:hover, +input[type=""reset""]:hover, +input[type=""submit""]:hover { + background-color: #007af4; + text-decoration: none; + color: #FFFFFF; +} +``` + +```html + +``` + +I've already looked at these two threads: + +[a:hover color is not working](https://stackoverflow.com/questions/16967118/ahover-color-is-not-working) + +[a: hover, color is not changing](https://stackoverflow.com/questions/35241294/a-hover-color-is-not-changing) + +Neither of the answers given on those threads helped with my problem (Unless I've overlooked something), so any help is greatly appreciated!",2017/09/05,"['https://Stackoverflow.com/questions/46061388', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8565234/']","If you want to change the `` text color when hovering over the enclosing `.button` you can do this: + +``` +.button:hover a { + color: #FFFFFF +} + +``` + +This has the advantage of not needing to hover over the actual link -- when you hover over any part of the button, the link color will change and stay readable. + +```css +button, +input, +select, +textarea { + font-size: 100%; + /* Corrects font size not being inherited in all browsers */ + margin: 0; + /* Addresses margins set differently in IE6/7, F3/4, S5, Chrome */ + vertical-align: baseline; + /* Improves appearance and consistency in all browsers */ + padding: 15px; +} + +button, +.button, +input[type=""button""], +input[type=""reset""], +input[type=""submit""] { + font-size: 12px; + padding: 12px 30px; + margin-bottom: 10px; + width: 200px; + border: 1px solid #007af4; + color: #007af4; + text-transform: uppercase; + letter-spacing: 4px; + background-color: transparent; + -webkit-transition: all 0.3s; + transition: all 0.3s; + cursor: pointer; + /* Improves usability and consistency of cursor style between image-type 'input' and others */ + -webkit-appearance: button; + /* Corrects inability to style clickable 'input' types in iOS */ +} +.button:hover a { +color: #FFFFFF +} +.button { + -webkit-appearance: none; +} + +input[type=""submit""] { + margin-top: 5px; +} + +button:hover, +.button:hover, +input[type=""button""]:hover, +input[type=""reset""]:hover, +input[type=""submit""]:hover { + background-color: #007af4; + text-decoration: none; + color: #FFFFFF; +} +``` + +```html + +```","A link already has an predefined style. You need to remove that style first to apply your style. Try this in your link + +``` +text-decoration: none + +``` + +Try hover after that." +11934236,"Is there anything similar to [Celery](http://celeryproject.org) for Ruby? Is there anyone with any experience with [rcelery](https://github.com/leapfrogonline/rcelery)? Is it a good choice for production? + +Update: I came across [resque](https://github.com/resque/resque), which looks like something I might be able to use for my task. Any further suggestions welcome!",2012/08/13,"['https://Stackoverflow.com/questions/11934236', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']","There are a lot of options for queues in ruby. + +Sidekiq -> + +Resque, you got the link + +DelayedJob -> + +All of them are pretty much the same. So you just need to use the one you are more confortable working with the examples. + +In my projects i ended up using `Sidekiq`, the reviews about it are pretty awesome.","Here is a good comparison of Resque and Sidekiq. +[Resque vs Sidekiq?](https://stackoverflow.com/questions/11580954/resque-vs-sidekiq) + +Sidekiq uses threads so there is a much lower memory footprint then Resque or delayed job. the downside, and a huge one i think, is your workers MUST be thread safe, including whatever gems you use in them. vetting all the code that goes into workers for thread safety is a on-taking for sure, as is potentially debugging contention in lower level libs, seg faults, etc.." +11012218,"I have the following mysql table. I have been trying to select all the rows which are related with the row that has `B` as value in the `code` column. The relation is based on the value of the column `trans_id` + +``` +id trans_id code amount side +1 1 A 200 left +2 1 B 200 right +3 2 J 100 right +4 2 C 100 right +5 2 B 200 left +6 3 A 630 right +7 3 K 630 left + +``` + +My Expected Result: + +``` + id trans_id code amount side + 1 1 A 200 left + 3 2 J 100 right + 4 2 C 100 right + +``` + +Could you please tell me what should be the mysql query to achieve this? + +Thanks :)",2012/06/13,"['https://Stackoverflow.com/questions/11012218', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1209690/']","Your question is unclear, but as far as I understand, you could use a self join like this: + +``` +select a.id, + a.trans_id, + a.code, + a.amount, + a.side + from table as a + inner join table as b on (a.id=b.trans_id and b.code='B'); + +``` + +This will return the row with table.id=2: + +``` +id trans_id code amount side +2 1 B 200 right + +```","If I'm understanding your problem correctly then a subquery would get you what you need. + +``` +SELECT * FROM yourTable WHERE id IN (SELECT trans_id FROM yourTable WHERE code='B') + +```" +11012218,"I have the following mysql table. I have been trying to select all the rows which are related with the row that has `B` as value in the `code` column. The relation is based on the value of the column `trans_id` + +``` +id trans_id code amount side +1 1 A 200 left +2 1 B 200 right +3 2 J 100 right +4 2 C 100 right +5 2 B 200 left +6 3 A 630 right +7 3 K 630 left + +``` + +My Expected Result: + +``` + id trans_id code amount side + 1 1 A 200 left + 3 2 J 100 right + 4 2 C 100 right + +``` + +Could you please tell me what should be the mysql query to achieve this? + +Thanks :)",2012/06/13,"['https://Stackoverflow.com/questions/11012218', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1209690/']","``` +select + t1.* +from + table_name t1 + inner join table_name t2 on t1.trans_id = t2.trans_id +where + t2.code = 'B' and + t2.code <> t1.code + +```","If I'm understanding your problem correctly then a subquery would get you what you need. + +``` +SELECT * FROM yourTable WHERE id IN (SELECT trans_id FROM yourTable WHERE code='B') + +```" +11012218,"I have the following mysql table. I have been trying to select all the rows which are related with the row that has `B` as value in the `code` column. The relation is based on the value of the column `trans_id` + +``` +id trans_id code amount side +1 1 A 200 left +2 1 B 200 right +3 2 J 100 right +4 2 C 100 right +5 2 B 200 left +6 3 A 630 right +7 3 K 630 left + +``` + +My Expected Result: + +``` + id trans_id code amount side + 1 1 A 200 left + 3 2 J 100 right + 4 2 C 100 right + +``` + +Could you please tell me what should be the mysql query to achieve this? + +Thanks :)",2012/06/13,"['https://Stackoverflow.com/questions/11012218', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1209690/']","The following query should return the results you want. This uses a select query to return results to the WHERE clause. + +``` +SELECT * FROM yourTable +WHERE trans_id IN ( + SELECT trans_id FROM yourTable WHERE code='B' +) +AND code!='B' + +```","If I'm understanding your problem correctly then a subquery would get you what you need. + +``` +SELECT * FROM yourTable WHERE id IN (SELECT trans_id FROM yourTable WHERE code='B') + +```" +11012218,"I have the following mysql table. I have been trying to select all the rows which are related with the row that has `B` as value in the `code` column. The relation is based on the value of the column `trans_id` + +``` +id trans_id code amount side +1 1 A 200 left +2 1 B 200 right +3 2 J 100 right +4 2 C 100 right +5 2 B 200 left +6 3 A 630 right +7 3 K 630 left + +``` + +My Expected Result: + +``` + id trans_id code amount side + 1 1 A 200 left + 3 2 J 100 right + 4 2 C 100 right + +``` + +Could you please tell me what should be the mysql query to achieve this? + +Thanks :)",2012/06/13,"['https://Stackoverflow.com/questions/11012218', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1209690/']","The following query should return the results you want. This uses a select query to return results to the WHERE clause. + +``` +SELECT * FROM yourTable +WHERE trans_id IN ( + SELECT trans_id FROM yourTable WHERE code='B' +) +AND code!='B' + +```","Your question is unclear, but as far as I understand, you could use a self join like this: + +``` +select a.id, + a.trans_id, + a.code, + a.amount, + a.side + from table as a + inner join table as b on (a.id=b.trans_id and b.code='B'); + +``` + +This will return the row with table.id=2: + +``` +id trans_id code amount side +2 1 B 200 right + +```" +11012218,"I have the following mysql table. I have been trying to select all the rows which are related with the row that has `B` as value in the `code` column. The relation is based on the value of the column `trans_id` + +``` +id trans_id code amount side +1 1 A 200 left +2 1 B 200 right +3 2 J 100 right +4 2 C 100 right +5 2 B 200 left +6 3 A 630 right +7 3 K 630 left + +``` + +My Expected Result: + +``` + id trans_id code amount side + 1 1 A 200 left + 3 2 J 100 right + 4 2 C 100 right + +``` + +Could you please tell me what should be the mysql query to achieve this? + +Thanks :)",2012/06/13,"['https://Stackoverflow.com/questions/11012218', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1209690/']","The following query should return the results you want. This uses a select query to return results to the WHERE clause. + +``` +SELECT * FROM yourTable +WHERE trans_id IN ( + SELECT trans_id FROM yourTable WHERE code='B' +) +AND code!='B' + +```","``` +select + t1.* +from + table_name t1 + inner join table_name t2 on t1.trans_id = t2.trans_id +where + t2.code = 'B' and + t2.code <> t1.code + +```" +9544602,"graph.h + +``` +struct Edge { + int from; + int to; + int elabel; + unsigned int id; + Edge(): from(0), to(0), elabel(0), id(0) {}; +}; + +``` + +What is the difference between `vector` and `vector`? I know `vector` is an array storing `Edge` objects, but what is the `Edge*` object?",2012/03/03,"['https://Stackoverflow.com/questions/9544602', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/419284/']","The `Edge*` type is a pointer-to-edge. So a `vector` is a vector that stores pointers-to-edges. + +The vector itself doesn't store the objects, only pointers to those objects. This means in particular that the pointed-to objects don't get automatically deleted when the pointer's lifetime ends.",`Edge*` is a pointer to an `Edge`. [Read up on Pointers in C++.](http://www.cplusplus.com/doc/tutorial/pointers/) +2289288,"Say I'm cloning a repository that I always clone to `C:\working_copies\\\` and that the project has variables in it's `build.properties` that get filled in with ` ` (by me) everytime I clone the repo. + +Is there a way that I can fill in these values in the file automatically by placing some special value in the file (in ant it's something like `${base-dir}` or something like that) that would fill in these build.property values for me?",2010/02/18,"['https://Stackoverflow.com/questions/2289288', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/18149/']","From (hazy) memory, that was the tag used by SCCS back in the ""good old days"". Given that (to my knowledge), BitKeeper uses SCCS underneath, it could be BitKeeper.",It is usually something that is added automatically by the version control system. +2289288,"Say I'm cloning a repository that I always clone to `C:\working_copies\\\` and that the project has variables in it's `build.properties` that get filled in with ` ` (by me) everytime I clone the repo. + +Is there a way that I can fill in these values in the file automatically by placing some special value in the file (in ant it's something like `${base-dir}` or something like that) that would fill in these build.property values for me?",2010/02/18,"['https://Stackoverflow.com/questions/2289288', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/18149/']","`@(#)` is the character string used by the Unix `what` command to filter strings from binaries to list the components that were used to build that binary. For instance `what java` on AIX yields: + +``` +java: + 23 1.4 src/bos/usr/ccs/lib/libpthreads/init.c, libpth, bos520 8/19/99 12:20:14 + 61 1.14 src/bos/usr/ccs/lib/libc/__threads_init.c, libcthrd, bos520 7/11/00 12:04:14 + src/tools/sov/java.c, tool, asdev, 20081128 1.83.1.36 + src/misc/sov/copyrght.c, core, asdev, 20081128 1.8 + +``` + +while `strings java | grep '@(#)' yields: + +``` +@(#)23 1.4 src/bos/usr/ccs/lib/libpthreads/init.c, libpth, bos520 8/19/99 12:20:14 +@(#)61 1.14 src/bos/usr/ccs/lib/libc/__threads_init.c, libcthrd, bos520 7/11/00 12:04:14 +@(#)src/tools/sov/java.c, tool, asdev, 20081128 1.83.1.36 +@(#)src/misc/sov/copyrght.c, core, asdev, 20081128 1.8 + +``` + +`@(#)` was chosen as marker because it would not occur elsewhere, source code controls systems typically add a line containing this marker and the description of the file version on synchronisation, expanding keywords with values reflecting the file contents. +For instance, the comment you list would be the result of expanding the SCCS keywords `%Z% %M% %R%.%L% %E%` where the `%Z%` translates into `@(#)`.",It is usually something that is added automatically by the version control system. +2289288,"Say I'm cloning a repository that I always clone to `C:\working_copies\\\` and that the project has variables in it's `build.properties` that get filled in with ` ` (by me) everytime I clone the repo. + +Is there a way that I can fill in these values in the file automatically by placing some special value in the file (in ant it's something like `${base-dir}` or something like that) that would fill in these build.property values for me?",2010/02/18,"['https://Stackoverflow.com/questions/2289288', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/18149/']","From (hazy) memory, that was the tag used by SCCS back in the ""good old days"". Given that (to my knowledge), BitKeeper uses SCCS underneath, it could be BitKeeper.","That construct has no special meaning in Java. It is just some text in a comment. + +It looks like something that's inserted by a version control system." +2289288,"Say I'm cloning a repository that I always clone to `C:\working_copies\\\` and that the project has variables in it's `build.properties` that get filled in with ` ` (by me) everytime I clone the repo. + +Is there a way that I can fill in these values in the file automatically by placing some special value in the file (in ant it's something like `${base-dir}` or something like that) that would fill in these build.property values for me?",2010/02/18,"['https://Stackoverflow.com/questions/2289288', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/18149/']","`@(#)` is the character string used by the Unix `what` command to filter strings from binaries to list the components that were used to build that binary. For instance `what java` on AIX yields: + +``` +java: + 23 1.4 src/bos/usr/ccs/lib/libpthreads/init.c, libpth, bos520 8/19/99 12:20:14 + 61 1.14 src/bos/usr/ccs/lib/libc/__threads_init.c, libcthrd, bos520 7/11/00 12:04:14 + src/tools/sov/java.c, tool, asdev, 20081128 1.83.1.36 + src/misc/sov/copyrght.c, core, asdev, 20081128 1.8 + +``` + +while `strings java | grep '@(#)' yields: + +``` +@(#)23 1.4 src/bos/usr/ccs/lib/libpthreads/init.c, libpth, bos520 8/19/99 12:20:14 +@(#)61 1.14 src/bos/usr/ccs/lib/libc/__threads_init.c, libcthrd, bos520 7/11/00 12:04:14 +@(#)src/tools/sov/java.c, tool, asdev, 20081128 1.83.1.36 +@(#)src/misc/sov/copyrght.c, core, asdev, 20081128 1.8 + +``` + +`@(#)` was chosen as marker because it would not occur elsewhere, source code controls systems typically add a line containing this marker and the description of the file version on synchronisation, expanding keywords with values reflecting the file contents. +For instance, the comment you list would be the result of expanding the SCCS keywords `%Z% %M% %R%.%L% %E%` where the `%Z%` translates into `@(#)`.","That construct has no special meaning in Java. It is just some text in a comment. + +It looks like something that's inserted by a version control system." +2289288,"Say I'm cloning a repository that I always clone to `C:\working_copies\\\` and that the project has variables in it's `build.properties` that get filled in with ` ` (by me) everytime I clone the repo. + +Is there a way that I can fill in these values in the file automatically by placing some special value in the file (in ant it's something like `${base-dir}` or something like that) that would fill in these build.property values for me?",2010/02/18,"['https://Stackoverflow.com/questions/2289288', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/18149/']","`@(#)` is the character string used by the Unix `what` command to filter strings from binaries to list the components that were used to build that binary. For instance `what java` on AIX yields: + +``` +java: + 23 1.4 src/bos/usr/ccs/lib/libpthreads/init.c, libpth, bos520 8/19/99 12:20:14 + 61 1.14 src/bos/usr/ccs/lib/libc/__threads_init.c, libcthrd, bos520 7/11/00 12:04:14 + src/tools/sov/java.c, tool, asdev, 20081128 1.83.1.36 + src/misc/sov/copyrght.c, core, asdev, 20081128 1.8 + +``` + +while `strings java | grep '@(#)' yields: + +``` +@(#)23 1.4 src/bos/usr/ccs/lib/libpthreads/init.c, libpth, bos520 8/19/99 12:20:14 +@(#)61 1.14 src/bos/usr/ccs/lib/libc/__threads_init.c, libcthrd, bos520 7/11/00 12:04:14 +@(#)src/tools/sov/java.c, tool, asdev, 20081128 1.83.1.36 +@(#)src/misc/sov/copyrght.c, core, asdev, 20081128 1.8 + +``` + +`@(#)` was chosen as marker because it would not occur elsewhere, source code controls systems typically add a line containing this marker and the description of the file version on synchronisation, expanding keywords with values reflecting the file contents. +For instance, the comment you list would be the result of expanding the SCCS keywords `%Z% %M% %R%.%L% %E%` where the `%Z%` translates into `@(#)`.","From (hazy) memory, that was the tag used by SCCS back in the ""good old days"". Given that (to my knowledge), BitKeeper uses SCCS underneath, it could be BitKeeper." +52322097,"Say I was observing a variable + +`m.someObject.observeField(""content"", ""onContentChanged"")` + +after a certain period of time I no longer need `m.someObject`. +Do I need to cleanup and call + +`m.someObject.unobserveField(""content"")` + +or can I just leave it?",2018/09/13,"['https://Stackoverflow.com/questions/52322097', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5673746/']","Yes, try to follow this as a good practice, just like when dealing with files after `open()` should eventually call `close()` (even as, generally speaking going out of scope takes care of closing connections, it's a good practice to explicitly take care of it). + +Now, beware that `node.unobserveField(""X"")` is a ""nuclear"" option in that it drops *any and all* observers on node.X that were placed with `node.observeField(""X"", ...)`, regardless from what component or thread they came. So if having more than one observer per field, you may end up regretting and eventually avoiding unobserveField() use altogether. Mind you, when the `node` is destroyed, these observers will be taken care of (i.e. not a memory leak). + +Now, there is also a newer API that's better in many cases - the ""...Scoped()"" versions of these methods. In that version, the `node.unobserveFieldScoped(""X"")` is more selective - it only removes the observer(s) on node.X that were placed by the *current component*; observers set by other components remain active. + +For me it's easier to distinguish between these two approaches by thinking of *where* is the observer link stored. In the non-scoped versions, all links are stored with the observed object - and so the destructor takes care of cleaning the links. In the scoped versions, links are stored with each observING component - so Unobserve acts locally only on these. And so i believe there is a caveat - if observED object is destroyed, it will leave (temporarily) some hanging *scoped* links in observING objects. Conversely, if non-scoped ObserveField() was used, destruction of observING object will leave uncleaned link in the observED object (that will get cleaned when it gets droped).","Yeah, you should. Roku doesn't have the worlds greatest garbage collection and we've noticed considerable performance improvements from being careful about that." +11661,"or is there something else that is opposite or similar to it... + +From all the teachings i have received the rule I'd say is Islamic is do what's the best. Basically people change so labelling someone as sinner may make us overlook his/her good parts and overlook their change if it occurs. + +Please provide hadiths/Quran if possible",2014/03/06,"['https://islam.stackexchange.com/questions/11661', 'https://islam.stackexchange.com', 'https://islam.stackexchange.com/users/2948/']","“Hate the sin, not the sinner” is only partly correct in Islam. Only a sinner with sins wholly occupying his heart making his heart dark lacking any light spot survived in it is one we should hate and even curse against them, though, if we can identify them correctly. About any other sinner no we cannot hate himself, but we must hate the sin, and the majority of the sinners belong to this latter group. The former group are those who would be left in the hell eternally, the rest will be survived from the hell and let enter the heaven after centuries and maybe millenniums or more of being tortured in the hell. + +Those with completely dark hearts will never find the opportunity to repent in Dunya (world), they are Taqut (طاغوت: or leaders inviting to the Fire: أَئِمَّةً يَدْعُونَ إِلَى النَّارِ‌, Al-Qasas,41) against which Allah has ordered us to be Kafir about them. The others we should always have hope that they may repent, and we should help them so by enjoying them to what is right and banning them from what s wrong. + +> +> اللَّـهُ وَلِيُّ الَّذِينَ آمَنُوا يُخْرِ‌جُهُم مِّنَ الظُّلُمَاتِ +> إِلَى النُّورِ‌ ۖ وَالَّذِينَ كَفَرُ‌وا أَوْلِيَاؤُهُمُ الطَّاغُوتُ +> يُخْرِ‌جُونَهُم مِّنَ النُّورِ‌ إِلَى الظُّلُمَاتِ ۗ أُولَـٰئِكَ +> أَصْحَابُ النَّارِ‌ ۖ هُمْ فِيهَا خَالِدُونَ +> +> +> Allah is the ally of those who believe. He brings them out from +> darknesses into the light. And those who disbelieve - their allies are +> Taghut. They take them out of the light into darknesses. Those are the +> companions of the Fire; they will abide eternally therein. +> [Al-Baqareh, 257] +> +> +> + +Godspeed","It depends on the type of sin. + +Quran says there has already been for you an excellent pattern in Abraham. So this means that we should follow this pattern. He many times invited his people to monotheism by kindness. But they still insisted on Shirk and did not leave their idols and tried to kill prophet Ibrahim a.s. + +A Muslims should disassociate and have animosity and hatred about Mushrik people (those who worship other than Allah like idol, Satan...). But hating is some different. We can disassociate one but still love him for guidance. + +> +> There has already been for you an excellent pattern in Abraham and +> those with him, when they said to their people, ""Indeed, we are +> disassociated from you and from whatever you worship other than Allah. +> We have denied you, and there has appeared between us and you +> animosity and hatred forever until you believe in Allah alone"" except +> for the saying of Abraham to his father, ""I will surely ask +> forgiveness for you, but I have not [power to do] for you anything +> against Allah. Our Lord, upon You we have relied, and to You we have +> returned, and to You is the destination. +> +> +> + +Prophet Muhammad SAWW did so also. he invited people many times and many of them accepted but some still did not accept and tried to kill prophet and made wars like Badr, Uhod and other wars and tried to kill Muslims. so then prophet made around 100 wars against them (although himself did not participate in all of them directly). + +But it is important to distinguish between clear Shirk and Hidden Shirk. This applies only to clear Shirk. Because many of believers have hidden shirk: + +> +> And most of them believe not in Allah except while they associate +> others with Him. +> +> +> + +But a Muslim who believes in Allah but still is sinner is different. + +> +> There has certainly come to you a Messenger from among yourselves. +> Grievous to him is what you suffer; [he is] concerned over you and to +> the believers is kind and merciful. +> +> +> + +We should love and guide Muslims who are going astray and are sinner." +23010340,"How do you use **name** with a function that I'd like to pass a keyword argument through? + +For example, I have the following function: + +``` +def func(keyword1='A'): + print keyword1 + +``` + +I can do this: + +``` +func.__name__ +>> 'func' + +``` + +But, I'd like to do this: + +``` +func(keyword1='B').__name__ +>>> 'func' + +``` + +The reason I'd like to do this is because I have another method that takes in this function as an argument and it needs to pull the name of the function and run that function with different keywords. + +So, what I'm really trying to do is get this function to work: + +``` +def Function_Name_And_Result(x): + print x.__name__ + x() + +Function_Name_And_Result(func(keyword1='B')) +>> funcB + +```",2014/04/11,"['https://Stackoverflow.com/questions/23010340', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2850808/']","Python's functions are objects too, so you can pass them along just like any other object. What you're doing (which can't obviously work) is passing the result of calling the function. What you want is to pass the function and the function's argument: + +``` +def print_function_name_and_result(func, *args, **kw): + print ""%s : %s"" % (func.__name__, func(*args, **kw)) + +print_function_name_and_result(func, keyword1='B') +>> func : B + +```","If you have a method that takes a function, **then pass in the function**, not the return value. + +You are instead calling the function. The `.__name__` attribute lookup is applied to the return value of that call. If you are passing the *return value* of a function call to your method, you are **not** passing the function object itself. + +If you need to pass in a function that needs to be called with certain arguments *by the method*, you can pass in those extra arguments instead, and have the method use those arguments for you: + +``` +def Function_Name_And_Result(x, *args, **kw): + print x.__name__, x(*args, **kw) + +``` + +Now you can still pass in your function object *itself*: + +``` +Function_Name_And_Result(func, keyword1='B') + +``` + +Demo: + +``` +>>> def Function_Name_And_Result(x, *args, **kw): +... print x.__name__, x(*args, **kw) +... +>>> def func(keyword1='A'): +... print keyword1 +... +>>> Function_Name_And_Result(func, keyword1='B') +func B +None + +```" +44871,"I have a big share (~5TB) that is getting full. +Now I want to make a script that deletes data from 2 specified folders. But this need to be the oldest files/folders and it need to stop when ~50GB has been removed, so it won't delete all folders. + +**Edit:** This need to work with Samba shares for my Synology DS-409. The script need to run on the Synology in /etc/crontab. + +Somewhere else they gave me this code: + +``` + #!/opt/bin/bash +dir=/data/video +min_dirs=3 +full=60 +logfile=/var/tmp/removed.log + +df=`df | grep data | awk '{print $5}' | sed s/%//g` +if [ $df -gt $full ]; then + [[ $(find ""$dir"" -type d | wc -l) -ge $min_dirs ]] && + IFS= read -r -d $'\0' line < <(find ""$dir"" -printf '%T@ %p\0' 2>/dev/null | sort -z -n) + file=""${line#* }"" + ls -lLd ""$file"" + #rm -rf ""$file"" + date=`date` + if [ -f ""$file"" ]; then + echo ""$date $file could not be removed!"" >> $logfile + else + echo ""$date $file removed"" >> $logfile + fi +fi + +```",2012/08/06,"['https://unix.stackexchange.com/questions/44871', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/21697/']","This should work: + +``` +DIRS=""a/ b/"" +MAXDELBYTES=""53687091200"" # 50GB +DELBYTES=""0"" + +find $DIRS -type f -printf ""%T@ %s %p\n"" | sort -r -n | while read time bytes filename +do + rm -fv ""$filename"" + DELBYTES=$((DELBYTES + bytes)) + + if [ $DELBYTES -ge $MAXDELBYTES ]; then break; fi +done + +```","scai, autodelete.txt is a file i created in windows and uploaded to a linux share :) +Now i have made this code in nano because of windows linux code problems. + +But now it gives a bunch of error's + +``` +root ~/.config # sh autodelete +find: unrecognized: -printf +BusyBox v1.20.2 (2012-08-09 05:49:15 CEST) multi-call binary. + +Usage: find [PATH]... [OPTIONS] [ACTIONS] + +Search for files and perform actions on them. +First failed action stops processing of current file. +Defaults: PATH is current directory, action is '-print' + + -follow Follow symlinks + +Actions: + ! ACT Invert ACT's success/failure + ACT1 [-a] ACT2 If ACT1 fails, stop, else do ACT2 + ACT1 -o ACT2 If ACT1 succeeds, stop, else do ACT2 + Note: -a has higher priority than -o + -name PATTERN Match file name (w/o directory name) to PATTERN + -iname PATTERN Case insensitive -name + -path PATTERN Match path to PATTERN + -ipath PATTERN Case insensitive -path + -type X File type is X (one of: f,d,l,b,c,...) + -links N Number of links is greater than (+N), less than (-N), + or exactly N +If none of the following actions is specified, -print is assumed + -print Print file name + -exec CMD ARG ; Run CMD with all instances of {} replaced by + file name. Fails if CMD exits with nonzero + +autodelete: line 11: bytes: not found + +```" +282604,"I have two tables. Each holds some attributes for a business entity and the date range for which those attributes were valid. I want to combine these tables into one, matching rows on the common business key and splitting the time ranges. + +The real-world example is two source temporal tables feeding a type-2 dimension table in the data warehouse. + +The entity can be present in neither, one or both of the source systems at any point in time. Once an entity is recorded in a source system the intervals are well-behaved - no gaps, duplicates or other monkey business. Membership in the sources can end at different dates. + +The business rules state we only want to return intervals where the entity is present in both sources simultaneously. + +What query will give this result? + +This illustrates the situation: + +``` +Month J F M A M J J +Source A: <--><----------><----------><----> +Source B: <----><----><----------------><--> + +Result: <----><----><----><----> + +``` + +Sample Data +----------- + +For simplicity I've used closed date intervals; likely any solution could be extended to half-open intervals with a little typing. + +``` +drop table if exists dbo.SourceA; +drop table if exists dbo.SourceB; +go + +create table dbo.SourceA +( + BusinessKey int, + StartDate date, + EndDate date, + Attribute char(9) +); + +create table dbo.SourceB +( + BusinessKey int, + StartDate date, + EndDate date, + Attribute char(9) +); +GO + +insert dbo.SourceA(BusinessKey, StartDate, EndDate, Attribute) +values + (1, '19990101', '19990113', 'black'), + (1, '19990114', '19990313', 'red'), + (1, '19990314', '19990513', 'blue'), + (1, '19990514', '19990613', 'green'), + (2, '20110714', '20110913', 'pink'), + (2, '20110914', '20111113', 'white'), + (2, '20111114', '20111213', 'gray'); + +insert dbo.SourceB(BusinessKey, StartDate, EndDate, Attribute) +values + (1, '19990214', '19990313', 'left'), + (1, '19990314', '19990413', 'right'), + (1, '19990414', '19990713', 'centre'), + (1, '19990714', '19990730', 'back'), + (2, '20110814', '20110913', 'top'), + (2, '20110914', '20111013', 'middle'), + (2, '20111014', '20120113', 'bottom'); + +``` + +Desired output +-------------- + +``` +BusinessKey StartDate EndDate a_Colour b_Placement +----------- ---------- ---------- --------- ----------- +1 1999-02-14 1999-03-13 red left +1 1999-03-14 1999-04-13 blue right +1 1999-04-14 1999-05-13 blue centre +1 1999-05-14 1999-06-13 green centre +2 2011-08-14 2011-09-13 pink top +2 2011-09-14 2011-10-13 white middle +2 2011-10-14 2011-11-13 white bottom +2 2011-11-14 2011-12-13 gray bottom + +```",2021/01/05,"['https://dba.stackexchange.com/questions/282604', 'https://dba.stackexchange.com', 'https://dba.stackexchange.com/users/36809/']","I may have misunderstood your question, but the results seem to be according to your question: + +``` +select a.businesskey + -- greatest(a.startdate, b.startdate) + , case when a.startdate > b.startdate + then a.startdate + else b.startdate + end as startdate + -- least(a.enddate, b.enddate) + , case when a.enddate < b.enddate + then a.enddate + else b.enddate + end as enddate + , a.attribute as a_color + , b.attribute as b_placement +from dbo.SourceA a +join dbo.SourceB b + on a.businesskey = b.businesskey + and (a.startdate between b.startdate and b.enddate + or b.startdate between a.startdate and a.enddate) +order by 1,2 + +``` + +Since intervals need to overlap most of the work can be done with a join with that as the predicate. Then it's just a matter of choosing the intersection of the intervals. + +LEAST and GREATEST seem to be missing as functions, so I used a case expression instead. + +[Fiddle](https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=5cf15423456c3e879560cb0df46948c5)","This solution deconstructs the source intervals to just their starting dates. By combining these two list a set of output interval start dates are obtained. From these the corresponding output end dates are calculated by a window function. As the final output interval must end when either of the two input intervals end there is special processing to determine this value. + +``` +;with Dates as +( + select BusinessKey, StartDate + from dbo.SourceA + + union + + select BusinessKey, StartDate + from dbo.SourceB + + union + + select x.BusinessKey, DATEADD(DAY, 1, MIN(x.EndDate)) + from + ( + select BusinessKey, EndDate = MAX(EndDate) + from dbo.SourceA + group by BusinessKey + + union all + + select BusinessKey, EndDate = MAX(EndDate) + from dbo.SourceB + group by BusinessKey + ) as x + group by x.BusinessKey +), +Intervals as +( + select + dt.BusinessKey, + dt.StartDate, + EndDate = lead (DATEADD(DAY, -1, dt.StartDate), 1) + over (partition by dt.BusinessKey order by dt.StartDate) + from Dates as dt +) +select + i.BusinessKey, + i.StartDate, + i.EndDate, + a_Colour = a.Attribute, + b_Placement = b.Attribute +from Intervals as i +inner join dbo.SourceA as a + on i.BusinessKey = a.BusinessKey + and i.StartDate between a.StartDate and a.EndDate +inner join dbo.SourceB as b + on i.BusinessKey = b.BusinessKey + and i.StartDate between b.StartDate and b.EndDate +where i.EndDate is not NULL +order by + i.BusinessKey, + i.StartDate; + +``` + +The ""Dates"" CTE uses UNION rather than UNION ALL to eliminate duplicates. If both sources change on the same date we want only one corresponding output row. + +As we want to close output when either source closes the third query in ""Dates"" adds the earliest end date i.e. the MIN of the MAX of EndDates. As it is an EndDate masquerading as a StartDate it must have another day added to it. It's purpose is to allow the window function to calculate the end of the preceding interval. It will be eliminated in the final predicate. + +Using inner joins for the final query eliminates those source intervals for which there is no corresponding value in the other source." +282604,"I have two tables. Each holds some attributes for a business entity and the date range for which those attributes were valid. I want to combine these tables into one, matching rows on the common business key and splitting the time ranges. + +The real-world example is two source temporal tables feeding a type-2 dimension table in the data warehouse. + +The entity can be present in neither, one or both of the source systems at any point in time. Once an entity is recorded in a source system the intervals are well-behaved - no gaps, duplicates or other monkey business. Membership in the sources can end at different dates. + +The business rules state we only want to return intervals where the entity is present in both sources simultaneously. + +What query will give this result? + +This illustrates the situation: + +``` +Month J F M A M J J +Source A: <--><----------><----------><----> +Source B: <----><----><----------------><--> + +Result: <----><----><----><----> + +``` + +Sample Data +----------- + +For simplicity I've used closed date intervals; likely any solution could be extended to half-open intervals with a little typing. + +``` +drop table if exists dbo.SourceA; +drop table if exists dbo.SourceB; +go + +create table dbo.SourceA +( + BusinessKey int, + StartDate date, + EndDate date, + Attribute char(9) +); + +create table dbo.SourceB +( + BusinessKey int, + StartDate date, + EndDate date, + Attribute char(9) +); +GO + +insert dbo.SourceA(BusinessKey, StartDate, EndDate, Attribute) +values + (1, '19990101', '19990113', 'black'), + (1, '19990114', '19990313', 'red'), + (1, '19990314', '19990513', 'blue'), + (1, '19990514', '19990613', 'green'), + (2, '20110714', '20110913', 'pink'), + (2, '20110914', '20111113', 'white'), + (2, '20111114', '20111213', 'gray'); + +insert dbo.SourceB(BusinessKey, StartDate, EndDate, Attribute) +values + (1, '19990214', '19990313', 'left'), + (1, '19990314', '19990413', 'right'), + (1, '19990414', '19990713', 'centre'), + (1, '19990714', '19990730', 'back'), + (2, '20110814', '20110913', 'top'), + (2, '20110914', '20111013', 'middle'), + (2, '20111014', '20120113', 'bottom'); + +``` + +Desired output +-------------- + +``` +BusinessKey StartDate EndDate a_Colour b_Placement +----------- ---------- ---------- --------- ----------- +1 1999-02-14 1999-03-13 red left +1 1999-03-14 1999-04-13 blue right +1 1999-04-14 1999-05-13 blue centre +1 1999-05-14 1999-06-13 green centre +2 2011-08-14 2011-09-13 pink top +2 2011-09-14 2011-10-13 white middle +2 2011-10-14 2011-11-13 white bottom +2 2011-11-14 2011-12-13 gray bottom + +```",2021/01/05,"['https://dba.stackexchange.com/questions/282604', 'https://dba.stackexchange.com', 'https://dba.stackexchange.com/users/36809/']","I may have misunderstood your question, but the results seem to be according to your question: + +``` +select a.businesskey + -- greatest(a.startdate, b.startdate) + , case when a.startdate > b.startdate + then a.startdate + else b.startdate + end as startdate + -- least(a.enddate, b.enddate) + , case when a.enddate < b.enddate + then a.enddate + else b.enddate + end as enddate + , a.attribute as a_color + , b.attribute as b_placement +from dbo.SourceA a +join dbo.SourceB b + on a.businesskey = b.businesskey + and (a.startdate between b.startdate and b.enddate + or b.startdate between a.startdate and a.enddate) +order by 1,2 + +``` + +Since intervals need to overlap most of the work can be done with a join with that as the predicate. Then it's just a matter of choosing the intersection of the intervals. + +LEAST and GREATEST seem to be missing as functions, so I used a case expression instead. + +[Fiddle](https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=5cf15423456c3e879560cb0df46948c5)","There are a lot of interesting solutions to this problem (stated in different terms) [here](https://sqlperformance.com/2022/03/t-sql-queries/supply-demand-solutions-3) and its preceding pages. There it is presented as matching supply and demand in an auction. The units supplied/demanded is directly analogous to the days in an interval from this question so the solution translates. I've left it in the terms used in the linked site, though. + +Sample data. + +``` +DROP TABLE IF EXISTS dbo.Auctions; + +CREATE TABLE dbo.Auctions +( + ID INT NOT NULL IDENTITY(1, 1) + CONSTRAINT pk_Auctions PRIMARY KEY CLUSTERED, + Code CHAR(1) NOT NULL + CONSTRAINT ck_Auctions_Code CHECK (Code = 'D' OR Code = 'S'), + Quantity DECIMAL(19, 6) NOT NULL + CONSTRAINT ck_Auctions_Quantity CHECK (Quantity > 0) +); + +SET NOCOUNT ON; + +DELETE FROM dbo.Auctions; + +SET IDENTITY_INSERT dbo.Auctions ON; + +INSERT INTO dbo.Auctions(ID, Code, Quantity) VALUES + (1, 'D', 5.0), + (2, 'D', 3.0), + (3, 'D', 8.0), + (5, 'D', 2.0), + (6, 'D', 8.0), + (7, 'D', 4.0), + (8, 'D', 2.0), + (1000, 'S', 8.0), + (2000, 'S', 6.0), + (3000, 'S', 2.0), + (4000, 'S', 2.0), + (5000, 'S', 4.0), + (6000, 'S', 3.0), + (7000, 'S', 2.0); + +``` + +The solutions expounded reduce the elapsed time for his 400k row sample data from a naive 11 seconds to 0.4s. The fastest is by Paul White (of this parish), shown here. + +``` +DROP TABLE IF EXISTS #MyPairings; + +CREATE TABLE #MyPairings +( + DemandID integer NOT NULL, + SupplyID integer NOT NULL, + TradeQuantity decimal(19, 6) NOT NULL +); +GO + +INSERT #MyPairings + WITH (TABLOCK) +( + DemandID, + SupplyID, + TradeQuantity +) +SELECT + Q3.DemandID, + Q3.SupplyID, + Q3.TradeQuantity +FROM +( + SELECT + Q2.DemandID, + Q2.SupplyID, + TradeQuantity = + -- Interval overlap + CASE + WHEN Q2.Code = 'S' THEN + CASE + WHEN Q2.CumDemand >= Q2.IntEnd THEN Q2.IntLength + WHEN Q2.CumDemand > Q2.IntStart THEN Q2.CumDemand - Q2.IntStart + ELSE 0.0 + END + WHEN Q2.Code = 'D' THEN + CASE + WHEN Q2.CumSupply >= Q2.IntEnd THEN Q2.IntLength + WHEN Q2.CumSupply > Q2.IntStart THEN Q2.CumSupply - Q2.IntStart + ELSE 0.0 + END + END + FROM + ( + SELECT + Q1.Code, + Q1.IntStart, + Q1.IntEnd, + Q1.IntLength, + DemandID = MAX(IIF(Q1.Code = 'D', Q1.ID, 0)) OVER ( + ORDER BY Q1.IntStart, Q1.ID + ROWS UNBOUNDED PRECEDING), + SupplyID = MAX(IIF(Q1.Code = 'S', Q1.ID, 0)) OVER ( + ORDER BY Q1.IntStart, Q1.ID + ROWS UNBOUNDED PRECEDING), + CumSupply = SUM(IIF(Q1.Code = 'S', Q1.IntLength, 0)) OVER ( + ORDER BY Q1.IntStart, Q1.ID + ROWS UNBOUNDED PRECEDING), + CumDemand = SUM(IIF(Q1.Code = 'D', Q1.IntLength, 0)) OVER ( + ORDER BY Q1.IntStart, Q1.ID + ROWS UNBOUNDED PRECEDING) + FROM + ( + -- Demand intervals + SELECT + A.ID, + A.Code, + IntStart = SUM(A.Quantity) OVER ( + ORDER BY A.ID + ROWS UNBOUNDED PRECEDING) - A.Quantity, + IntEnd = SUM(A.Quantity) OVER ( + ORDER BY A.ID + ROWS UNBOUNDED PRECEDING), + IntLength = A.Quantity + FROM dbo.Auctions AS A + WHERE + A.Code = 'D' + + UNION ALL + + -- Supply intervals + SELECT + A.ID, + A.Code, + IntStart = SUM(A.Quantity) OVER ( + ORDER BY A.ID + ROWS UNBOUNDED PRECEDING) - A.Quantity, + IntEnd = SUM(A.Quantity) OVER ( + ORDER BY A.ID + ROWS UNBOUNDED PRECEDING), + IntLength = A.Quantity + FROM dbo.Auctions AS A + WHERE + A.Code = 'S' + ) AS Q1 + ) AS Q2 +) AS Q3 +WHERE + Q3.TradeQuantity > 0; + +```" +34015595,"For some unfathomable reason Google decided to add Splash Screens (Launch Screen) to their design guidelines, I know that, + +**1. Splash screen is better than staring at an empty screen.** + +................ [ Inflating the main layout and showing a UI without any dynamic data should be very fast. If that's not the case in your app you should fix it by making it fast to load instead of adding a splash screen that will then guarantee that your app is always launching slow.] + +**2. Splash screen is better than not having any information if the app is launching other than the launcher button getting pressed.** + +**3.app's data takes a long time to load. A splash screen is better than a loading indicator. This especially with slow internet speeds.** + +**All these problems , But splash Screen Is not only Single solution I think, It also have some Cons Like:** + +1. If you show your app's UI to the user first and then load the data into it you allow user to orient to the UI and they're immediately ready to go when the data comes in. +2. Users don't always want to interact with the data on the app's landing screen. Let the user get on with their task without forcing them to load the first screen's data. This is very important especially on a slow internet connection. Let user interact with your app while the data is loading. In many cases they might not care about the data you're loading by default. + +\*\*\*\*\*\*\*\*\*\* Friends,**I am using \*\*UBER App** & even only I want to see my **""Promo code""** To share with friend I need to Open app & Its take lots of time to open and for that much time I stuck on Splash screen & If there is no internet connection then app Stuck on startup I can't even read my **""Promo Code""** + +So, My question is that , **can we avoid splash screen there is another alternative?** **Its really needed & useful?** **Why cant we think about any other innovative Concept?**",2015/12/01,"['https://Stackoverflow.com/questions/34015595', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5021501/']","Sanket, splash screens also allow for the app itself to load. some apps like facebook are not actually apps but the normal website for mobile phones... made into its own special browser for only that website. thus, the app itself must load even its menus, which have icons and all on them. splash screens definitely would be great for those apps, though, other apps such as a non-website app..IE, something that loads locally then connects to the internet to update and cache data would totally be usable without a splash screen. you could straight up display or open the app to a menu and show a loading wheel on the menu options that aren't fully loaded yet. instead of a splash screen, you could also show terms and conditions of your app so users can go ahead and agree to them if they are required (such as apps that require use of an online service.)",Just display a dialog about you app updates or If ur app contains login functionality just use login using dialog.I think it may be an best alternative for splash. +24226385,"How can I get the next word after pregmatch with PHP. + +For example, If I have a string like this: + +``` +""This is a string, keyword next, some more text. keyword next-word."" + +``` + +I want to use a `preg_match` to get the next word after “keyword”, including if the word is hyphenated. + +So in the case above, I want to return “next” and ”next-word” + +I’ve tried : + +``` +$string = ""This is a string, keyword next, some more text. keyword next-word.""; + +$keywords = preg_split(""/(?<=\keyword\s)(\w+)/"", $string); +print_r($keywords); + +``` + +Which just returns everything and doesn’t seem to work at all. + +Any help is much appreciated.",2014/06/15,"['https://Stackoverflow.com/questions/24226385', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3143218/']","Using your example this should work using [`preg_match_all`](http://www.php.net/manual/en/function.preg-match-all.php): + +``` +// Set the test string. +$string = ""This is a string, keyword next, some more text. keyword next-word. keyword another_word. Okay, keyword do-rae-mi-fa_so_la.""; + +// Set the regex. +$regex = '/(?<=\bkeyword\s)(?:[\w-]+)/is'; + +// Run the regex with preg_match_all. +preg_match_all($regex, $string, $matches); + +// Dump the resulst for testing. +echo '
';
+print_r($matches);
+echo '
'; + +``` + +And the results I get are: + +``` +Array +( + [0] => Array + ( + [0] => next + [1] => next-word + [2] => another_word + [3] => do-rae-mi-fa_so_la + ) + +) + +```","Positive look behind is what you are looking for: + +``` +(?<=\bkeyword\s)([a-zA-Z-]+) + +``` + +Should work perfect with `preg_match`. Use `g` modifier to catch all matches. + +[Demo](http://regex101.com/r/nB9rU1) + +Reference Question: [How to match the first word after an expression with regex?](https://stackoverflow.com/questions/546220/how-to-match-the-first-word-after-an-expression-with-regex)" +24226385,"How can I get the next word after pregmatch with PHP. + +For example, If I have a string like this: + +``` +""This is a string, keyword next, some more text. keyword next-word."" + +``` + +I want to use a `preg_match` to get the next word after “keyword”, including if the word is hyphenated. + +So in the case above, I want to return “next” and ”next-word” + +I’ve tried : + +``` +$string = ""This is a string, keyword next, some more text. keyword next-word.""; + +$keywords = preg_split(""/(?<=\keyword\s)(\w+)/"", $string); +print_r($keywords); + +``` + +Which just returns everything and doesn’t seem to work at all. + +Any help is much appreciated.",2014/06/15,"['https://Stackoverflow.com/questions/24226385', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3143218/']","Using your example this should work using [`preg_match_all`](http://www.php.net/manual/en/function.preg-match-all.php): + +``` +// Set the test string. +$string = ""This is a string, keyword next, some more text. keyword next-word. keyword another_word. Okay, keyword do-rae-mi-fa_so_la.""; + +// Set the regex. +$regex = '/(?<=\bkeyword\s)(?:[\w-]+)/is'; + +// Run the regex with preg_match_all. +preg_match_all($regex, $string, $matches); + +// Dump the resulst for testing. +echo '
';
+print_r($matches);
+echo '
'; + +``` + +And the results I get are: + +``` +Array +( + [0] => Array + ( + [0] => next + [1] => next-word + [2] => another_word + [3] => do-rae-mi-fa_so_la + ) + +) + +```","While regex is powerful, it's also for most of us hard to debug and memorize. + +On this particular case, **Get next word after ... match with PHP**, which is a very common string operation. + +Simply, by exploding the string in an array, and searching the index. This is useful because we can specify how much words forward or backward. + +This match the first occurrence + `1 word`: + +``` +setWordWrap(true); +usernameLabel->setText(""Username""); +mainlogin->addWidget(usernameLabel, 0, 0); + +QComboBox *usernameLineEdit = new QComboBox; +usernameLineEdit->setEditable(true); +usernameLabel->setBuddy(usernameLineEdit); +mainlogin->addWidget(usernameLineEdit, 0, 1); + +QLabel *capslockShow = new QLabel; +capslockShow->setWordWrap(true); +capslockShow->setText("" ""); +mainlogin->addWidget(capslockShow, 1, 1); + +QLabel *passwordLabel = new QLabel; +passwordLabel->setWordWrap(true); +passwordLabel->setText(""Password""); +mainlogin->addWidget(passwordLabel, 2, 0); +QLineEdit *passwordLineEdit = new QLineEdit; +passwordLineEdit->setEchoMode(QLineEdit::Password); +QAction *myAction = passwordLineEdit->addAction(QIcon("":/eyeOff.png""), QLineEdit::TrailingPosition); +passwordLabel->setBuddy(passwordLineEdit); +mainlogin->addWidget(passwordLineEdit, 2, 1); + +``` + +What should I do next? Pls help me with code snippet.",2018/07/05,"['https://Stackoverflow.com/questions/51192832', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4196709/']","The solution is to add a `QAction` to the `QLineEdit`, this will create a `QToolButton` that we can obtain from the `associatedWidgets()` (it will be the second widget since the first one is the one associated with `clearButton`). Already having the `QToolButton` you must use the `pressed` and `released` signal. + +**passwordlineedit.h** + +``` +#ifndef PASSWORDLINEEDIT_H +#define PASSWORDLINEEDIT_H + +#include +#include +#include + +class PasswordLineEdit: public QLineEdit +{ +public: + PasswordLineEdit(QWidget *parent=nullptr); +private slots: + void onPressed(); + void onReleased(); +protected: + void enterEvent(QEvent *event); + void leaveEvent(QEvent *event); + void focusInEvent(QFocusEvent *event); + void focusOutEvent(QFocusEvent *event); +private: + QToolButton *button; +}; + +#endif // PASSWORDLINEEDIT_H + +``` + +**passwordlineedit.cpp** + +``` +#include ""passwordlineedit.h"" + +PasswordLineEdit::PasswordLineEdit(QWidget *parent): + QLineEdit(parent) +{ + setEchoMode(QLineEdit::Password); + QAction *action = addAction(QIcon("":/eyeOff""), QLineEdit::TrailingPosition); + button = qobject_cast(action->associatedWidgets().last()); + button->hide(); + button->setCursor(QCursor(Qt::PointingHandCursor)); + connect(button, &QToolButton::pressed, this, &PasswordLineEdit::onPressed); + connect(button, &QToolButton::released, this, &PasswordLineEdit::onReleased); +} + +void PasswordLineEdit::onPressed(){ + QToolButton *button = qobject_cast(sender()); + button->setIcon(QIcon("":/eyeOn"")); + setEchoMode(QLineEdit::Normal); +} + +void PasswordLineEdit::onReleased(){ + QToolButton *button = qobject_cast(sender()); + button->setIcon(QIcon("":/eyeOff"")); + setEchoMode(QLineEdit::Password); +} + +void PasswordLineEdit::enterEvent(QEvent *event){ + button->show(); + QLineEdit::enterEvent(event); +} + +void PasswordLineEdit::leaveEvent(QEvent *event){ + button->hide(); + QLineEdit::leaveEvent(event); +} + +void PasswordLineEdit::focusInEvent(QFocusEvent *event){ + button->show(); + QLineEdit::focusInEvent(event); +} + +void PasswordLineEdit::focusOutEvent(QFocusEvent *event){ + button->hide(); + QLineEdit::focusOutEvent(event); +} + +``` + +The complete example can be downloaded from the following [link](https://github.com/eyllanesc/stackoverflow/tree/master/questions/51192832).","Rather than trying to make use of the `QAction` returned by `QLineEdit::addAction` you could probably use a [`QWidgetAction`](http://doc.qt.io/qt-5/qwidgetaction.html) for this when combined with a suitable event filter... + +``` +class eye_spy: public QWidgetAction { + using super = QWidgetAction; +public: + explicit eye_spy (QLineEdit *control, QWidget *parent = nullptr) + : super(parent) + , m_control(control) + , m_on("":/eyeOn"") + , m_off("":/eyeOff"") + , m_pixmap_size(50, 50) + { + m_label.setScaledContents(true); + m_control->setEchoMode(QLineEdit::Password); + m_label.setPixmap(m_off.pixmap(m_pixmap_size)); + m_label.installEventFilter(this); + setDefaultWidget(&m_label); + } +protected: + virtual bool eventFilter (QObject *obj, QEvent *event) override + { + if (event->type() == QEvent::MouseButtonPress) { + m_control->setEchoMode(QLineEdit::Normal); + m_label.setPixmap(m_on.pixmap(m_pixmap_size)); + } else if (event->type() == QEvent::MouseButtonRelease) { + m_control->setEchoMode(QLineEdit::Password); + m_label.setPixmap(m_off.pixmap(m_pixmap_size)); + } + return(super::eventFilter(obj, event)); + } +private: + QLineEdit *m_control; + QLabel m_label; + QIcon m_on; + QIcon m_off; + QSize m_pixmap_size; +}; + +``` + +Now, rather than... + +``` +QAction *myAction = passwordLineEdit->addAction(QIcon("":/eyeOff.png""), QLineEdit::TrailingPosition); + +``` + +Use... + +``` +eye_spy eye_spy(passwordLineEdit); +passwordLineEdit->addAction(&eye_spy, QLineEdit::TrailingPosition); + +``` + +Seems to provide the desired behaviour." +284228,"In my modern SharePoint, I have a simple webpart and there's scenerio where to allow user to choose colour from custom properties pane configuration. + +it can be colour picker + +[![enter image description here](https://i.stack.imgur.com/lSoht.png)](https://i.stack.imgur.com/lSoht.png) + +or as simple as dropdown options with the background colour. + +[![enter image description here](https://i.stack.imgur.com/xHT4y.png)](https://i.stack.imgur.com/xHT4y.png) + +How to achieve this in client-webpart?",2020/08/28,"['https://sharepoint.stackexchange.com/questions/284228', 'https://sharepoint.stackexchange.com', 'https://sharepoint.stackexchange.com/users/92501/']","If you are implementing SPFx you can use PnP controls color picker in prperty pane to allow user select the color value. It's easier to implement than creating custom one. +[PnP Color Picker](https://pnp.github.io/sp-dev-fx-property-controls/controls/PropertyFieldColorPicker/) + +[![color picker](https://i.stack.imgur.com/h25sN.png)](https://i.stack.imgur.com/h25sN.png)","[![enter image description here](https://i.stack.imgur.com/3v9s8.gif)](https://i.stack.imgur.com/3v9s8.gif) +Main code: + +``` +import * as React from 'react'; +import * as ReactDom from 'react-dom'; +import { Version } from '@microsoft/sp-core-library'; +import { + IPropertyPaneConfiguration, + PropertyPaneTextField, + PropertyPaneDropdown +} from '@microsoft/sp-property-pane'; +import { BaseClientSideWebPart } from '@microsoft/sp-webpart-base'; + +import * as strings from 'ReactSpfxWebPartStrings'; +import ReactSpfx from './components/ReactSpfx'; +import { IReactSpfxProps } from './components/IReactSpfxProps'; + +export interface IReactSpfxWebPartProps { + description: string; + bgcolor:Array; + selectedColor:string; +} + +export default class ReactSpfxWebPart extends BaseClientSideWebPart { + + public render(): void { + const element: React.ReactElement = React.createElement( + ReactSpfx, + { + description: this.properties.description, + bgcolor:this.properties.bgcolor, + selectedColor:this.properties.selectedColor + } + ); + console.log(this.properties.bgcolor) + ReactDom.render(element, this.domElement); + } + + protected onDispose(): void { + ReactDom.unmountComponentAtNode(this.domElement); + } + + protected get dataVersion(): Version { + return Version.parse('1.0'); + } + protected onPropertyPaneFieldChanged(propertyPath: string, oldValue: any, newValue: any): void { + if (propertyPath === 'BGcolor' && newValue) { + this.properties.selectedColor=newValue; + // push new list value + super.onPropertyPaneFieldChanged(propertyPath, oldValue, newValue); + // refresh the item selector control by repainting the property pane + this.context.propertyPane.refresh(); + // re-render the web part as clearing the loading indicator removes the web part body + this.render(); + } + else { + super.onPropertyPaneFieldChanged(propertyPath, oldValue, oldValue); + } + } + protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration { + return { + pages: [ + { + header: { + description: strings.PropertyPaneDescription, + + }, + groups: [ + { + groupName: strings.BasicGroupName, + groupFields: [ + PropertyPaneTextField('description', { + label: strings.DescriptionFieldLabel, + + }), + PropertyPaneDropdown('BGcolor', { + label:'BGcolor', + selectedKey:""red"", + options: this.properties.bgcolor + + }) + ] + } + ] + } + ] + }; + } +} + +``` + +You could get the full project here:" +46810,"I'm buying a train ticket on the long-distance Amtrak Empire Builder train that runs Chicago-Milwaukee-...-St. Paul-... + +I'm traveling from Milwaukee to St. Paul. All the saver tickets are sold out. Value tickets are sold out for Milwaukee-St. Paul, but not for Chicago-St. Paul. This means it cheaper to buy a ticket from Chicago and just get on the train at it's second stop in Milwaukee. + +I found this similar question [Can you get on an Amtrak train at a later station?](https://travel.stackexchange.com/questions/35960/can-you-get-on-an-amtrak-train-at-a-later-station/35979#35979), which notes I need to change my ticket after purchase. It doesn't address the possibility of a fare increase, is there a possibility that Amtrak would charge me extra and make me change my Chicago-Milwaukee-Minneapolis value ticket into a Milwaukee-St Paul flexible ticket?",2015/04/27,"['https://travel.stackexchange.com/questions/46810', 'https://travel.stackexchange.com', 'https://travel.stackexchange.com/users/20576/']","I asked a similar question to an Amtrak agent a few days ago. Here's what he told me: + +Officially, your ticket gets treated as a ""no-show"" and is ""subject to automatic cancellation"" if you haven't boarded the train within two hours of the originally-scheduled departure time at your ticketed station. + +He said that if you're traveling without checked baggage & printed your own ticket, it's ""very unlikely"" anyone would give you any problems as long as you were on board within that two hour window of time. + +If the train is running late, or you have checked baggage, things get more complicated & uncertain. Apparently, staff have a tiny bit of discretion to relax an official policy, and almost unlimited discretion to rigidly ENFORCE an official policy. So, if your train is scheduled to depart from Chicago at noon, and Milwaukee at 1:45, but gets delayed and doesn't arrive in Milwaukee until 2:05, you COULD be denied boarding if someone wanted to be mean, but it's unlikely to happen unless you give them an excuse to SAY ""no"". If you're on board the train, have a valid ticket, and it's within 2 hours of the train's actual departure from Chicago, it's almost *inconceivable* that they'd make you get off the train at the next station & leave you stranded. But if you showed up at the station in Milwaukee 4 minutes before departure with checked baggage & needed to have them print your ticket, they COULD refuse, and management would back them up (possibly giving you a retroactive credit for future travel if you got lucky, but nevertheless leaving you in a world of hurt at that particular moment). + +Another issue: if you DO need to check baggage, they probably WON'T tag it for the earlier station on the return trip. They won't do anything to prevent YOU from getting off the train before your official stop, but any checked baggage will probably be going to your official ticketed destination whether you like it or not. That's not to say you might not get lucky... but if they refused to pull your bags in Milwaukee, or refused to tag them at check-in FOR Milwaukee, they'd be entirely within their discretion, and you'd be out of luck.","Amtrak terms and conditions state that if you fail to board your train as booked your entire reservation is subject to cancellation + +It's one of the first things detailed on the conditions of carriage page here. + + + +If discovered that you boarded at the wrong station the conductor at the very least might ask you to pay the difference in fare, and possibly be forced purchase a whole new ticket. + +You ask about changing your ticket. + +All saver fares are non refundable, so you can't change the booking, however if cancelled in advance they will issue you an e voucher for the value of the fare. Value fares also have conditions about cancellation and refunds + + + +You would then need to purchace a whole new ticket, and if the saver or value fares have already sold out then you will be forced to buy a full fare ticket" +55715000,"I'm creating an application, which interacts with OpenGL via *QOpenGL\** classes. The graphics is shown through a *QOpenGLWidget*, which is placed in a UI-form. + +Now, there is a library for CAD purposes ([Open CASCADE](https://www.opencascade.com)), an OpenGL interface of which requires a handle to the render window. The question is: can I somehow say the library to render everything to the mentioned widget? + +In other words, is there a way to interpret the widget as a native, probably, platform-specific (HWND here) window, so that the library renders its own stuff exactly there? + +Thanks",2019/04/16,"['https://Stackoverflow.com/questions/55715000', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4886665/']","**QOpenGLWidget** is not the same thing as **QGLWidget**. + +The classical approach for embedding OCCT 3D viewer, which you can find in Qt IESample coming with OCCT, creates QWidget with unique window handle flag, takes this window handle and ask OCCT to take care about OpenGL context creation for this window. This is most straightforward, robust and portable way with one limitation - Qt will not be able drawing semitransparent widgets on top of this QWidget. This is not a limitation of OCCT, but rather limitation of Qt Widgets design. + +**QOpenGLWidget** was intended to solve this limitation by allowing to mix custom OpenGL rendering and normal widgets. The integration of external OpenGL graphics engine, however, became more complicated and fragile. It is not very helpful stealing winId() from QOpenGLWidget, as rendering content is expected to be drawn not into window itself, but rather into OpenGL framebufer object (FBO), created by QOpenGLWidget - see **QOpenGLWidget::defaultFramebufferObject()** property. + +External renderer is expected to render into this FBO for proper composition of Qt widgets. Luckily, OCCT is flexible enough to allow such integration. Unluckily, such integration requires some knowledge of OpenGL, as well as its usage by Qt and OCCT. +For that, you need to ask OCCT wrapping OpenGL context already created by Qt (for that **V3d\_View::SetWindow()** provides an optional argument of type *Aspect\_RenderingContext*, which corresponds to **HGLRC** on Windows and can be fetched using **wglGetCurrentContext()** within rendering thread) as well as FBO created by QOpenGLWidget (for that, OCCT provides **OpenGl\_FrameBuffer::InitWrapper()** and **OpenGl\_Context::SetDefaultFrameBuffer()** methods, as well as **OpenGl\_Caps::buffersNoSwap** flag to leave window buffer swapping management to Qt). + +OCCT doesn't come yet with a sample using **QOpenGLWidget**, but you can find also **qt/AndroidQt** sample implementing similar thing for embedding OCCT 3D Viewer into **QtQuick** application.","After some investigation, I found that method *QOpenGLWidget::winId()* returns the correct handle. It's been found out only now, because the rendered scene disappeared immediately, leaving a black picture instead. However, when the viewport is resized, the scene returns back (and disappears again, though). Looks like Open CASCADE has problems with Qt 5 OpenGL implementation, since QGLWidget didn't have such problems, as far as I know." +31581537,"here the df(i updated by real data ): + +``` +>TIMESTAMP OLTPSOURCE RNR RQDRECORD +>20150425232836 0PU_IS_PS_44 REQU_51NHAJUV06IMMP16BVE572JM2 17020 +>20150128165726 ZFI_DS41 REQU_50P1AABLYXE86KYE3O6EY390M 6925 +>20150701144253 ZZZJB_TEXT REQU_52DV5FB812JCDXDVIV9P35DGM 2 +>20150107201358 0EQUIPMENT_ATTR REQU_50EVHXSDOITYUQLP4L8UXOBT6 14205 +>20150623215202 0CO_OM_CCA_1 REQU_528XSXYWTK6FSJXDQY2ROQQ4Q 0 +>20150715144139 0HRPOSITION_TEXT REQU_52I9KQ1LN4ZWTNIP0N1R68NDY 25381 +>20150625175157 0HR_PA_0 REQU_528ZS1RFN0N3Y3AEB48UDCUKQ 100020 +>20150309153828 0HR_PA_0 REQU_51385K5F3AGGFVCGHU997QF9M 0 +>20150626185531 0FI_AA_001 REQU_52BO3RJCOG4JGHEIIZMJP9V4A 0 +>20150307222336 0FUNCT_LOC_ATTR REQU_513JJ6I6ER5ZVW5CAJMVSKAJQ 13889 +>20150630163419 0WBS_ELEMT_ATTR REQU_52CUPVUFCY2DDOG6SPQ1XOYQ2 0 +>20150424162226 6DB_V_DGP_EXPORTDATA REQU_51N1F5ZC8G3LW68E4TFXRGH9I 0 +>20150617143720 ZRZMS_TEXT REQU_5268R1YE6G1U7HUK971LX1FPM 6 +>20150405162213 0HR_PA_0 REQU_51FFR7T4YQ2F766PFY0W9WUDM 0 +>20150202165933 ZFI_DS41 REQU_50QPTCF0VPGLBYM9MGFXMWHGM 6925 +>20150102162140 0HR_PA_0 REQU_50CNUT7I9OXH2WSNLC4WTUZ7U 0 +>20150417184916 0FI_AA_004 REQU_51KFWWT6PPTI5X44D3MWD7CYU 0 +>20150416220451 0FUNCT_LOC_ATTR REQU_51JP3BDCD6TUOBL2GK9ZE35UU 13889 +>20150205150633 ZHR_DS09 REQU_50RFRYRADMA9QXB1PW4PRF5XM 6667 +>20150419230724 0PU_IS_PS_44 REQU_51LC5XX6VWEERAVHEFJ9K5A6I 22528 + +>and the relationships between columns is +>OLTPSOURCE--RNR:1>n +>RNR--RQDRECORD:1>N + +``` + +> +> and my requirement is: +> +> +> + +1. sum the RQDRECORD by RNR; +2. get the max sum result of every OLTPSOURCE; +3. Finally, I would draw a graph showing the results of all +sumed largest OLTPSOURCE by time + +Thanks everyone, I further explain my problem: + +1. if OLTPSOURCE:RNR:RQDRECORD= 1:1:1 + +> +> just sum RQDRECORD,RETURN OLTPSOURCE AND SUM RESULT +> +> +> +2. if OLTPSOURCE:RNR:RQDRECORD= 1:1:N + +> +> just sum RQDRECORD,RETURN OLTPSOURCE AND SUM RESULT +> +> +> +3. if OLTPSOURCE:RNR:RQDRECORD= 1:N:(N OR 1) + +> +> sum RQDRECORD by RNR GROUP first,THEN Find the max result of one OLTPSOURCE,return all the OLTPSOURCE with the max RQDRECORD . +> +> +> + +So for the above sample data, I eventually want the result as follows + +``` +>TIMESTAMP OLTPSOURCE RNR RQDRECORD +>20150623215202 0CO_OM_CCA_1 REQU_528XSXYWTK6FSJXDQY2ROQQ4Q 0 +>20150107201358 0EQUIPMENT_ATTR REQU_50EVHXSDOITYUQLP4L8UXOBT6 14205 +>20150626185531 0FI_AA_001 REQU_52BO3RJCOG4JGHEIIZMJP9V4A 0 +>20150417184916 0FI_AA_004 REQU_51KFWWT6PPTI5X44D3MWD7CYU 0 +>20150416220451 0FUNCT_LOC_ATTR REQU_51JP3BDCD6TUOBL2GK9ZE35UU 13889 +>20150625175157 0HR_PA_0 REQU_528ZS1RFN0N3Y3AEB48UDCUKQ 100020 +>20150715144139 0HRPOSITION_TEXT REQU_52I9KQ1LN4ZWTNIP0N1R68NDY 25381 +>20150419230724 0PU_IS_PS_44 REQU_51LC5XX6VWEERAVHEFJ9K5A6I 22528 +>20150630163419 0WBS_ELEMT_ATTR REQU_52CUPVUFCY2DDOG6SPQ1XOYQ2 0 +>20150424162226 6DB_V_DGP_EXPORTDATA REQU_51N1F5ZC8G3LW68E4TFXRGH9I 0 +>20150202165933 ZFI_DS41 REQU_50QPTCF0VPGLBYM9MGFXMWHGM 6925 +>20150205150633 ZHR_DS09 REQU_50RFRYRADMA9QXB1PW4PRF5XM 6667 +>20150617143720 ZRZMS_TEXT REQU_5268R1YE6G1U7HUK971LX1FPM 6 +>20150701144253 ZZZJB_TEXT REQU_52DV5FB812JCDXDVIV9P35DGM 2 + +``` + +Referring to EdChum's approach, I made some adjustments, the results were as follows, because the amount of data is too big, I did ""'RQDRECORD> 100000'"" is set, in fact I would like to sort and then take the top 100, but not success + +> +> [1]: ""result"" +> +> +>",2015/07/23,"['https://Stackoverflow.com/questions/31581537', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5146939/']","Peter, we've just implemented the same thing. + +Users have the software pre-installed on their device and we host update APK's on the companies servers. + +From the app they can then check for updates where we have a WCF service which extracts the APK file (essentially a .zip) and returns the manifest details. From there we have the version of the APK and can compare it against the local version. + +If the user decides to upgrade they can download the APK and you can automatically launch it. At which point the user will be told the application is going to be updated. There are no file locks etc, the app will just close and restart using the new version. + +Note: Downgrading is not ""automatic"". The user would have to first uninstall the app. For upgrades, however, it's a simple case of downloading and launching the APK version (the user will be told they need to allow installations from unknown sources if this is not checked).","You have a couple of options, depending upon your target system. + +1. Use the link you posted. This will provide the user with a traditional install dialog, whereby the user can choose to install or not. You should avoid doing that automatically, as APKs can be large and you might irritate the user if they don't want updates. +2. You can install updates magically, but you will require the firmware signing key (or possibly root, but I haven't tested that). That will not ask for consent from the user. You will need to add additional code using reflection to access the installation methods of Android. If you go this way, you should build an opt-out/in mechanism." +31581537,"here the df(i updated by real data ): + +``` +>TIMESTAMP OLTPSOURCE RNR RQDRECORD +>20150425232836 0PU_IS_PS_44 REQU_51NHAJUV06IMMP16BVE572JM2 17020 +>20150128165726 ZFI_DS41 REQU_50P1AABLYXE86KYE3O6EY390M 6925 +>20150701144253 ZZZJB_TEXT REQU_52DV5FB812JCDXDVIV9P35DGM 2 +>20150107201358 0EQUIPMENT_ATTR REQU_50EVHXSDOITYUQLP4L8UXOBT6 14205 +>20150623215202 0CO_OM_CCA_1 REQU_528XSXYWTK6FSJXDQY2ROQQ4Q 0 +>20150715144139 0HRPOSITION_TEXT REQU_52I9KQ1LN4ZWTNIP0N1R68NDY 25381 +>20150625175157 0HR_PA_0 REQU_528ZS1RFN0N3Y3AEB48UDCUKQ 100020 +>20150309153828 0HR_PA_0 REQU_51385K5F3AGGFVCGHU997QF9M 0 +>20150626185531 0FI_AA_001 REQU_52BO3RJCOG4JGHEIIZMJP9V4A 0 +>20150307222336 0FUNCT_LOC_ATTR REQU_513JJ6I6ER5ZVW5CAJMVSKAJQ 13889 +>20150630163419 0WBS_ELEMT_ATTR REQU_52CUPVUFCY2DDOG6SPQ1XOYQ2 0 +>20150424162226 6DB_V_DGP_EXPORTDATA REQU_51N1F5ZC8G3LW68E4TFXRGH9I 0 +>20150617143720 ZRZMS_TEXT REQU_5268R1YE6G1U7HUK971LX1FPM 6 +>20150405162213 0HR_PA_0 REQU_51FFR7T4YQ2F766PFY0W9WUDM 0 +>20150202165933 ZFI_DS41 REQU_50QPTCF0VPGLBYM9MGFXMWHGM 6925 +>20150102162140 0HR_PA_0 REQU_50CNUT7I9OXH2WSNLC4WTUZ7U 0 +>20150417184916 0FI_AA_004 REQU_51KFWWT6PPTI5X44D3MWD7CYU 0 +>20150416220451 0FUNCT_LOC_ATTR REQU_51JP3BDCD6TUOBL2GK9ZE35UU 13889 +>20150205150633 ZHR_DS09 REQU_50RFRYRADMA9QXB1PW4PRF5XM 6667 +>20150419230724 0PU_IS_PS_44 REQU_51LC5XX6VWEERAVHEFJ9K5A6I 22528 + +>and the relationships between columns is +>OLTPSOURCE--RNR:1>n +>RNR--RQDRECORD:1>N + +``` + +> +> and my requirement is: +> +> +> + +1. sum the RQDRECORD by RNR; +2. get the max sum result of every OLTPSOURCE; +3. Finally, I would draw a graph showing the results of all +sumed largest OLTPSOURCE by time + +Thanks everyone, I further explain my problem: + +1. if OLTPSOURCE:RNR:RQDRECORD= 1:1:1 + +> +> just sum RQDRECORD,RETURN OLTPSOURCE AND SUM RESULT +> +> +> +2. if OLTPSOURCE:RNR:RQDRECORD= 1:1:N + +> +> just sum RQDRECORD,RETURN OLTPSOURCE AND SUM RESULT +> +> +> +3. if OLTPSOURCE:RNR:RQDRECORD= 1:N:(N OR 1) + +> +> sum RQDRECORD by RNR GROUP first,THEN Find the max result of one OLTPSOURCE,return all the OLTPSOURCE with the max RQDRECORD . +> +> +> + +So for the above sample data, I eventually want the result as follows + +``` +>TIMESTAMP OLTPSOURCE RNR RQDRECORD +>20150623215202 0CO_OM_CCA_1 REQU_528XSXYWTK6FSJXDQY2ROQQ4Q 0 +>20150107201358 0EQUIPMENT_ATTR REQU_50EVHXSDOITYUQLP4L8UXOBT6 14205 +>20150626185531 0FI_AA_001 REQU_52BO3RJCOG4JGHEIIZMJP9V4A 0 +>20150417184916 0FI_AA_004 REQU_51KFWWT6PPTI5X44D3MWD7CYU 0 +>20150416220451 0FUNCT_LOC_ATTR REQU_51JP3BDCD6TUOBL2GK9ZE35UU 13889 +>20150625175157 0HR_PA_0 REQU_528ZS1RFN0N3Y3AEB48UDCUKQ 100020 +>20150715144139 0HRPOSITION_TEXT REQU_52I9KQ1LN4ZWTNIP0N1R68NDY 25381 +>20150419230724 0PU_IS_PS_44 REQU_51LC5XX6VWEERAVHEFJ9K5A6I 22528 +>20150630163419 0WBS_ELEMT_ATTR REQU_52CUPVUFCY2DDOG6SPQ1XOYQ2 0 +>20150424162226 6DB_V_DGP_EXPORTDATA REQU_51N1F5ZC8G3LW68E4TFXRGH9I 0 +>20150202165933 ZFI_DS41 REQU_50QPTCF0VPGLBYM9MGFXMWHGM 6925 +>20150205150633 ZHR_DS09 REQU_50RFRYRADMA9QXB1PW4PRF5XM 6667 +>20150617143720 ZRZMS_TEXT REQU_5268R1YE6G1U7HUK971LX1FPM 6 +>20150701144253 ZZZJB_TEXT REQU_52DV5FB812JCDXDVIV9P35DGM 2 + +``` + +Referring to EdChum's approach, I made some adjustments, the results were as follows, because the amount of data is too big, I did ""'RQDRECORD> 100000'"" is set, in fact I would like to sort and then take the top 100, but not success + +> +> [1]: ""result"" +> +> +>",2015/07/23,"['https://Stackoverflow.com/questions/31581537', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5146939/']","Peter, we've just implemented the same thing. + +Users have the software pre-installed on their device and we host update APK's on the companies servers. + +From the app they can then check for updates where we have a WCF service which extracts the APK file (essentially a .zip) and returns the manifest details. From there we have the version of the APK and can compare it against the local version. + +If the user decides to upgrade they can download the APK and you can automatically launch it. At which point the user will be told the application is going to be updated. There are no file locks etc, the app will just close and restart using the new version. + +Note: Downgrading is not ""automatic"". The user would have to first uninstall the app. For upgrades, however, it's a simple case of downloading and launching the APK version (the user will be told they need to allow installations from unknown sources if this is not checked).","If your app is open-source, [F-Droid](https://f-droid.org/) would solve the problem for you. + +> +> F-Droid is an installable catalogue of FOSS (Free and Open Source +> Software) applications for the Android platform. The client makes it +> easy to browse, install, and keep track of updates on your device. +> +> +> + +Mainly, it updates your app when necessary. (Or just have a look at its [source code](https://gitlab.com/fdroid/fdroidclient) for inspiration on how to do it)." +31581537,"here the df(i updated by real data ): + +``` +>TIMESTAMP OLTPSOURCE RNR RQDRECORD +>20150425232836 0PU_IS_PS_44 REQU_51NHAJUV06IMMP16BVE572JM2 17020 +>20150128165726 ZFI_DS41 REQU_50P1AABLYXE86KYE3O6EY390M 6925 +>20150701144253 ZZZJB_TEXT REQU_52DV5FB812JCDXDVIV9P35DGM 2 +>20150107201358 0EQUIPMENT_ATTR REQU_50EVHXSDOITYUQLP4L8UXOBT6 14205 +>20150623215202 0CO_OM_CCA_1 REQU_528XSXYWTK6FSJXDQY2ROQQ4Q 0 +>20150715144139 0HRPOSITION_TEXT REQU_52I9KQ1LN4ZWTNIP0N1R68NDY 25381 +>20150625175157 0HR_PA_0 REQU_528ZS1RFN0N3Y3AEB48UDCUKQ 100020 +>20150309153828 0HR_PA_0 REQU_51385K5F3AGGFVCGHU997QF9M 0 +>20150626185531 0FI_AA_001 REQU_52BO3RJCOG4JGHEIIZMJP9V4A 0 +>20150307222336 0FUNCT_LOC_ATTR REQU_513JJ6I6ER5ZVW5CAJMVSKAJQ 13889 +>20150630163419 0WBS_ELEMT_ATTR REQU_52CUPVUFCY2DDOG6SPQ1XOYQ2 0 +>20150424162226 6DB_V_DGP_EXPORTDATA REQU_51N1F5ZC8G3LW68E4TFXRGH9I 0 +>20150617143720 ZRZMS_TEXT REQU_5268R1YE6G1U7HUK971LX1FPM 6 +>20150405162213 0HR_PA_0 REQU_51FFR7T4YQ2F766PFY0W9WUDM 0 +>20150202165933 ZFI_DS41 REQU_50QPTCF0VPGLBYM9MGFXMWHGM 6925 +>20150102162140 0HR_PA_0 REQU_50CNUT7I9OXH2WSNLC4WTUZ7U 0 +>20150417184916 0FI_AA_004 REQU_51KFWWT6PPTI5X44D3MWD7CYU 0 +>20150416220451 0FUNCT_LOC_ATTR REQU_51JP3BDCD6TUOBL2GK9ZE35UU 13889 +>20150205150633 ZHR_DS09 REQU_50RFRYRADMA9QXB1PW4PRF5XM 6667 +>20150419230724 0PU_IS_PS_44 REQU_51LC5XX6VWEERAVHEFJ9K5A6I 22528 + +>and the relationships between columns is +>OLTPSOURCE--RNR:1>n +>RNR--RQDRECORD:1>N + +``` + +> +> and my requirement is: +> +> +> + +1. sum the RQDRECORD by RNR; +2. get the max sum result of every OLTPSOURCE; +3. Finally, I would draw a graph showing the results of all +sumed largest OLTPSOURCE by time + +Thanks everyone, I further explain my problem: + +1. if OLTPSOURCE:RNR:RQDRECORD= 1:1:1 + +> +> just sum RQDRECORD,RETURN OLTPSOURCE AND SUM RESULT +> +> +> +2. if OLTPSOURCE:RNR:RQDRECORD= 1:1:N + +> +> just sum RQDRECORD,RETURN OLTPSOURCE AND SUM RESULT +> +> +> +3. if OLTPSOURCE:RNR:RQDRECORD= 1:N:(N OR 1) + +> +> sum RQDRECORD by RNR GROUP first,THEN Find the max result of one OLTPSOURCE,return all the OLTPSOURCE with the max RQDRECORD . +> +> +> + +So for the above sample data, I eventually want the result as follows + +``` +>TIMESTAMP OLTPSOURCE RNR RQDRECORD +>20150623215202 0CO_OM_CCA_1 REQU_528XSXYWTK6FSJXDQY2ROQQ4Q 0 +>20150107201358 0EQUIPMENT_ATTR REQU_50EVHXSDOITYUQLP4L8UXOBT6 14205 +>20150626185531 0FI_AA_001 REQU_52BO3RJCOG4JGHEIIZMJP9V4A 0 +>20150417184916 0FI_AA_004 REQU_51KFWWT6PPTI5X44D3MWD7CYU 0 +>20150416220451 0FUNCT_LOC_ATTR REQU_51JP3BDCD6TUOBL2GK9ZE35UU 13889 +>20150625175157 0HR_PA_0 REQU_528ZS1RFN0N3Y3AEB48UDCUKQ 100020 +>20150715144139 0HRPOSITION_TEXT REQU_52I9KQ1LN4ZWTNIP0N1R68NDY 25381 +>20150419230724 0PU_IS_PS_44 REQU_51LC5XX6VWEERAVHEFJ9K5A6I 22528 +>20150630163419 0WBS_ELEMT_ATTR REQU_52CUPVUFCY2DDOG6SPQ1XOYQ2 0 +>20150424162226 6DB_V_DGP_EXPORTDATA REQU_51N1F5ZC8G3LW68E4TFXRGH9I 0 +>20150202165933 ZFI_DS41 REQU_50QPTCF0VPGLBYM9MGFXMWHGM 6925 +>20150205150633 ZHR_DS09 REQU_50RFRYRADMA9QXB1PW4PRF5XM 6667 +>20150617143720 ZRZMS_TEXT REQU_5268R1YE6G1U7HUK971LX1FPM 6 +>20150701144253 ZZZJB_TEXT REQU_52DV5FB812JCDXDVIV9P35DGM 2 + +``` + +Referring to EdChum's approach, I made some adjustments, the results were as follows, because the amount of data is too big, I did ""'RQDRECORD> 100000'"" is set, in fact I would like to sort and then take the top 100, but not success + +> +> [1]: ""result"" +> +> +>",2015/07/23,"['https://Stackoverflow.com/questions/31581537', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5146939/']","Peter, we've just implemented the same thing. + +Users have the software pre-installed on their device and we host update APK's on the companies servers. + +From the app they can then check for updates where we have a WCF service which extracts the APK file (essentially a .zip) and returns the manifest details. From there we have the version of the APK and can compare it against the local version. + +If the user decides to upgrade they can download the APK and you can automatically launch it. At which point the user will be told the application is going to be updated. There are no file locks etc, the app will just close and restart using the new version. + +Note: Downgrading is not ""automatic"". The user would have to first uninstall the app. For upgrades, however, it's a simple case of downloading and launching the APK version (the user will be told they need to allow installations from unknown sources if this is not checked).",Yes but as far as I remember only if you had Root privileges in order to have access to the INSTALL\_PACKAGES permission. +9590702,"I have a ListBox which I put some files, if the file is not AVI I automatically converts it but I want when the files converting message will write on a label that the files are now converted to another format, i know i need use Dispatcher in order to update the UI thread but i use now Winform instead of WPF, and i need help with this. +BTW i cannot use Task because i am using .Net 3.5 + +``` +private void btnAdd_Click(object sender, EventArgs e) +{ + System.IO.Stream myStream; + OpenFileDialog thisDialog = new OpenFileDialog(); + thisDialog.InitialDirectory = ""c:\\""; + thisDialog.Filter = ""All files (*.*)|*.*""; + thisDialog.FilterIndex = 1; + thisDialog.RestoreDirectory = false; + thisDialog.Multiselect = true; // Allow the user to select multiple files + thisDialog.Title = ""Please Select Source File""; + thisDialog.FileName = lastPath; + List list = new List(); + + if (thisDialog.ShowDialog() == DialogResult.OK) + { + foreach (String file in thisDialog.FileNames) + { + try + { + if ((myStream = thisDialog.OpenFile()) != null) + { + using (myStream) + { + listBoxFiles.Items.Add(file); + lastPath = file; + } + } + } + + catch (Exception ex) + { + MessageBox.Show(""Error: Could not read file from disk. Original error: "" + ex.Message); + } + } + + for (int i = 0; i < listBoxFiles.Items.Count; i++) + { + string path = (string)listBoxFiles.Items[i]; + FileInfo fileInfo = new FileInfo(path); + + if (fileInfo.Extension != "".AVI"") + { + listToRemove.Add(path); + } + } + + (new System.Threading.Thread(sendFilesToConvertToPcap)).Start(); + + foreach (string file in listToRemove) //remove all non .AVI files from listbox + { + listBoxFiles.Items.Remove(file); + } + } +} + +``` + +this function need to change the Label: + +``` + public void sendFilesToConvertToPcap() + { + if (listToRemove.Count == 0) // nothing to do + { + return; + } + +lblStatus2.Content = ""Convert file to .AVI...""; + + foreach (String file in listToRemove) + { + FileInfo fileInfo = new FileInfo(file); + myClass = new (class who convert the files)(fileInfo); + String newFileName = myClass.mNewFileName; + listBoxFiles.Items.Add(myClass._newFileName); + } + +lblStatus2.Content = ""Finished...""; + + } + +```",2012/03/06,"['https://Stackoverflow.com/questions/9590702', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/979033/']","From your question, it seems that you'd like to convert several files. You may want to consider using the [BackgroundWorker](http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx) class and overwrite the DoWork and ProgressChanged events as described in [this article](http://msdn.microsoft.com/en-us/library/cc221403%28v=vs.95%29.aspx). You can update the label and other controls in the ProgressChanged event.","This is a very common requirement for long-running processes. If you don't explicitly call methods on a separate thread, they will automatically run on the main (see: UI) thread and cause your UI to hand (as I suspect you already know). + + + +Here is an old, but excellent link with an example on how to use the background worker to handle the threadpool for you. + +This way, you can just create a worker to manage running your conversion process on a separate thread, and I believe there is even an example for creating a process bar." +9590702,"I have a ListBox which I put some files, if the file is not AVI I automatically converts it but I want when the files converting message will write on a label that the files are now converted to another format, i know i need use Dispatcher in order to update the UI thread but i use now Winform instead of WPF, and i need help with this. +BTW i cannot use Task because i am using .Net 3.5 + +``` +private void btnAdd_Click(object sender, EventArgs e) +{ + System.IO.Stream myStream; + OpenFileDialog thisDialog = new OpenFileDialog(); + thisDialog.InitialDirectory = ""c:\\""; + thisDialog.Filter = ""All files (*.*)|*.*""; + thisDialog.FilterIndex = 1; + thisDialog.RestoreDirectory = false; + thisDialog.Multiselect = true; // Allow the user to select multiple files + thisDialog.Title = ""Please Select Source File""; + thisDialog.FileName = lastPath; + List list = new List(); + + if (thisDialog.ShowDialog() == DialogResult.OK) + { + foreach (String file in thisDialog.FileNames) + { + try + { + if ((myStream = thisDialog.OpenFile()) != null) + { + using (myStream) + { + listBoxFiles.Items.Add(file); + lastPath = file; + } + } + } + + catch (Exception ex) + { + MessageBox.Show(""Error: Could not read file from disk. Original error: "" + ex.Message); + } + } + + for (int i = 0; i < listBoxFiles.Items.Count; i++) + { + string path = (string)listBoxFiles.Items[i]; + FileInfo fileInfo = new FileInfo(path); + + if (fileInfo.Extension != "".AVI"") + { + listToRemove.Add(path); + } + } + + (new System.Threading.Thread(sendFilesToConvertToPcap)).Start(); + + foreach (string file in listToRemove) //remove all non .AVI files from listbox + { + listBoxFiles.Items.Remove(file); + } + } +} + +``` + +this function need to change the Label: + +``` + public void sendFilesToConvertToPcap() + { + if (listToRemove.Count == 0) // nothing to do + { + return; + } + +lblStatus2.Content = ""Convert file to .AVI...""; + + foreach (String file in listToRemove) + { + FileInfo fileInfo = new FileInfo(file); + myClass = new (class who convert the files)(fileInfo); + String newFileName = myClass.mNewFileName; + listBoxFiles.Items.Add(myClass._newFileName); + } + +lblStatus2.Content = ""Finished...""; + + } + +```",2012/03/06,"['https://Stackoverflow.com/questions/9590702', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/979033/']","From your question, it seems that you'd like to convert several files. You may want to consider using the [BackgroundWorker](http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx) class and overwrite the DoWork and ProgressChanged events as described in [this article](http://msdn.microsoft.com/en-us/library/cc221403%28v=vs.95%29.aspx). You can update the label and other controls in the ProgressChanged event.","``` +public void sendFilesToConvertToPcap() +{ + ..... + .... + this.Invoke((MethodInvoker)delegate { + lblStatus2.Text = ""Convert file to .AVI...""; }); + + .... +} + +```" +9590702,"I have a ListBox which I put some files, if the file is not AVI I automatically converts it but I want when the files converting message will write on a label that the files are now converted to another format, i know i need use Dispatcher in order to update the UI thread but i use now Winform instead of WPF, and i need help with this. +BTW i cannot use Task because i am using .Net 3.5 + +``` +private void btnAdd_Click(object sender, EventArgs e) +{ + System.IO.Stream myStream; + OpenFileDialog thisDialog = new OpenFileDialog(); + thisDialog.InitialDirectory = ""c:\\""; + thisDialog.Filter = ""All files (*.*)|*.*""; + thisDialog.FilterIndex = 1; + thisDialog.RestoreDirectory = false; + thisDialog.Multiselect = true; // Allow the user to select multiple files + thisDialog.Title = ""Please Select Source File""; + thisDialog.FileName = lastPath; + List list = new List(); + + if (thisDialog.ShowDialog() == DialogResult.OK) + { + foreach (String file in thisDialog.FileNames) + { + try + { + if ((myStream = thisDialog.OpenFile()) != null) + { + using (myStream) + { + listBoxFiles.Items.Add(file); + lastPath = file; + } + } + } + + catch (Exception ex) + { + MessageBox.Show(""Error: Could not read file from disk. Original error: "" + ex.Message); + } + } + + for (int i = 0; i < listBoxFiles.Items.Count; i++) + { + string path = (string)listBoxFiles.Items[i]; + FileInfo fileInfo = new FileInfo(path); + + if (fileInfo.Extension != "".AVI"") + { + listToRemove.Add(path); + } + } + + (new System.Threading.Thread(sendFilesToConvertToPcap)).Start(); + + foreach (string file in listToRemove) //remove all non .AVI files from listbox + { + listBoxFiles.Items.Remove(file); + } + } +} + +``` + +this function need to change the Label: + +``` + public void sendFilesToConvertToPcap() + { + if (listToRemove.Count == 0) // nothing to do + { + return; + } + +lblStatus2.Content = ""Convert file to .AVI...""; + + foreach (String file in listToRemove) + { + FileInfo fileInfo = new FileInfo(file); + myClass = new (class who convert the files)(fileInfo); + String newFileName = myClass.mNewFileName; + listBoxFiles.Items.Add(myClass._newFileName); + } + +lblStatus2.Content = ""Finished...""; + + } + +```",2012/03/06,"['https://Stackoverflow.com/questions/9590702', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/979033/']","``` +public void sendFilesToConvertToPcap() +{ + ..... + .... + this.Invoke((MethodInvoker)delegate { + lblStatus2.Text = ""Convert file to .AVI...""; }); + + .... +} + +```","This is a very common requirement for long-running processes. If you don't explicitly call methods on a separate thread, they will automatically run on the main (see: UI) thread and cause your UI to hand (as I suspect you already know). + + + +Here is an old, but excellent link with an example on how to use the background worker to handle the threadpool for you. + +This way, you can just create a worker to manage running your conversion process on a separate thread, and I believe there is even an example for creating a process bar." +419654,"I'm not sure what I'm doing wrong on my questions in [Go](https://en.wikipedia.org/wiki/Go_%28programming_language%29) as I always get downvotes. + +Do you think something can be improved in these questions? Can I do something else to avoid being banned? + +*[Deleting endpoint in Go is not working as expected](https://stackoverflow.com/questions/73249646/delete-endpoint-in-golang-not-working-as-expected/)* + +*[Improving GET request using the default Go HTTP client](https://stackoverflow.com/questions/73232160/improving-get-request-with-net-http-packet-in-go)* + +I always try to search the site first, research documentation, but for these two questions I'm banned...",2022/08/05,"['https://meta.stackoverflow.com/questions/419654', 'https://meta.stackoverflow.com', 'https://meta.stackoverflow.com/users/15083173/']","I closed both questions. + +[Delete endpoint in golang not working as expected](https://stackoverflow.com/questions/73249646/delete-endpoint-in-golang-not-working-as-expected/73250074#73250074) + +This question seems to have just been a typo. It doesn't look useful to others unless you explain what the mistake in the URL was. Even then, the question would probably be misleading and not very useful, hence the downvotes. + +[Improving get request with net/http packet](https://stackoverflow.com/questions/73232160/improving-get-request-with-net-http-packet-in-go) + +This question needs to be narrowed down. What improvement are you looking for? If the code works and you are only looking for code review, then it should have been asked on ","Your titles are not very informative - since SO primarily intends to be useful for other people with the same issue, a title like 'Delete endpoint in golang not working as expected' is really not very helpful, since nobody else knows what 'as expected' is meant to be. For some users, that would be grounds for a downvote as it renders the question 'not useful'. + +Try and focus on titles which concisely but specifically explain your problem." +24371011,"I have a Rails4 app with the following models: + +``` + 1. Systems (has many devices, has many parameters through devices) + 2. Devices (belongs to a system, has many parameters) + 3. Parameters (belongs to a Device) + 4. Events (polymorphic - Systems, Devices and Parameters can have events) + +``` + +When an event is created, a boolean field (on the event) is assigned a value. False indicated a failure. + +I have a scope on my events, to only show failing events: + +``` +scope :failing, -> { where(okay: false).order('created_at desc') } + +``` + +I can retrieve events as follows: + +``` +System.events.failing +Device.events.failing +Parameter.events.failing + +``` + +I am trying to return a list of Systems where either: + +``` +1. the most recent event for the system has failed +2. the most recent event for any of it's devices has failed +3. the most recent event for any parameters of it's devices have failed + +``` + +I have written this (horrible) SQL query which when executed in the console, returns the systems as an array: + +``` +""SELECT * FROM Systems WHERE Systems.id IN (SELECT Devices.system_id FROM Devices WHERE Devices.id IN (SELECT Parameters.device_id FROM Parameters JOIN EVENTS ON Parameters.id=Events.eventable_id WHERE Events.okay ='f')) OR Systems.id IN (SELECT Devices.system_id FROM Devices JOIN Events ON Devices.id=Events.eventable_id WHERE Events.okay='f')"") + +``` + +I need to either define a scope on the System model or a class method to return a list of 'failing' systems. Can you help?",2014/06/23,"['https://Stackoverflow.com/questions/24371011', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2778833/']","Basically your Javascript could be shortened to: + +``` +$("".question"").click(function(argument) { + $(this).parent().find("".answer"").removeClass(""hideinit"").addClass(""display""); +}); + +``` + +In order to make this work the only other thing you need to do is to make `question` a class rather than as an id. That looks like: + +``` +

the answer

+ +``` + +**[See the fiddle here](http://jsfiddle.net/6S9r3/2/)** + +--- + +**Edit: Add Hide / Show** + +To get this to hide and show as expected you'll want to update the code to check the current class before hiding and showing. That looks like: + +``` +$("".question"").click(function(argument) { + var el = $(this).parent().find("".answer""); + if (el.hasClass(""display"")) { + el.removeClass(""display"").addClass(""hideinit""); + } else { + el.removeClass(""hideinit"").addClass(""display""); + } +}); + +``` + +**[See the fiddle here](http://jsfiddle.net/6S9r3/3/)**","Well, for one thing, in your JSFiddle you were not including the jQuery library. I've adjusted your code, I think this is what you were going for: + +``` +$("".question"").click(function() { + $(this).siblings().toggle(); +}); + +``` + +Here's an [updated JSFiddle](http://jsfiddle.net/8UVAf/5/). +===========================================================" +24371011,"I have a Rails4 app with the following models: + +``` + 1. Systems (has many devices, has many parameters through devices) + 2. Devices (belongs to a system, has many parameters) + 3. Parameters (belongs to a Device) + 4. Events (polymorphic - Systems, Devices and Parameters can have events) + +``` + +When an event is created, a boolean field (on the event) is assigned a value. False indicated a failure. + +I have a scope on my events, to only show failing events: + +``` +scope :failing, -> { where(okay: false).order('created_at desc') } + +``` + +I can retrieve events as follows: + +``` +System.events.failing +Device.events.failing +Parameter.events.failing + +``` + +I am trying to return a list of Systems where either: + +``` +1. the most recent event for the system has failed +2. the most recent event for any of it's devices has failed +3. the most recent event for any parameters of it's devices have failed + +``` + +I have written this (horrible) SQL query which when executed in the console, returns the systems as an array: + +``` +""SELECT * FROM Systems WHERE Systems.id IN (SELECT Devices.system_id FROM Devices WHERE Devices.id IN (SELECT Parameters.device_id FROM Parameters JOIN EVENTS ON Parameters.id=Events.eventable_id WHERE Events.okay ='f')) OR Systems.id IN (SELECT Devices.system_id FROM Devices JOIN Events ON Devices.id=Events.eventable_id WHERE Events.okay='f')"") + +``` + +I need to either define a scope on the System model or a class method to return a list of 'failing' systems. Can you help?",2014/06/23,"['https://Stackoverflow.com/questions/24371011', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2778833/']","Basically your Javascript could be shortened to: + +``` +$("".question"").click(function(argument) { + $(this).parent().find("".answer"").removeClass(""hideinit"").addClass(""display""); +}); + +``` + +In order to make this work the only other thing you need to do is to make `question` a class rather than as an id. That looks like: + +``` +

the answer

+ +``` + +**[See the fiddle here](http://jsfiddle.net/6S9r3/2/)** + +--- + +**Edit: Add Hide / Show** + +To get this to hide and show as expected you'll want to update the code to check the current class before hiding and showing. That looks like: + +``` +$("".question"").click(function(argument) { + var el = $(this).parent().find("".answer""); + if (el.hasClass(""display"")) { + el.removeClass(""display"").addClass(""hideinit""); + } else { + el.removeClass(""hideinit"").addClass(""display""); + } +}); + +``` + +**[See the fiddle here](http://jsfiddle.net/6S9r3/3/)**","Please watch your includes in your JSFiddle as the version you linked was not including the jQuery library. You should also clean up your multiple `id` references (as this is invalid HTML and will cause some issues down the road). + +Those issues aside, you can use jQuery's [`.next()`](http://api.jquery.com/next/) method to help you with this particular problem: + +``` +$("".question"").click(function (argument) { + $(this).next("".hideinit"").removeClass(""hideinit"").addClass(""display""); +}); + +``` + +[JSFiddle](http://jsfiddle.net/8UVAf/4/)" +24371011,"I have a Rails4 app with the following models: + +``` + 1. Systems (has many devices, has many parameters through devices) + 2. Devices (belongs to a system, has many parameters) + 3. Parameters (belongs to a Device) + 4. Events (polymorphic - Systems, Devices and Parameters can have events) + +``` + +When an event is created, a boolean field (on the event) is assigned a value. False indicated a failure. + +I have a scope on my events, to only show failing events: + +``` +scope :failing, -> { where(okay: false).order('created_at desc') } + +``` + +I can retrieve events as follows: + +``` +System.events.failing +Device.events.failing +Parameter.events.failing + +``` + +I am trying to return a list of Systems where either: + +``` +1. the most recent event for the system has failed +2. the most recent event for any of it's devices has failed +3. the most recent event for any parameters of it's devices have failed + +``` + +I have written this (horrible) SQL query which when executed in the console, returns the systems as an array: + +``` +""SELECT * FROM Systems WHERE Systems.id IN (SELECT Devices.system_id FROM Devices WHERE Devices.id IN (SELECT Parameters.device_id FROM Parameters JOIN EVENTS ON Parameters.id=Events.eventable_id WHERE Events.okay ='f')) OR Systems.id IN (SELECT Devices.system_id FROM Devices JOIN Events ON Devices.id=Events.eventable_id WHERE Events.okay='f')"") + +``` + +I need to either define a scope on the System model or a class method to return a list of 'failing' systems. Can you help?",2014/06/23,"['https://Stackoverflow.com/questions/24371011', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2778833/']","Basically your Javascript could be shortened to: + +``` +$("".question"").click(function(argument) { + $(this).parent().find("".answer"").removeClass(""hideinit"").addClass(""display""); +}); + +``` + +In order to make this work the only other thing you need to do is to make `question` a class rather than as an id. That looks like: + +``` +

the answer

+ +``` + +**[See the fiddle here](http://jsfiddle.net/6S9r3/2/)** + +--- + +**Edit: Add Hide / Show** + +To get this to hide and show as expected you'll want to update the code to check the current class before hiding and showing. That looks like: + +``` +$("".question"").click(function(argument) { + var el = $(this).parent().find("".answer""); + if (el.hasClass(""display"")) { + el.removeClass(""display"").addClass(""hideinit""); + } else { + el.removeClass(""hideinit"").addClass(""display""); + } +}); + +``` + +**[See the fiddle here](http://jsfiddle.net/6S9r3/3/)**","``` +$("".question"").on('click',function() { + $(this).next().toggle(); +}); + +```" +40584664,"I am new to TYPO3 and have a big problem. I deleted the page with the id 1 (startpage, I know its stupid) and now I woudl like to know if it is possible to restore the page somehow.",2016/11/14,"['https://Stackoverflow.com/questions/40584664', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3649851/']","Install extension Recycler, it ships with TYPO3 by default. You can then restore pages and content you deleted using the backend UI it has. + +","You can use the recycler that is found under the web module and click on a page in the page tree at a higher level than the deleted page. You can also set the depth to infinitive if not certain where the page used to be in the page tree. Then put a tick beside the page you want to restore and click undelete. Note that PID is 'Parent ID' (not Page ID), and UID is the ID of the deleted page.If you click on the little + you will get additional information, e.g. the original path to the deleted page. If part of the path is highlighted in red, then that indicates another deleted branch or page. Remember to leave the Recycler module with 'Depth' NOT set to 'Infinite' (leave it at 'This page' or '1-4 levels') otherwise the recycler will hang if you use it on a larger part of your page t ree. Hope this will help you." +29516573,"This is something that has bugged me for many many years and have never asked. + +Why is it that when writing SQL against a schema in a databases, whether it be Oracle, Postgres, MySQL or MSSQL I have to specify the database name and the table name? e.g. +SELECT id FROM mydb.mytable; +and other times as +SELECT id FROM mytable; + +Is this some sort of configuration thing of the database I really would like to know why. + +I am currently using the Postgres PGAdmin SQL Editor. I am selecting in the drop down the DB schema to utilize. When connecting to DB A I wont have to specify the DB in the query but when connecting to DB B I do have to specify the DB in the query. This is inconsistent and does not make any sense to me.",2015/04/08,"['https://Stackoverflow.com/questions/29516573', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/588492/']","The main problem is that you have declared `position1` as a `VARCHAR(100)` instead of as an `INTEGER`. This leads to the unhelpful error here as there is no substring version that takes a varchar parameter (and in this context conversion from varchar to integer is not supported). + +A working (or at least: compiling) version of your function is: + +```sql +CREATE OR ALTER FUNCTION TRANSLATE_func + (text varchar(10000), + toReplace varchar(10000), + replacePattern varchar(10000)) +RETURNS VARCHAR(100) +AS + declare variable resultat varchar(100); + declare variable cut varchar(100); + declare variable i integer; + declare variable position1 integer; + declare variable letter varchar(100); + declare variable lenght integer; +BEGIN + i = 1; + resultat =''; + lenght = char_length(text); + while(i <= lenght) do + begin + cut = substring(text from i for 1); + position1 = position(cut, toReplace); + if (position1 > 0) then + begin + letter = substring(replacePattern from position1 for 1); + resultat = resultat||''||letter; + end + else + begin + resultat = resultat ||''|| cut; + end + i = i+1; + end + return resultat; +END + +```","For Firebird 3 + +```sql +SET TERM ^ ; + +create function translator ( + inp varchar(10000), + pat varchar(1000), + rep varchar(1000)) +returns varchar(10000) +as + declare variable tex varchar(10000); + declare variable inp_idx integer = 1; + declare variable cha char(1); + declare variable pos integer; +begin + tex = ''; + while (inp_idx <= char_length(inp)) do + begin + cha = substring(inp from inp_idx for 1); + pos = position(cha, pat); + if (pos > 0) then + cha = substring(rep from pos for 1); + tex = tex || cha; + inp_idx = inp_idx + 1; + end + return tex; +end^ + +SET TERM ; ^ + +``` + +Test + +```sql +select translator('džiná lasaí ireo dana kýrne číraž', 'ážíýč', 'AZIYC') + from rdb$database; + +``` + +Result + +``` +dZinA lasaI ireo dana kYrne CIraZ + +```" +8414930,"I have... + +``` +Func del2 = new Func(MyMethod); + +``` + +and I really want to do.. + +``` +Func<> del2 = new Func<>(MyMethod); + +``` + +so the return type of the callback method is void. Is this possible using the generic type func?",2011/12/07,"['https://Stackoverflow.com/questions/8414930', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/223863/']","Yes a function returning void (no value) is a `Action` + +``` +public Test() +{ + // first approach + Action firstApproach = delegate + { + // do your stuff + }; + firstApproach(); + + //second approach + Action secondApproach = MyMethod; + secondApproach(); +} + +void MyMethod() +{ + // do your stuff +} + +``` + +**hope this helps**",Use [Action delegate type](http://msdn.microsoft.com/en-us/library/system.action.aspx). +8414930,"I have... + +``` +Func del2 = new Func(MyMethod); + +``` + +and I really want to do.. + +``` +Func<> del2 = new Func<>(MyMethod); + +``` + +so the return type of the callback method is void. Is this possible using the generic type func?",2011/12/07,"['https://Stackoverflow.com/questions/8414930', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/223863/']","The `Func` family of delegates is for methods that take zero or more parameters and return a value. For methods that take zero or more parameters an don't return a value use one of the `Action` delegates. If the method has no parameters, use [the non-generic version of `Action`](http://msdn.microsoft.com/en-us/library/system.action.aspx): + +``` +Action del = MyMethod; + +```",Use [Action delegate type](http://msdn.microsoft.com/en-us/library/system.action.aspx). +8414930,"I have... + +``` +Func del2 = new Func(MyMethod); + +``` + +and I really want to do.. + +``` +Func<> del2 = new Func<>(MyMethod); + +``` + +so the return type of the callback method is void. Is this possible using the generic type func?",2011/12/07,"['https://Stackoverflow.com/questions/8414930', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/223863/']","Yes a function returning void (no value) is a `Action` + +``` +public Test() +{ + // first approach + Action firstApproach = delegate + { + // do your stuff + }; + firstApproach(); + + //second approach + Action secondApproach = MyMethod; + secondApproach(); +} + +void MyMethod() +{ + // do your stuff +} + +``` + +**hope this helps**","In cases where you're 'forced' to use `Func`, e.g. in an internal generic API which you want to reuse, you can just define it as `new Func(() => { SomeStuff(); return null; });`." +8414930,"I have... + +``` +Func del2 = new Func(MyMethod); + +``` + +and I really want to do.. + +``` +Func<> del2 = new Func<>(MyMethod); + +``` + +so the return type of the callback method is void. Is this possible using the generic type func?",2011/12/07,"['https://Stackoverflow.com/questions/8414930', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/223863/']","The `Func` family of delegates is for methods that take zero or more parameters and return a value. For methods that take zero or more parameters an don't return a value use one of the `Action` delegates. If the method has no parameters, use [the non-generic version of `Action`](http://msdn.microsoft.com/en-us/library/system.action.aspx): + +``` +Action del = MyMethod; + +```","Yes a function returning void (no value) is a `Action` + +``` +public Test() +{ + // first approach + Action firstApproach = delegate + { + // do your stuff + }; + firstApproach(); + + //second approach + Action secondApproach = MyMethod; + secondApproach(); +} + +void MyMethod() +{ + // do your stuff +} + +``` + +**hope this helps**" +8414930,"I have... + +``` +Func del2 = new Func(MyMethod); + +``` + +and I really want to do.. + +``` +Func<> del2 = new Func<>(MyMethod); + +``` + +so the return type of the callback method is void. Is this possible using the generic type func?",2011/12/07,"['https://Stackoverflow.com/questions/8414930', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/223863/']","Yes a function returning void (no value) is a `Action` + +``` +public Test() +{ + // first approach + Action firstApproach = delegate + { + // do your stuff + }; + firstApproach(); + + //second approach + Action secondApproach = MyMethod; + secondApproach(); +} + +void MyMethod() +{ + // do your stuff +} + +``` + +**hope this helps**","Here is a code example using Lambda expressions instead of Action/Func delegates. + +``` +delegate void TestDelegate(); + +static void Main(string[] args) +{ + TestDelegate testDelegate = () => { /*your code*/; }; + + testDelegate(); +} + +```" +8414930,"I have... + +``` +Func del2 = new Func(MyMethod); + +``` + +and I really want to do.. + +``` +Func<> del2 = new Func<>(MyMethod); + +``` + +so the return type of the callback method is void. Is this possible using the generic type func?",2011/12/07,"['https://Stackoverflow.com/questions/8414930', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/223863/']","The `Func` family of delegates is for methods that take zero or more parameters and return a value. For methods that take zero or more parameters an don't return a value use one of the `Action` delegates. If the method has no parameters, use [the non-generic version of `Action`](http://msdn.microsoft.com/en-us/library/system.action.aspx): + +``` +Action del = MyMethod; + +```","In cases where you're 'forced' to use `Func`, e.g. in an internal generic API which you want to reuse, you can just define it as `new Func(() => { SomeStuff(); return null; });`." +8414930,"I have... + +``` +Func del2 = new Func(MyMethod); + +``` + +and I really want to do.. + +``` +Func<> del2 = new Func<>(MyMethod); + +``` + +so the return type of the callback method is void. Is this possible using the generic type func?",2011/12/07,"['https://Stackoverflow.com/questions/8414930', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/223863/']","The `Func` family of delegates is for methods that take zero or more parameters and return a value. For methods that take zero or more parameters an don't return a value use one of the `Action` delegates. If the method has no parameters, use [the non-generic version of `Action`](http://msdn.microsoft.com/en-us/library/system.action.aspx): + +``` +Action del = MyMethod; + +```","Here is a code example using Lambda expressions instead of Action/Func delegates. + +``` +delegate void TestDelegate(); + +static void Main(string[] args) +{ + TestDelegate testDelegate = () => { /*your code*/; }; + + testDelegate(); +} + +```" +9247730,"My question concerns writing JAXB plugins, in particular JAXB codemodel. + +What is the role of `ClassOutline` (and it's [companions](http://www.docjar.com/docs/api/com/sun/tools/internal/xjc/outline/package-index.html)) and `JClass` (and [companions](http://codemodel.java.net/nonav/apidocs/com/sun/codemodel/package-summary.html)) and `CClass` (and [companions](http://www.docjar.com/docs/api/com/sun/tools/internal/xjc/model/package-index.html))? When looking at the list of classes in corresponding packages it is not clear what is chicken and what is egg. + +My interpretation is that `CClass` (`CPropertyInfo`, `CEnumConstant`, ...) are created by XJC at first draft parsing of XSD. Then some magic happens and this model is transformed into `JClass` (`JFieldVar`, `JEnumConstant`, ...) and during this transformation customizations are applied. Afterwards plugins are invoked. `ClassOutline` is used as a bridge between these two models. Altogether looks very complicated. + +With these parallel models I believe that the same information can be derived in several ways. For example, class field type: + +* `JClass#fields()` → `JFieldVar#type` → `JType` +* `CClassInfo#getProperties()` → `CPropertyInfo#baseType` → `JType` + +I am looking for verbose explanation of the lifecycle of above mentioned models. Thanks.",2012/02/12,"['https://Stackoverflow.com/questions/9247730', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/267197/']","Oh, oh, someone is interested in XJC internals. I might be of some help since I've probably developed more JAXB plugins than anyone else (see [JAXB2 Basics](https://github.com/highsource/jaxb2-basics) for instance) + +Ok, let's start. In XJC the schema compiler does approximately following + +* Parses the schema +* Creates the model of the schema (CClass, CPropertyInfo etc.) +* Creates the outline (ClassOutline, FieldOutline etc.) +* Renders the code model (JClass, JDefinedClass, JMethod etc.) +* Writes the physical code (ex.Java files on the disk) + +Let's start with the last two. + +Java files don't need explanation, I hope. + +Code model is also a relativesly easy thing. It is an API which can be used to construct Java code programmatically. You could just use string concatination instead, but it's much more error-prone. With CodeModel you're almost guaranteed to get at least grammatically correct Java code. So I hope this part is also clear. (By the way, I like CodeModel very much. I recently wrote [JavaScript Code Model](https://github.com/highsource/javascript-codemodel) based on ideas from the CodeModel.) + +Let's now look at the ""model"" and the ""outline"". +Model is the result of parsing the incoming schema. It models the constructs of the incoming schema, mainly in terms of ""classes"" which corresponds to complex types and ""properties"" which corresponds to elements, attributes and values (ex. when you have a complex type with simple content). + +The model should be understand as a logical modelling construct close to XML and schema. As such, it just describes types and properties that they have. It's surely much more complex that how I'm describing it, there's all sorts of exceptions and caveats - starting from wilcard types (xsd:any), substitution groups, enums, built-in types and so on. + +Quite interestingly, a sibling of `Model` is `RuntimeTypeInfoSetImpl` which is used by JAXB in the runtime. So it's also a type of model - which is however not parsed from the XML Schema but rather from JAXB annotations in classes. The concept is the same. Both Model and `RuntimeTypeInfoSetImpl` implement the `TypeInfoSet` interface which is a super-construct. Check interfaces like `ClassInfo` and `PropertyInfo` - they have implementation both for compile-time (`CClassInfo` and `CPropertyInfo` in XJC) and run-time (`RuntimeClassInfoImpl` etc. for JAXB RI). + +Ok, so when XJC parsed and analysed the schema, you've got the `Model`. This `Model` can't produce the code yet. There are, indeed, different strategies of producing the code. You can generate just annotated classes or you can generate interface/implementing class pair like in JAXB 1. The whole code generation thing isn't actually the task of the model. Moreover, there is a number of aspects that are relevant to the physical nature of the Java code, but aren't really relevant for the model. For instance, you have to group classes into packages. This is driven by the packing system of Java, not by the properties of the model itself. + +And this is where outlines come into play. You can see outlines as step between the schema model and the code model. You can view outlines as factories for code model elements responsible for organization of the code and generation of `JDefinedClass`es from `CClassInfo`s. + +So you're right, it is indeed very complicated. I am not a Sun/Oracle employee, I did not design it (I know the person who did it, though and respect him very much). +I can guess a couple of reasons for certain design decisions, for instance: + +* Use the same interfaces for compile-time and run-time models +* Allow different strategies of code generation +* Allow plugins to manipulate the created model + +I agree that this design is very complicated, but it has its reasons. One proof for that is that it was actually possible to build a mapping generator for XML-to-JavaScript mappings - basically on the same models. I just had to replace the code generation leaving schema analysis intact. (See [Jsonix](https://github.com/highsource/jsonix) for that.) + +Ok, hopefully I shed some light on why things in XJC are how they are. Good luck with these APIs, they're not straghtforward. Feel free to check existing open-source code, there's a lot of examples available. + +ps. Really always wanted to write this. :)","(This is to answer your further questions.) + +Yes, it is possible to check customizations. [Here is](https://svn.java.net/svn/jaxb2-commons~svn/basics/trunk/tools/src/main/java/org/jvnet/jaxb2_commons/util/CustomizationUtils.java) a class I am using to access customizations. + +The trick is that reference properties don't have own customizations, customizations are placed in the referenced element properties. + +``` +public static CCustomizations getCustomizations( + final CPropertyInfo propertyInfo) { + + final CCustomizations main = new CCustomizations( + propertyInfo.getCustomizations()); + + final Collection elementCustomizations = propertyInfo + .accept(new CPropertyVisitor>() { + public Collection onAttribute( + CAttributePropertyInfo info) { + return Collections.emptyList(); + } + + public Collection onElement( + CElementPropertyInfo arg0) { + return Collections.emptyList(); + } + + public Collection onReference( + CReferencePropertyInfo info) { + + final List elementCustomizations = new ArrayList( + info.getElements().size()); + + for (CElement element : info.getElements()) { + if (!(element instanceof CElementInfo && ((CElementInfo) element) + .hasClass())) { + elementCustomizations.add(element + .getCustomizations()); + } + } + + return elementCustomizations; + } + + public Collection onValue( + CValuePropertyInfo arg0) { + return Collections.emptyList(); + }; + + }); + + CCustomizations customizations = main; + + for (CCustomizations e : elementCustomizations) { + main.addAll(e); + } + + return customizations; +} + +``` + +I'd say users@jaxb.java.net is a good place for such discussions." +5861428,"In lots of Linux programs, like curl, wget, and anything with a progress meter, they have the bottom line constantly update, every certain amount of time. How do I do that in a bash script? All I can do now is just echo a new line, and that's not what I want because it builds up. I did come across something that mentioned ""tput cup 0 0"", but I tried it and it's kind of quirky. What's the best way?",2011/05/02,"['https://Stackoverflow.com/questions/5861428', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/689317/']","Small variation on linuts' code sample to move the cursor not to the beginning, but the end of the current line. + +``` +{ + for pc in {1..100}; do + #echo -ne ""$pc%\033[0K\r"" + echo -ne ""\r\033[0K${pc}%"" + sleep 1 + done + echo +} + +```","man terminfo(5) and look at the ""cap-nam"" column. + +``` +clr_eol=$(tput el) +while true +do + printf ""${clr_eol}your message here\r"" + sleep 60 +done + +```" +5861428,"In lots of Linux programs, like curl, wget, and anything with a progress meter, they have the bottom line constantly update, every certain amount of time. How do I do that in a bash script? All I can do now is just echo a new line, and that's not what I want because it builds up. I did come across something that mentioned ""tput cup 0 0"", but I tried it and it's kind of quirky. What's the best way?",2011/05/02,"['https://Stackoverflow.com/questions/5861428', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/689317/']","You can also use `tput cuu1;tput el` (or `printf '\e[A\e[K'`) to move the cursor up one line and erase the line: + +``` +for i in {1..100};do echo $i;sleep 1;tput cuu1;tput el;done + +```","`printf '\r'`, usually. There's no reason for cursor addressing in this case." +5861428,"In lots of Linux programs, like curl, wget, and anything with a progress meter, they have the bottom line constantly update, every certain amount of time. How do I do that in a bash script? All I can do now is just echo a new line, and that's not what I want because it builds up. I did come across something that mentioned ""tput cup 0 0"", but I tried it and it's kind of quirky. What's the best way?",2011/05/02,"['https://Stackoverflow.com/questions/5861428', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/689317/']","Small variation on linuts' code sample to move the cursor not to the beginning, but the end of the current line. + +``` +{ + for pc in {1..100}; do + #echo -ne ""$pc%\033[0K\r"" + echo -ne ""\r\033[0K${pc}%"" + sleep 1 + done + echo +} + +```","`printf '\r'`, usually. There's no reason for cursor addressing in this case." +5861428,"In lots of Linux programs, like curl, wget, and anything with a progress meter, they have the bottom line constantly update, every certain amount of time. How do I do that in a bash script? All I can do now is just echo a new line, and that's not what I want because it builds up. I did come across something that mentioned ""tput cup 0 0"", but I tried it and it's kind of quirky. What's the best way?",2011/05/02,"['https://Stackoverflow.com/questions/5861428', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/689317/']","``` +{ + for pc in $(seq 1 100); do + echo -ne ""$pc%\033[0K\r"" + usleep 100000 + done + echo +} + +``` + +The ""\033[0K"" will delete to the end of the line - in case your progress line gets shorter at some point, although this may not be necessary for your purposes. + +The ""\r"" will move the cursor to the beginning of the current line + +The -n on echo will prevent the cursor advancing to the next line","man terminfo(5) and look at the ""cap-nam"" column. + +``` +clr_eol=$(tput el) +while true +do + printf ""${clr_eol}your message here\r"" + sleep 60 +done + +```" +5861428,"In lots of Linux programs, like curl, wget, and anything with a progress meter, they have the bottom line constantly update, every certain amount of time. How do I do that in a bash script? All I can do now is just echo a new line, and that's not what I want because it builds up. I did come across something that mentioned ""tput cup 0 0"", but I tried it and it's kind of quirky. What's the best way?",2011/05/02,"['https://Stackoverflow.com/questions/5861428', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/689317/']","To actually erase *previous* lines, not just the current line, you can use the following bash functions: + +``` +# Clears the entire current line regardless of terminal size. +# See the magic by running: +# { sleep 1; clear_this_line ; }& +clear_this_line(){ + printf '\r' + cols=""$(tput cols)"" + for i in $(seq ""$cols""); do + printf ' ' + done + printf '\r' +} + +# Erases the amount of lines specified. +# Usage: erase_lines [AMOUNT] +# See the magic by running: +# { sleep 1; erase_lines 2; }& +erase_lines(){ + # Default line count to 1. + test -z ""$1"" && lines=""1"" || lines=""$1"" + + # This is what we use to move the cursor to previous lines. + UP='\033[1A' + + # Exit if erase count is zero. + [ ""$lines"" = 0 ] && return + + # Erase. + if [ ""$lines"" = 1 ]; then + clear_this_line + else + lines=$((lines-1)) + clear_this_line + for i in $(seq ""$lines""); do + printf ""$UP"" + clear_this_line + done + fi +} + +``` + +Now, simply call `erase_lines 5` for example to clear the last 5 lines in the terminal.","man terminfo(5) and look at the ""cap-nam"" column. + +``` +clr_eol=$(tput el) +while true +do + printf ""${clr_eol}your message here\r"" + sleep 60 +done + +```" +5861428,"In lots of Linux programs, like curl, wget, and anything with a progress meter, they have the bottom line constantly update, every certain amount of time. How do I do that in a bash script? All I can do now is just echo a new line, and that's not what I want because it builds up. I did come across something that mentioned ""tput cup 0 0"", but I tried it and it's kind of quirky. What's the best way?",2011/05/02,"['https://Stackoverflow.com/questions/5861428', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/689317/']","``` +{ + for pc in $(seq 1 100); do + echo -ne ""$pc%\033[0K\r"" + usleep 100000 + done + echo +} + +``` + +The ""\033[0K"" will delete to the end of the line - in case your progress line gets shorter at some point, although this may not be necessary for your purposes. + +The ""\r"" will move the cursor to the beginning of the current line + +The -n on echo will prevent the cursor advancing to the next line","`printf '\r'`, usually. There's no reason for cursor addressing in this case." +5861428,"In lots of Linux programs, like curl, wget, and anything with a progress meter, they have the bottom line constantly update, every certain amount of time. How do I do that in a bash script? All I can do now is just echo a new line, and that's not what I want because it builds up. I did come across something that mentioned ""tput cup 0 0"", but I tried it and it's kind of quirky. What's the best way?",2011/05/02,"['https://Stackoverflow.com/questions/5861428', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/689317/']","``` +{ + for pc in $(seq 1 100); do + echo -ne ""$pc%\033[0K\r"" + usleep 100000 + done + echo +} + +``` + +The ""\033[0K"" will delete to the end of the line - in case your progress line gets shorter at some point, although this may not be necessary for your purposes. + +The ""\r"" will move the cursor to the beginning of the current line + +The -n on echo will prevent the cursor advancing to the next line","To actually erase *previous* lines, not just the current line, you can use the following bash functions: + +``` +# Clears the entire current line regardless of terminal size. +# See the magic by running: +# { sleep 1; clear_this_line ; }& +clear_this_line(){ + printf '\r' + cols=""$(tput cols)"" + for i in $(seq ""$cols""); do + printf ' ' + done + printf '\r' +} + +# Erases the amount of lines specified. +# Usage: erase_lines [AMOUNT] +# See the magic by running: +# { sleep 1; erase_lines 2; }& +erase_lines(){ + # Default line count to 1. + test -z ""$1"" && lines=""1"" || lines=""$1"" + + # This is what we use to move the cursor to previous lines. + UP='\033[1A' + + # Exit if erase count is zero. + [ ""$lines"" = 0 ] && return + + # Erase. + if [ ""$lines"" = 1 ]; then + clear_this_line + else + lines=$((lines-1)) + clear_this_line + for i in $(seq ""$lines""); do + printf ""$UP"" + clear_this_line + done + fi +} + +``` + +Now, simply call `erase_lines 5` for example to clear the last 5 lines in the terminal." +5861428,"In lots of Linux programs, like curl, wget, and anything with a progress meter, they have the bottom line constantly update, every certain amount of time. How do I do that in a bash script? All I can do now is just echo a new line, and that's not what I want because it builds up. I did come across something that mentioned ""tput cup 0 0"", but I tried it and it's kind of quirky. What's the best way?",2011/05/02,"['https://Stackoverflow.com/questions/5861428', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/689317/']","You can also use `tput cuu1;tput el` (or `printf '\e[A\e[K'`) to move the cursor up one line and erase the line: + +``` +for i in {1..100};do echo $i;sleep 1;tput cuu1;tput el;done + +```","To actually erase *previous* lines, not just the current line, you can use the following bash functions: + +``` +# Clears the entire current line regardless of terminal size. +# See the magic by running: +# { sleep 1; clear_this_line ; }& +clear_this_line(){ + printf '\r' + cols=""$(tput cols)"" + for i in $(seq ""$cols""); do + printf ' ' + done + printf '\r' +} + +# Erases the amount of lines specified. +# Usage: erase_lines [AMOUNT] +# See the magic by running: +# { sleep 1; erase_lines 2; }& +erase_lines(){ + # Default line count to 1. + test -z ""$1"" && lines=""1"" || lines=""$1"" + + # This is what we use to move the cursor to previous lines. + UP='\033[1A' + + # Exit if erase count is zero. + [ ""$lines"" = 0 ] && return + + # Erase. + if [ ""$lines"" = 1 ]; then + clear_this_line + else + lines=$((lines-1)) + clear_this_line + for i in $(seq ""$lines""); do + printf ""$UP"" + clear_this_line + done + fi +} + +``` + +Now, simply call `erase_lines 5` for example to clear the last 5 lines in the terminal." +5861428,"In lots of Linux programs, like curl, wget, and anything with a progress meter, they have the bottom line constantly update, every certain amount of time. How do I do that in a bash script? All I can do now is just echo a new line, and that's not what I want because it builds up. I did come across something that mentioned ""tput cup 0 0"", but I tried it and it's kind of quirky. What's the best way?",2011/05/02,"['https://Stackoverflow.com/questions/5861428', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/689317/']","``` +{ + for pc in $(seq 1 100); do + echo -ne ""$pc%\033[0K\r"" + usleep 100000 + done + echo +} + +``` + +The ""\033[0K"" will delete to the end of the line - in case your progress line gets shorter at some point, although this may not be necessary for your purposes. + +The ""\r"" will move the cursor to the beginning of the current line + +The -n on echo will prevent the cursor advancing to the next line","Small variation on linuts' code sample to move the cursor not to the beginning, but the end of the current line. + +``` +{ + for pc in {1..100}; do + #echo -ne ""$pc%\033[0K\r"" + echo -ne ""\r\033[0K${pc}%"" + sleep 1 + done + echo +} + +```" +5861428,"In lots of Linux programs, like curl, wget, and anything with a progress meter, they have the bottom line constantly update, every certain amount of time. How do I do that in a bash script? All I can do now is just echo a new line, and that's not what I want because it builds up. I did come across something that mentioned ""tput cup 0 0"", but I tried it and it's kind of quirky. What's the best way?",2011/05/02,"['https://Stackoverflow.com/questions/5861428', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/689317/']","``` +{ + for pc in $(seq 1 100); do + echo -ne ""$pc%\033[0K\r"" + usleep 100000 + done + echo +} + +``` + +The ""\033[0K"" will delete to the end of the line - in case your progress line gets shorter at some point, although this may not be necessary for your purposes. + +The ""\r"" will move the cursor to the beginning of the current line + +The -n on echo will prevent the cursor advancing to the next line","You can also use `tput cuu1;tput el` (or `printf '\e[A\e[K'`) to move the cursor up one line and erase the line: + +``` +for i in {1..100};do echo $i;sleep 1;tput cuu1;tput el;done + +```" +17572348,"According to : + +``` +HTTP Verb Path Action Used for +GET /photos index display a list of all photos +GET /photos/new new return an HTML form for creating a new photo +POST /photos create create a new photo +GET /photos/:id show display a specific photo +GET /photos/:id/edit edit return an HTML form for editing a photo +PATCH/PUT /photos/:id update update a specific photo +DELETE /photos/:id destroy delete a specific photo + +``` + +How does rails know when a PATCH/PUT REST is received. I understand the get/post but PATCH/PUT I cannot figure it out. Is something being done internally, like in the input.",2013/07/10,"['https://Stackoverflow.com/questions/17572348', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2542493/']",Rails figures out which method to call based on whether the form submitted is a form for a new record that has not yet been saved or for a record that already exists in the database.,"Read about ""resource routing"" in the document you referenced at the top of your post. + +Also, run `rake routes` to see how rails is currently configured to route." +17572348,"According to : + +``` +HTTP Verb Path Action Used for +GET /photos index display a list of all photos +GET /photos/new new return an HTML form for creating a new photo +POST /photos create create a new photo +GET /photos/:id show display a specific photo +GET /photos/:id/edit edit return an HTML form for editing a photo +PATCH/PUT /photos/:id update update a specific photo +DELETE /photos/:id destroy delete a specific photo + +``` + +How does rails know when a PATCH/PUT REST is received. I understand the get/post but PATCH/PUT I cannot figure it out. Is something being done internally, like in the input.",2013/07/10,"['https://Stackoverflow.com/questions/17572348', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2542493/']","Read about ""resource routing"" in the document you referenced at the top of your post. + +Also, run `rake routes` to see how rails is currently configured to route.","In The Terminal Type: + +``` +$rake routes + +``` + +and hit enter + +Prefix Verb URI Pattern Controller#Action + +root GET / welcome#index" +17572348,"According to : + +``` +HTTP Verb Path Action Used for +GET /photos index display a list of all photos +GET /photos/new new return an HTML form for creating a new photo +POST /photos create create a new photo +GET /photos/:id show display a specific photo +GET /photos/:id/edit edit return an HTML form for editing a photo +PATCH/PUT /photos/:id update update a specific photo +DELETE /photos/:id destroy delete a specific photo + +``` + +How does rails know when a PATCH/PUT REST is received. I understand the get/post but PATCH/PUT I cannot figure it out. Is something being done internally, like in the input.",2013/07/10,"['https://Stackoverflow.com/questions/17572348', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2542493/']",Rails figures out which method to call based on whether the form submitted is a form for a new record that has not yet been saved or for a record that already exists in the database.,"In The Terminal Type: + +``` +$rake routes + +``` + +and hit enter + +Prefix Verb URI Pattern Controller#Action + +root GET / welcome#index" +425937,"I leanred, if all partial derivatives exist and all are continuous, then it is differentiable. Am I wrong? + +I tried same way for this problem, I think it is differentiable because + +all the derivative exist and are continuous. + +However, it is not differentiable at 0. + +Why is it the case? + +![The problem](https://i.stack.imgur.com/UWjHD.jpg) + +![Another problem](https://i.stack.imgur.com/ozRR1.jpg) + +// then I think... the functions of tho problems all have discontinuous partial derivative at (0,0)... right? + +then, why is it differentiable or not?..",2013/06/21,"['https://math.stackexchange.com/questions/425937', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/78027/']","The partial derivatives evaluate to both to $0$. Thus, **if** the function is differentiable, it must be the case the differential is identically zero. + +You're looking at $$\lim\_{(x,y)\to (0,0)}\left|\frac{f(x,y)-\nabla f(x,y)\cdot (x-y) }{\lVert (x,y)\rVert}\right|$$ + +This is $$\lim\_{(x,y)\to (0,0)}\left|\frac{xy}{x^2+y^2}\right|$$ + +What happens if you take the limit along $y=x$? Is it $0$, as it should be? + +**ADD** The partial derivatives are $$\eqalign{ + & \frac{{\partial f}}{{\partial x}} = \frac{{{y^2}}}{{{x^2} + {y^2}}}\frac{y}{{\sqrt {{x^2} + {y^2}} }} \cr + & \frac{{\partial f}}{{\partial y}} = \frac{{{x^2}}}{{{x^2} + {y^2}}}\frac{x}{{\sqrt {{x^2} + {y^2}} }} \cr} $$ + +Are you **sure** they are continuous at the origin?","For the first one. +if $y = ax$, +$\dfrac{xy}{\sqrt{x^2+y^2}} +=\dfrac{ax^2}{\sqrt{x^2+a^2x^2}} +=\dfrac{a}{\sqrt{1+a^2}} +$, +so the function is not even continuous +at $(0, 0)$. + +(This is, of course, not original.)" +4261219,"I've been tinkering around trying to make an AI player for the popular card game, Dominion (http://www.boardgamegeek.com/boardgame/36218/dominion). + +If you are not familiar with the game, it is basically a very streamlined cousin of Magic: The Gathering, where there is a large-ish library of cards with different rules on them. Over the course of a game, players buy these cards and incorporate them into their deck. + +I am interested in this game from a machine learning perspective - I want to pit bots against each other, have them play millions of games, and try to datamine insights that will make them play better. + +I am unsure how to separate the rules of the game (the verbatim instructions printed on each card) from the core AI decision-making logic. + +The obvious path that I have started down is creating a class for each Card, and putting both rules and AI stuff in the same place. This is sort of gross - but it seems like the path of least resistance. But maybe it is best for each card to support some sort of interface and then have AI components code against these? + +Is there a ""Correct"" OOP design for this? Or several reasonable possibilities?",2010/11/23,"['https://Stackoverflow.com/questions/4261219', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/409020/']","I would lean toward encapsulating the behaviour of a card as its own class, allowing easily for cards that have multiple behaviours (i.e. choices). It would also allow you to write parameterizable behaviours and mix and match them with cards. + +So cards would contain things like the cost of the card, when it can be played, its name, etc. It would also contain a list of behaviours that the card can do. + +The behaviours are seen by the AI actors as part of the cards. Just another property the cards have that can be weighed along with the cost. + +The AI actor that is actually *using* the card's behaviour needs to be able to interpret the behaviours, so the behaviour class might need to contain some hints for the AI to understand it, but no actual AI logic itself should be contained there. If AIs need specific behaviours for specific cards, write that kind of thing into the AI actor, not the card behaviour. + +If an AI actor needs to know that, for example, this behaviour has an expected victory point payoff of .2 points/round, that might be a part of the behaviour that acts as a hint to the AI when choosing what cards to buy/play. + +But really I don't know how you're approaching your AI actor design so maybe this doesn't make sense. But I think that thinking of behaviour as a property of cards rather than a fundamental part of the cards themselves might help. + +It gives you the advantage of encapsulating the AI actors' default actions (things the actors can do without needing cards) as behaviours as well, so you can weigh those actions against card actions without any special-case code.","I'm not familiar with all the variations of cards in Dominion, but the idea of writing a class for each one seems burdensome. Ideally, you would want to create a general card class that encapsulated all the variations of instructions on the card, and then load the particular values for a given card into that general class. + +I can imagine a class that contains sets of powers and restrictions could be a good general representation. Something like: + +* Required in play resources for play +* State where play is prohibited +* Damage types/value +* Health/mana changes +* Effects on other cards (perhaps a dictionary of card ids and effects) +* etc..." +4261219,"I've been tinkering around trying to make an AI player for the popular card game, Dominion (http://www.boardgamegeek.com/boardgame/36218/dominion). + +If you are not familiar with the game, it is basically a very streamlined cousin of Magic: The Gathering, where there is a large-ish library of cards with different rules on them. Over the course of a game, players buy these cards and incorporate them into their deck. + +I am interested in this game from a machine learning perspective - I want to pit bots against each other, have them play millions of games, and try to datamine insights that will make them play better. + +I am unsure how to separate the rules of the game (the verbatim instructions printed on each card) from the core AI decision-making logic. + +The obvious path that I have started down is creating a class for each Card, and putting both rules and AI stuff in the same place. This is sort of gross - but it seems like the path of least resistance. But maybe it is best for each card to support some sort of interface and then have AI components code against these? + +Is there a ""Correct"" OOP design for this? Or several reasonable possibilities?",2010/11/23,"['https://Stackoverflow.com/questions/4261219', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/409020/']","there are several ""correct"" OOP designs for this, depending on *how you want to model the game process and the game-playing-agent's AI* + +personally, i would take the minimum number of cards for a valid *round* in the game and implement those as instances of a Card class, and implement the players as instances of an Agent class, and implement a few simple playing strategies as instances of a Strategy (pattern) class, and then *see what happens* + +run through some tests, have a totally random player as a foil, look at short-term gain/loss max/min operators, try mutating the agent's strategies using a genetic algorithm, download an XCS classifier and see if it is useful to derive strategies... + +...the notion of a correct model depends strongly on how it will be used. Once you understand how you need to use the elements of the game and model/manipulate the player strategies/tactics, then you'll know what the 'correct' structure is for your solution","I'm not familiar with all the variations of cards in Dominion, but the idea of writing a class for each one seems burdensome. Ideally, you would want to create a general card class that encapsulated all the variations of instructions on the card, and then load the particular values for a given card into that general class. + +I can imagine a class that contains sets of powers and restrictions could be a good general representation. Something like: + +* Required in play resources for play +* State where play is prohibited +* Damage types/value +* Health/mana changes +* Effects on other cards (perhaps a dictionary of card ids and effects) +* etc..." +4261219,"I've been tinkering around trying to make an AI player for the popular card game, Dominion (http://www.boardgamegeek.com/boardgame/36218/dominion). + +If you are not familiar with the game, it is basically a very streamlined cousin of Magic: The Gathering, where there is a large-ish library of cards with different rules on them. Over the course of a game, players buy these cards and incorporate them into their deck. + +I am interested in this game from a machine learning perspective - I want to pit bots against each other, have them play millions of games, and try to datamine insights that will make them play better. + +I am unsure how to separate the rules of the game (the verbatim instructions printed on each card) from the core AI decision-making logic. + +The obvious path that I have started down is creating a class for each Card, and putting both rules and AI stuff in the same place. This is sort of gross - but it seems like the path of least resistance. But maybe it is best for each card to support some sort of interface and then have AI components code against these? + +Is there a ""Correct"" OOP design for this? Or several reasonable possibilities?",2010/11/23,"['https://Stackoverflow.com/questions/4261219', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/409020/']","I would lean toward encapsulating the behaviour of a card as its own class, allowing easily for cards that have multiple behaviours (i.e. choices). It would also allow you to write parameterizable behaviours and mix and match them with cards. + +So cards would contain things like the cost of the card, when it can be played, its name, etc. It would also contain a list of behaviours that the card can do. + +The behaviours are seen by the AI actors as part of the cards. Just another property the cards have that can be weighed along with the cost. + +The AI actor that is actually *using* the card's behaviour needs to be able to interpret the behaviours, so the behaviour class might need to contain some hints for the AI to understand it, but no actual AI logic itself should be contained there. If AIs need specific behaviours for specific cards, write that kind of thing into the AI actor, not the card behaviour. + +If an AI actor needs to know that, for example, this behaviour has an expected victory point payoff of .2 points/round, that might be a part of the behaviour that acts as a hint to the AI when choosing what cards to buy/play. + +But really I don't know how you're approaching your AI actor design so maybe this doesn't make sense. But I think that thinking of behaviour as a property of cards rather than a fundamental part of the cards themselves might help. + +It gives you the advantage of encapsulating the AI actors' default actions (things the actors can do without needing cards) as behaviours as well, so you can weigh those actions against card actions without any special-case code.","I've been thinking about the logic for a non-AI version of Dominion, and it's still a mess to figure out. + +You almost have to have a class for each card deck and an interface for each card type, keeping in mind that cards may have multiple types (such as Great Hall which is both Action and Victory). + +At present, all Attack cards are also Actions, so you may want to make the Attack interface subclass action. For most cards, the Action would just call the Attack method. However, there are a few cards where this would need to be different, such as for Minion where you have a choice whether or not to attack. + +Reaction cards are also Actions, but will also need special handling, as they can be revealed during an opponent's turn in response to an Attack card. As of Prosperity, they can also be revealed in response to things other than attacks... Watchtower can be revealed any time you would gain a card. + +Duration cards (which I missed in my list of 7 card types earlier) are Actions that stay in play for an extra turn... and also count for the Peddler's buy cost in Prosperity. + +Edit: Whoops, I didn't address the AI issue at all here... probably because my own development had been aimed more at a multiplayer network version." +4261219,"I've been tinkering around trying to make an AI player for the popular card game, Dominion (http://www.boardgamegeek.com/boardgame/36218/dominion). + +If you are not familiar with the game, it is basically a very streamlined cousin of Magic: The Gathering, where there is a large-ish library of cards with different rules on them. Over the course of a game, players buy these cards and incorporate them into their deck. + +I am interested in this game from a machine learning perspective - I want to pit bots against each other, have them play millions of games, and try to datamine insights that will make them play better. + +I am unsure how to separate the rules of the game (the verbatim instructions printed on each card) from the core AI decision-making logic. + +The obvious path that I have started down is creating a class for each Card, and putting both rules and AI stuff in the same place. This is sort of gross - but it seems like the path of least resistance. But maybe it is best for each card to support some sort of interface and then have AI components code against these? + +Is there a ""Correct"" OOP design for this? Or several reasonable possibilities?",2010/11/23,"['https://Stackoverflow.com/questions/4261219', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/409020/']","there are several ""correct"" OOP designs for this, depending on *how you want to model the game process and the game-playing-agent's AI* + +personally, i would take the minimum number of cards for a valid *round* in the game and implement those as instances of a Card class, and implement the players as instances of an Agent class, and implement a few simple playing strategies as instances of a Strategy (pattern) class, and then *see what happens* + +run through some tests, have a totally random player as a foil, look at short-term gain/loss max/min operators, try mutating the agent's strategies using a genetic algorithm, download an XCS classifier and see if it is useful to derive strategies... + +...the notion of a correct model depends strongly on how it will be used. Once you understand how you need to use the elements of the game and model/manipulate the player strategies/tactics, then you'll know what the 'correct' structure is for your solution","I've been thinking about the logic for a non-AI version of Dominion, and it's still a mess to figure out. + +You almost have to have a class for each card deck and an interface for each card type, keeping in mind that cards may have multiple types (such as Great Hall which is both Action and Victory). + +At present, all Attack cards are also Actions, so you may want to make the Attack interface subclass action. For most cards, the Action would just call the Attack method. However, there are a few cards where this would need to be different, such as for Minion where you have a choice whether or not to attack. + +Reaction cards are also Actions, but will also need special handling, as they can be revealed during an opponent's turn in response to an Attack card. As of Prosperity, they can also be revealed in response to things other than attacks... Watchtower can be revealed any time you would gain a card. + +Duration cards (which I missed in my list of 7 card types earlier) are Actions that stay in play for an extra turn... and also count for the Peddler's buy cost in Prosperity. + +Edit: Whoops, I didn't address the AI issue at all here... probably because my own development had been aimed more at a multiplayer network version." +4261219,"I've been tinkering around trying to make an AI player for the popular card game, Dominion (http://www.boardgamegeek.com/boardgame/36218/dominion). + +If you are not familiar with the game, it is basically a very streamlined cousin of Magic: The Gathering, where there is a large-ish library of cards with different rules on them. Over the course of a game, players buy these cards and incorporate them into their deck. + +I am interested in this game from a machine learning perspective - I want to pit bots against each other, have them play millions of games, and try to datamine insights that will make them play better. + +I am unsure how to separate the rules of the game (the verbatim instructions printed on each card) from the core AI decision-making logic. + +The obvious path that I have started down is creating a class for each Card, and putting both rules and AI stuff in the same place. This is sort of gross - but it seems like the path of least resistance. But maybe it is best for each card to support some sort of interface and then have AI components code against these? + +Is there a ""Correct"" OOP design for this? Or several reasonable possibilities?",2010/11/23,"['https://Stackoverflow.com/questions/4261219', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/409020/']","I would lean toward encapsulating the behaviour of a card as its own class, allowing easily for cards that have multiple behaviours (i.e. choices). It would also allow you to write parameterizable behaviours and mix and match them with cards. + +So cards would contain things like the cost of the card, when it can be played, its name, etc. It would also contain a list of behaviours that the card can do. + +The behaviours are seen by the AI actors as part of the cards. Just another property the cards have that can be weighed along with the cost. + +The AI actor that is actually *using* the card's behaviour needs to be able to interpret the behaviours, so the behaviour class might need to contain some hints for the AI to understand it, but no actual AI logic itself should be contained there. If AIs need specific behaviours for specific cards, write that kind of thing into the AI actor, not the card behaviour. + +If an AI actor needs to know that, for example, this behaviour has an expected victory point payoff of .2 points/round, that might be a part of the behaviour that acts as a hint to the AI when choosing what cards to buy/play. + +But really I don't know how you're approaching your AI actor design so maybe this doesn't make sense. But I think that thinking of behaviour as a property of cards rather than a fundamental part of the cards themselves might help. + +It gives you the advantage of encapsulating the AI actors' default actions (things the actors can do without needing cards) as behaviours as well, so you can weigh those actions against card actions without any special-case code.","there are several ""correct"" OOP designs for this, depending on *how you want to model the game process and the game-playing-agent's AI* + +personally, i would take the minimum number of cards for a valid *round* in the game and implement those as instances of a Card class, and implement the players as instances of an Agent class, and implement a few simple playing strategies as instances of a Strategy (pattern) class, and then *see what happens* + +run through some tests, have a totally random player as a foil, look at short-term gain/loss max/min operators, try mutating the agent's strategies using a genetic algorithm, download an XCS classifier and see if it is useful to derive strategies... + +...the notion of a correct model depends strongly on how it will be used. Once you understand how you need to use the elements of the game and model/manipulate the player strategies/tactics, then you'll know what the 'correct' structure is for your solution" +12726149,"I downloaded and configured eclipse cdt along with MinGW and able to compile c programs. + +My question, how to start executing the program in command prompt when Run option clicked from eclipse. Currently it always executes the program in eclipse console. + +Reason to have command prompt for executing c programs is to accept user inputs. +I would also like to know is there a way to accept user inputs when c program running in eclipse console. + +Thanks in advance, +-Manju",2012/10/04,"['https://Stackoverflow.com/questions/12726149', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/612465/']","Yes. + +``` + select + substring(data, 1, PATINDEX('%[0-9]%',data)-1) as ename, + substring(data, PATINDEX('%[0-9]%',data), len(data)) as sal + from + table + +```","``` +SELECT SUBSTRING(@ourName, 1, CHARINDEX(' ', @ourName)) AS [First], +SUBSTRING(@ourName, CHARINDEX(' ', @ourName) + 2, LEN(@ourName)) AS[Last] + +```" +26371381,"Let's say I have two Tables, called Person, and Couple, where each Couple record stores a pair of Person id's (also assume that each person is bound to *at most* another different person). +I am planning to support a lot of queries where I will ask for Person records that are not married yet. Do you guys think it's worthwhile to add a 'partnerId' field to Person? (It would be set to null if that person is not married yet) +I am hesitant to do this because the partnerId field is something that is computable - just go through the Couple table to find out. The performance cost for creating new couple will also increase because I have to do this extra book keeping. + +I hope that it doesn't sound like I am asking two different questions here, but I felt that this is relevant. Is it a good/common idea to include extra fields that are redundant (computable/inferable by joining with other tables), but will make your query a lot easier to write and faster? +Thanks!",2014/10/14,"['https://Stackoverflow.com/questions/26371381', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4143394/']","A better option is to keep the data normalized, and utilize a view (indexed, if supported by your rdbms). This gets you the convenience of dealing with all the relevant fields in one place, without denormalizing your data. + +Note: Even if a database doesn't support indexed views, you'll likely still be better off with a view as the indexes on the underlying tables can be utilized.","Is there always a zero to one relationship between Person and Couples? i.e. a person can have zero or one partner? If so then your `Couple` table is actually redundant, and your new field is a better approach. + +The only reason to split `Couple` off to another table is if one Person can have many partners. + +When someone gets a partner you either write one record to the `Couple` table or update one record in the `Person` table. I argue that your `Couple` table is redundant here. You haven't indicated that there is any extra info on the `Couple` record besides the link, and it appears that there is only ever zero or one Couple record for every `Person` record." +26371381,"Let's say I have two Tables, called Person, and Couple, where each Couple record stores a pair of Person id's (also assume that each person is bound to *at most* another different person). +I am planning to support a lot of queries where I will ask for Person records that are not married yet. Do you guys think it's worthwhile to add a 'partnerId' field to Person? (It would be set to null if that person is not married yet) +I am hesitant to do this because the partnerId field is something that is computable - just go through the Couple table to find out. The performance cost for creating new couple will also increase because I have to do this extra book keeping. + +I hope that it doesn't sound like I am asking two different questions here, but I felt that this is relevant. Is it a good/common idea to include extra fields that are redundant (computable/inferable by joining with other tables), but will make your query a lot easier to write and faster? +Thanks!",2014/10/14,"['https://Stackoverflow.com/questions/26371381', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4143394/']","A better option is to keep the data normalized, and utilize a view (indexed, if supported by your rdbms). This gets you the convenience of dealing with all the relevant fields in one place, without denormalizing your data. + +Note: Even if a database doesn't support indexed views, you'll likely still be better off with a view as the indexes on the underlying tables can be utilized.","How about one table? + +``` +-- This is psuedo-code, the syntax is not correct, but it should +-- be clear what it's doing +CREATE TABLE Person + ( + PersonId int not null + primary key + ,PartnerId int null + foreign key references Person (PersonId) + ) + +``` + +With this, + +* Everyone on the system has a row and a PersonId +* If you have a partner, they are listed in the PartnerId column + +Unnormalized data is always bad. Denormalized data, now, that can be beneficial under very specific circumstances. The best advice I ever heard on this subject it to first fully normalize your data, assess performance/goals/objectives, and then carefully denormalize only if it's demonstrably worth the extra overhead." +26371381,"Let's say I have two Tables, called Person, and Couple, where each Couple record stores a pair of Person id's (also assume that each person is bound to *at most* another different person). +I am planning to support a lot of queries where I will ask for Person records that are not married yet. Do you guys think it's worthwhile to add a 'partnerId' field to Person? (It would be set to null if that person is not married yet) +I am hesitant to do this because the partnerId field is something that is computable - just go through the Couple table to find out. The performance cost for creating new couple will also increase because I have to do this extra book keeping. + +I hope that it doesn't sound like I am asking two different questions here, but I felt that this is relevant. Is it a good/common idea to include extra fields that are redundant (computable/inferable by joining with other tables), but will make your query a lot easier to write and faster? +Thanks!",2014/10/14,"['https://Stackoverflow.com/questions/26371381', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4143394/']","A better option is to keep the data normalized, and utilize a view (indexed, if supported by your rdbms). This gets you the convenience of dealing with all the relevant fields in one place, without denormalizing your data. + +Note: Even if a database doesn't support indexed views, you'll likely still be better off with a view as the indexes on the underlying tables can be utilized.","I agree with Nick. Also consider the need for history of the couples. You could use row versioning in the same table, but this doesn't work very well for application databases, works best in a in a DW scenario. A history table in theory would duplicate all the data in the table, not just the relationship. A secondary table would give you this flexibility to add additional information about the relationship including StartDate and EndDate." +26371381,"Let's say I have two Tables, called Person, and Couple, where each Couple record stores a pair of Person id's (also assume that each person is bound to *at most* another different person). +I am planning to support a lot of queries where I will ask for Person records that are not married yet. Do you guys think it's worthwhile to add a 'partnerId' field to Person? (It would be set to null if that person is not married yet) +I am hesitant to do this because the partnerId field is something that is computable - just go through the Couple table to find out. The performance cost for creating new couple will also increase because I have to do this extra book keeping. + +I hope that it doesn't sound like I am asking two different questions here, but I felt that this is relevant. Is it a good/common idea to include extra fields that are redundant (computable/inferable by joining with other tables), but will make your query a lot easier to write and faster? +Thanks!",2014/10/14,"['https://Stackoverflow.com/questions/26371381', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4143394/']","Is there always a zero to one relationship between Person and Couples? i.e. a person can have zero or one partner? If so then your `Couple` table is actually redundant, and your new field is a better approach. + +The only reason to split `Couple` off to another table is if one Person can have many partners. + +When someone gets a partner you either write one record to the `Couple` table or update one record in the `Person` table. I argue that your `Couple` table is redundant here. You haven't indicated that there is any extra info on the `Couple` record besides the link, and it appears that there is only ever zero or one Couple record for every `Person` record.","How about one table? + +``` +-- This is psuedo-code, the syntax is not correct, but it should +-- be clear what it's doing +CREATE TABLE Person + ( + PersonId int not null + primary key + ,PartnerId int null + foreign key references Person (PersonId) + ) + +``` + +With this, + +* Everyone on the system has a row and a PersonId +* If you have a partner, they are listed in the PartnerId column + +Unnormalized data is always bad. Denormalized data, now, that can be beneficial under very specific circumstances. The best advice I ever heard on this subject it to first fully normalize your data, assess performance/goals/objectives, and then carefully denormalize only if it's demonstrably worth the extra overhead." +26371381,"Let's say I have two Tables, called Person, and Couple, where each Couple record stores a pair of Person id's (also assume that each person is bound to *at most* another different person). +I am planning to support a lot of queries where I will ask for Person records that are not married yet. Do you guys think it's worthwhile to add a 'partnerId' field to Person? (It would be set to null if that person is not married yet) +I am hesitant to do this because the partnerId field is something that is computable - just go through the Couple table to find out. The performance cost for creating new couple will also increase because I have to do this extra book keeping. + +I hope that it doesn't sound like I am asking two different questions here, but I felt that this is relevant. Is it a good/common idea to include extra fields that are redundant (computable/inferable by joining with other tables), but will make your query a lot easier to write and faster? +Thanks!",2014/10/14,"['https://Stackoverflow.com/questions/26371381', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4143394/']","Is there always a zero to one relationship between Person and Couples? i.e. a person can have zero or one partner? If so then your `Couple` table is actually redundant, and your new field is a better approach. + +The only reason to split `Couple` off to another table is if one Person can have many partners. + +When someone gets a partner you either write one record to the `Couple` table or update one record in the `Person` table. I argue that your `Couple` table is redundant here. You haven't indicated that there is any extra info on the `Couple` record besides the link, and it appears that there is only ever zero or one Couple record for every `Person` record.","I agree with Nick. Also consider the need for history of the couples. You could use row versioning in the same table, but this doesn't work very well for application databases, works best in a in a DW scenario. A history table in theory would duplicate all the data in the table, not just the relationship. A secondary table would give you this flexibility to add additional information about the relationship including StartDate and EndDate." +70342429,"I trying to change the color of the chevron indicator that appears on the section headers in a List view likest one shown here: + +[![enter image description here](https://i.stack.imgur.com/paNRA.png)](https://i.stack.imgur.com/paNRA.png) + +I tried to do that by setting the tint color on the list view: + +``` +List { +... +} + .tint(.red) +... + +``` + +That is not working. + +How can I change the color of that indicator?",2021/12/14,"['https://Stackoverflow.com/questions/70342429', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/728246/']",You haven't provided much code but some change with `accentColor` instead of `tint`,"The chevron can't react on any color changing modifiers. + +You have to disable standard chevron and use own, custom, (behaviour of the List is the same), like below + +```js +HStack { + Text(text) + NavigationLink(destination: Text(""D"")) { EmptyView() } // disabled ! + Image(systemName: ""chevron.right"") // << custom !! + .foregroundColor(Color.red) // any color !!! +} +```" +18274428,"I'm tried to deploy a new version of my app to heroku. The deployment fails because heroku says, that the gem pg is not in my GEMFILE ... I have this postgres gem in my GEMFILE. I also looked for some answers, but no one worked ... As anyone an idea? + +I use Ruby 2.0.0p247, Rails 3.2.14 refinery-cms 2.1.0 + +Here is my Gemfile: + +``` +source 'https://rubygems.org' +ruby '2.0.0' + +gem 'rails' +gem 'newrelic_rpm' + +group :production do + gem 'pg' + gem 'fog' +end + +# Gems used only for assets and not required +# in production environments by default. +group :assets do + gem 'sass-rails' + gem 'coffee-rails' + + # See https://github.com/sstephenson/execjs#readme for more supported runtimes + # gem 'therubyracer', :platforms => :ruby + + gem 'uglifier', '>= 1.0.3' +end + +gem 'jquery-rails' + +# To use ActiveModel has_secure_password +# gem 'bcrypt-ruby' + +# To use Jbuilder templates for JSON + gem 'jbuilder' + +# Use unicorn as the app server + gem 'unicorn' + +# Deploy with Capistrano + gem 'capistrano' + +# To use debugger + gem 'debugger' + +# The Heroku gem allows you to interface with Heroku's API +gem 'heroku' + +# Fog allows you to use S3 assets (added for Heroku) +gem 'fog' + +# Postgres support (added for Heroku) +#gem 'pg' + +#Connecting to Amazon S3 +gem 'aws-s3' +#gem 'taps' + +# Refinery CMS +#gem 'refinerycms', '~> 2.0.0', :git => 'git://github.com/refinery/refinerycms.git', :branch => '2-0-stable' +gem 'refinerycms' + +# Specify additional Refinery CMS Extensions here (all optional): +gem 'refinerycms-i18n' +# gem 'refinerycms-blog', '~> 2.0.0' +# gem 'refinerycms-inquiries', '~> 2.0.0' +# gem 'refinerycms-search', '~> 2.0.0' +gem 'refinerycms-page-images' + +gem 'refinerycms-announcements', :path => 'vendor/extensions' +gem 'refinerycms-publications', :path => 'vendor/extensions' +gem 'refinerycms-workers', :path => 'vendor/extensions' + +``` + +And here the error message: + +``` +-----> Writing config/database.yml to read from DATABASE_URL +-----> Preparing app for Rails asset pipeline + Running: rake assets:precompile + rake aborted! + Please install the postgresql adapter: `gem install activerecord-postgresql-adapter` (pg is not part of the bundle. Add it to Gemfile.) + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/bundler-1.3.2/lib/bundler/rubygems_integration.rb:214:in `block in replace_gem' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/activerecord-3.2.14/lib/active_record/connection_adapters/postgresql_adapter.rb:7:in `' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/activesupport-3.2.14/lib/active_support/dependencies.rb:251:in `require' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/activesupport-3.2.14/lib/active_support/dependencies.rb:251:in `block in require' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/activesupport-3.2.14/lib/active_support/dependencies.rb:236:in `load_dependency' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/activesupport-3.2.14/lib/active_support/dependencies.rb:251:in `require' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/activerecord-3.2.14/lib/active_record/connection_adapters/abstract/connection_specification.rb:50:in `resolve_hash_connection' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/activerecord-3.2.14/lib/active_record/connection_adapters/abstract/connection_specification.rb:41:in `resolve_string_connection' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/activerecord-3.2.14/lib/active_record/connection_adapters/abstract/connection_specification.rb:27:in `spec' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/activerecord-3.2.14/lib/active_record/connection_adapters/abstract/connection_specification.rb:130:in `establish_connection' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/activerecord-3.2.14/lib/active_record/railtie.rb:88:in `block (2 levels) in ' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/activesupport-3.2.14/lib/active_support/lazy_load_hooks.rb:36:in `instance_eval' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/activesupport-3.2.14/lib/active_support/lazy_load_hooks.rb:36:in `execute_hook' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/activesupport-3.2.14/lib/active_support/lazy_load_hooks.rb:26:in `block in on_load' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/activesupport-3.2.14/lib/active_support/lazy_load_hooks.rb:25:in `each' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/activesupport-3.2.14/lib/active_support/lazy_load_hooks.rb:25:in `on_load' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/activerecord-3.2.14/lib/active_record/railtie.rb:80:in `block in ' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/railties-3.2.14/lib/rails/initializable.rb:30:in `instance_exec' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/railties-3.2.14/lib/rails/initializable.rb:30:in `run' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/railties-3.2.14/lib/rails/initializable.rb:55:in `block in run_initializers' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/railties-3.2.14/lib/rails/initializable.rb:54:in `each' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/railties-3.2.14/lib/rails/initializable.rb:54:in `run_initializers' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/railties-3.2.14/lib/rails/application.rb:136:in `initialize!' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/railties-3.2.14/lib/rails/railtie/configurable.rb:30:in `method_missing' + /tmp/build_37zyls4tcoz59/config/environment.rb:5:in `' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/activesupport-3.2.14/lib/active_support/dependencies.rb:251:in `require' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/activesupport-3.2.14/lib/active_support/dependencies.rb:251:in `block in require' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/activesupport-3.2.14/lib/active_support/dependencies.rb:236:in `load_dependency' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/activesupport-3.2.14/lib/active_support/dependencies.rb:251:in `require' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/railties-3.2.14/lib/rails/application.rb:103:in `require_environment!' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/railties-3.2.14/lib/rails/application.rb:305:in `block (2 levels) in initialize_tasks' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/actionpack-3.2.14/lib/sprockets/assets.rake:93:in `block (2 levels) in ' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/actionpack-3.2.14/lib/sprockets/assets.rake:60:in `block (3 levels) in ' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/actionpack-3.2.14/lib/sprockets/assets.rake:23:in `invoke_or_reboot_rake_task' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/actionpack-3.2.14/lib/sprockets/assets.rake:29:in `block (2 levels) in ' + Tasks: TOP => environment + (See full trace by running task with --trace) + Precompiling assets failed, enabling runtime asset compilation + Injecting rails31_enable_runtime_asset_compilation + Please see this article for troubleshooting help: + http://devcenter.heroku.com/articles/rails31_heroku_cedar#troubleshooting + +```",2013/08/16,"['https://Stackoverflow.com/questions/18274428', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1458773/']","according to the gemfile: + +``` +# Postgres support (added for Heroku) +#gem 'pg' + +``` + +pg is commented-out. uncomment it to install it + +``` +gem 'pg' + +``` + +In my gemfile for instance, I work in windows, and heroku doesn't. So I have + +``` +gem ""pg"", '~> 0.15.1', :group => :production +group :development, :test do + gem 'pg', ""~> 0.15.1"", :platform => [:mswin, :mingw] + +``` + +since you must have some db installed, preferbly pg since it is heroku + +also, as Gavin in the comments said - make sure you are in production, since it seems that heroku doesn't think o..","The problem is that you have the pg gem in the production group. Therefore when assets are precompiled on Heroku (which uses the global group + assets group) then the PG gem cannot indeed be found because it's in the production group. + +I would suggest having the pg gem in the global group and available to allow asset groups." +18274428,"I'm tried to deploy a new version of my app to heroku. The deployment fails because heroku says, that the gem pg is not in my GEMFILE ... I have this postgres gem in my GEMFILE. I also looked for some answers, but no one worked ... As anyone an idea? + +I use Ruby 2.0.0p247, Rails 3.2.14 refinery-cms 2.1.0 + +Here is my Gemfile: + +``` +source 'https://rubygems.org' +ruby '2.0.0' + +gem 'rails' +gem 'newrelic_rpm' + +group :production do + gem 'pg' + gem 'fog' +end + +# Gems used only for assets and not required +# in production environments by default. +group :assets do + gem 'sass-rails' + gem 'coffee-rails' + + # See https://github.com/sstephenson/execjs#readme for more supported runtimes + # gem 'therubyracer', :platforms => :ruby + + gem 'uglifier', '>= 1.0.3' +end + +gem 'jquery-rails' + +# To use ActiveModel has_secure_password +# gem 'bcrypt-ruby' + +# To use Jbuilder templates for JSON + gem 'jbuilder' + +# Use unicorn as the app server + gem 'unicorn' + +# Deploy with Capistrano + gem 'capistrano' + +# To use debugger + gem 'debugger' + +# The Heroku gem allows you to interface with Heroku's API +gem 'heroku' + +# Fog allows you to use S3 assets (added for Heroku) +gem 'fog' + +# Postgres support (added for Heroku) +#gem 'pg' + +#Connecting to Amazon S3 +gem 'aws-s3' +#gem 'taps' + +# Refinery CMS +#gem 'refinerycms', '~> 2.0.0', :git => 'git://github.com/refinery/refinerycms.git', :branch => '2-0-stable' +gem 'refinerycms' + +# Specify additional Refinery CMS Extensions here (all optional): +gem 'refinerycms-i18n' +# gem 'refinerycms-blog', '~> 2.0.0' +# gem 'refinerycms-inquiries', '~> 2.0.0' +# gem 'refinerycms-search', '~> 2.0.0' +gem 'refinerycms-page-images' + +gem 'refinerycms-announcements', :path => 'vendor/extensions' +gem 'refinerycms-publications', :path => 'vendor/extensions' +gem 'refinerycms-workers', :path => 'vendor/extensions' + +``` + +And here the error message: + +``` +-----> Writing config/database.yml to read from DATABASE_URL +-----> Preparing app for Rails asset pipeline + Running: rake assets:precompile + rake aborted! + Please install the postgresql adapter: `gem install activerecord-postgresql-adapter` (pg is not part of the bundle. Add it to Gemfile.) + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/bundler-1.3.2/lib/bundler/rubygems_integration.rb:214:in `block in replace_gem' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/activerecord-3.2.14/lib/active_record/connection_adapters/postgresql_adapter.rb:7:in `' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/activesupport-3.2.14/lib/active_support/dependencies.rb:251:in `require' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/activesupport-3.2.14/lib/active_support/dependencies.rb:251:in `block in require' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/activesupport-3.2.14/lib/active_support/dependencies.rb:236:in `load_dependency' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/activesupport-3.2.14/lib/active_support/dependencies.rb:251:in `require' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/activerecord-3.2.14/lib/active_record/connection_adapters/abstract/connection_specification.rb:50:in `resolve_hash_connection' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/activerecord-3.2.14/lib/active_record/connection_adapters/abstract/connection_specification.rb:41:in `resolve_string_connection' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/activerecord-3.2.14/lib/active_record/connection_adapters/abstract/connection_specification.rb:27:in `spec' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/activerecord-3.2.14/lib/active_record/connection_adapters/abstract/connection_specification.rb:130:in `establish_connection' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/activerecord-3.2.14/lib/active_record/railtie.rb:88:in `block (2 levels) in ' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/activesupport-3.2.14/lib/active_support/lazy_load_hooks.rb:36:in `instance_eval' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/activesupport-3.2.14/lib/active_support/lazy_load_hooks.rb:36:in `execute_hook' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/activesupport-3.2.14/lib/active_support/lazy_load_hooks.rb:26:in `block in on_load' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/activesupport-3.2.14/lib/active_support/lazy_load_hooks.rb:25:in `each' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/activesupport-3.2.14/lib/active_support/lazy_load_hooks.rb:25:in `on_load' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/activerecord-3.2.14/lib/active_record/railtie.rb:80:in `block in ' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/railties-3.2.14/lib/rails/initializable.rb:30:in `instance_exec' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/railties-3.2.14/lib/rails/initializable.rb:30:in `run' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/railties-3.2.14/lib/rails/initializable.rb:55:in `block in run_initializers' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/railties-3.2.14/lib/rails/initializable.rb:54:in `each' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/railties-3.2.14/lib/rails/initializable.rb:54:in `run_initializers' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/railties-3.2.14/lib/rails/application.rb:136:in `initialize!' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/railties-3.2.14/lib/rails/railtie/configurable.rb:30:in `method_missing' + /tmp/build_37zyls4tcoz59/config/environment.rb:5:in `' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/activesupport-3.2.14/lib/active_support/dependencies.rb:251:in `require' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/activesupport-3.2.14/lib/active_support/dependencies.rb:251:in `block in require' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/activesupport-3.2.14/lib/active_support/dependencies.rb:236:in `load_dependency' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/activesupport-3.2.14/lib/active_support/dependencies.rb:251:in `require' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/railties-3.2.14/lib/rails/application.rb:103:in `require_environment!' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/railties-3.2.14/lib/rails/application.rb:305:in `block (2 levels) in initialize_tasks' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/actionpack-3.2.14/lib/sprockets/assets.rake:93:in `block (2 levels) in ' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/actionpack-3.2.14/lib/sprockets/assets.rake:60:in `block (3 levels) in ' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/actionpack-3.2.14/lib/sprockets/assets.rake:23:in `invoke_or_reboot_rake_task' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/actionpack-3.2.14/lib/sprockets/assets.rake:29:in `block (2 levels) in ' + Tasks: TOP => environment + (See full trace by running task with --trace) + Precompiling assets failed, enabling runtime asset compilation + Injecting rails31_enable_runtime_asset_compilation + Please see this article for troubleshooting help: + http://devcenter.heroku.com/articles/rails31_heroku_cedar#troubleshooting + +```",2013/08/16,"['https://Stackoverflow.com/questions/18274428', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1458773/']","according to the gemfile: + +``` +# Postgres support (added for Heroku) +#gem 'pg' + +``` + +pg is commented-out. uncomment it to install it + +``` +gem 'pg' + +``` + +In my gemfile for instance, I work in windows, and heroku doesn't. So I have + +``` +gem ""pg"", '~> 0.15.1', :group => :production +group :development, :test do + gem 'pg', ""~> 0.15.1"", :platform => [:mswin, :mingw] + +``` + +since you must have some db installed, preferbly pg since it is heroku + +also, as Gavin in the comments said - make sure you are in production, since it seems that heroku doesn't think o..","Oh no ... the solution was to delete my git repo and create a new one. I don't know why, but my repo got messed up (I added new files and so on ..) and so it didn't commit all data. After the tip of chucknelson I tried to lock a certain rails version and saw that heroku didn't get this." +18274428,"I'm tried to deploy a new version of my app to heroku. The deployment fails because heroku says, that the gem pg is not in my GEMFILE ... I have this postgres gem in my GEMFILE. I also looked for some answers, but no one worked ... As anyone an idea? + +I use Ruby 2.0.0p247, Rails 3.2.14 refinery-cms 2.1.0 + +Here is my Gemfile: + +``` +source 'https://rubygems.org' +ruby '2.0.0' + +gem 'rails' +gem 'newrelic_rpm' + +group :production do + gem 'pg' + gem 'fog' +end + +# Gems used only for assets and not required +# in production environments by default. +group :assets do + gem 'sass-rails' + gem 'coffee-rails' + + # See https://github.com/sstephenson/execjs#readme for more supported runtimes + # gem 'therubyracer', :platforms => :ruby + + gem 'uglifier', '>= 1.0.3' +end + +gem 'jquery-rails' + +# To use ActiveModel has_secure_password +# gem 'bcrypt-ruby' + +# To use Jbuilder templates for JSON + gem 'jbuilder' + +# Use unicorn as the app server + gem 'unicorn' + +# Deploy with Capistrano + gem 'capistrano' + +# To use debugger + gem 'debugger' + +# The Heroku gem allows you to interface with Heroku's API +gem 'heroku' + +# Fog allows you to use S3 assets (added for Heroku) +gem 'fog' + +# Postgres support (added for Heroku) +#gem 'pg' + +#Connecting to Amazon S3 +gem 'aws-s3' +#gem 'taps' + +# Refinery CMS +#gem 'refinerycms', '~> 2.0.0', :git => 'git://github.com/refinery/refinerycms.git', :branch => '2-0-stable' +gem 'refinerycms' + +# Specify additional Refinery CMS Extensions here (all optional): +gem 'refinerycms-i18n' +# gem 'refinerycms-blog', '~> 2.0.0' +# gem 'refinerycms-inquiries', '~> 2.0.0' +# gem 'refinerycms-search', '~> 2.0.0' +gem 'refinerycms-page-images' + +gem 'refinerycms-announcements', :path => 'vendor/extensions' +gem 'refinerycms-publications', :path => 'vendor/extensions' +gem 'refinerycms-workers', :path => 'vendor/extensions' + +``` + +And here the error message: + +``` +-----> Writing config/database.yml to read from DATABASE_URL +-----> Preparing app for Rails asset pipeline + Running: rake assets:precompile + rake aborted! + Please install the postgresql adapter: `gem install activerecord-postgresql-adapter` (pg is not part of the bundle. Add it to Gemfile.) + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/bundler-1.3.2/lib/bundler/rubygems_integration.rb:214:in `block in replace_gem' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/activerecord-3.2.14/lib/active_record/connection_adapters/postgresql_adapter.rb:7:in `' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/activesupport-3.2.14/lib/active_support/dependencies.rb:251:in `require' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/activesupport-3.2.14/lib/active_support/dependencies.rb:251:in `block in require' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/activesupport-3.2.14/lib/active_support/dependencies.rb:236:in `load_dependency' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/activesupport-3.2.14/lib/active_support/dependencies.rb:251:in `require' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/activerecord-3.2.14/lib/active_record/connection_adapters/abstract/connection_specification.rb:50:in `resolve_hash_connection' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/activerecord-3.2.14/lib/active_record/connection_adapters/abstract/connection_specification.rb:41:in `resolve_string_connection' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/activerecord-3.2.14/lib/active_record/connection_adapters/abstract/connection_specification.rb:27:in `spec' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/activerecord-3.2.14/lib/active_record/connection_adapters/abstract/connection_specification.rb:130:in `establish_connection' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/activerecord-3.2.14/lib/active_record/railtie.rb:88:in `block (2 levels) in ' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/activesupport-3.2.14/lib/active_support/lazy_load_hooks.rb:36:in `instance_eval' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/activesupport-3.2.14/lib/active_support/lazy_load_hooks.rb:36:in `execute_hook' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/activesupport-3.2.14/lib/active_support/lazy_load_hooks.rb:26:in `block in on_load' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/activesupport-3.2.14/lib/active_support/lazy_load_hooks.rb:25:in `each' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/activesupport-3.2.14/lib/active_support/lazy_load_hooks.rb:25:in `on_load' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/activerecord-3.2.14/lib/active_record/railtie.rb:80:in `block in ' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/railties-3.2.14/lib/rails/initializable.rb:30:in `instance_exec' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/railties-3.2.14/lib/rails/initializable.rb:30:in `run' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/railties-3.2.14/lib/rails/initializable.rb:55:in `block in run_initializers' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/railties-3.2.14/lib/rails/initializable.rb:54:in `each' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/railties-3.2.14/lib/rails/initializable.rb:54:in `run_initializers' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/railties-3.2.14/lib/rails/application.rb:136:in `initialize!' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/railties-3.2.14/lib/rails/railtie/configurable.rb:30:in `method_missing' + /tmp/build_37zyls4tcoz59/config/environment.rb:5:in `' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/activesupport-3.2.14/lib/active_support/dependencies.rb:251:in `require' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/activesupport-3.2.14/lib/active_support/dependencies.rb:251:in `block in require' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/activesupport-3.2.14/lib/active_support/dependencies.rb:236:in `load_dependency' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/activesupport-3.2.14/lib/active_support/dependencies.rb:251:in `require' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/railties-3.2.14/lib/rails/application.rb:103:in `require_environment!' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/railties-3.2.14/lib/rails/application.rb:305:in `block (2 levels) in initialize_tasks' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/actionpack-3.2.14/lib/sprockets/assets.rake:93:in `block (2 levels) in ' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/actionpack-3.2.14/lib/sprockets/assets.rake:60:in `block (3 levels) in ' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/actionpack-3.2.14/lib/sprockets/assets.rake:23:in `invoke_or_reboot_rake_task' + /tmp/build_37zyls4tcoz59/vendor/bundle/ruby/2.0.0/gems/actionpack-3.2.14/lib/sprockets/assets.rake:29:in `block (2 levels) in ' + Tasks: TOP => environment + (See full trace by running task with --trace) + Precompiling assets failed, enabling runtime asset compilation + Injecting rails31_enable_runtime_asset_compilation + Please see this article for troubleshooting help: + http://devcenter.heroku.com/articles/rails31_heroku_cedar#troubleshooting + +```",2013/08/16,"['https://Stackoverflow.com/questions/18274428', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1458773/']","The problem is that you have the pg gem in the production group. Therefore when assets are precompiled on Heroku (which uses the global group + assets group) then the PG gem cannot indeed be found because it's in the production group. + +I would suggest having the pg gem in the global group and available to allow asset groups.","Oh no ... the solution was to delete my git repo and create a new one. I don't know why, but my repo got messed up (I added new files and so on ..) and so it didn't commit all data. After the tip of chucknelson I tried to lock a certain rails version and saw that heroku didn't get this." +42103738,"I am really new to Swift and working on my first project (I have a bit of experience with Javascript and web development). I have run into trouble (going on 4 hours of trying different solutions). + +I have an app where when a `UIButton` is pushed it logs a value to FireBase (ON). When it is pushed a second time it logs (OFF) to the database. + +When I make the button change the `view.backgroundColor` and put if else tied to the colour it works. + +But I can't for the life of me figure out how to build my if else based on the state of the button. I have now ended up trying to change the colour of the button itself and tie the if else to that. Which I know is a really messy improper way to go about it. + +``` +import UIKit +import Firebase +import FirebaseDatabase + +class ViewController: UIViewController { + @IBAction func OnOffButton(_ sender: UITapGestureRecognizer){ + if button.backgroundColor == UIColor.white { + OnOff(state:""ON"") + OnOffButton.backgroundColor = UIColor.blue + } else{ + OnOff(state:""OFF"") + OnOffButton.backgroundColor = UIColor.white + } + } + + override func viewDidLoad() { + super.viewDidLoad() + // Do any additional setup after loading the view, typically from a nib. + OnOff(state: ""Off"") + OnOffButton.backgroundColor = UIColor.white + } + +```",2017/02/08,"['https://Stackoverflow.com/questions/42103738', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7532077/']","`UIButton` inherits from `UIControl` which has an `isSelected` property. Use this to track state. Typically you'll use `button.isSelected == true` to correspond to your on state, and `false` is your off state. + +To toggle state you can use `button.isSelected = !button.isSelected`. + +For your specific example: + +``` +// User pressed the button, so toggle the state: +button.isSelected = !button.isSelected + +// Now do something with the new state +if button.isSelected { + // button is on, so ... +} else { + // button is off, so... +} + +```","Par's solution should work. However, I would suggest a different approach. + +In general it's not good design to store state in a view object. It's fragile, and doesn't follow the MVC design pattern, where view objects display and collect state information, not store it. + +Instead I would create an instance variable in your view controller, buttonIsSelected. Toggle that when the button is tapped, and have it change the state of the button's selected property, the button's color, AND log the new state to FireBase. + +If you store more complex state in your view controller it would be worth separating that out into a model object. It can be as simple as a struct that holds the different state values. That way you have a clear separation between your controller (view controller) and model." +42103738,"I am really new to Swift and working on my first project (I have a bit of experience with Javascript and web development). I have run into trouble (going on 4 hours of trying different solutions). + +I have an app where when a `UIButton` is pushed it logs a value to FireBase (ON). When it is pushed a second time it logs (OFF) to the database. + +When I make the button change the `view.backgroundColor` and put if else tied to the colour it works. + +But I can't for the life of me figure out how to build my if else based on the state of the button. I have now ended up trying to change the colour of the button itself and tie the if else to that. Which I know is a really messy improper way to go about it. + +``` +import UIKit +import Firebase +import FirebaseDatabase + +class ViewController: UIViewController { + @IBAction func OnOffButton(_ sender: UITapGestureRecognizer){ + if button.backgroundColor == UIColor.white { + OnOff(state:""ON"") + OnOffButton.backgroundColor = UIColor.blue + } else{ + OnOff(state:""OFF"") + OnOffButton.backgroundColor = UIColor.white + } + } + + override func viewDidLoad() { + super.viewDidLoad() + // Do any additional setup after loading the view, typically from a nib. + OnOff(state: ""Off"") + OnOffButton.backgroundColor = UIColor.white + } + +```",2017/02/08,"['https://Stackoverflow.com/questions/42103738', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7532077/']","`UIButton` inherits from `UIControl` which has an `isSelected` property. Use this to track state. Typically you'll use `button.isSelected == true` to correspond to your on state, and `false` is your off state. + +To toggle state you can use `button.isSelected = !button.isSelected`. + +For your specific example: + +``` +// User pressed the button, so toggle the state: +button.isSelected = !button.isSelected + +// Now do something with the new state +if button.isSelected { + // button is on, so ... +} else { + // button is off, so... +} + +```","Here’s a quick and dirty implementation of Duncan C’s suggestion to use a `buttonIsSelected` variable to store the button state: + +``` +import UIKit + +class ViewController: UIViewController { + + var buttonIsSelected = false + @IBOutlet weak var onOffButton: UIButton! + + override func viewDidLoad() { + super.viewDidLoad() + updateOnOffButton() + } + + override func didReceiveMemoryWarning() { + super.didReceiveMemoryWarning() + // Dispose of any resources that can be recreated. + } + + @IBAction func onOffButtonTapped(_ sender: Any) { + buttonIsSelected = !buttonIsSelected + updateOnOffButton() + } + + func updateOnOffButton() { + if buttonIsSelected { + onOffButton.backgroundColor = UIColor.blue + } + else { + onOffButton.backgroundColor = UIColor.white + } + } + +} + +```" +42103738,"I am really new to Swift and working on my first project (I have a bit of experience with Javascript and web development). I have run into trouble (going on 4 hours of trying different solutions). + +I have an app where when a `UIButton` is pushed it logs a value to FireBase (ON). When it is pushed a second time it logs (OFF) to the database. + +When I make the button change the `view.backgroundColor` and put if else tied to the colour it works. + +But I can't for the life of me figure out how to build my if else based on the state of the button. I have now ended up trying to change the colour of the button itself and tie the if else to that. Which I know is a really messy improper way to go about it. + +``` +import UIKit +import Firebase +import FirebaseDatabase + +class ViewController: UIViewController { + @IBAction func OnOffButton(_ sender: UITapGestureRecognizer){ + if button.backgroundColor == UIColor.white { + OnOff(state:""ON"") + OnOffButton.backgroundColor = UIColor.blue + } else{ + OnOff(state:""OFF"") + OnOffButton.backgroundColor = UIColor.white + } + } + + override func viewDidLoad() { + super.viewDidLoad() + // Do any additional setup after loading the view, typically from a nib. + OnOff(state: ""Off"") + OnOffButton.backgroundColor = UIColor.white + } + +```",2017/02/08,"['https://Stackoverflow.com/questions/42103738', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7532077/']","Here’s a quick and dirty implementation of Duncan C’s suggestion to use a `buttonIsSelected` variable to store the button state: + +``` +import UIKit + +class ViewController: UIViewController { + + var buttonIsSelected = false + @IBOutlet weak var onOffButton: UIButton! + + override func viewDidLoad() { + super.viewDidLoad() + updateOnOffButton() + } + + override func didReceiveMemoryWarning() { + super.didReceiveMemoryWarning() + // Dispose of any resources that can be recreated. + } + + @IBAction func onOffButtonTapped(_ sender: Any) { + buttonIsSelected = !buttonIsSelected + updateOnOffButton() + } + + func updateOnOffButton() { + if buttonIsSelected { + onOffButton.backgroundColor = UIColor.blue + } + else { + onOffButton.backgroundColor = UIColor.white + } + } + +} + +```","Par's solution should work. However, I would suggest a different approach. + +In general it's not good design to store state in a view object. It's fragile, and doesn't follow the MVC design pattern, where view objects display and collect state information, not store it. + +Instead I would create an instance variable in your view controller, buttonIsSelected. Toggle that when the button is tapped, and have it change the state of the button's selected property, the button's color, AND log the new state to FireBase. + +If you store more complex state in your view controller it would be worth separating that out into a model object. It can be as simple as a struct that holds the different state values. That way you have a clear separation between your controller (view controller) and model." +69550532,"I'm learning haskell, and I'm trying to rewrite a function using composition only + +Here's the function I'm trying to refactor: + +```hs +ceilingDiv a b = ceiling (a / b) + +``` + +So far I managed to make it work using curry and uncurry but it feels dirty: + +```hs +ceilingDiv = curry $ ceiling . uncurry (/) + +``` + +Is there any way to do this more cleanly? I was thinking `ceiling . div`, but it doesn't work because `(/)` returns a function and ceiling takes a Double as its argument.",2021/10/13,"['https://Stackoverflow.com/questions/69550532', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2410957/']","Compositions with multiple arguments are usually best just left in point-ful form. None of the alternatives is as clean and clear. Do make use of composition- and grouping operators, but don't golf away arguments just for the sake of it. + +``` +ceilingDiv a b = ceiling $ a/b + +``` + +What you can certainly do is eta-reduce the `b` argument + +``` +ceilingDiv a = ceiling . (a/) + +``` + +but I'd leave it at that. Even that is IMO less clean than the original 2-argument form, because the division operator needs to be sectioned. + +When directly passing compositions to a higher-order function then it can make sense to aim a bit more agressively point-free, to avoid lambda bindings. The [`composition` package](https://hackage.haskell.org/package/composition-1.0.2.2/docs/Data-Composition.html#v:.:) has a whole bunch of operators for composing with more arguments. In this case, you could use the indeed quite concise + +``` +ceilingDiv = ceiling .: (/) + +```","There's a fun site called - it provides a solution to your problem like this: `ceilingDiv = (ceiling .) . (/)`. It looks ugly because point-free composition with multiple arguments is a pain. Sometimes it's achieved by using `.` [sections](https://wiki.haskell.org/Section_of_an_infix_operator) like here, sometimes by using an [Applicative](https://wiki.haskell.org/Applicative_functor) instance of functions and the `<*>` operator. + +I think your solution with curry-uncurry is nice. It deals with passing multiple arguments by wrapping them into one tuple." +59499722,"The predicate function: + +``` +bool Schedule::predicateFunc(map,pair >::iterator it,string &a) +{ + return (it->first).first == a; +} + +``` + +Function which I have to use predicate func: + +``` + void Schedule::studentSchedule() { + string s,c; + cout<<""Enter the student and course name to create schedule""<>s>>c; + list::iterator studentLoc; + map,pair >::iterator courseL; + map,pair >::iterator location; + + studentLoc = find(getStudentList().begin(),getStudentList().end(),s); + location = find_if(getMatchMap().begin(), getMatchMap().end(), predicateFunc(courseL,c) ) + if(studentLoc != getStudentList().end() && location != getMatchMap().end()) + { + cout<<""I found it""<::operator()(_Iterator) [with _Iterator = std::_Rb_tree_iterator, int>, std::pair, std::array > > >; _Predicate = bool]': +C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/stl_algo.h:104:42: required from '_InputIterator std::__find_if(_InputIterator, _InputIterator, _Predicate, std::input_iterator_tag) [with _InputIterator = std::_Rb_tree_iterator, int>, std::pair, std::array > > >; _Predicate = __gnu_cxx::__ops::_Iter_pred]' +C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/stl_algo.h:161:23: required from '_Iterator std::__find_if(_Iterator, _Iterator, _Predicate) [with _Iterator = std::_Rb_tree_iterator, int>, std::pair, std::array > > >; _Predicate = __gnu_cxx::__ops::_Iter_pred]' +C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/stl_algo.h:3930:28: required from '_IIter std::find_if(_IIter, _IIter, _Predicate) [with _IIter = std::_Rb_tree_iterator, int>, std::pair, std::array > > >; _Predicate = bool]' +C:\Users\Fatih\Desktop\clion\SchoolProject1\Schedule.cpp:25:93: required from here +C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/predefined_ops.h:283:11: error: expression cannot be used as a function + { return bool(_M_pred(*__it)); } + ^~~~~~~~~~~~~~~~~~~~ + +``` + +What is the true usage of the predicate funtion in here ?",2019/12/27,"['https://Stackoverflow.com/questions/59499722', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12543764/']","Please execute query inside the loop as given below + +``` +... +$conn = mysqli_connect($servername, $username, $password, $dbname); +... + +if (isset($_POST['array'])) { + foreach ($_POST['array'] as $loop) { + + $sql = ""insert into persons (Name, Email) + values ('"" . $loop['name'] . ""', '"" . $loop['email'] . ""')""; + $conn->query($sql);// Query should execute inside loop + + } +} + +```","If you want to execute the query outside the loop +Try using as following + +``` + if (isset($_POST['array'])) { + $sql=""""; + foreach ($_POST['array'] as $loop) { + + $sql .= ""insert into persons (Name, Email) + values ('"" . $loop['name'] . ""', '"" . $loop['email'] . ""');\n""; + } + } + +```" +59499722,"The predicate function: + +``` +bool Schedule::predicateFunc(map,pair >::iterator it,string &a) +{ + return (it->first).first == a; +} + +``` + +Function which I have to use predicate func: + +``` + void Schedule::studentSchedule() { + string s,c; + cout<<""Enter the student and course name to create schedule""<>s>>c; + list::iterator studentLoc; + map,pair >::iterator courseL; + map,pair >::iterator location; + + studentLoc = find(getStudentList().begin(),getStudentList().end(),s); + location = find_if(getMatchMap().begin(), getMatchMap().end(), predicateFunc(courseL,c) ) + if(studentLoc != getStudentList().end() && location != getMatchMap().end()) + { + cout<<""I found it""<::operator()(_Iterator) [with _Iterator = std::_Rb_tree_iterator, int>, std::pair, std::array > > >; _Predicate = bool]': +C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/stl_algo.h:104:42: required from '_InputIterator std::__find_if(_InputIterator, _InputIterator, _Predicate, std::input_iterator_tag) [with _InputIterator = std::_Rb_tree_iterator, int>, std::pair, std::array > > >; _Predicate = __gnu_cxx::__ops::_Iter_pred]' +C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/stl_algo.h:161:23: required from '_Iterator std::__find_if(_Iterator, _Iterator, _Predicate) [with _Iterator = std::_Rb_tree_iterator, int>, std::pair, std::array > > >; _Predicate = __gnu_cxx::__ops::_Iter_pred]' +C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/stl_algo.h:3930:28: required from '_IIter std::find_if(_IIter, _IIter, _Predicate) [with _IIter = std::_Rb_tree_iterator, int>, std::pair, std::array > > >; _Predicate = bool]' +C:\Users\Fatih\Desktop\clion\SchoolProject1\Schedule.cpp:25:93: required from here +C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/predefined_ops.h:283:11: error: expression cannot be used as a function + { return bool(_M_pred(*__it)); } + ^~~~~~~~~~~~~~~~~~~~ + +``` + +What is the true usage of the predicate funtion in here ?",2019/12/27,"['https://Stackoverflow.com/questions/59499722', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12543764/']","Better way is only one time create `insert` + +``` +if (isset($_POST['array'])) { + $values = []; + $sql = ""insert into persons (Name, Email) values ""; + + foreach ($_POST['array'] as $loop) { + $values[] = ""('"" . $conn->real_escape_string($loop['name']) . ""', '"" . $conn->real_escape_string($loop['email']) . ""')""; + } + + if (!empty($values)) { + $conn->query($sql . implode(', ', $values)); + } +} + +```","Please execute query inside the loop as given below + +``` +... +$conn = mysqli_connect($servername, $username, $password, $dbname); +... + +if (isset($_POST['array'])) { + foreach ($_POST['array'] as $loop) { + + $sql = ""insert into persons (Name, Email) + values ('"" . $loop['name'] . ""', '"" . $loop['email'] . ""')""; + $conn->query($sql);// Query should execute inside loop + + } +} + +```" +59499722,"The predicate function: + +``` +bool Schedule::predicateFunc(map,pair >::iterator it,string &a) +{ + return (it->first).first == a; +} + +``` + +Function which I have to use predicate func: + +``` + void Schedule::studentSchedule() { + string s,c; + cout<<""Enter the student and course name to create schedule""<>s>>c; + list::iterator studentLoc; + map,pair >::iterator courseL; + map,pair >::iterator location; + + studentLoc = find(getStudentList().begin(),getStudentList().end(),s); + location = find_if(getMatchMap().begin(), getMatchMap().end(), predicateFunc(courseL,c) ) + if(studentLoc != getStudentList().end() && location != getMatchMap().end()) + { + cout<<""I found it""<::operator()(_Iterator) [with _Iterator = std::_Rb_tree_iterator, int>, std::pair, std::array > > >; _Predicate = bool]': +C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/stl_algo.h:104:42: required from '_InputIterator std::__find_if(_InputIterator, _InputIterator, _Predicate, std::input_iterator_tag) [with _InputIterator = std::_Rb_tree_iterator, int>, std::pair, std::array > > >; _Predicate = __gnu_cxx::__ops::_Iter_pred]' +C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/stl_algo.h:161:23: required from '_Iterator std::__find_if(_Iterator, _Iterator, _Predicate) [with _Iterator = std::_Rb_tree_iterator, int>, std::pair, std::array > > >; _Predicate = __gnu_cxx::__ops::_Iter_pred]' +C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/stl_algo.h:3930:28: required from '_IIter std::find_if(_IIter, _IIter, _Predicate) [with _IIter = std::_Rb_tree_iterator, int>, std::pair, std::array > > >; _Predicate = bool]' +C:\Users\Fatih\Desktop\clion\SchoolProject1\Schedule.cpp:25:93: required from here +C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/predefined_ops.h:283:11: error: expression cannot be used as a function + { return bool(_M_pred(*__it)); } + ^~~~~~~~~~~~~~~~~~~~ + +``` + +What is the true usage of the predicate funtion in here ?",2019/12/27,"['https://Stackoverflow.com/questions/59499722', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12543764/']","The reason why it doesn't work is because you never execute your SQL query anywhere. + +To execute the query you should first prepare the statement and then bind the params and execute. + +``` +// Your connection to DB +mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); +$mysqli = new mysqli('localhost', 'username', 'password', 'dbname'); +$mysqli->set_charset('utf8mb4'); // always set the charset + +if (isset($_POST['array'])) { + $stmt = $mysqli->prepare('INSERT INTO persons (Name, Email) VALUES (?,?)'); + foreach ($_POST['array'] as $loop) { + $stmt->bind_param('ss', $loop['name'], $loop['email']); + $stmt->execute(); + } +} + +```","Please execute query inside the loop as given below + +``` +... +$conn = mysqli_connect($servername, $username, $password, $dbname); +... + +if (isset($_POST['array'])) { + foreach ($_POST['array'] as $loop) { + + $sql = ""insert into persons (Name, Email) + values ('"" . $loop['name'] . ""', '"" . $loop['email'] . ""')""; + $conn->query($sql);// Query should execute inside loop + + } +} + +```" +59499722,"The predicate function: + +``` +bool Schedule::predicateFunc(map,pair >::iterator it,string &a) +{ + return (it->first).first == a; +} + +``` + +Function which I have to use predicate func: + +``` + void Schedule::studentSchedule() { + string s,c; + cout<<""Enter the student and course name to create schedule""<>s>>c; + list::iterator studentLoc; + map,pair >::iterator courseL; + map,pair >::iterator location; + + studentLoc = find(getStudentList().begin(),getStudentList().end(),s); + location = find_if(getMatchMap().begin(), getMatchMap().end(), predicateFunc(courseL,c) ) + if(studentLoc != getStudentList().end() && location != getMatchMap().end()) + { + cout<<""I found it""<::operator()(_Iterator) [with _Iterator = std::_Rb_tree_iterator, int>, std::pair, std::array > > >; _Predicate = bool]': +C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/stl_algo.h:104:42: required from '_InputIterator std::__find_if(_InputIterator, _InputIterator, _Predicate, std::input_iterator_tag) [with _InputIterator = std::_Rb_tree_iterator, int>, std::pair, std::array > > >; _Predicate = __gnu_cxx::__ops::_Iter_pred]' +C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/stl_algo.h:161:23: required from '_Iterator std::__find_if(_Iterator, _Iterator, _Predicate) [with _Iterator = std::_Rb_tree_iterator, int>, std::pair, std::array > > >; _Predicate = __gnu_cxx::__ops::_Iter_pred]' +C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/stl_algo.h:3930:28: required from '_IIter std::find_if(_IIter, _IIter, _Predicate) [with _IIter = std::_Rb_tree_iterator, int>, std::pair, std::array > > >; _Predicate = bool]' +C:\Users\Fatih\Desktop\clion\SchoolProject1\Schedule.cpp:25:93: required from here +C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/predefined_ops.h:283:11: error: expression cannot be used as a function + { return bool(_M_pred(*__it)); } + ^~~~~~~~~~~~~~~~~~~~ + +``` + +What is the true usage of the predicate funtion in here ?",2019/12/27,"['https://Stackoverflow.com/questions/59499722', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12543764/']","Please execute query inside the loop as given below + +``` +... +$conn = mysqli_connect($servername, $username, $password, $dbname); +... + +if (isset($_POST['array'])) { + foreach ($_POST['array'] as $loop) { + + $sql = ""insert into persons (Name, Email) + values ('"" . $loop['name'] . ""', '"" . $loop['email'] . ""')""; + $conn->query($sql);// Query should execute inside loop + + } +} + +```","I had the same issue inserting JSON arrays into MySQL and fixed it by putting the `mysqli_stmt->execute()` function inside the `foreach` + +``` +// loop through the array +foreach ($data as $row) { + echo ""Data has been Uploaded successfully
""; + // get the project details + $id = $row['id']; + $name = $row['name']; + $togglCid = $row['cid']; + // execute insert query + mysqli_stmt_execute($sql); +} + +``` + +This means it executes the code after each loop" +59499722,"The predicate function: + +``` +bool Schedule::predicateFunc(map,pair >::iterator it,string &a) +{ + return (it->first).first == a; +} + +``` + +Function which I have to use predicate func: + +``` + void Schedule::studentSchedule() { + string s,c; + cout<<""Enter the student and course name to create schedule""<>s>>c; + list::iterator studentLoc; + map,pair >::iterator courseL; + map,pair >::iterator location; + + studentLoc = find(getStudentList().begin(),getStudentList().end(),s); + location = find_if(getMatchMap().begin(), getMatchMap().end(), predicateFunc(courseL,c) ) + if(studentLoc != getStudentList().end() && location != getMatchMap().end()) + { + cout<<""I found it""<::operator()(_Iterator) [with _Iterator = std::_Rb_tree_iterator, int>, std::pair, std::array > > >; _Predicate = bool]': +C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/stl_algo.h:104:42: required from '_InputIterator std::__find_if(_InputIterator, _InputIterator, _Predicate, std::input_iterator_tag) [with _InputIterator = std::_Rb_tree_iterator, int>, std::pair, std::array > > >; _Predicate = __gnu_cxx::__ops::_Iter_pred]' +C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/stl_algo.h:161:23: required from '_Iterator std::__find_if(_Iterator, _Iterator, _Predicate) [with _Iterator = std::_Rb_tree_iterator, int>, std::pair, std::array > > >; _Predicate = __gnu_cxx::__ops::_Iter_pred]' +C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/stl_algo.h:3930:28: required from '_IIter std::find_if(_IIter, _IIter, _Predicate) [with _IIter = std::_Rb_tree_iterator, int>, std::pair, std::array > > >; _Predicate = bool]' +C:\Users\Fatih\Desktop\clion\SchoolProject1\Schedule.cpp:25:93: required from here +C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/predefined_ops.h:283:11: error: expression cannot be used as a function + { return bool(_M_pred(*__it)); } + ^~~~~~~~~~~~~~~~~~~~ + +``` + +What is the true usage of the predicate funtion in here ?",2019/12/27,"['https://Stackoverflow.com/questions/59499722', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12543764/']","Better way is only one time create `insert` + +``` +if (isset($_POST['array'])) { + $values = []; + $sql = ""insert into persons (Name, Email) values ""; + + foreach ($_POST['array'] as $loop) { + $values[] = ""('"" . $conn->real_escape_string($loop['name']) . ""', '"" . $conn->real_escape_string($loop['email']) . ""')""; + } + + if (!empty($values)) { + $conn->query($sql . implode(', ', $values)); + } +} + +```","If you want to execute the query outside the loop +Try using as following + +``` + if (isset($_POST['array'])) { + $sql=""""; + foreach ($_POST['array'] as $loop) { + + $sql .= ""insert into persons (Name, Email) + values ('"" . $loop['name'] . ""', '"" . $loop['email'] . ""');\n""; + } + } + +```" +59499722,"The predicate function: + +``` +bool Schedule::predicateFunc(map,pair >::iterator it,string &a) +{ + return (it->first).first == a; +} + +``` + +Function which I have to use predicate func: + +``` + void Schedule::studentSchedule() { + string s,c; + cout<<""Enter the student and course name to create schedule""<>s>>c; + list::iterator studentLoc; + map,pair >::iterator courseL; + map,pair >::iterator location; + + studentLoc = find(getStudentList().begin(),getStudentList().end(),s); + location = find_if(getMatchMap().begin(), getMatchMap().end(), predicateFunc(courseL,c) ) + if(studentLoc != getStudentList().end() && location != getMatchMap().end()) + { + cout<<""I found it""<::operator()(_Iterator) [with _Iterator = std::_Rb_tree_iterator, int>, std::pair, std::array > > >; _Predicate = bool]': +C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/stl_algo.h:104:42: required from '_InputIterator std::__find_if(_InputIterator, _InputIterator, _Predicate, std::input_iterator_tag) [with _InputIterator = std::_Rb_tree_iterator, int>, std::pair, std::array > > >; _Predicate = __gnu_cxx::__ops::_Iter_pred]' +C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/stl_algo.h:161:23: required from '_Iterator std::__find_if(_Iterator, _Iterator, _Predicate) [with _Iterator = std::_Rb_tree_iterator, int>, std::pair, std::array > > >; _Predicate = __gnu_cxx::__ops::_Iter_pred]' +C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/stl_algo.h:3930:28: required from '_IIter std::find_if(_IIter, _IIter, _Predicate) [with _IIter = std::_Rb_tree_iterator, int>, std::pair, std::array > > >; _Predicate = bool]' +C:\Users\Fatih\Desktop\clion\SchoolProject1\Schedule.cpp:25:93: required from here +C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/predefined_ops.h:283:11: error: expression cannot be used as a function + { return bool(_M_pred(*__it)); } + ^~~~~~~~~~~~~~~~~~~~ + +``` + +What is the true usage of the predicate funtion in here ?",2019/12/27,"['https://Stackoverflow.com/questions/59499722', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12543764/']","The reason why it doesn't work is because you never execute your SQL query anywhere. + +To execute the query you should first prepare the statement and then bind the params and execute. + +``` +// Your connection to DB +mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); +$mysqli = new mysqli('localhost', 'username', 'password', 'dbname'); +$mysqli->set_charset('utf8mb4'); // always set the charset + +if (isset($_POST['array'])) { + $stmt = $mysqli->prepare('INSERT INTO persons (Name, Email) VALUES (?,?)'); + foreach ($_POST['array'] as $loop) { + $stmt->bind_param('ss', $loop['name'], $loop['email']); + $stmt->execute(); + } +} + +```","If you want to execute the query outside the loop +Try using as following + +``` + if (isset($_POST['array'])) { + $sql=""""; + foreach ($_POST['array'] as $loop) { + + $sql .= ""insert into persons (Name, Email) + values ('"" . $loop['name'] . ""', '"" . $loop['email'] . ""');\n""; + } + } + +```" +59499722,"The predicate function: + +``` +bool Schedule::predicateFunc(map,pair >::iterator it,string &a) +{ + return (it->first).first == a; +} + +``` + +Function which I have to use predicate func: + +``` + void Schedule::studentSchedule() { + string s,c; + cout<<""Enter the student and course name to create schedule""<>s>>c; + list::iterator studentLoc; + map,pair >::iterator courseL; + map,pair >::iterator location; + + studentLoc = find(getStudentList().begin(),getStudentList().end(),s); + location = find_if(getMatchMap().begin(), getMatchMap().end(), predicateFunc(courseL,c) ) + if(studentLoc != getStudentList().end() && location != getMatchMap().end()) + { + cout<<""I found it""<::operator()(_Iterator) [with _Iterator = std::_Rb_tree_iterator, int>, std::pair, std::array > > >; _Predicate = bool]': +C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/stl_algo.h:104:42: required from '_InputIterator std::__find_if(_InputIterator, _InputIterator, _Predicate, std::input_iterator_tag) [with _InputIterator = std::_Rb_tree_iterator, int>, std::pair, std::array > > >; _Predicate = __gnu_cxx::__ops::_Iter_pred]' +C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/stl_algo.h:161:23: required from '_Iterator std::__find_if(_Iterator, _Iterator, _Predicate) [with _Iterator = std::_Rb_tree_iterator, int>, std::pair, std::array > > >; _Predicate = __gnu_cxx::__ops::_Iter_pred]' +C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/stl_algo.h:3930:28: required from '_IIter std::find_if(_IIter, _IIter, _Predicate) [with _IIter = std::_Rb_tree_iterator, int>, std::pair, std::array > > >; _Predicate = bool]' +C:\Users\Fatih\Desktop\clion\SchoolProject1\Schedule.cpp:25:93: required from here +C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/predefined_ops.h:283:11: error: expression cannot be used as a function + { return bool(_M_pred(*__it)); } + ^~~~~~~~~~~~~~~~~~~~ + +``` + +What is the true usage of the predicate funtion in here ?",2019/12/27,"['https://Stackoverflow.com/questions/59499722', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12543764/']","I had the same issue inserting JSON arrays into MySQL and fixed it by putting the `mysqli_stmt->execute()` function inside the `foreach` + +``` +// loop through the array +foreach ($data as $row) { + echo ""Data has been Uploaded successfully
""; + // get the project details + $id = $row['id']; + $name = $row['name']; + $togglCid = $row['cid']; + // execute insert query + mysqli_stmt_execute($sql); +} + +``` + +This means it executes the code after each loop","If you want to execute the query outside the loop +Try using as following + +``` + if (isset($_POST['array'])) { + $sql=""""; + foreach ($_POST['array'] as $loop) { + + $sql .= ""insert into persons (Name, Email) + values ('"" . $loop['name'] . ""', '"" . $loop['email'] . ""');\n""; + } + } + +```" +59499722,"The predicate function: + +``` +bool Schedule::predicateFunc(map,pair >::iterator it,string &a) +{ + return (it->first).first == a; +} + +``` + +Function which I have to use predicate func: + +``` + void Schedule::studentSchedule() { + string s,c; + cout<<""Enter the student and course name to create schedule""<>s>>c; + list::iterator studentLoc; + map,pair >::iterator courseL; + map,pair >::iterator location; + + studentLoc = find(getStudentList().begin(),getStudentList().end(),s); + location = find_if(getMatchMap().begin(), getMatchMap().end(), predicateFunc(courseL,c) ) + if(studentLoc != getStudentList().end() && location != getMatchMap().end()) + { + cout<<""I found it""<::operator()(_Iterator) [with _Iterator = std::_Rb_tree_iterator, int>, std::pair, std::array > > >; _Predicate = bool]': +C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/stl_algo.h:104:42: required from '_InputIterator std::__find_if(_InputIterator, _InputIterator, _Predicate, std::input_iterator_tag) [with _InputIterator = std::_Rb_tree_iterator, int>, std::pair, std::array > > >; _Predicate = __gnu_cxx::__ops::_Iter_pred]' +C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/stl_algo.h:161:23: required from '_Iterator std::__find_if(_Iterator, _Iterator, _Predicate) [with _Iterator = std::_Rb_tree_iterator, int>, std::pair, std::array > > >; _Predicate = __gnu_cxx::__ops::_Iter_pred]' +C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/stl_algo.h:3930:28: required from '_IIter std::find_if(_IIter, _IIter, _Predicate) [with _IIter = std::_Rb_tree_iterator, int>, std::pair, std::array > > >; _Predicate = bool]' +C:\Users\Fatih\Desktop\clion\SchoolProject1\Schedule.cpp:25:93: required from here +C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/predefined_ops.h:283:11: error: expression cannot be used as a function + { return bool(_M_pred(*__it)); } + ^~~~~~~~~~~~~~~~~~~~ + +``` + +What is the true usage of the predicate funtion in here ?",2019/12/27,"['https://Stackoverflow.com/questions/59499722', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12543764/']","The reason why it doesn't work is because you never execute your SQL query anywhere. + +To execute the query you should first prepare the statement and then bind the params and execute. + +``` +// Your connection to DB +mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); +$mysqli = new mysqli('localhost', 'username', 'password', 'dbname'); +$mysqli->set_charset('utf8mb4'); // always set the charset + +if (isset($_POST['array'])) { + $stmt = $mysqli->prepare('INSERT INTO persons (Name, Email) VALUES (?,?)'); + foreach ($_POST['array'] as $loop) { + $stmt->bind_param('ss', $loop['name'], $loop['email']); + $stmt->execute(); + } +} + +```","Better way is only one time create `insert` + +``` +if (isset($_POST['array'])) { + $values = []; + $sql = ""insert into persons (Name, Email) values ""; + + foreach ($_POST['array'] as $loop) { + $values[] = ""('"" . $conn->real_escape_string($loop['name']) . ""', '"" . $conn->real_escape_string($loop['email']) . ""')""; + } + + if (!empty($values)) { + $conn->query($sql . implode(', ', $values)); + } +} + +```" +59499722,"The predicate function: + +``` +bool Schedule::predicateFunc(map,pair >::iterator it,string &a) +{ + return (it->first).first == a; +} + +``` + +Function which I have to use predicate func: + +``` + void Schedule::studentSchedule() { + string s,c; + cout<<""Enter the student and course name to create schedule""<>s>>c; + list::iterator studentLoc; + map,pair >::iterator courseL; + map,pair >::iterator location; + + studentLoc = find(getStudentList().begin(),getStudentList().end(),s); + location = find_if(getMatchMap().begin(), getMatchMap().end(), predicateFunc(courseL,c) ) + if(studentLoc != getStudentList().end() && location != getMatchMap().end()) + { + cout<<""I found it""<::operator()(_Iterator) [with _Iterator = std::_Rb_tree_iterator, int>, std::pair, std::array > > >; _Predicate = bool]': +C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/stl_algo.h:104:42: required from '_InputIterator std::__find_if(_InputIterator, _InputIterator, _Predicate, std::input_iterator_tag) [with _InputIterator = std::_Rb_tree_iterator, int>, std::pair, std::array > > >; _Predicate = __gnu_cxx::__ops::_Iter_pred]' +C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/stl_algo.h:161:23: required from '_Iterator std::__find_if(_Iterator, _Iterator, _Predicate) [with _Iterator = std::_Rb_tree_iterator, int>, std::pair, std::array > > >; _Predicate = __gnu_cxx::__ops::_Iter_pred]' +C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/stl_algo.h:3930:28: required from '_IIter std::find_if(_IIter, _IIter, _Predicate) [with _IIter = std::_Rb_tree_iterator, int>, std::pair, std::array > > >; _Predicate = bool]' +C:\Users\Fatih\Desktop\clion\SchoolProject1\Schedule.cpp:25:93: required from here +C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/predefined_ops.h:283:11: error: expression cannot be used as a function + { return bool(_M_pred(*__it)); } + ^~~~~~~~~~~~~~~~~~~~ + +``` + +What is the true usage of the predicate funtion in here ?",2019/12/27,"['https://Stackoverflow.com/questions/59499722', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12543764/']","Better way is only one time create `insert` + +``` +if (isset($_POST['array'])) { + $values = []; + $sql = ""insert into persons (Name, Email) values ""; + + foreach ($_POST['array'] as $loop) { + $values[] = ""('"" . $conn->real_escape_string($loop['name']) . ""', '"" . $conn->real_escape_string($loop['email']) . ""')""; + } + + if (!empty($values)) { + $conn->query($sql . implode(', ', $values)); + } +} + +```","I had the same issue inserting JSON arrays into MySQL and fixed it by putting the `mysqli_stmt->execute()` function inside the `foreach` + +``` +// loop through the array +foreach ($data as $row) { + echo ""Data has been Uploaded successfully
""; + // get the project details + $id = $row['id']; + $name = $row['name']; + $togglCid = $row['cid']; + // execute insert query + mysqli_stmt_execute($sql); +} + +``` + +This means it executes the code after each loop" +59499722,"The predicate function: + +``` +bool Schedule::predicateFunc(map,pair >::iterator it,string &a) +{ + return (it->first).first == a; +} + +``` + +Function which I have to use predicate func: + +``` + void Schedule::studentSchedule() { + string s,c; + cout<<""Enter the student and course name to create schedule""<>s>>c; + list::iterator studentLoc; + map,pair >::iterator courseL; + map,pair >::iterator location; + + studentLoc = find(getStudentList().begin(),getStudentList().end(),s); + location = find_if(getMatchMap().begin(), getMatchMap().end(), predicateFunc(courseL,c) ) + if(studentLoc != getStudentList().end() && location != getMatchMap().end()) + { + cout<<""I found it""<::operator()(_Iterator) [with _Iterator = std::_Rb_tree_iterator, int>, std::pair, std::array > > >; _Predicate = bool]': +C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/stl_algo.h:104:42: required from '_InputIterator std::__find_if(_InputIterator, _InputIterator, _Predicate, std::input_iterator_tag) [with _InputIterator = std::_Rb_tree_iterator, int>, std::pair, std::array > > >; _Predicate = __gnu_cxx::__ops::_Iter_pred]' +C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/stl_algo.h:161:23: required from '_Iterator std::__find_if(_Iterator, _Iterator, _Predicate) [with _Iterator = std::_Rb_tree_iterator, int>, std::pair, std::array > > >; _Predicate = __gnu_cxx::__ops::_Iter_pred]' +C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/stl_algo.h:3930:28: required from '_IIter std::find_if(_IIter, _IIter, _Predicate) [with _IIter = std::_Rb_tree_iterator, int>, std::pair, std::array > > >; _Predicate = bool]' +C:\Users\Fatih\Desktop\clion\SchoolProject1\Schedule.cpp:25:93: required from here +C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/predefined_ops.h:283:11: error: expression cannot be used as a function + { return bool(_M_pred(*__it)); } + ^~~~~~~~~~~~~~~~~~~~ + +``` + +What is the true usage of the predicate funtion in here ?",2019/12/27,"['https://Stackoverflow.com/questions/59499722', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12543764/']","The reason why it doesn't work is because you never execute your SQL query anywhere. + +To execute the query you should first prepare the statement and then bind the params and execute. + +``` +// Your connection to DB +mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); +$mysqli = new mysqli('localhost', 'username', 'password', 'dbname'); +$mysqli->set_charset('utf8mb4'); // always set the charset + +if (isset($_POST['array'])) { + $stmt = $mysqli->prepare('INSERT INTO persons (Name, Email) VALUES (?,?)'); + foreach ($_POST['array'] as $loop) { + $stmt->bind_param('ss', $loop['name'], $loop['email']); + $stmt->execute(); + } +} + +```","I had the same issue inserting JSON arrays into MySQL and fixed it by putting the `mysqli_stmt->execute()` function inside the `foreach` + +``` +// loop through the array +foreach ($data as $row) { + echo ""Data has been Uploaded successfully
""; + // get the project details + $id = $row['id']; + $name = $row['name']; + $togglCid = $row['cid']; + // execute insert query + mysqli_stmt_execute($sql); +} + +``` + +This means it executes the code after each loop" +12070601,"The [NQueen problem](http://en.wikipedia.org/wiki/Eight_queens_puzzle) is a famous example of [backtracking](http://en.wikipedia.org/wiki/Backtracking). After reading from the [source](http://www.geeksforgeeks.org/archives/13387), I have tried the below code snippet. + +``` +int isSafe(int k,int i,int *x) +{ + int j; + for(j=0;j + +int abs(int a){ + return a>0? a : -a; +} + +int isSafe(int col[],int row){ + int row2,col2,i,yDiff,xDiff; + if(row == 0) return 1; + + for(row2=0;row2 + +int abs(int a){ + return a>0? a : -a; +} + +int isSafe(int col[],int row){ + int row2,col2,i,yDiff,xDiff; + if(row == 0) return 1; + + for(row2=0;row2 +> I was really hoping for some sort of like ""abort mechanism"" that I +> could use. Is there any other ways of working around this? Any +> interesting work-arounds for this? +> +> +> + +Yes, there is. It is called *exception handling*. + +Let's rewrite your code: + +``` +namespace PHOEBE +{ + public class Analyzer + { + public Analyzer() + { + try + { + DoAnalysis(); + DoFurtherAnalysis(); + } + catch + { + //ERROR OCCURRED, ABORT ALL ANALYSIS + return; + } + } + + public class DoAnalysis() + { + Convert.ToInt32(""someNumber....""); //obviously fails.. + } +} + +``` + +Now, the constructor will abort and not run the second method since the exception will ""bubble through"" and be catched where you want it. + +On an unrelated note: Please try to catch as specific exceptions as possible, in this case a `FormatException`","You could just move `DoFurtherAnalysis();` into the the try block + +And I would do this entire process somewhere other than the constructor. +Only thing I ever do in the constructor is initialize properties." +9776878,"I'm looking for the best method of handling errors in a c# winforms class that I have. The gist of the application is that it has a data analyzer that analyzes the data for statistics and other such stuff. However, I'm looking for the proper way of handling an ABORT. + +For example, I have the class called Analyzer + +``` +namespace PHOEBE +{ + public class Analyzer + { + public Analyzer(){ + DoAnalysis(); + DoFurtherAnalysis(); + } + + public class DoAnalysis(){ + try{ + Convert.ToInt32(""someNumber....""); //obviously fails.. + } + catch{ + //ERROR OCCURRED, ABORT ALL ANALYSIS + return; + } + } +} + +``` + +Obviously, when DoAnalysis() is called, there will be an error that occurs. The catch block will catch the exception. However, when this catch occurs, it will return to the constructor and run DoFurtherAnalysis(). This is a problem. + +I know that you could do return values from each method where each value indicates a certain outcome (ie. 1 = success, 0 = fail). However, a lot of the methods I call, use return values already. I could also use a boolean that gets flagged when an error occurs and check that value before calling the next method from the constructor, but checking this value each time is annoying and repetitive. + +I was really hoping for some sort of like ""abort mechanism"" that I could use. Is there any other ways of working around this? Any interesting work-arounds for this? + +Assume this class is being called from a form.",2012/03/19,"['https://Stackoverflow.com/questions/9776878', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/821484/']","Just let the exception propagate up - you should only catch the exception if you can actually *handle* it. Exceptions *are* the ""abort mechanism"" in .NET. You're currently *swallowing* the signal that everything's gone wrong, and returning as if all were well. + +Generally I find catching exceptions to be pretty rare - usually it's either at the top level (to stop a whole server from going down just because of one request) or in order to transform an exception of one kind into another in order to maintain appropriate abstractions.","> +> I was really hoping for some sort of like ""abort mechanism"" that I +> could use. Is there any other ways of working around this? Any +> interesting work-arounds for this? +> +> +> + +Yes, there is. It is called *exception handling*. + +Let's rewrite your code: + +``` +namespace PHOEBE +{ + public class Analyzer + { + public Analyzer() + { + try + { + DoAnalysis(); + DoFurtherAnalysis(); + } + catch + { + //ERROR OCCURRED, ABORT ALL ANALYSIS + return; + } + } + + public class DoAnalysis() + { + Convert.ToInt32(""someNumber....""); //obviously fails.. + } +} + +``` + +Now, the constructor will abort and not run the second method since the exception will ""bubble through"" and be catched where you want it. + +On an unrelated note: Please try to catch as specific exceptions as possible, in this case a `FormatException`" +9776878,"I'm looking for the best method of handling errors in a c# winforms class that I have. The gist of the application is that it has a data analyzer that analyzes the data for statistics and other such stuff. However, I'm looking for the proper way of handling an ABORT. + +For example, I have the class called Analyzer + +``` +namespace PHOEBE +{ + public class Analyzer + { + public Analyzer(){ + DoAnalysis(); + DoFurtherAnalysis(); + } + + public class DoAnalysis(){ + try{ + Convert.ToInt32(""someNumber....""); //obviously fails.. + } + catch{ + //ERROR OCCURRED, ABORT ALL ANALYSIS + return; + } + } +} + +``` + +Obviously, when DoAnalysis() is called, there will be an error that occurs. The catch block will catch the exception. However, when this catch occurs, it will return to the constructor and run DoFurtherAnalysis(). This is a problem. + +I know that you could do return values from each method where each value indicates a certain outcome (ie. 1 = success, 0 = fail). However, a lot of the methods I call, use return values already. I could also use a boolean that gets flagged when an error occurs and check that value before calling the next method from the constructor, but checking this value each time is annoying and repetitive. + +I was really hoping for some sort of like ""abort mechanism"" that I could use. Is there any other ways of working around this? Any interesting work-arounds for this? + +Assume this class is being called from a form.",2012/03/19,"['https://Stackoverflow.com/questions/9776878', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/821484/']","The easiest work-around is *don't catch the exception*. If that were to happen, it'd go straight past the `DoFurtherAnalysis()` function and out to the original caller.",use a try...catch in the constructor? +9776878,"I'm looking for the best method of handling errors in a c# winforms class that I have. The gist of the application is that it has a data analyzer that analyzes the data for statistics and other such stuff. However, I'm looking for the proper way of handling an ABORT. + +For example, I have the class called Analyzer + +``` +namespace PHOEBE +{ + public class Analyzer + { + public Analyzer(){ + DoAnalysis(); + DoFurtherAnalysis(); + } + + public class DoAnalysis(){ + try{ + Convert.ToInt32(""someNumber....""); //obviously fails.. + } + catch{ + //ERROR OCCURRED, ABORT ALL ANALYSIS + return; + } + } +} + +``` + +Obviously, when DoAnalysis() is called, there will be an error that occurs. The catch block will catch the exception. However, when this catch occurs, it will return to the constructor and run DoFurtherAnalysis(). This is a problem. + +I know that you could do return values from each method where each value indicates a certain outcome (ie. 1 = success, 0 = fail). However, a lot of the methods I call, use return values already. I could also use a boolean that gets flagged when an error occurs and check that value before calling the next method from the constructor, but checking this value each time is annoying and repetitive. + +I was really hoping for some sort of like ""abort mechanism"" that I could use. Is there any other ways of working around this? Any interesting work-arounds for this? + +Assume this class is being called from a form.",2012/03/19,"['https://Stackoverflow.com/questions/9776878', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/821484/']","Just let the exception propagate up - you should only catch the exception if you can actually *handle* it. Exceptions *are* the ""abort mechanism"" in .NET. You're currently *swallowing* the signal that everything's gone wrong, and returning as if all were well. + +Generally I find catching exceptions to be pretty rare - usually it's either at the top level (to stop a whole server from going down just because of one request) or in order to transform an exception of one kind into another in order to maintain appropriate abstractions.","Well, you've got several issues mixed up here. First, it looks like you do possibly-very expensive processing from your constructor. If that processing can throw, you really don't want to call it from your constructor becuase you don't even have the option of returning an error code. + +Second, (and you'll read in many threads here,) how you handlee errors really depends on the application and expectation of your users. Some errors could be corrected by changes to inputs. Others might happen in the middle of the night if analysis takes a long time and you might want to continue with another analysis, logging this error. + +So I think we're really going to punt back to you for more information about the above." +9776878,"I'm looking for the best method of handling errors in a c# winforms class that I have. The gist of the application is that it has a data analyzer that analyzes the data for statistics and other such stuff. However, I'm looking for the proper way of handling an ABORT. + +For example, I have the class called Analyzer + +``` +namespace PHOEBE +{ + public class Analyzer + { + public Analyzer(){ + DoAnalysis(); + DoFurtherAnalysis(); + } + + public class DoAnalysis(){ + try{ + Convert.ToInt32(""someNumber....""); //obviously fails.. + } + catch{ + //ERROR OCCURRED, ABORT ALL ANALYSIS + return; + } + } +} + +``` + +Obviously, when DoAnalysis() is called, there will be an error that occurs. The catch block will catch the exception. However, when this catch occurs, it will return to the constructor and run DoFurtherAnalysis(). This is a problem. + +I know that you could do return values from each method where each value indicates a certain outcome (ie. 1 = success, 0 = fail). However, a lot of the methods I call, use return values already. I could also use a boolean that gets flagged when an error occurs and check that value before calling the next method from the constructor, but checking this value each time is annoying and repetitive. + +I was really hoping for some sort of like ""abort mechanism"" that I could use. Is there any other ways of working around this? Any interesting work-arounds for this? + +Assume this class is being called from a form.",2012/03/19,"['https://Stackoverflow.com/questions/9776878', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/821484/']","Don't see anything anoying in returning and checking `bool` return value from the function. It's much much better solution then having some tricky internal state management, that you for sure will messed up after a couple of months when you return to your code. + +Make code sumple and streghtforward. It's not anoying, it's good. + +In your specific case if you want just abort **everything**, just do not `catch` exception it will abort your program.","You could just move `DoFurtherAnalysis();` into the the try block + +And I would do this entire process somewhere other than the constructor. +Only thing I ever do in the constructor is initialize properties." +9776878,"I'm looking for the best method of handling errors in a c# winforms class that I have. The gist of the application is that it has a data analyzer that analyzes the data for statistics and other such stuff. However, I'm looking for the proper way of handling an ABORT. + +For example, I have the class called Analyzer + +``` +namespace PHOEBE +{ + public class Analyzer + { + public Analyzer(){ + DoAnalysis(); + DoFurtherAnalysis(); + } + + public class DoAnalysis(){ + try{ + Convert.ToInt32(""someNumber....""); //obviously fails.. + } + catch{ + //ERROR OCCURRED, ABORT ALL ANALYSIS + return; + } + } +} + +``` + +Obviously, when DoAnalysis() is called, there will be an error that occurs. The catch block will catch the exception. However, when this catch occurs, it will return to the constructor and run DoFurtherAnalysis(). This is a problem. + +I know that you could do return values from each method where each value indicates a certain outcome (ie. 1 = success, 0 = fail). However, a lot of the methods I call, use return values already. I could also use a boolean that gets flagged when an error occurs and check that value before calling the next method from the constructor, but checking this value each time is annoying and repetitive. + +I was really hoping for some sort of like ""abort mechanism"" that I could use. Is there any other ways of working around this? Any interesting work-arounds for this? + +Assume this class is being called from a form.",2012/03/19,"['https://Stackoverflow.com/questions/9776878', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/821484/']","> +> I was really hoping for some sort of like ""abort mechanism"" that I +> could use. Is there any other ways of working around this? Any +> interesting work-arounds for this? +> +> +> + +Yes, there is. It is called *exception handling*. + +Let's rewrite your code: + +``` +namespace PHOEBE +{ + public class Analyzer + { + public Analyzer() + { + try + { + DoAnalysis(); + DoFurtherAnalysis(); + } + catch + { + //ERROR OCCURRED, ABORT ALL ANALYSIS + return; + } + } + + public class DoAnalysis() + { + Convert.ToInt32(""someNumber....""); //obviously fails.. + } +} + +``` + +Now, the constructor will abort and not run the second method since the exception will ""bubble through"" and be catched where you want it. + +On an unrelated note: Please try to catch as specific exceptions as possible, in this case a `FormatException`","You are subverting the existing ""abort"" mechanism by catching an exception that you are not doing anything about and swallowing it. + +You should not use a `try{}catch{}` block in this case and let the exception bubble up and cause the application to abort." +9776878,"I'm looking for the best method of handling errors in a c# winforms class that I have. The gist of the application is that it has a data analyzer that analyzes the data for statistics and other such stuff. However, I'm looking for the proper way of handling an ABORT. + +For example, I have the class called Analyzer + +``` +namespace PHOEBE +{ + public class Analyzer + { + public Analyzer(){ + DoAnalysis(); + DoFurtherAnalysis(); + } + + public class DoAnalysis(){ + try{ + Convert.ToInt32(""someNumber....""); //obviously fails.. + } + catch{ + //ERROR OCCURRED, ABORT ALL ANALYSIS + return; + } + } +} + +``` + +Obviously, when DoAnalysis() is called, there will be an error that occurs. The catch block will catch the exception. However, when this catch occurs, it will return to the constructor and run DoFurtherAnalysis(). This is a problem. + +I know that you could do return values from each method where each value indicates a certain outcome (ie. 1 = success, 0 = fail). However, a lot of the methods I call, use return values already. I could also use a boolean that gets flagged when an error occurs and check that value before calling the next method from the constructor, but checking this value each time is annoying and repetitive. + +I was really hoping for some sort of like ""abort mechanism"" that I could use. Is there any other ways of working around this? Any interesting work-arounds for this? + +Assume this class is being called from a form.",2012/03/19,"['https://Stackoverflow.com/questions/9776878', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/821484/']","Don't see anything anoying in returning and checking `bool` return value from the function. It's much much better solution then having some tricky internal state management, that you for sure will messed up after a couple of months when you return to your code. + +Make code sumple and streghtforward. It's not anoying, it's good. + +In your specific case if you want just abort **everything**, just do not `catch` exception it will abort your program.",use a try...catch in the constructor? +9776878,"I'm looking for the best method of handling errors in a c# winforms class that I have. The gist of the application is that it has a data analyzer that analyzes the data for statistics and other such stuff. However, I'm looking for the proper way of handling an ABORT. + +For example, I have the class called Analyzer + +``` +namespace PHOEBE +{ + public class Analyzer + { + public Analyzer(){ + DoAnalysis(); + DoFurtherAnalysis(); + } + + public class DoAnalysis(){ + try{ + Convert.ToInt32(""someNumber....""); //obviously fails.. + } + catch{ + //ERROR OCCURRED, ABORT ALL ANALYSIS + return; + } + } +} + +``` + +Obviously, when DoAnalysis() is called, there will be an error that occurs. The catch block will catch the exception. However, when this catch occurs, it will return to the constructor and run DoFurtherAnalysis(). This is a problem. + +I know that you could do return values from each method where each value indicates a certain outcome (ie. 1 = success, 0 = fail). However, a lot of the methods I call, use return values already. I could also use a boolean that gets flagged when an error occurs and check that value before calling the next method from the constructor, but checking this value each time is annoying and repetitive. + +I was really hoping for some sort of like ""abort mechanism"" that I could use. Is there any other ways of working around this? Any interesting work-arounds for this? + +Assume this class is being called from a form.",2012/03/19,"['https://Stackoverflow.com/questions/9776878', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/821484/']","> +> I was really hoping for some sort of like ""abort mechanism"" that I +> could use. Is there any other ways of working around this? Any +> interesting work-arounds for this? +> +> +> + +Yes, there is. It is called *exception handling*. + +Let's rewrite your code: + +``` +namespace PHOEBE +{ + public class Analyzer + { + public Analyzer() + { + try + { + DoAnalysis(); + DoFurtherAnalysis(); + } + catch + { + //ERROR OCCURRED, ABORT ALL ANALYSIS + return; + } + } + + public class DoAnalysis() + { + Convert.ToInt32(""someNumber....""); //obviously fails.. + } +} + +``` + +Now, the constructor will abort and not run the second method since the exception will ""bubble through"" and be catched where you want it. + +On an unrelated note: Please try to catch as specific exceptions as possible, in this case a `FormatException`","Don't see anything anoying in returning and checking `bool` return value from the function. It's much much better solution then having some tricky internal state management, that you for sure will messed up after a couple of months when you return to your code. + +Make code sumple and streghtforward. It's not anoying, it's good. + +In your specific case if you want just abort **everything**, just do not `catch` exception it will abort your program." +9776878,"I'm looking for the best method of handling errors in a c# winforms class that I have. The gist of the application is that it has a data analyzer that analyzes the data for statistics and other such stuff. However, I'm looking for the proper way of handling an ABORT. + +For example, I have the class called Analyzer + +``` +namespace PHOEBE +{ + public class Analyzer + { + public Analyzer(){ + DoAnalysis(); + DoFurtherAnalysis(); + } + + public class DoAnalysis(){ + try{ + Convert.ToInt32(""someNumber....""); //obviously fails.. + } + catch{ + //ERROR OCCURRED, ABORT ALL ANALYSIS + return; + } + } +} + +``` + +Obviously, when DoAnalysis() is called, there will be an error that occurs. The catch block will catch the exception. However, when this catch occurs, it will return to the constructor and run DoFurtherAnalysis(). This is a problem. + +I know that you could do return values from each method where each value indicates a certain outcome (ie. 1 = success, 0 = fail). However, a lot of the methods I call, use return values already. I could also use a boolean that gets flagged when an error occurs and check that value before calling the next method from the constructor, but checking this value each time is annoying and repetitive. + +I was really hoping for some sort of like ""abort mechanism"" that I could use. Is there any other ways of working around this? Any interesting work-arounds for this? + +Assume this class is being called from a form.",2012/03/19,"['https://Stackoverflow.com/questions/9776878', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/821484/']","Just let the exception propagate up - you should only catch the exception if you can actually *handle* it. Exceptions *are* the ""abort mechanism"" in .NET. You're currently *swallowing* the signal that everything's gone wrong, and returning as if all were well. + +Generally I find catching exceptions to be pretty rare - usually it's either at the top level (to stop a whole server from going down just because of one request) or in order to transform an exception of one kind into another in order to maintain appropriate abstractions.","You could just move `DoFurtherAnalysis();` into the the try block + +And I would do this entire process somewhere other than the constructor. +Only thing I ever do in the constructor is initialize properties." +9776878,"I'm looking for the best method of handling errors in a c# winforms class that I have. The gist of the application is that it has a data analyzer that analyzes the data for statistics and other such stuff. However, I'm looking for the proper way of handling an ABORT. + +For example, I have the class called Analyzer + +``` +namespace PHOEBE +{ + public class Analyzer + { + public Analyzer(){ + DoAnalysis(); + DoFurtherAnalysis(); + } + + public class DoAnalysis(){ + try{ + Convert.ToInt32(""someNumber....""); //obviously fails.. + } + catch{ + //ERROR OCCURRED, ABORT ALL ANALYSIS + return; + } + } +} + +``` + +Obviously, when DoAnalysis() is called, there will be an error that occurs. The catch block will catch the exception. However, when this catch occurs, it will return to the constructor and run DoFurtherAnalysis(). This is a problem. + +I know that you could do return values from each method where each value indicates a certain outcome (ie. 1 = success, 0 = fail). However, a lot of the methods I call, use return values already. I could also use a boolean that gets flagged when an error occurs and check that value before calling the next method from the constructor, but checking this value each time is annoying and repetitive. + +I was really hoping for some sort of like ""abort mechanism"" that I could use. Is there any other ways of working around this? Any interesting work-arounds for this? + +Assume this class is being called from a form.",2012/03/19,"['https://Stackoverflow.com/questions/9776878', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/821484/']","Just let the exception propagate up - you should only catch the exception if you can actually *handle* it. Exceptions *are* the ""abort mechanism"" in .NET. You're currently *swallowing* the signal that everything's gone wrong, and returning as if all were well. + +Generally I find catching exceptions to be pretty rare - usually it's either at the top level (to stop a whole server from going down just because of one request) or in order to transform an exception of one kind into another in order to maintain appropriate abstractions.","Don't see anything anoying in returning and checking `bool` return value from the function. It's much much better solution then having some tricky internal state management, that you for sure will messed up after a couple of months when you return to your code. + +Make code sumple and streghtforward. It's not anoying, it's good. + +In your specific case if you want just abort **everything**, just do not `catch` exception it will abort your program." +42317542,"Yesterday I was making an HTML element and this problem hit me up. +The Background-image of the DIV is not showing, and I was curious, the link worked fine. + +Here is my code + +```html +
"" class=""fl-"" style="" + background-image: url(https://images.pexels.com/photos/290470/pexels-photo-290470.jpeg?h=350&auto=compress&cs=tinysrgb); + margin-top: 20px; + height: 200px; + width: 200px; + background-position: center center; + background-repeat: no-repeat; + transform: translateY(0px); + background-size: contain; + position: relative; + margin-right: auto; + margin-left: auto; + max-width: 80%; + display:block; + "">
+``` + +**EDIT** +ok, I edited the dynamic codes and replaced them with some static output. +Sorry for misleading +**Another EDIT** +I changed the image and now I am using a smaller image, but still it doesn't show up",2017/02/18,"['https://Stackoverflow.com/questions/42317542', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']","I have checked, background image is properly working. Your image size is very big, approx 7 MB. Reduce it upto 300KB, too big to show.","Issue is in the image, +You have used very high quality image. +if you use a low quality image than you have currently used, +it will work fine." +42317542,"Yesterday I was making an HTML element and this problem hit me up. +The Background-image of the DIV is not showing, and I was curious, the link worked fine. + +Here is my code + +```html +
"" class=""fl-"" style="" + background-image: url(https://images.pexels.com/photos/290470/pexels-photo-290470.jpeg?h=350&auto=compress&cs=tinysrgb); + margin-top: 20px; + height: 200px; + width: 200px; + background-position: center center; + background-repeat: no-repeat; + transform: translateY(0px); + background-size: contain; + position: relative; + margin-right: auto; + margin-left: auto; + max-width: 80%; + display:block; + "">
+``` + +**EDIT** +ok, I edited the dynamic codes and replaced them with some static output. +Sorry for misleading +**Another EDIT** +I changed the image and now I am using a smaller image, but still it doesn't show up",2017/02/18,"['https://Stackoverflow.com/questions/42317542', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']","The solution is going to be solved only by me since it is included in a project. + +Thanks for your help, and if I found the real solution, I will post it here. + +**EDIT** + +Well, I feel bad now, about the wasted hour in my life. + +Anyway, I found the solution and it was about the animations. +I made this feature in my theme, so the user could create animations easily. + +The whole story summerizes in few words, "" Didn't enable animations in the parent Section, So the normal css code goes as .class{**OPACITY:0;**} "". + +Sorry! and Thanks for your deep concern in such a problem","Issue is in the image, +You have used very high quality image. +if you use a low quality image than you have currently used, +it will work fine." +130194,"Would be possible to apply genetic changes (like splicing in a radiation hardening gene) to an adult human? With near future technology, like advanced forms of CRISPR? Or can things like that only be applied t unborn infants?",2018/11/13,"['https://worldbuilding.stackexchange.com/questions/130194', 'https://worldbuilding.stackexchange.com', 'https://worldbuilding.stackexchange.com/users/47304/']","Yes but it's much harder and the effects can be limited and much slower. + +**Genetic Surgery** + +Enough engineered viruses can change the DNA but can be limited on changing physical structures. + +Here's an [example](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4401361/) where viral surgery was used to repair genetic deafness in mice + +If you are making large physical changes, it might take a very long time to take effect if at all.","[Gene Therapy](https://en.wikipedia.org/wiki/Gene_therapy) +========================================================== + +With the gene therapy, is possible to modify the DNA of a born creature using Virus, Retrovirus, Adenovirus, Non-Virus or others as a Vector. (Surprisingly, the Spanish Wikipedia has more information about different vectors). + +This [vectors](https://en.wikipedia.org/wiki/Vectors_in_gene_therapy) are programmed to modify the DNA structure of alive cells from the host. + +At the moment it's quite dangerous or ineffective this gene therapy, but in the future, with the boom of genetical manipulation, it will no longe be a problem." +130194,"Would be possible to apply genetic changes (like splicing in a radiation hardening gene) to an adult human? With near future technology, like advanced forms of CRISPR? Or can things like that only be applied t unborn infants?",2018/11/13,"['https://worldbuilding.stackexchange.com/questions/130194', 'https://worldbuilding.stackexchange.com', 'https://worldbuilding.stackexchange.com/users/47304/']","**Genetic engineering of adult subjects is currently not possible, especially with splicing** + +But it might be theoretically possible, with some huge challenges to overcome: + +A retrovirus is a virus capable of modifying a host cell's genome. I think the current scientific cliff is left at this: The virus can either modify the genome to our purposes or replicate itself but not both. The goal is to get it to both modify a genome beneficially to our purposes and the cells as well as enable replication of the virus. +Otherwise it would require infeasible sums of engineered virus to modify one person. + +**The virus can be attacked by the immune system.** Does no good if the virus is constantly eaten before it does its job. This can be overcome as some viruses can remain invisible to the immune system by the configuration of their protein shell. Its also problematic if the immune system kills the host in trying to kill the virus. + +**The virus mutates.** Viruses are inherently genetically unstable and tend to mutate often. It becomes dangerous as hell if it mutates something dangerous with all the weapons its been granted. Its also dangerous if it becomes contagious infecting random people or creatures causing unknowable havoc. + +**Getting the Virus Everywhere is Hard** Getting the virus into every cell is tricky as things reach different parts of the body at different rates. This also covers the fact that there are different types of cells which require different entry procedures for the virus to mutate. These problems come together in the most troublesome spot, the brain. Nerves are hard, both hard for viruses to enter (because they are less common) and are generally more protected (like the blood brain barrier). So getting the virus into everything uniformly can be difficult. + +**Adults are adults:** Physical maturation is an important biological process regulated by hormones in the brain. This is important in where genes are inserted as well as the process for activating them. For instance if your re-engineering intended to grow a third eye you need someway to activate and more importantly shut off the growth process. You wouldn't want a thousand eyes. Currently this process isn't well understood either. It could be that you simply need to supply your patient hormonal treatments in order to progress the mutations construction. + +**Some Cells don't Divide** Mutating a nerve would be tricky because they don't divide. That isn't to say nerves cant be enhanced because you can highjack something like a stem cell but how you manage modification of the brain can be enormously difficult and tricky. The slightest mistake could result in the permanent crippling or 'resetting'of the patient. Not to mention after you reset a person it might be possible to rehabilitate them either as the adult brain is no longer performing the same cognitive formatting as an infants. This challenge alone makes retroviral gene editing both dangerous and completely rules out neural modifications for at least the next 100 years if not the next millennium. It also limits the significance of mutations. Because general motor skills are hard wired during infancy, it would be impossible for an adult to grow 4 arms and then be able to learn how to use them. + +**Complexity of the mutation** Since adults are fully grown trying to unleash massive rewrites would be dangerous. This might be conquerable through iterative editing but if you change too much too fast you run the risk of killing the host in an infinitesimal array of ways.","Yes but it's much harder and the effects can be limited and much slower. + +**Genetic Surgery** + +Enough engineered viruses can change the DNA but can be limited on changing physical structures. + +Here's an [example](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4401361/) where viral surgery was used to repair genetic deafness in mice + +If you are making large physical changes, it might take a very long time to take effect if at all." +130194,"Would be possible to apply genetic changes (like splicing in a radiation hardening gene) to an adult human? With near future technology, like advanced forms of CRISPR? Or can things like that only be applied t unborn infants?",2018/11/13,"['https://worldbuilding.stackexchange.com/questions/130194', 'https://worldbuilding.stackexchange.com', 'https://worldbuilding.stackexchange.com/users/47304/']","**Genetic engineering of adult subjects is currently not possible, especially with splicing** + +But it might be theoretically possible, with some huge challenges to overcome: + +A retrovirus is a virus capable of modifying a host cell's genome. I think the current scientific cliff is left at this: The virus can either modify the genome to our purposes or replicate itself but not both. The goal is to get it to both modify a genome beneficially to our purposes and the cells as well as enable replication of the virus. +Otherwise it would require infeasible sums of engineered virus to modify one person. + +**The virus can be attacked by the immune system.** Does no good if the virus is constantly eaten before it does its job. This can be overcome as some viruses can remain invisible to the immune system by the configuration of their protein shell. Its also problematic if the immune system kills the host in trying to kill the virus. + +**The virus mutates.** Viruses are inherently genetically unstable and tend to mutate often. It becomes dangerous as hell if it mutates something dangerous with all the weapons its been granted. Its also dangerous if it becomes contagious infecting random people or creatures causing unknowable havoc. + +**Getting the Virus Everywhere is Hard** Getting the virus into every cell is tricky as things reach different parts of the body at different rates. This also covers the fact that there are different types of cells which require different entry procedures for the virus to mutate. These problems come together in the most troublesome spot, the brain. Nerves are hard, both hard for viruses to enter (because they are less common) and are generally more protected (like the blood brain barrier). So getting the virus into everything uniformly can be difficult. + +**Adults are adults:** Physical maturation is an important biological process regulated by hormones in the brain. This is important in where genes are inserted as well as the process for activating them. For instance if your re-engineering intended to grow a third eye you need someway to activate and more importantly shut off the growth process. You wouldn't want a thousand eyes. Currently this process isn't well understood either. It could be that you simply need to supply your patient hormonal treatments in order to progress the mutations construction. + +**Some Cells don't Divide** Mutating a nerve would be tricky because they don't divide. That isn't to say nerves cant be enhanced because you can highjack something like a stem cell but how you manage modification of the brain can be enormously difficult and tricky. The slightest mistake could result in the permanent crippling or 'resetting'of the patient. Not to mention after you reset a person it might be possible to rehabilitate them either as the adult brain is no longer performing the same cognitive formatting as an infants. This challenge alone makes retroviral gene editing both dangerous and completely rules out neural modifications for at least the next 100 years if not the next millennium. It also limits the significance of mutations. Because general motor skills are hard wired during infancy, it would be impossible for an adult to grow 4 arms and then be able to learn how to use them. + +**Complexity of the mutation** Since adults are fully grown trying to unleash massive rewrites would be dangerous. This might be conquerable through iterative editing but if you change too much too fast you run the risk of killing the host in an infinitesimal array of ways.","[Gene Therapy](https://en.wikipedia.org/wiki/Gene_therapy) +========================================================== + +With the gene therapy, is possible to modify the DNA of a born creature using Virus, Retrovirus, Adenovirus, Non-Virus or others as a Vector. (Surprisingly, the Spanish Wikipedia has more information about different vectors). + +This [vectors](https://en.wikipedia.org/wiki/Vectors_in_gene_therapy) are programmed to modify the DNA structure of alive cells from the host. + +At the moment it's quite dangerous or ineffective this gene therapy, but in the future, with the boom of genetical manipulation, it will no longe be a problem." +58764751,"Got some problems with setting up drone with my gitea instance and because there are so much different guides with different configs over the past years for different environment variables for drone, i cannot setup this the way it works for me. +And yes, i do know, they explicitly stated *""We strongly recommend installing Drone on a dedicated instance. We do not offer end-user support for installing Drone and Gitea on the same instance. We do not offer end-user support for troubleshooting network complications resulting from single-instance installations.""* but i think there must be a way to install it on the same server? + +my current setup +---------------- + +* [jwilder nginx automated proxy](https://github.com/jwilder/nginx-proxy) +* [lets encrypt companion](https://github.com/JrCs/docker-letsencrypt-nginx-proxy-companion) +* [gitea](https://github.com/go-gitea/gitea) +* [drone](https://github.com/drone/drone) + +drone docker-compose.yaml +------------------------- + +``` +version: ""3.7"" +services: + drone_server: + image: drone/drone + container_name: drone_server + ports: + - 127.0.0.1:8091:80 + volumes: + - /var/run/docker.sock:/var/run/docker.sock + - /srv/drone:/var/lib/drone/ + restart: always + environment: + - DRONE_GITEA_SERVER=https://gitea.mydomain.tld + - DRONE_GITEA_CLIENT_ID=$GITEA_CLIENT_ID + - DRONE_GITEA_CLIENT_SECRET=$GITEA_CLIENT_SECRET + - DRONE_SERVER_HOST=drone.mydomain.tld + - DRONE_SERVER_PROTO=https + - DRONE_LOGS_DEBUG=true + - DRONE_RPC_SECRET=$DRONE_SECRET + - VIRTUAL_HOST=drone.mydomain.tld + - LETSENCRYPT_HOST=drone.mydomain.tld + networks: + - proxy + +networks: + proxy: + external: + name: proxy_default + +``` + +corresponding (autogenerated) nginx config for drone +---------------------------------------------------- + +(gitea is equal, but with different subdomian) + +``` +map $http_x_forwarded_proto $proxy_x_forwarded_proto { + default $http_x_forwarded_proto; + '' $scheme; +} +map $http_x_forwarded_port $proxy_x_forwarded_port { + default $http_x_forwarded_port; + '' $server_port; +} +map $http_upgrade $proxy_connection { + default upgrade; + '' close; +} +server_names_hash_bucket_size 128; +ssl_dhparam /etc/nginx/dhparam/dhparam.pem; +map $scheme $proxy_x_forwarded_ssl { + default off; + https on; +} +gzip_types text/plain text/css application/javascript application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript; +log_format vhost '$host $remote_addr - $remote_user [$time_local] ' + '""$request"" $status $body_bytes_sent ' + '""$http_referer"" ""$http_user_agent""'; +access_log off; + ssl_protocols TLSv1.2 TLSv1.3; + ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384'; + ssl_prefer_server_ciphers off; +resolver 127.0.0.11; +proxy_buffering off; +proxy_set_header Host $http_host; +proxy_set_header Upgrade $http_upgrade; +proxy_set_header Connection $proxy_connection; +proxy_set_header X-Real-IP $remote_addr; +proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; +proxy_set_header X-Forwarded-Proto $proxy_x_forwarded_proto; +proxy_set_header X-Forwarded-Ssl $proxy_x_forwarded_ssl; +proxy_set_header X-Forwarded-Port $proxy_x_forwarded_port; + +# drone.mydomain.tld +upstream drone.mydomain.tld { + ## Can be connected with ""proxy_default"" network + # drone_server + server 172.22.0.8:80; + # Cannot connect to network of this container + server 127.0.0.1 down; +} +server { + server_name drone.mydomain.tld; + listen 80 ; + access_log /var/log/nginx/access.log vhost; + return 301 https://$host$request_uri; +} +server { + server_name drone.mydomain.tld; + listen 443 ssl http2 ; + access_log /var/log/nginx/access.log vhost; + ssl_session_timeout 5m; + ssl_session_cache shared:SSL:50m; + ssl_session_tickets off; + ssl_certificate /etc/nginx/certs/drone.mydomain.tld.crt; + ssl_certificate_key /etc/nginx/certs/drone.mydomain.tld.key; + ssl_dhparam /etc/nginx/certs/drone.mydomain.tld.dhparam.pem; + ssl_stapling on; + ssl_stapling_verify on; + ssl_trusted_certificate /etc/nginx/certs/drone.mydomain.tld.chain.pem; + add_header Strict-Transport-Security ""max-age=31536000"" always; + include /etc/nginx/vhost.d/default; + location / { + proxy_pass http://drone.mydomain.tld; + } +} + +``` + +the gitea\_client\_id and secret are created via gitea webinterface, the redirect url is set to `https://drone.mydomain.tld/login` + +here is what i am seeing visiting drone.mydomain.tld +---------------------------------------------------- + +[![drone auth](https://i.stack.imgur.com/3zpwC.png)](https://i.stack.imgur.com/3zpwC.png) + +After clicking authorize application the the url in my browser request changes to and it just loads until nginx throws a 502. After this initial authorization, every request just results in the following logs and erorr. + +### nginx logs + +``` +nginx.1 | 2019/11/08 10:44:16 [warn] 3762#3762: *47660 upstream server temporarily disabled while reading response header from upstream, client: 111.111.111.111, server: drone.mydomain.tld, request: ""GET /login?XXXXXXXX HTTP/2.0"", upstream: ""http://172.22.0.8:80/login?XXXXXXXX"", host: ""drone.mydomain.tld"", referrer: ""https://drone.mydomain.tld/"" +nginx.1 | 2019/11/08 10:44:16 [error] 3762#3762: *47660 upstream timed out (110: Operation timed out) while reading response header from upstream, client: 111.111.111.111, server: drone.mydomain.tld, request: ""GET /login?XXXXXXXX HTTP/2.0"", upstream: ""http://172.22.0.8:80/login?XXXXXXXX"", host: ""drone.mydomain.tld"", referrer: ""https://drone.mydomain.tld/"" +nginx.1 | 2019/11/08 10:44:16 [error] 3762#3762: *47660 no live upstreams while connecting to upstream, client: 111.111.111.111, server: drone.mydomain.tld, request: ""GET /login?XXXXXXXX HTTP/2.0"", upstream: ""http://drone.mydomain.tld/login?XXXXXXXX"", host: ""drone.mydomain.tld"", referrer: ""https://drone.mydomain.tld/"" + +``` + +### drone logs + +``` +{""level"":""debug"",""msg"":""api: authentication required"",""request-id"":""1TKR8MAfIewZpiiwn2YkUNEqBrt"",""time"":""2019-11-08T09:50:39Z""} +{""level"":""debug"",""msg"":""api: guest access"",""request-id"":""1TKR8MAfIewZpiiwn2YkUNEqBrt"",""time"":""2019-11-08T09:50:39Z""} +{""fields.time"":""2019-11-08T09:50:39Z"",""latency"":109385,""level"":""debug"",""method"":""GET"",""msg"":"""",""remote"":""172.22.0.2:60330"",""request"":""/api/user"",""request-id"":""1TKR8MAfIewZpiiwn2YkUNEqBrt"",""time"":""2019-11-08T09:50:39Z""} +{""fields.time"":""2019-11-08T09:50:39Z"",""latency"":64377,""level"":""debug"",""method"":""GET"",""msg"":"""",""remote"":""172.22.0.2:60332"",""request"":""/login"",""request-id"":""1TKR8IicJybGXkQf3ebpiGV4VXi"",""time"":""2019-11-08T09:50:39Z""} +{""level"":""debug"",""msg"":""events: stream opened"",""request-id"":""1TKR8Jv7zQrCQSzRyCFbeRLeC8M"",""time"":""2019-11-08T09:50:39Z""} +{""level"":""debug"",""msg"":""events: stream cancelled"",""request-id"":""1TKR8Jv7zQrCQSzRyCFbeRLeC8M"",""time"":""2019-11-08T09:51:39Z""} +{""level"":""debug"",""msg"":""events: stream closed"",""request-id"":""1TKR8Jv7zQrCQSzRyCFbeRLeC8M"",""time"":""2019-11-08T09:51:39Z""} +{""level"":""debug"",""msg"":""api: guest access"",""request-id"":""1TKR8Jv7zQrCQSzRyCFbeRLeC8M"",""time"":""2019-11-08T09:51:39Z""} +{""fields.time"":""2019-11-08T09:51:39Z"",""latency"":60182954972,""level"":""debug"",""method"":""GET"",""msg"":"""",""remote"":""172.22.0.2:60334"",""request"":""/api/stream"",""request-id"":""1TKR8Jv7zQrCQSzRyCFbeRLeC8M"",""time"":""2019-11-08T09:51:39Z""} +{""level"":""error"",""msg"":""oauth: cannot exchange code: ysvAfRKVkRz4ZtN9zX635Vd-mnB__oXW7Rmqpra1VGU=: Post https://gitea.mydomain.tld/login/oauth/access_token: dial tcp 144.76.155.172:443: connect: connection timed out"",""time"":""2019-11-08T09:52:32Z""} +{""level"":""debug"",""msg"":""cannot authenticate user: Post https://gitea.mydomain.tld/login/oauth/access_token: dial tcp 144.76.155.172:443: connect: connection timed out"",""time"":""2019-11-08T09:52:32Z""} + +``` + +### gitea logs + +``` +[Macaron] 2019-11-08 10:50:21: Started GET /login/oauth/authorize?client_id=$GITEA_CLIENT_ID&redirect_uri=https%3A%2F%2Fdrone.mydomain.tld%2Flogin&response_type=code&state=c697f48392907a0 for 134.96.216.2 +[Macaron] 2019-11-08 10:50:21: Completed GET /login/oauth/authorize?client_id=$GITEA_CLIENT_ID&redirect_uri=https%3A%2F%2Fdrone.mydomain.tld%2Flogin&response_type=code&state=c697f48392907a0 302 Found in 58.954698ms +[Macaron] 2019-11-08 10:50:39: Started GET /login/oauth/authorize?client_id=$GITEA_CLIENT_ID&redirect_uri=https%3A%2F%2Fdrone.mydomain.tld%2Flogin&response_type=code&state=68255aaf95e94627 for 134.96.216.2 +[Macaron] 2019-11-08 10:50:39: Completed GET /login/oauth/authorize?client_id=$GITEA_CLIENT_ID&redirect_uri=https%3A%2F%2Fdrone.mydomain.tld%2Flogin&response_type=code&state=68255aaf95e94627 302 Found in 78.11159ms + +``` + +### page source + +this is what my browser is showing while, obviously, javascript is activated + +```html + + + + + + + + + Drone | Continuous Integration + + + + + + + + +
+ + + + + + +``` + +is there any configuration i missed or any environment variable which is outdated (i followed different guides, but in the end checked everything with the [drone docs](https://docs.drone.io/installation/providers/gitea/))? is there anybody out there who is running a similar setup who can share his config with me? i tried pretty much every combination of http/https combination and different outdated env vars for drone, but never got to the actual webfrontend.",2019/11/08,"['https://Stackoverflow.com/questions/58764751', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9239809/']","Try: + +``` +import matplotlib.pyplot as plt +ax = df.plot.bar(y='Profile_ID Count') +plt.show() + +```","``` +# Importing the requisite libraries +import pandas as pd +import matplotlib.pyplot as plt + +# Creating the DataFrame +df = pd.DataFrame({'Creation Date':['2016-06-01','2016-06-03','2016-06-04'],'Profile_ID Count':[150,3,20]}) + +# Creating the bar chart below. +fig, ax = plt.subplots() +ax.bar(df['Creation Date'],df['Profile_ID Count'], color='red', width = 0.5) +fig.autofmt_xdate() # This tilts the dates displayed along X-axis. +ax.set_title('Creation Date vs. Profile ID Count') +ax.set_xlabel('Creation Date') +ax.set_ylabel('Profile ID Count') +plt.show() + +``` + +[![Bar-Chart](https://i.stack.imgur.com/FInW9.png)](https://i.stack.imgur.com/FInW9.png)" +11106110,"Does anyone know the standard size of a single listview item in android, in dpi or pixels? + +Or maybe there isn't a standard?",2012/06/19,"['https://Stackoverflow.com/questions/11106110', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1301563/']","Android defines a ""preferred size"" using, + +``` +android:minHeight=""?android:attr/listPreferredItemHeight"" + +``` + +Documented [here](http://developer.android.com/reference/android/R.attr.html#listPreferredItemHeight) as well.","there is a strongly recommended list view item size, which you should use: [48dip](http://developer.android.com/design/style/metrics-grids.html#48dp-rhythm). This is recommended by the new Android Design Guidelines." +2996,"I recently upgraded to CiviCRM 4.6.3 from 4.4.XX. Since then, the WYSIWYG editor is missing when creating a new scheduled reminder or editing an existing one. To reproduce the error: +1. Click Manage Events +2. Click Configure an event, and choose Schedule Reminders. +3. Edit or create a new reminder +4. See the editor missing. + +However if on step 2, you instead choose Info and Settings, then click Schedule Reminders, the WYSIWYG editor does appear. + +I've verified the error with IE, FF and Chrome, and I see the issue 100% of the time. Using Joomla 2.5.28. + +Anybody else see this issue?",2015/06/03,"['https://civicrm.stackexchange.com/questions/2996', 'https://civicrm.stackexchange.com', 'https://civicrm.stackexchange.com/users/614/']","Adding the contribution status itself is pretty easy. You can do that with Administer/System Settings/Option Groups, find the one for Contribution Status and click on 'options'. You will then get the possibility to add a value. + +This is just adding a status, so I assume the settings of the status will be done manually. If you want to automate that you will have to develop a small extension that acts when a contribution is added or changed, and sets your status in relevant cases. + +Am I making sense?","Normally, you can set new options in Administer > System Settings > Option Groups, but you'll notice that it says: + +> +> This option group is reserved for system use. You cannot add or delete options in this list. +> +> +> + +You could work around it by adding a new item in the civicrm\_option\_value table, but you'd be definitely doing something that CiviCRM is telling you not to do. You may have upgrade problems at some later point, because CiviCRM will assume nobody has gone in and messed around with those options. + +Instead, you might consider that there really is no *new* data to be stored; you just want to be able to find really old pending contributions. If you just create a report based upon the donor detail report with the following changes, you ought to be able to find the right folks: + +* Contribution Status set to Pending, Cancelled, or whatever else +* Receive date set to ""To end of previous quarter"" or an equivalent relative date (I know it's not exactly what you want, but date filters will be improving soon, I hear) + +You can even set this as a dashlet so that the person in charge of pestering people about this can have it on his or her dashboard." +4144,"I want to burn a .img file of Wheezy OS to my 8GB SD Card from Mac OS X but can't figure out how. + +Any help would be appreciated.",2012/12/27,"['https://raspberrypi.stackexchange.com/questions/4144', 'https://raspberrypi.stackexchange.com', 'https://raspberrypi.stackexchange.com/users/-1/']","First, verify the path to your SD card. You can do this by running the following command from terminal: + +`diskutil list` + +The output shows a list of disks currently mounted on the system. Here's the relevant line from my output: + +``` +/dev/disk3 +#: TYPE NAME SIZE IDENTIFIER +0: FDisk_partition_scheme *8.0 GB disk3 +1: DOS_FAT_32 RPISDCARD 8.0 GB disk3s1 + +``` + +In this case I can verify `/dev/disk3` is my SD card because the TYPE, NAME and SIZE values are correct. + +If you have an existing partition on the disk you may need to unmount it, otherwise you'll get a ""Resource busy"" error message when you try to write the image. + +``` +diskutil unmount /dev/disk3s1 + +``` + +Now to write the image file to the disk. Note the 'r' added to `rdisk3` which drastically improves write performance by telling `dd` to operate in raw disk mode: + +``` +sudo dd if=RetroPieImage_ver2.3.img of=/dev/rdisk3 bs=1m + +``` + +Depending on the size of your SDcard this may take a while. You can press `CTRL+T` to see the current status of `dd`. As an example for my Samsung 8GB SD card the write speed was 12MB/s the command took 11mins to complete.","Try this: [ApplePi-Baker](http://www.tweaking4all.com/hardware/raspberry-pi/macosx-apple-pi-baker/) + +It's free, writes IMG files to SD-Card, can prepare a NOOBS card and can make a backup to IMG of your SD-Card." +4144,"I want to burn a .img file of Wheezy OS to my 8GB SD Card from Mac OS X but can't figure out how. + +Any help would be appreciated.",2012/12/27,"['https://raspberrypi.stackexchange.com/questions/4144', 'https://raspberrypi.stackexchange.com', 'https://raspberrypi.stackexchange.com/users/-1/']","I made a script to burn .img or .iso files to SD card or USB. + +[Github > burn.sh](https://github.com/jmcerrejon/scripts/blob/master/burn.sh)","Use `df` to find the device path, in this case `/dev/disk2`. + +``` +$ df -h + +Filesystem Size Used Avail Capacity iused ifree %iused Mounted on +/dev/disk1 465Gi 414Gi 51Gi 90% 108573777 13263821 89% / +devfs 214Ki 214Ki 0Bi 100% 741 0 100% /dev +map -hosts 0Bi 0Bi 0Bi 100% 0 0 100% /net +map auto_home 0Bi 0Bi 0Bi 100% 0 0 100% /home +/dev/disk2s1 3.7Gi 2.3Mi 3.7Gi 1% 0 0 100% /Volumes/UNTITLED + +```" +4144,"I want to burn a .img file of Wheezy OS to my 8GB SD Card from Mac OS X but can't figure out how. + +Any help would be appreciated.",2012/12/27,"['https://raspberrypi.stackexchange.com/questions/4144', 'https://raspberrypi.stackexchange.com', 'https://raspberrypi.stackexchange.com/users/-1/']","There is a faq/howto available that discusses all the various OS-es. For the Mac it is (nearly) the same as under the various other types of Unix versions. The use of dd. + +In short you type: + +``` +sudo dd if=path_of_your_image.img of=/dev/rdiskn bs=1m + +``` + +**N.B: the of=/rdev/diskn needs to be the SD card, if you do this wrong you might end up destroying your Mac system!!!! Be careful!** + +Be sure to use `/dev/rdiskn` instead of just `/dev/diskn`. This way you are not writing to a buffered device and [it will complete much faster](https://raspberrypi.stackexchange.com/questions/3204/sd-card-write-speed-seems-to-be-14-times-slower-than-read-speed/4059#4059). + +For a total step by step guide through this process please consult this [explanation](http://elinux.org/RPi_Easy_SD_Card_Setup). There are 3 chapters for the Mac in this document. + +The most easy way is described on the first chapter on Mac ([Copying an image to the SD card in Mac OS X (Only with graphical interface)](http://elinux.org/RPi_Easy_SD_Card_Setup#Copying_an_image_to_the_SD_card_in_Mac.C2.A0OS.C2.A0X_.28Only_with_graphical_interface.29)), it involves an application that does everything for you, to be complete I copy the link to this application [here](http://alltheware.wordpress.com/2012/12/11/easiest-way-sd-card-setup/)","Try this: [ApplePi-Baker](http://www.tweaking4all.com/hardware/raspberry-pi/macosx-apple-pi-baker/) + +It's free, writes IMG files to SD-Card, can prepare a NOOBS card and can make a backup to IMG of your SD-Card." +4144,"I want to burn a .img file of Wheezy OS to my 8GB SD Card from Mac OS X but can't figure out how. + +Any help would be appreciated.",2012/12/27,"['https://raspberrypi.stackexchange.com/questions/4144', 'https://raspberrypi.stackexchange.com', 'https://raspberrypi.stackexchange.com/users/-1/']","In 2020, this accepted answer is obsolete: For *most* cases, people should follow the new [raspberrypi.org Installation Guide](https://www.raspberrypi.org/documentation/installation/installing-images/README.md). + +Alternatively, the community-provided [Etcher](https://www.balena.io/etcher/) tool also provides a graphical tool to burn Pi IMG files to SD card. + +Sometimes the built-in SD card reader gives errors with Etcher. If you don't have a USB SD adapter, 'dd' sometimes still works although the user must *take care* because the wrong command may damage their mac's OS. + +If you must use 'dd', the accepted answer `sudo dd if=path_of_your_image.img of=/dev/rdiskn bs=1m` works (with care taken) *however* if you have installed [Homebrew](https://brew.sh/) with the 'gnubin' utilities, it provides the GNU dd utility which has different syntax. For GNU dd (including Linux hosts) use `1M` instead of `1m` (otherwise you get error: ""`dd: invalid number: ‘1m’`"" which is what inspired me to add a new answer).","You could also try: [dd Utility](https://www.thefanclub.co.za/how-to/dd-utility-write-and-backup-operating-system-img-files-memory-card-mac-os-x) + +Features: + +* Write IMG files to memory cards and hard drives. +* Backup and Restore IMG files to memory cards and hard drives. +* Install and Restore compressed disk image files on the fly. Supported +file formats: IMG, Zip, GZip and XZ. +* Backup and compress disk image files on the fly in ZIP format to +significantly reduce the file size of backups. +* Ideal for flashing IMG files to SD Cards for use with Raspberry Pi, +Arduino, BeagleBoard and other ARM boards. +* Mac Retina displays supported." +4144,"I want to burn a .img file of Wheezy OS to my 8GB SD Card from Mac OS X but can't figure out how. + +Any help would be appreciated.",2012/12/27,"['https://raspberrypi.stackexchange.com/questions/4144', 'https://raspberrypi.stackexchange.com', 'https://raspberrypi.stackexchange.com/users/-1/']","There is a faq/howto available that discusses all the various OS-es. For the Mac it is (nearly) the same as under the various other types of Unix versions. The use of dd. + +In short you type: + +``` +sudo dd if=path_of_your_image.img of=/dev/rdiskn bs=1m + +``` + +**N.B: the of=/rdev/diskn needs to be the SD card, if you do this wrong you might end up destroying your Mac system!!!! Be careful!** + +Be sure to use `/dev/rdiskn` instead of just `/dev/diskn`. This way you are not writing to a buffered device and [it will complete much faster](https://raspberrypi.stackexchange.com/questions/3204/sd-card-write-speed-seems-to-be-14-times-slower-than-read-speed/4059#4059). + +For a total step by step guide through this process please consult this [explanation](http://elinux.org/RPi_Easy_SD_Card_Setup). There are 3 chapters for the Mac in this document. + +The most easy way is described on the first chapter on Mac ([Copying an image to the SD card in Mac OS X (Only with graphical interface)](http://elinux.org/RPi_Easy_SD_Card_Setup#Copying_an_image_to_the_SD_card_in_Mac.C2.A0OS.C2.A0X_.28Only_with_graphical_interface.29)), it involves an application that does everything for you, to be complete I copy the link to this application [here](http://alltheware.wordpress.com/2012/12/11/easiest-way-sd-card-setup/)","Found a really good link: for installing file.img on SD card, very detailed steps!" +4144,"I want to burn a .img file of Wheezy OS to my 8GB SD Card from Mac OS X but can't figure out how. + +Any help would be appreciated.",2012/12/27,"['https://raspberrypi.stackexchange.com/questions/4144', 'https://raspberrypi.stackexchange.com', 'https://raspberrypi.stackexchange.com/users/-1/']","First, verify the path to your SD card. You can do this by running the following command from terminal: + +`diskutil list` + +The output shows a list of disks currently mounted on the system. Here's the relevant line from my output: + +``` +/dev/disk3 +#: TYPE NAME SIZE IDENTIFIER +0: FDisk_partition_scheme *8.0 GB disk3 +1: DOS_FAT_32 RPISDCARD 8.0 GB disk3s1 + +``` + +In this case I can verify `/dev/disk3` is my SD card because the TYPE, NAME and SIZE values are correct. + +If you have an existing partition on the disk you may need to unmount it, otherwise you'll get a ""Resource busy"" error message when you try to write the image. + +``` +diskutil unmount /dev/disk3s1 + +``` + +Now to write the image file to the disk. Note the 'r' added to `rdisk3` which drastically improves write performance by telling `dd` to operate in raw disk mode: + +``` +sudo dd if=RetroPieImage_ver2.3.img of=/dev/rdisk3 bs=1m + +``` + +Depending on the size of your SDcard this may take a while. You can press `CTRL+T` to see the current status of `dd`. As an example for my Samsung 8GB SD card the write speed was 12MB/s the command took 11mins to complete.","Found a really good link: for installing file.img on SD card, very detailed steps!" +4144,"I want to burn a .img file of Wheezy OS to my 8GB SD Card from Mac OS X but can't figure out how. + +Any help would be appreciated.",2012/12/27,"['https://raspberrypi.stackexchange.com/questions/4144', 'https://raspberrypi.stackexchange.com', 'https://raspberrypi.stackexchange.com/users/-1/']","Yes the simple answer is to just [dd](http://linux.die.net/man/1/dd) it, but there are some safety precautions you may want to enforce by wrapping your dd in a script; + +``` +#!/bin/bash + +# +# copy_img_to_sd.sh +# + +ME=$( id | grep root | wc -l | perl -p -e 's/[^0-9]+//g'); +if [ ""$ME"" != ""1"" ] ;then + echo ""must be root"" + exit 1; +fi +IMG=$1 +if [ ! -f $IMG ] ;then + echo ""can not find $IMG""; + exit 2; +fi +DISK=$(ls -l /dev/disk? | wc -l |perl -p -e 's/[^0-9]//g') +if [ $DISK -lt 3 ] ; then + echo ""can not find sdcard""; + ls -l /dev/disk? + exit 2; +fi +DISK=$(ls -1 /dev/disk? | tail -1); +R_DISK=$(ls -1 /dev/rdisk? | tail -1); +echo ""we are about to do this:"" +echo $(diskutil information $DISK | grep Total) +ls -1 /dev/disk?s* | grep ""$DISK"" | perl -p -e 's/^(.*)$/diskutil unmount $1;/g' +echo dd bs=1m if=$IMG of=$R_DISK +echo sync +echo diskutil eject $R_DISK +echo ""Press [enter] to continue or [Ctrl]+[C] to cancel""; +read YNM; +ls -1 /dev/disk?s* | grep ""$DISK"" | perl -p -e 's/^(.*)$/diskutil unmount $1;/g' | bash 2>/dev/null +dd bs=1m if=$IMG of=$R_DISK +sync +diskutil eject $R_DISK + +``` + +Accidentally writing an image to your internal drive will require a fresh OS X install to correct. Backup and keep an install.log so if it ever happens to you you can laugh it off.","Use `df` to find the device path, in this case `/dev/disk2`. + +``` +$ df -h + +Filesystem Size Used Avail Capacity iused ifree %iused Mounted on +/dev/disk1 465Gi 414Gi 51Gi 90% 108573777 13263821 89% / +devfs 214Ki 214Ki 0Bi 100% 741 0 100% /dev +map -hosts 0Bi 0Bi 0Bi 100% 0 0 100% /net +map auto_home 0Bi 0Bi 0Bi 100% 0 0 100% /home +/dev/disk2s1 3.7Gi 2.3Mi 3.7Gi 1% 0 0 100% /Volumes/UNTITLED + +```" +4144,"I want to burn a .img file of Wheezy OS to my 8GB SD Card from Mac OS X but can't figure out how. + +Any help would be appreciated.",2012/12/27,"['https://raspberrypi.stackexchange.com/questions/4144', 'https://raspberrypi.stackexchange.com', 'https://raspberrypi.stackexchange.com/users/-1/']","Found a really good link: for installing file.img on SD card, very detailed steps!","Use `df` to find the device path, in this case `/dev/disk2`. + +``` +$ df -h + +Filesystem Size Used Avail Capacity iused ifree %iused Mounted on +/dev/disk1 465Gi 414Gi 51Gi 90% 108573777 13263821 89% / +devfs 214Ki 214Ki 0Bi 100% 741 0 100% /dev +map -hosts 0Bi 0Bi 0Bi 100% 0 0 100% /net +map auto_home 0Bi 0Bi 0Bi 100% 0 0 100% /home +/dev/disk2s1 3.7Gi 2.3Mi 3.7Gi 1% 0 0 100% /Volumes/UNTITLED + +```" +4144,"I want to burn a .img file of Wheezy OS to my 8GB SD Card from Mac OS X but can't figure out how. + +Any help would be appreciated.",2012/12/27,"['https://raspberrypi.stackexchange.com/questions/4144', 'https://raspberrypi.stackexchange.com', 'https://raspberrypi.stackexchange.com/users/-1/']","There is a faq/howto available that discusses all the various OS-es. For the Mac it is (nearly) the same as under the various other types of Unix versions. The use of dd. + +In short you type: + +``` +sudo dd if=path_of_your_image.img of=/dev/rdiskn bs=1m + +``` + +**N.B: the of=/rdev/diskn needs to be the SD card, if you do this wrong you might end up destroying your Mac system!!!! Be careful!** + +Be sure to use `/dev/rdiskn` instead of just `/dev/diskn`. This way you are not writing to a buffered device and [it will complete much faster](https://raspberrypi.stackexchange.com/questions/3204/sd-card-write-speed-seems-to-be-14-times-slower-than-read-speed/4059#4059). + +For a total step by step guide through this process please consult this [explanation](http://elinux.org/RPi_Easy_SD_Card_Setup). There are 3 chapters for the Mac in this document. + +The most easy way is described on the first chapter on Mac ([Copying an image to the SD card in Mac OS X (Only with graphical interface)](http://elinux.org/RPi_Easy_SD_Card_Setup#Copying_an_image_to_the_SD_card_in_Mac.C2.A0OS.C2.A0X_.28Only_with_graphical_interface.29)), it involves an application that does everything for you, to be complete I copy the link to this application [here](http://alltheware.wordpress.com/2012/12/11/easiest-way-sd-card-setup/)","Use `df` to find the device path, in this case `/dev/disk2`. + +``` +$ df -h + +Filesystem Size Used Avail Capacity iused ifree %iused Mounted on +/dev/disk1 465Gi 414Gi 51Gi 90% 108573777 13263821 89% / +devfs 214Ki 214Ki 0Bi 100% 741 0 100% /dev +map -hosts 0Bi 0Bi 0Bi 100% 0 0 100% /net +map auto_home 0Bi 0Bi 0Bi 100% 0 0 100% /home +/dev/disk2s1 3.7Gi 2.3Mi 3.7Gi 1% 0 0 100% /Volumes/UNTITLED + +```" +4144,"I want to burn a .img file of Wheezy OS to my 8GB SD Card from Mac OS X but can't figure out how. + +Any help would be appreciated.",2012/12/27,"['https://raspberrypi.stackexchange.com/questions/4144', 'https://raspberrypi.stackexchange.com', 'https://raspberrypi.stackexchange.com/users/-1/']","First, verify the path to your SD card. You can do this by running the following command from terminal: + +`diskutil list` + +The output shows a list of disks currently mounted on the system. Here's the relevant line from my output: + +``` +/dev/disk3 +#: TYPE NAME SIZE IDENTIFIER +0: FDisk_partition_scheme *8.0 GB disk3 +1: DOS_FAT_32 RPISDCARD 8.0 GB disk3s1 + +``` + +In this case I can verify `/dev/disk3` is my SD card because the TYPE, NAME and SIZE values are correct. + +If you have an existing partition on the disk you may need to unmount it, otherwise you'll get a ""Resource busy"" error message when you try to write the image. + +``` +diskutil unmount /dev/disk3s1 + +``` + +Now to write the image file to the disk. Note the 'r' added to `rdisk3` which drastically improves write performance by telling `dd` to operate in raw disk mode: + +``` +sudo dd if=RetroPieImage_ver2.3.img of=/dev/rdisk3 bs=1m + +``` + +Depending on the size of your SDcard this may take a while. You can press `CTRL+T` to see the current status of `dd`. As an example for my Samsung 8GB SD card the write speed was 12MB/s the command took 11mins to complete.","I made a script to burn .img or .iso files to SD card or USB. + +[Github > burn.sh](https://github.com/jmcerrejon/scripts/blob/master/burn.sh)" +47550227,"I'm trying to mount mongo `/data` directory on to a NFS volume in my kubernetes master machine for persisting mongo data. I see the volume is mounted successfully but I can see only `configdb` and `db` dirs but not their subdirectories. And I see the data is not even persisting in the volume. when I `kubectl describe ` it shows `NFS (an NFS mount that lasts the lifetime of a pod)` + +Why is that so? + +I see in kubernetes docs stating that: + +> +> An nfs volume allows an existing NFS (Network File System) share to be +> mounted into your pod. Unlike emptyDir, which is erased when a Pod is +> removed, the contents of an nfs volume are preserved and the volume is +> merely unmounted. This means that an NFS volume can be pre-populated +> with data, and that data can be “handed off” between pods. NFS can be +> mounted by multiple writers simultaneously. +> +> +> + +I'm using kubernetes version 1.8.3. + +mongo-deployment.yml: + +``` +apiVersion: apps/v1beta2 +kind: Deployment +metadata: + name: mongo + labels: + name: mongo + app: mongo +spec: + replicas: 3 + selector: + matchLabels: + name: mongo + app: mongo + template: + metadata: + name: mongo + labels: + name: mongo + app: mongo + spec: + containers: + - name: mongo + image: mongo:3.4.9 + ports: + - name: mongo + containerPort: 27017 + protocol: TCP + volumeMounts: + - name: mongovol + mountPath: ""/data"" + volumes: + - name: mongovol + persistentVolumeClaim: + claimName: mongo-pvc + +``` + +mongo-pv.yml: + +``` +apiVersion: v1 +kind: PersistentVolume +metadata: + name: mongo-pv + labels: + type: NFS +spec: + capacity: + storage: 5Gi + accessModes: + - ReadWriteMany + persistentVolumeReclaimPolicy: Retain + storageClassName: slow + mountOptions: + - hard + - nfsvers=4.1 + nfs: + path: ""/mongodata"" + server: 172.20.33.81 + +``` + +mongo-pvc.yml: + +``` +apiVersion: v1 +kind: PersistentVolumeClaim +metadata: + name: mongo-pvc +spec: + accessModes: + - ReadWriteMany + resources: + requests: + storage: 3Gi + storageClassName: slow + selector: + matchLabels: + type: NFS + +``` + +The way I mounted my nfs share on my kubernetes master machine: + +``` +1) apt-get install nfs-kernel-server +2) mkdir /mongodata +3) chown nobody:nogroup -R /mongodata +4) vi /etc/exports +5) added the line ""/mongodata *(rw,sync,all_squash,no_subtree_check)"" +6) exportfs -ra +7) service nfs-kernel-server restart +8) showmount -e ----> shows the share + +``` + +I logged into the bash of my pod and I see the directory is mounted correctly but data is not persisting in my nfs server (kubernetes master machine). + +Please help me see what I am doing wrong here.",2017/11/29,"['https://Stackoverflow.com/questions/47550227', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4088785/']","It's possible that pods don't have permission to create files and directories. You can `exec` to your pod and try to `touch` a file in NFS share if you get permission error you can ease up permission on file system and `exports` file to allow write access. + +It's possible to specify `GID` in PV object to avoid permission denied issues. +","I see you did a `chown nobody:nogroup -R /mongodata`. +Make sure that the application on your pod runs as `nobody:nogroup`" +47550227,"I'm trying to mount mongo `/data` directory on to a NFS volume in my kubernetes master machine for persisting mongo data. I see the volume is mounted successfully but I can see only `configdb` and `db` dirs but not their subdirectories. And I see the data is not even persisting in the volume. when I `kubectl describe ` it shows `NFS (an NFS mount that lasts the lifetime of a pod)` + +Why is that so? + +I see in kubernetes docs stating that: + +> +> An nfs volume allows an existing NFS (Network File System) share to be +> mounted into your pod. Unlike emptyDir, which is erased when a Pod is +> removed, the contents of an nfs volume are preserved and the volume is +> merely unmounted. This means that an NFS volume can be pre-populated +> with data, and that data can be “handed off” between pods. NFS can be +> mounted by multiple writers simultaneously. +> +> +> + +I'm using kubernetes version 1.8.3. + +mongo-deployment.yml: + +``` +apiVersion: apps/v1beta2 +kind: Deployment +metadata: + name: mongo + labels: + name: mongo + app: mongo +spec: + replicas: 3 + selector: + matchLabels: + name: mongo + app: mongo + template: + metadata: + name: mongo + labels: + name: mongo + app: mongo + spec: + containers: + - name: mongo + image: mongo:3.4.9 + ports: + - name: mongo + containerPort: 27017 + protocol: TCP + volumeMounts: + - name: mongovol + mountPath: ""/data"" + volumes: + - name: mongovol + persistentVolumeClaim: + claimName: mongo-pvc + +``` + +mongo-pv.yml: + +``` +apiVersion: v1 +kind: PersistentVolume +metadata: + name: mongo-pv + labels: + type: NFS +spec: + capacity: + storage: 5Gi + accessModes: + - ReadWriteMany + persistentVolumeReclaimPolicy: Retain + storageClassName: slow + mountOptions: + - hard + - nfsvers=4.1 + nfs: + path: ""/mongodata"" + server: 172.20.33.81 + +``` + +mongo-pvc.yml: + +``` +apiVersion: v1 +kind: PersistentVolumeClaim +metadata: + name: mongo-pvc +spec: + accessModes: + - ReadWriteMany + resources: + requests: + storage: 3Gi + storageClassName: slow + selector: + matchLabels: + type: NFS + +``` + +The way I mounted my nfs share on my kubernetes master machine: + +``` +1) apt-get install nfs-kernel-server +2) mkdir /mongodata +3) chown nobody:nogroup -R /mongodata +4) vi /etc/exports +5) added the line ""/mongodata *(rw,sync,all_squash,no_subtree_check)"" +6) exportfs -ra +7) service nfs-kernel-server restart +8) showmount -e ----> shows the share + +``` + +I logged into the bash of my pod and I see the directory is mounted correctly but data is not persisting in my nfs server (kubernetes master machine). + +Please help me see what I am doing wrong here.",2017/11/29,"['https://Stackoverflow.com/questions/47550227', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4088785/']","It's possible that pods don't have permission to create files and directories. You can `exec` to your pod and try to `touch` a file in NFS share if you get permission error you can ease up permission on file system and `exports` file to allow write access. + +It's possible to specify `GID` in PV object to avoid permission denied issues. +","Add the parameter `mountOptions: ""vers=4.1""` to your StorageClass config, this should fix your issue. + +See this Github comment for more info: + +" +66288,"I recently upgraded to Oneiric and noticed that the calendar is no longer persistent like it was in Natty and Maverick. I could open the calendar to January 2007, then move to another window and still refer to the calendar. Now, as soon as I lose focus the calendar goes back into hiding. Is this a setting somewhere?",2011/10/14,"['https://askubuntu.com/questions/66288', 'https://askubuntu.com', 'https://askubuntu.com/users/23482/']","Temporarily downloaded files +---------------------------- + +All Linux browsers (including Firefox and Chrome) store ""Open for viewing"" downloads in the `/tmp` directory. Old `/tmp` files are deleted the following situations: + +1. When you close your browser +2. When you restart Ubuntu +3. When your disk space is low + +If you want to make a temporary download permanent, you can simply navigate to `/tmp`, find the file in question, and copy it into your home folder. + +Streaming media +--------------- + +Flash, audio, and video files you play are cached in highly obfuscated directories like `$HOME/.mozilla/firefox/3lms8ke.default/C/2A` for Firefox. Woozie's answer to [this question](https://askubuntu.com/q/37267/24694) can help you find and retrieve flash files. Remove the `| grep Flash` part of his command to get a list of all cached files by their data type.","do you mean : ""the browser cache + +take a look at : + +``` +/home/$USER/.mozilla/firefox/SOMETHIN.default/Cache + +```" +66288,"I recently upgraded to Oneiric and noticed that the calendar is no longer persistent like it was in Natty and Maverick. I could open the calendar to January 2007, then move to another window and still refer to the calendar. Now, as soon as I lose focus the calendar goes back into hiding. Is this a setting somewhere?",2011/10/14,"['https://askubuntu.com/questions/66288', 'https://askubuntu.com', 'https://askubuntu.com/users/23482/']","Mozilla Firefox +--------------- + +`~/.mozilla/firefox/[something].default/Cache` + +You can go to `about:cache` in your Browser to see information about this as well. + +![About Cache Link](https://i.stack.imgur.com/sieVZ.png) + +Chromium +-------- + +`~/.cache/chromium/[profile]/Cache/` + +Google Chrome +------------- + +`~/.cache/google-chrome/[profile]/Cache/` + +Also, Chromium and Google Chrome store some additional cache at `~/.config/chromium/[profile]/Application Cache/Cache/` and `~/.config/google-chrome/[profile]/Application Cache/Cache/` + +Safari +------ + +`~/.wine/drive_c/Document and Settings/$USER/Application Data/Apple Computer/Safari` + +`~/.wine/drive_c/Document and Settings/$USER/Local Settings/Application Data/Apple Computer/Safari` + +Other than this, browsers can store temporary files in `/tmp/` as well + +Reference: [Chrome, Chromium](http://code.google.com/p/chromium/wiki/ChromiumBrowserVsGoogleChrome), [Firefox](http://kb.mozillazine.org/Browser.cache.disk.parent_directory), [Safari](https://discussions.apple.com/thread/1047105?start=0&tstart=0)","do you mean : ""the browser cache + +take a look at : + +``` +/home/$USER/.mozilla/firefox/SOMETHIN.default/Cache + +```" +66288,"I recently upgraded to Oneiric and noticed that the calendar is no longer persistent like it was in Natty and Maverick. I could open the calendar to January 2007, then move to another window and still refer to the calendar. Now, as soon as I lose focus the calendar goes back into hiding. Is this a setting somewhere?",2011/10/14,"['https://askubuntu.com/questions/66288', 'https://askubuntu.com', 'https://askubuntu.com/users/23482/']","Mozilla Firefox +--------------- + +`~/.mozilla/firefox/[something].default/Cache` + +You can go to `about:cache` in your Browser to see information about this as well. + +![About Cache Link](https://i.stack.imgur.com/sieVZ.png) + +Chromium +-------- + +`~/.cache/chromium/[profile]/Cache/` + +Google Chrome +------------- + +`~/.cache/google-chrome/[profile]/Cache/` + +Also, Chromium and Google Chrome store some additional cache at `~/.config/chromium/[profile]/Application Cache/Cache/` and `~/.config/google-chrome/[profile]/Application Cache/Cache/` + +Safari +------ + +`~/.wine/drive_c/Document and Settings/$USER/Application Data/Apple Computer/Safari` + +`~/.wine/drive_c/Document and Settings/$USER/Local Settings/Application Data/Apple Computer/Safari` + +Other than this, browsers can store temporary files in `/tmp/` as well + +Reference: [Chrome, Chromium](http://code.google.com/p/chromium/wiki/ChromiumBrowserVsGoogleChrome), [Firefox](http://kb.mozillazine.org/Browser.cache.disk.parent_directory), [Safari](https://discussions.apple.com/thread/1047105?start=0&tstart=0)","Temporarily downloaded files +---------------------------- + +All Linux browsers (including Firefox and Chrome) store ""Open for viewing"" downloads in the `/tmp` directory. Old `/tmp` files are deleted the following situations: + +1. When you close your browser +2. When you restart Ubuntu +3. When your disk space is low + +If you want to make a temporary download permanent, you can simply navigate to `/tmp`, find the file in question, and copy it into your home folder. + +Streaming media +--------------- + +Flash, audio, and video files you play are cached in highly obfuscated directories like `$HOME/.mozilla/firefox/3lms8ke.default/C/2A` for Firefox. Woozie's answer to [this question](https://askubuntu.com/q/37267/24694) can help you find and retrieve flash files. Remove the `| grep Flash` part of his command to get a list of all cached files by their data type." +263735,"Problem: +How can I tell if a selection of text in the CRichEditCtrl has multiple font sizes in it? + +--- + +Goal: +I am sort of making my own RichEdit toolbar (bold, italic, font type, font size, etc). I want to emulate what MS Word does when a selection of text has more than a single font size spanning the selection. + +Ex - You have a line of text with the first 10 characters 9 pt font and the next 15 characters 14 pt font. If you highlight the first 5 characters, the ""Font Pt Selection"" drop down displays ""9"". If you then select the first 20 characters, the same drop down should have a empty/blank display. + +--- + +What I have going so far: +I am getting the necessary notification when the selection changes inside of the CRichEditCtrl. Also, if there is only a single font size in the selection I am able to figure that out + +``` +CHARFORMAT cf; +cf.cbSize = sizeof(CHARFORMAT); +CRichEditCtrl ctrl; +ctrl.GetSelectionCharFormat( cf ); +int nFontPtSize = cf.yHeight / 20; + +``` + +This will give me the needed info for the first case of my example above. Unfortunately, what I seem to get for the second part of my example only gives me back the info for where the selection ends (instead of the entire selection). + +In conclusion, is there some info I am missing in the CHARFORMAT or some other struct I can get from the CRichEditCtrl or some kind of interesting calculation I can do to make the decision that there are multiple sizes in the selection? So far my only idea is to chug through the selection a character at a time and see if the current font size of that character is different than any of the previous characters. I am mostly just hoping the info I need is there, and I just don't see it (In a similar way that from the CHARFORMAT's dwMask member tells me that any or all of Bold, Italic, Underline, etc are turned on).",2008/11/04,"['https://Stackoverflow.com/questions/263735', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/34460/']","As the above answer notes, the easiest way I can think of to do this is to use the Text Object Model (TOM), which is accessed through the ITextDocument COM interface. To get at this from your rich edit control (note code not tested, but should work): + +``` +CComPtr richOle; +richOle.Attach(edit.GetIRichEditOle()); +CComQIPtr textDoc(richOle); + +``` + +Then get a range. Here this is for the selected text, but one of the advantages of TOM is that you can operate on any range, not just what's selected. + +``` +CComPtr range; +textDoc->GetSelection(&range); + +``` + +Then get the font for the range, and see what its characteristics are, e.g. + +``` +CComPtr font; +range->GetFont(&font); +long size; +font->GetSize(&size); + +``` + +If the range is formatted with a single font size, you'll get that back in ""size"". If there's multiple font sizes, you'll get the value ""tomUndefined"" instead.","Been juggling a couple things, but I was finally able to work. +This is how I finally was able to get everything to compile and run: + +``` +HWND hwnd; +ITextDocument* pDoc; +IUnknown* pUnk = NULL; +float size = 0; +hwnd = GetSafeHwnd(); +::SendMessage( hwnd, EM_GETOLEINTERFACE, 0, (LPARAM)&pUnk ); + if ( pUnk && pUnk->QueryInterface( __uuidof(ITextDocument), (void**)&pDoc ) == NOERROR ) + { + CComPtr range; + pDoc->GetSelection( &range ); + CComPtr font; + range->GetFont( &font ); + // If there are multiple font sizes in the selection, ""size"" comes back as -9999 + font->GetSize(&size); + } +return size; + +```" +56659834,"I want to get the text of a tag and span tag at the same time. + +``` + + Silicon Power +
48 Hours Only + + + + Silicon Power + 48 Hours Only + + +``` + +Result should be Silicon Power 48 Hours Only",2019/06/19,"['https://Stackoverflow.com/questions/56659834', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9730468/']","I suggest you create an array to store all your `a` elements like so: + +``` +var arr = [10, 15, 20]; + +``` + +Which you can then loop over using a for loop. In the array the 0th index represents the `a1` and the n-1th index represents `a*n*`: + +```js +var arr = [10, 15, 20]; +for (var i = 0; i < arr.length; i++) { + console.log(arr[i]); +} +``` + +Another approach would be to use an object, where `a1`, `a2`, ... `a*n*` are keys in your object: + +``` +var obj = { + 'a1': 10, + 'a2': 15, + 'a3': 20 +} + +``` + +You can then use bracket notation to access your keys and values: + +```js +var obj = { + 'a1': 10, + 'a2': 15, + 'a3': 20 +} + +for (var i = 1; i <= 3; i++) { + console.log(obj['a' + i]); +} +``` + +...or use a `for...in` loop to loop over your properties instead: + +```js +var obj = { + 'a1': 10, + 'a2': 15, + 'a3': 20 +} + +for (var prop in obj) { + console.log(obj[prop]); +} +```","``` +var a = [10, 15, 20]; +for (var i=0; i and it says + +> +> If everything goes well, the server accepts the connection. Upon acceptance, +> the server gets a new socket bound to the same local port and also has +> its remote endpoint set to the address and port of the client. It needs +> a new socket so that it can continue to listen to the original socket for +> connection requests while tending to the needs of the connected client. +> +> +> + +Here are a few things that I don't quite understand + +> +> If everything goes well, the server accepts the connection. +> +> +> + +1. Does it mean that a client request successfully arrived at the listening socket? + +> +> Upon acceptance, the server gets a new socket bound to the same local port and +> also has its remote endpoint set to the address and port of the client +> +> +> + +2. The new socket is created. It also gets bound to the same port but it doesn't listen for incoming requests. After server processed client request resonse is written to this socket and then it gets closed. Is it correct? +3. Does it mean that request is somehow passed from the first socket to the second socket? + +> +> It needs a new socket so that it can continue to listen to the original +> socket for connection requests while tending to the needs of the connected client. +> +> +> + +4. So, the new socket is created then that listens for incoming request. Are there different type of sockets? Some kind of ""listening"" sockets and other? +5. Why does the server have to create a new listening socket? Why can't it reuse the previous one?",2014/01/05,"['https://Stackoverflow.com/questions/20939193', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1745356/']","1. No. It means that an incoming connection arrived at the server. +2. No. It gets closed if the server closes it. Not otherwise. +3. No. It means that the incoming connection causes a connection to be fully formed and a socket created at the server to represent the server-end endpoint of it. +4. (a) No. A new socket is created to *receive* requests and send responses. (b) Yes. There are passive and active sockets. A passive socket listens for connections. An active socket sends and receives data. +5. It doesn't have to create a new listening (passive) socket. It has to create a new active socket to be the endpoint of the new connection. + +> +> Is new socket created for every request? +> +> +> + +Most protocols, for example HTTP with keep-alive, allow multiple requests per connection.","1) An incoming connection has arrived +2) Socket doesn't get closed +3) There is server socket and just socket. Server socket.accept returns a socket object when a client connects" +206967,"This is my first Atmega project so I have following questions: + +1. Do I have to connect all those gnds and vcc's? +2. In programming I used Vcc Reset Gnd Tx Rx SClk of USART0 is that okay? +3. I didn't used external clock generator (quarks) because I'm planning to use inside clock? +4. Is there any fundamental circuits or pins that must be connected to work simple code? (I connected only Vccs and Gnds) +5. Is there simple circuit that tests if the atmega 128 is working or not without programming it?",2015/12/20,"['https://electronics.stackexchange.com/questions/206967', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/89445/']","1. **Yes.** +2. Only if you've programmed it with a serial bootloader already. Otherwise use ISP or HVPP as normal. +3. Okay? This is not a question. +4. AVCC must be connected. You probably also want to connect nPEN to a switch. +5. No. They come unprogrammed from the factory other than the ATmega103 compatibility fuse. Don't forget to unprogram that fuse before use.","@1: Yes, you have to connect all VCC and GND pins. This includes AVCC and AGND. + +@2: Does the device run your program? Did the programmer return any error code? + +@4: Connect a decoupling capacitor for every single VCC pin. Rule of thumb 100nF ceramic. + +@5: Some devices may support JTAG testing or similar debug interface (debugWIRE), but I doubt that qualifies for ""simple""." +206967,"This is my first Atmega project so I have following questions: + +1. Do I have to connect all those gnds and vcc's? +2. In programming I used Vcc Reset Gnd Tx Rx SClk of USART0 is that okay? +3. I didn't used external clock generator (quarks) because I'm planning to use inside clock? +4. Is there any fundamental circuits or pins that must be connected to work simple code? (I connected only Vccs and Gnds) +5. Is there simple circuit that tests if the atmega 128 is working or not without programming it?",2015/12/20,"['https://electronics.stackexchange.com/questions/206967', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/89445/']","1. Yes. It is also recommended to place a 100nF capacitor as close to VCC and GND of every pair. On most modern devices you will see VCC/GND placed next to each other to make that easier. +2. Normally a microcontroller is programmed in-circuit via a specific port. On Atmega's this is usually some sort of SPI port (called ISP) along with RESET. On more modern devices it is a ""TWI port"". It's often pretty well described in the datasheet. Via this port you can write and erase the device memories, and set fuses. However, you also need a specific hardware tool (often made by the vendor as well; sometimes you can get third-party ones - but watch out for software support!). + +Because of these limitations (unusual hardware connection, hardware tools, etc.) people write bootloaders. E.g. on the Arduino platform the ATMEGA can be partially reprogrammed via a serial port. However the ATMEGA needs to be preprogrammed with this bootloader software in order to do this. The preprogramming must be done via ISP. + +3. This is fine in most cases. Just want to point out a few things: + + * Do not set the AVR ISP communication speed too high. I am not sure of the exact oscillator to clock ratio, but a too fast speed will corrupt data and fuses. + * Corrupt fuses can turn off the ISP port (no more reprogramming via ISP!), tell the chip to use an external oscillator (bricking it if it's not there!), etc. +4. Pull RESET high via a pull-up resistor to make the chip run. +Connect all VCC/GND pairs, including AVCC/AGND. +Sometimes if there is a AREF pin, you need to place a 100nF capacitor to GND as well. +5. No, not automatically. But this is often called a blinky test. If you can upload a blinky test you have verified that you can: + + * access the chip + * write memories + * chip boots your program + * oscillator is running + +Then it's a case of figuring out if the oscillator speed is correct, and then you can start writing some real code.","@1: Yes, you have to connect all VCC and GND pins. This includes AVCC and AGND. + +@2: Does the device run your program? Did the programmer return any error code? + +@4: Connect a decoupling capacitor for every single VCC pin. Rule of thumb 100nF ceramic. + +@5: Some devices may support JTAG testing or similar debug interface (debugWIRE), but I doubt that qualifies for ""simple""." +19112318,"I want to be able to wrap text if there is a resizing of the window, I know this can be done as there have been other questions similar to mine in SO. (I guess this [one](https://stackoverflow.com/questions/18377376/how-to-get-textcolumns-to-auto-wrap-in-zurb-foundation-v3-2-5) would qualify ) + +I am using Foundation 4 (latest version) and the provided solution does not work; for example take a look at the following screenshot [here](https://imgur.com/KJSWntW) which shows the result, computed CSS rules and actual page markup. It also shows that the strings of consecutive a's are not wrapped as they should. Any ideas on how to go about an correcting this?",2013/10/01,"['https://Stackoverflow.com/questions/19112318', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1414710/']","Use dynamic memory allocation. + +``` +Items **type; +type = malloc(sizeof (Items *) * typenum); + +for (int i = 0; i < typenum; i++) + type[i] = malloc(sizeof Items) * typetotal); + +``` + +You need to manually free the allocated memory after using the array. + +``` +for (int i = 0; i < typenum; i++) + free(types[i]); + +free(types); + +``` + +Here is a tutorial on it: ","If `typenum` and `typetotal` increase as your program runs be sure to use `realloc`, which will reallocate more memory and keep the contents. You'll need to allocate the first dimension of the array like this: + +``` +myArray = realloc(myArray, sizeof(Items*) * typenum); + +``` + +and then allocate the second dimension for each of the first: + +``` +for(...) + myArray[i] = realloc(myArray[i], sizeof(Items) * typetotal); + +```" +53963876,"I am a new user to Laravel and have came from craft cms. On my homepage I want the navigation to be transparent and have a black background on all other pages. + +To do this I have added a class to the homepage header called header-home. I craft to add this class to the homepage inside the layout file I wrote this: + +``` +
+ +``` + +I know I could just create a different layout.blade.php file for the homepage but there will be other instances when I want to add a class or an element depending on what page or url the user is on. + +Thanks in advance, +Jamie",2018/12/28,"['https://Stackoverflow.com/questions/53963876', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3479267/']","You can send the class from controller: + +``` +public function myAction +{ + ... + return view('home', ['layoutClass'=>'dark']); +} + +
+ +``` + +or you can match the route in the view: + +``` +
getName() == 'myRoute') ? 'dark':'') }} /> + +```","I found the best way for me was to use an if statement in blade and check the route, below is how I done it: + +``` +@if (\Request::is('/')) + +@else + +@endif + +```" +40208857,"I have a question about the following code. + +``` +public class test +{ + public static void main (String[] args) + { + int a = 0; + int b = 0; + + for (int i = 0; i < 5; i++); { + b = b + a; + a++; + } + System.out.println(b); + +``` + +Why is the output of this 0? As you can see I'm a complete beginner but why does it not go through the loop 4 times before printing the answer? + +Help is appreciated! + +//Confused beginner",2016/10/23,"['https://Stackoverflow.com/questions/40208857', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7062013/']","For loops iterate over the statement or block immediately following the for statement. In this case you have a stray semicolon causing the next statement to be empty. Remove it and your code will work as indended + +Replace: + +``` +for (int i = 0; i < 5; i++); { + b = b + a; + a++; +} + +``` + +-with- + +``` +for (int i = 0; i < 5; i++) { + b = b + a; + a++; +} + +```","Just remove the semicolon after the for loop statement, otherwise the body surrounded by the curly braces will not be considered under the for loop. + +Replace the following: + +``` +for (int i = 0; i < 5; i++); { + ^ <--- remove it + b = b + a; + a++; +} + +``` + +by + +``` +for (int i = 0; i < 5; i++); { + b = b + a; + a++; +} + +```" +40208857,"I have a question about the following code. + +``` +public class test +{ + public static void main (String[] args) + { + int a = 0; + int b = 0; + + for (int i = 0; i < 5; i++); { + b = b + a; + a++; + } + System.out.println(b); + +``` + +Why is the output of this 0? As you can see I'm a complete beginner but why does it not go through the loop 4 times before printing the answer? + +Help is appreciated! + +//Confused beginner",2016/10/23,"['https://Stackoverflow.com/questions/40208857', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7062013/']","It does not return 0. In does not return anything as there are mistakes in your code. + +After the for loop, there is no ; + +``` +public static void main(String[] args){ + + int a = 0; + int b = 0; + + for (int i = 0; i < 5; i++) { + b = b + a; + a++; + } + System.out.println(b); +} + +```","Just remove the semicolon after the for loop statement, otherwise the body surrounded by the curly braces will not be considered under the for loop. + +Replace the following: + +``` +for (int i = 0; i < 5; i++); { + ^ <--- remove it + b = b + a; + a++; +} + +``` + +by + +``` +for (int i = 0; i < 5; i++); { + b = b + a; + a++; +} + +```" +61629887,"**Problem :** +Build a program that reads two strings from the keyboard and generates a third string which consists of combining two strings in such a way that the characters of the first string are placed in odd positions while the characters of the second string in even positions. The length of the new string will be twice the length of the smaller string. Display all three strings on the screen. + +My solution : (I've code something, but it gives me error. Can anyone show me where is the problem?) + +``` + #include +#include + +int main() +{ + char str1[100], str2[100], str3[100]; + int i=0; + int j; + int p; + + printf(""Give string 1: \n""); + gets(str1); + printf(""Give string 2: \n""); + gets(str2); + + if(strlen(str1) +#include + +int main() +{ + char str1[100], str2[100], str3[100]; + int i=0; + int j; + int p; + + printf(""Give string 1: \n""); + gets(str1); + printf(""Give string 2: \n""); + gets(str2); + + if(strlen(str1) +#include + +int main() +{ + char str1[100], str2[100], str3[100]; + int i=0; + int j; + int p; + + printf(""Give string 1: \n""); + gets(str1); + printf(""Give string 2: \n""); + gets(str2); + + if(strlen(str1) +#include + +int main() +{ + char str1[100], str2[100], str3[100]; + int i=0; + int j; + int p; + + printf(""Give string 1: \n""); + gets(str1); + printf(""Give string 2: \n""); + gets(str2); + + if(strlen(str1) +#include + +int main() +{ + char str1[100], str2[100], str3[100]; + int i=0; + int j; + int p; + + printf(""Give string 1: \n""); + gets(str1); + printf(""Give string 2: \n""); + gets(str2); + + if(strlen(str1) +#include + +int main() +{ + char str1[100], str2[100], str3[100]; + int i=0; + int j; + int p; + + printf(""Give string 1: \n""); + gets(str1); + printf(""Give string 2: \n""); + gets(str2); + + if(strlen(str1)" +85,"Neutron mass: 1.008664 u + +Proton mass: 1.007276 u + +Why the discrepancy? + +On a related note, how does one go about measuring the mass of a neutron or proton, anyway?",2010/11/02,"['https://physics.stackexchange.com/questions/85', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/104/']","Masses and coupling between quarks are free parameters in the standard model, so there is not real explanation to that fact. + +About the measurment: you can have a look at this [wikipedia article about Penning traps](http://en.wikipedia.org/wiki/Penning_trap) which are devices used for precision measurements for nucleus. Through the cyclotron frequency (Larmor factor) we can obtain the mass of the particle. + +Edit: ""A neutron is a proton + an electron"" is a common answer to this question, but it is a totally invalid reasoning. + +Both protons and neutrons are made of three quarks. The mass of the quarks is not known with enough precision, and even more important (and that's a why for the masses of the quarks), the interaction between them is responsible for the mass value to a much larger extend.","We can write approximately assuming strong energy $E\_s$ contribution inside proton and neutron is almost the same: + +$m\_n c^2 = m\_d c^2 +m\_d c^2 +m\_u c^2 +E\_s $ + +$m\_p c^2 = m\_u c^2 +m\_u c^2 +m\_d c^2 +E\_s +E\_c $ +in terms of quark u and d masses and $E\_c$ - electrostatic energy around and inside the proton, which can be calculated classically $E\_c = \frac{3}{5} \frac{k e^2} {R} = 1 MeV $, and R=0.87 fm is charge radius from scattering experiments. +Thus we have + $m\_n c^2 -m\_p c^2 $ = $ m\_d c^2 - m\_u c^2 - E\_c $ = 4.8 MeV - 2.3 MeV - 1 MeV= 1.5 MeV + +On the other hand we have $m\_n c^2 -m\_p c^2 $ = 1.3 MeV i.e very close (and quark masses are not know so precisely)" +85,"Neutron mass: 1.008664 u + +Proton mass: 1.007276 u + +Why the discrepancy? + +On a related note, how does one go about measuring the mass of a neutron or proton, anyway?",2010/11/02,"['https://physics.stackexchange.com/questions/85', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/104/']","Masses and coupling between quarks are free parameters in the standard model, so there is not real explanation to that fact. + +About the measurment: you can have a look at this [wikipedia article about Penning traps](http://en.wikipedia.org/wiki/Penning_trap) which are devices used for precision measurements for nucleus. Through the cyclotron frequency (Larmor factor) we can obtain the mass of the particle. + +Edit: ""A neutron is a proton + an electron"" is a common answer to this question, but it is a totally invalid reasoning. + +Both protons and neutrons are made of three quarks. The mass of the quarks is not known with enough precision, and even more important (and that's a why for the masses of the quarks), the interaction between them is responsible for the mass value to a much larger extend.","A recent paper [1] has computed the mass difference ab initio from the theory, using a technique know as lattice, where one writes the equations on a discretised spacetime (this is conceptually similar to what engineers do with finite elements method to study how a beam of metal flexes for example). They took into account + +* the contributions of electromagnetism and of the strong interaction, +* the difference of mass between up and down quarks, +* up, down, strange, and charm in the quark sea [\*], + +Their result is + +$$m\_n-m\_p = 1.51(16)(23) \text{MeV},$$ + +to be compared with the experimental value, + +$$m\_n - m\_p = 1.29,$$ + +with an error orders of magnitude smaller. This is pretty impressive: an accuracy of 390 keV, and according to the paper a proof that $m\_n > m\_p$ at the level of 5 standard deviations. Again, ab initio, just from the Standard Model. + +The authors of that paper also give the respective contributions of electromagnetism and of the strong interaction. This is very interesting as the electrostatic energy, just based on the quark charges, would naively be thought to be negative for the neutron but zero for the proton, on average [\*\*]. Their result is that + +* $(m\_n-m\_p)\_\text{QCD}=2.52(17)(24)$ MeV, +* $(m\_n-m\_p)\_\text{QED}=-1.00(07)(14)$ MeV, + +where QCD stands for Quantum ChromoDynamics, our best theory of the strong interaction, and QED for Quantum ElectroDynamics, our best theory of electromagnetism. So indeed, the different of electrostatic energy is in the intuitive direction I have just highlighted above. This is compensated by the contribution of the strong interaction which goes in the other direction. I don't have an intuitive reason for that to share. + +[\*] Protons and neutrons are made of 3 so-called valence quarks, but also of a ""soup"" of other quarks-antiquark pairs which is called the sea. + +[\*\*] The sum of the product of the charges are $\frac{2}{3}\frac{2}{3} + \frac{2}{3}\frac{-1}{3}+ \frac{2}{3}\frac{-1}{3}=0$ for the proton but $\frac{2}{3}\frac{-1}{3} + \frac{2}{3}\frac{-1}{3}+ \frac{-1}{3}\frac{-1}{3}=-\frac{1}{3}$ for the neutron. + +[1] Sz. Borsanyi, S. Durr, Z. Fodor, C. Hoelbling, S. D. Katz, S. Krieg, L. Lellouch, T. Lippert, A. Portelli, K. K. Szabo, and B. C. Toth. Ab initio calculation of the neutron-proton mass difference. Science, 347(6229):1452–1455, 2015. [arxiv.org/abs/1406.4088](https://arxiv.org/abs/1406.4088)" +85,"Neutron mass: 1.008664 u + +Proton mass: 1.007276 u + +Why the discrepancy? + +On a related note, how does one go about measuring the mass of a neutron or proton, anyway?",2010/11/02,"['https://physics.stackexchange.com/questions/85', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/104/']","A proton is made of two up quarks and a down quark, whereas a neutron is made of two down quarks and an up quark. The quark masses contribute very little of the actual mass of the proton and neutron, which mostly arises from energy associated with the strong interactions among the quarks. Still, they do contribute a small fraction, and the down quark is slightly heavier than the up quark, which approximately accounts for the difference. (The masses of the up and down quarks, because they're so small, are not extremely well-measured, and detailed calculations of what the proton and neutron masses would be for given quark masses are difficult. So it's hard to be quantitative about the answer in a precise way.) + +You can read a bit about the state of the art in calculations of the proton mass here: ","We can write approximately assuming strong energy $E\_s$ contribution inside proton and neutron is almost the same: + +$m\_n c^2 = m\_d c^2 +m\_d c^2 +m\_u c^2 +E\_s $ + +$m\_p c^2 = m\_u c^2 +m\_u c^2 +m\_d c^2 +E\_s +E\_c $ +in terms of quark u and d masses and $E\_c$ - electrostatic energy around and inside the proton, which can be calculated classically $E\_c = \frac{3}{5} \frac{k e^2} {R} = 1 MeV $, and R=0.87 fm is charge radius from scattering experiments. +Thus we have + $m\_n c^2 -m\_p c^2 $ = $ m\_d c^2 - m\_u c^2 - E\_c $ = 4.8 MeV - 2.3 MeV - 1 MeV= 1.5 MeV + +On the other hand we have $m\_n c^2 -m\_p c^2 $ = 1.3 MeV i.e very close (and quark masses are not know so precisely)" +85,"Neutron mass: 1.008664 u + +Proton mass: 1.007276 u + +Why the discrepancy? + +On a related note, how does one go about measuring the mass of a neutron or proton, anyway?",2010/11/02,"['https://physics.stackexchange.com/questions/85', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/104/']","A proton is made of two up quarks and a down quark, whereas a neutron is made of two down quarks and an up quark. The quark masses contribute very little of the actual mass of the proton and neutron, which mostly arises from energy associated with the strong interactions among the quarks. Still, they do contribute a small fraction, and the down quark is slightly heavier than the up quark, which approximately accounts for the difference. (The masses of the up and down quarks, because they're so small, are not extremely well-measured, and detailed calculations of what the proton and neutron masses would be for given quark masses are difficult. So it's hard to be quantitative about the answer in a precise way.) + +You can read a bit about the state of the art in calculations of the proton mass here: ","A recent paper [1] has computed the mass difference ab initio from the theory, using a technique know as lattice, where one writes the equations on a discretised spacetime (this is conceptually similar to what engineers do with finite elements method to study how a beam of metal flexes for example). They took into account + +* the contributions of electromagnetism and of the strong interaction, +* the difference of mass between up and down quarks, +* up, down, strange, and charm in the quark sea [\*], + +Their result is + +$$m\_n-m\_p = 1.51(16)(23) \text{MeV},$$ + +to be compared with the experimental value, + +$$m\_n - m\_p = 1.29,$$ + +with an error orders of magnitude smaller. This is pretty impressive: an accuracy of 390 keV, and according to the paper a proof that $m\_n > m\_p$ at the level of 5 standard deviations. Again, ab initio, just from the Standard Model. + +The authors of that paper also give the respective contributions of electromagnetism and of the strong interaction. This is very interesting as the electrostatic energy, just based on the quark charges, would naively be thought to be negative for the neutron but zero for the proton, on average [\*\*]. Their result is that + +* $(m\_n-m\_p)\_\text{QCD}=2.52(17)(24)$ MeV, +* $(m\_n-m\_p)\_\text{QED}=-1.00(07)(14)$ MeV, + +where QCD stands for Quantum ChromoDynamics, our best theory of the strong interaction, and QED for Quantum ElectroDynamics, our best theory of electromagnetism. So indeed, the different of electrostatic energy is in the intuitive direction I have just highlighted above. This is compensated by the contribution of the strong interaction which goes in the other direction. I don't have an intuitive reason for that to share. + +[\*] Protons and neutrons are made of 3 so-called valence quarks, but also of a ""soup"" of other quarks-antiquark pairs which is called the sea. + +[\*\*] The sum of the product of the charges are $\frac{2}{3}\frac{2}{3} + \frac{2}{3}\frac{-1}{3}+ \frac{2}{3}\frac{-1}{3}=0$ for the proton but $\frac{2}{3}\frac{-1}{3} + \frac{2}{3}\frac{-1}{3}+ \frac{-1}{3}\frac{-1}{3}=-\frac{1}{3}$ for the neutron. + +[1] Sz. Borsanyi, S. Durr, Z. Fodor, C. Hoelbling, S. D. Katz, S. Krieg, L. Lellouch, T. Lippert, A. Portelli, K. K. Szabo, and B. C. Toth. Ab initio calculation of the neutron-proton mass difference. Science, 347(6229):1452–1455, 2015. [arxiv.org/abs/1406.4088](https://arxiv.org/abs/1406.4088)" +85,"Neutron mass: 1.008664 u + +Proton mass: 1.007276 u + +Why the discrepancy? + +On a related note, how does one go about measuring the mass of a neutron or proton, anyway?",2010/11/02,"['https://physics.stackexchange.com/questions/85', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/104/']","A recent paper [1] has computed the mass difference ab initio from the theory, using a technique know as lattice, where one writes the equations on a discretised spacetime (this is conceptually similar to what engineers do with finite elements method to study how a beam of metal flexes for example). They took into account + +* the contributions of electromagnetism and of the strong interaction, +* the difference of mass between up and down quarks, +* up, down, strange, and charm in the quark sea [\*], + +Their result is + +$$m\_n-m\_p = 1.51(16)(23) \text{MeV},$$ + +to be compared with the experimental value, + +$$m\_n - m\_p = 1.29,$$ + +with an error orders of magnitude smaller. This is pretty impressive: an accuracy of 390 keV, and according to the paper a proof that $m\_n > m\_p$ at the level of 5 standard deviations. Again, ab initio, just from the Standard Model. + +The authors of that paper also give the respective contributions of electromagnetism and of the strong interaction. This is very interesting as the electrostatic energy, just based on the quark charges, would naively be thought to be negative for the neutron but zero for the proton, on average [\*\*]. Their result is that + +* $(m\_n-m\_p)\_\text{QCD}=2.52(17)(24)$ MeV, +* $(m\_n-m\_p)\_\text{QED}=-1.00(07)(14)$ MeV, + +where QCD stands for Quantum ChromoDynamics, our best theory of the strong interaction, and QED for Quantum ElectroDynamics, our best theory of electromagnetism. So indeed, the different of electrostatic energy is in the intuitive direction I have just highlighted above. This is compensated by the contribution of the strong interaction which goes in the other direction. I don't have an intuitive reason for that to share. + +[\*] Protons and neutrons are made of 3 so-called valence quarks, but also of a ""soup"" of other quarks-antiquark pairs which is called the sea. + +[\*\*] The sum of the product of the charges are $\frac{2}{3}\frac{2}{3} + \frac{2}{3}\frac{-1}{3}+ \frac{2}{3}\frac{-1}{3}=0$ for the proton but $\frac{2}{3}\frac{-1}{3} + \frac{2}{3}\frac{-1}{3}+ \frac{-1}{3}\frac{-1}{3}=-\frac{1}{3}$ for the neutron. + +[1] Sz. Borsanyi, S. Durr, Z. Fodor, C. Hoelbling, S. D. Katz, S. Krieg, L. Lellouch, T. Lippert, A. Portelli, K. K. Szabo, and B. C. Toth. Ab initio calculation of the neutron-proton mass difference. Science, 347(6229):1452–1455, 2015. [arxiv.org/abs/1406.4088](https://arxiv.org/abs/1406.4088)","We can write approximately assuming strong energy $E\_s$ contribution inside proton and neutron is almost the same: + +$m\_n c^2 = m\_d c^2 +m\_d c^2 +m\_u c^2 +E\_s $ + +$m\_p c^2 = m\_u c^2 +m\_u c^2 +m\_d c^2 +E\_s +E\_c $ +in terms of quark u and d masses and $E\_c$ - electrostatic energy around and inside the proton, which can be calculated classically $E\_c = \frac{3}{5} \frac{k e^2} {R} = 1 MeV $, and R=0.87 fm is charge radius from scattering experiments. +Thus we have + $m\_n c^2 -m\_p c^2 $ = $ m\_d c^2 - m\_u c^2 - E\_c $ = 4.8 MeV - 2.3 MeV - 1 MeV= 1.5 MeV + +On the other hand we have $m\_n c^2 -m\_p c^2 $ = 1.3 MeV i.e very close (and quark masses are not know so precisely)" +37548915,"I try to upload some videos to youtube. Somewhere in the stack it comes down to a `http.Client`. This part somehow behaves weird. + +The request and everything is created inside the youtube package. + +After doing my request in the end it fails with: + +``` +Error uploading video: Post https://www.googleapis.com/upload/youtube/v3/videos?alt=json&part=snippet%2Cstatus&uploadType=multipart: Post : unsupported protocol scheme """" + +``` + +I debugged the library a bit and printed the `URL.Scheme` content. As a string the result is `https` and in `[]byte` `[104 116 116 112 115]` + + on line 288 is the location where the error is thrown. + + the library I use + +My code where I prepare/upload the video: + +``` +//create video struct which holds info about the video +video := &yt3.Video{ +//TODO: set all required video info +} + +//create the insert call +insertCall := service.Videos.Insert(""snippet,status"", video) + +//attach media data to the call +insertCall = insertCall.Media(tmp, googleapi.ChunkSize(1*1024*1024)) //1MB chunk + +video, err = insertCall.Do() +if err != nil { + log.Printf(""Error uploading video: %v"", err) + return + //return errgo.Notef(err, ""Failed to upload to youtube"") +} + +``` + +So I have not idea why the schema check fails.",2016/05/31,"['https://Stackoverflow.com/questions/37548915', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/450598/']","Ok, I figured it out. The problem was not the call to YouTube itself. + +The library tried to refresh the token in the background but there was something wrong with the `TokenURL`. + +Ensuring there is a valid URL fixed the problem. + +A nicer error message would have helped a lot, but well...","This will probably apply to very, very few who arrive here: but my problem was that a [RoundTripper](https://pkg.go.dev/net/http#RoundTripper) was overriding the Host field with an empty string." +340403,"I have a validation Rule that I require assistance with , this validation rule should only allow fields to be updated by the two profile ids specified: + +``` +NOT( + OR( + $Profile.Id = ""00e58000000yYlm"", + $Profile.Id = ""00e58000000E6lK"", + AND( + ISPICKVAL((WorkOrder.Status ), 'WithTechnician'), + OR( + ISCHANGED ( ProposedWorkPerformed__c), + ISCHANGED ( ProposedOriginOfError__c ), + ISCHANGED ( ProposedErrorComment__c ), + ISCHANGED ( EstimatedDurationInMinutes__c ), + ISCHANGED ( ActualWorkPerformed__c ), + ISCHANGED ( ActualDurationInMinutes__c ), + ISCHANGED ( ActualOriginOfError__c ), + ISCHANGED ( ActualErrorComment__c ), + ISCHANGED ( Status ), + ISCHANGED ( Type__c ), + ISCHANGED ( Source__c) + ) + ) + ) +) + +```",2021/04/14,"['https://salesforce.stackexchange.com/questions/340403', 'https://salesforce.stackexchange.com', 'https://salesforce.stackexchange.com/users/94096/']","The big thing to keep in mind with validation rules is that their purpose isn't really to tell you what data is valid, but rather to tell you what data is *invalid*. It's a small shift in how you mentally frame the problem, but one that I find very helpful. + +Instead of stating the outcome as ""these profiles should be allowed to edit these fields"", try working from ""everyone who doesn't have one of these two profiles should be prevented from editing these fields"". + +Re-stating that a bit closer to a Validation Rule, ""If the profile isn't one of our targets, and workorder status is ``, and at least one of these fields are changing, then prevent the change"" + +**Note that** these comments are for clarity, and not in the appropriate format for a validation rule. + +``` +// segment 1 +// User is not one of our target profiles +// The NOT() here should be limited to just the profile check +NOT( + OR( + Profile = profile1, + Profile = profile2 + ) +) + +``` + +``` +// segment 2 +// workorder status check +ISPICKVAL((WorkOrder.Status ), 'WithTechnician') + +``` + +``` +// segment 3 +// field change check +// a change to any of these fields should make this segment evaluate to ""true"", so OR() +// is appropriate +OR( + ISCHANGED(ProposedWorkPerformed__c), + ISCHANGED(ProposedOriginOfError__c), + ISCHANGED(ProposedErrorComment__c), + ISCHANGED(EstimatedDurationInMinutes__c), + ISCHANGED(ActualWorkPerformed__c), + ISCHANGED(ActualDurationInMinutes__c), + ISCHANGED(ActualOriginOfError__c), + ISCHANGED(ActualErrorComment__c), + ISCHANGED(Status), + ISCHANGED( Type__c), + ISCHANGED(Source__c) +) + +``` + +The ""plain language"" description of what you're aiming to do tells you how these segments should be tied together (they should be `AND`-ed). + +` && && ` would work, but the more typical approach is to use `AND()`. + +``` +AND( + , + , + +) + +```","The issue is with OR operator on profile, AND operator on the status field, and NOT function. You haven't used/close them at appropriate places. + +Below is the updated snippet. + +``` +AND( +ISPICKVAL(Status, ""WithTechnician""), +NOT(OR( +$Profile.Id = ""00e58000000yYlm"", +$Profile.Id = ""00e58000000E6lK"")), +OR( +ISCHANGED(ProposedWorkPerformed__c), +ISCHANGED(ProposedOriginOfError__c), +ISCHANGED(ProposedErrorComment__c), +ISCHANGED(EstimatedDurationInMinutes__c), +ISCHANGED(ActualWorkPerformed__c), +ISCHANGED(ActualDurationInMinutes__c), +ISCHANGED(ActualOriginOfError__c), +ISCHANGED(ActualErrorComment__c), +ISCHANGED(Status), +ISCHANGED(Type__c), +ISCHANGED(Source__c))) + +``` + +Take a look at sample validation rule examples [here](https://help.salesforce.com/articleView?id=fields_useful_field_validation_formulas.htm&type=0). + +Thanks" +42713907,"I can fill my array,and found the two of biggest numbers.But,i can not delete it.May u guys could help me? + +``` + int n = sc.nextInt(); + int [] myArray = new int[n]; + int first = 0; + int second = 0; + for(int i = 0; i < myArray.length; i++) { + int num = sc.nextInt();` + if (num > first) { + second = first; + first = num; + } else if(num > second) + { + second = num; + } + } + + System.out.println(""The largest "" + first+ ""The second largest "" + second); + +```",2017/03/10,"['https://Stackoverflow.com/questions/42713907', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7513001/']","You may create a new array (in this case, `filteredArray`) in which you store all the elements in `myArray` but the greatest two. +Also, it is better to save the indexes of the two biggest numbers rather than their values in order to be able to filter them out more easily. + +This should work (you will find the array you want in `filteredArray`). + +``` +int n = sc.nextInt(); +int [] myArray = new int[n]; +int first = 0; +int second = 0; +for(int i = 0; i < myArray.length; i++) { + myArray[i] = sc.nextInt(); + if (myArray[i] > myArray[first]) { + second = first; + first = i; + } else if(myArray[i] > myArray[second]) { + second = i; + } +} +int [] filteredArray = new int[n-2]; +int skipped = 0; +for(int i = 0; i < myArray.length; i++) { + if(i != first && i != second) + filteredArray[i - skipped] = myArray[i]; + else + skipped++; +} + +```","May be following code will useful for you + +``` +again : +for (int i = 0; i < n; i++) +{ + if ((a[i] < a[i+1]) && (i+1) first) { + second = first; + first = num; + } else if(num > second) + { + second = num; + } + } + + System.out.println(""The largest "" + first+ ""The second largest "" + second); + +```",2017/03/10,"['https://Stackoverflow.com/questions/42713907', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7513001/']","If you are using Java 8 you can sort your array then you can loop throw your array and set it values to the other one avoiding the last two Integer for example : + +``` +//Your array +Integer[] array = {8, 99, 6, 336, 2}; + +//sort your array this can give your [2, 6, 8, 99, 336] +Arrays.sort(array); + +//create a new array with the length = array - 2 if the length of array < 2 then 0 +Integer[] array2 = new Integer[array.length > 2 ? array.length - 2 : 0]; + +//copy your array into the array2 avoiding the 2 last +System.arraycopy(array, 0, array2, 0, array.length > 2 ? array.length - 2 : 0); + +//print your array, this will print [2, 6, 8] +System.out.println(Arrays.toString(array2)); + +```","You may create a new array (in this case, `filteredArray`) in which you store all the elements in `myArray` but the greatest two. +Also, it is better to save the indexes of the two biggest numbers rather than their values in order to be able to filter them out more easily. + +This should work (you will find the array you want in `filteredArray`). + +``` +int n = sc.nextInt(); +int [] myArray = new int[n]; +int first = 0; +int second = 0; +for(int i = 0; i < myArray.length; i++) { + myArray[i] = sc.nextInt(); + if (myArray[i] > myArray[first]) { + second = first; + first = i; + } else if(myArray[i] > myArray[second]) { + second = i; + } +} +int [] filteredArray = new int[n-2]; +int skipped = 0; +for(int i = 0; i < myArray.length; i++) { + if(i != first && i != second) + filteredArray[i - skipped] = myArray[i]; + else + skipped++; +} + +```" +42713907,"I can fill my array,and found the two of biggest numbers.But,i can not delete it.May u guys could help me? + +``` + int n = sc.nextInt(); + int [] myArray = new int[n]; + int first = 0; + int second = 0; + for(int i = 0; i < myArray.length; i++) { + int num = sc.nextInt();` + if (num > first) { + second = first; + first = num; + } else if(num > second) + { + second = num; + } + } + + System.out.println(""The largest "" + first+ ""The second largest "" + second); + +```",2017/03/10,"['https://Stackoverflow.com/questions/42713907', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7513001/']","Sort your arrays (default sort is ascending, i.e. from smallest to largest) then make a new copy of the array without the last two elements. + +``` +if(myArray.length > 2) { + Arrays.sort(myArray); + myArray = Arrays.copyOf(myArray, myArray.length-2); +} else { + throw new IllegalArgumentException(""Need moar elements in array!""); +} + +``` + +Then perform any calculations on the resulting array. If you want to keep the original array, don't overwrite `myArray` when doing `copyOf()`.","You may create a new array (in this case, `filteredArray`) in which you store all the elements in `myArray` but the greatest two. +Also, it is better to save the indexes of the two biggest numbers rather than their values in order to be able to filter them out more easily. + +This should work (you will find the array you want in `filteredArray`). + +``` +int n = sc.nextInt(); +int [] myArray = new int[n]; +int first = 0; +int second = 0; +for(int i = 0; i < myArray.length; i++) { + myArray[i] = sc.nextInt(); + if (myArray[i] > myArray[first]) { + second = first; + first = i; + } else if(myArray[i] > myArray[second]) { + second = i; + } +} +int [] filteredArray = new int[n-2]; +int skipped = 0; +for(int i = 0; i < myArray.length; i++) { + if(i != first && i != second) + filteredArray[i - skipped] = myArray[i]; + else + skipped++; +} + +```" +42713907,"I can fill my array,and found the two of biggest numbers.But,i can not delete it.May u guys could help me? + +``` + int n = sc.nextInt(); + int [] myArray = new int[n]; + int first = 0; + int second = 0; + for(int i = 0; i < myArray.length; i++) { + int num = sc.nextInt();` + if (num > first) { + second = first; + first = num; + } else if(num > second) + { + second = num; + } + } + + System.out.println(""The largest "" + first+ ""The second largest "" + second); + +```",2017/03/10,"['https://Stackoverflow.com/questions/42713907', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7513001/']","If you are using Java 8 you can sort your array then you can loop throw your array and set it values to the other one avoiding the last two Integer for example : + +``` +//Your array +Integer[] array = {8, 99, 6, 336, 2}; + +//sort your array this can give your [2, 6, 8, 99, 336] +Arrays.sort(array); + +//create a new array with the length = array - 2 if the length of array < 2 then 0 +Integer[] array2 = new Integer[array.length > 2 ? array.length - 2 : 0]; + +//copy your array into the array2 avoiding the 2 last +System.arraycopy(array, 0, array2, 0, array.length > 2 ? array.length - 2 : 0); + +//print your array, this will print [2, 6, 8] +System.out.println(Arrays.toString(array2)); + +```","May be following code will useful for you + +``` +again : +for (int i = 0; i < n; i++) +{ + if ((a[i] < a[i+1]) && (i+1) first) { + second = first; + first = num; + } else if(num > second) + { + second = num; + } + } + + System.out.println(""The largest "" + first+ ""The second largest "" + second); + +```",2017/03/10,"['https://Stackoverflow.com/questions/42713907', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7513001/']","Sort your arrays (default sort is ascending, i.e. from smallest to largest) then make a new copy of the array without the last two elements. + +``` +if(myArray.length > 2) { + Arrays.sort(myArray); + myArray = Arrays.copyOf(myArray, myArray.length-2); +} else { + throw new IllegalArgumentException(""Need moar elements in array!""); +} + +``` + +Then perform any calculations on the resulting array. If you want to keep the original array, don't overwrite `myArray` when doing `copyOf()`.","May be following code will useful for you + +``` +again : +for (int i = 0; i < n; i++) +{ + if ((a[i] < a[i+1]) && (i+1) first) { + second = first; + first = num; + } else if(num > second) + { + second = num; + } + } + + System.out.println(""The largest "" + first+ ""The second largest "" + second); + +```",2017/03/10,"['https://Stackoverflow.com/questions/42713907', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7513001/']","You can simply sort the array and find or remove the two biggest elements. + +``` +int [] myArray = new int[]{14,5,2,16,18,20}; +System.out.println(""The original array is ""+ "" "" +Arrays.toString(myArray)); +Arrays.sort(myArray); +System.out.println(""The sorted array is ""+ "" "" +Arrays.toString(myArray));; + +int fisrtmax = myArray[myArray.length-1]; +int secondmax = myArray[myArray.length-2]; + +System.out.println(""The first biggest number is "" + fisrtmax+ "" The second biggest number is "" + secondmax); + +int [] arrafterremove= Arrays.copyOf(myArray, myArray.length-2); + +System.out.println(""The array after removing the two biggest numbers is "" + Arrays.toString(arrafterremove)); + +``` + +**RUN** + +``` +The original array is [14, 5, 2, 16, 18, 20] +The sorted array is [2, 5, 14, 16, 18, 20] +The first biggest number is 20 The second biggest number is 18 +Array after removing the two biggest numbers is [2, 5, 14, 16] + +```","May be following code will useful for you + +``` +again : +for (int i = 0; i < n; i++) +{ + if ((a[i] < a[i+1]) && (i+1) first) { + second = first; + first = num; + } else if(num > second) + { + second = num; + } + } + + System.out.println(""The largest "" + first+ ""The second largest "" + second); + +```",2017/03/10,"['https://Stackoverflow.com/questions/42713907', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7513001/']","If you are using Java 8 you can sort your array then you can loop throw your array and set it values to the other one avoiding the last two Integer for example : + +``` +//Your array +Integer[] array = {8, 99, 6, 336, 2}; + +//sort your array this can give your [2, 6, 8, 99, 336] +Arrays.sort(array); + +//create a new array with the length = array - 2 if the length of array < 2 then 0 +Integer[] array2 = new Integer[array.length > 2 ? array.length - 2 : 0]; + +//copy your array into the array2 avoiding the 2 last +System.arraycopy(array, 0, array2, 0, array.length > 2 ? array.length - 2 : 0); + +//print your array, this will print [2, 6, 8] +System.out.println(Arrays.toString(array2)); + +```","You can simply sort the array and find or remove the two biggest elements. + +``` +int [] myArray = new int[]{14,5,2,16,18,20}; +System.out.println(""The original array is ""+ "" "" +Arrays.toString(myArray)); +Arrays.sort(myArray); +System.out.println(""The sorted array is ""+ "" "" +Arrays.toString(myArray));; + +int fisrtmax = myArray[myArray.length-1]; +int secondmax = myArray[myArray.length-2]; + +System.out.println(""The first biggest number is "" + fisrtmax+ "" The second biggest number is "" + secondmax); + +int [] arrafterremove= Arrays.copyOf(myArray, myArray.length-2); + +System.out.println(""The array after removing the two biggest numbers is "" + Arrays.toString(arrafterremove)); + +``` + +**RUN** + +``` +The original array is [14, 5, 2, 16, 18, 20] +The sorted array is [2, 5, 14, 16, 18, 20] +The first biggest number is 20 The second biggest number is 18 +Array after removing the two biggest numbers is [2, 5, 14, 16] + +```" +42713907,"I can fill my array,and found the two of biggest numbers.But,i can not delete it.May u guys could help me? + +``` + int n = sc.nextInt(); + int [] myArray = new int[n]; + int first = 0; + int second = 0; + for(int i = 0; i < myArray.length; i++) { + int num = sc.nextInt();` + if (num > first) { + second = first; + first = num; + } else if(num > second) + { + second = num; + } + } + + System.out.println(""The largest "" + first+ ""The second largest "" + second); + +```",2017/03/10,"['https://Stackoverflow.com/questions/42713907', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7513001/']","Sort your arrays (default sort is ascending, i.e. from smallest to largest) then make a new copy of the array without the last two elements. + +``` +if(myArray.length > 2) { + Arrays.sort(myArray); + myArray = Arrays.copyOf(myArray, myArray.length-2); +} else { + throw new IllegalArgumentException(""Need moar elements in array!""); +} + +``` + +Then perform any calculations on the resulting array. If you want to keep the original array, don't overwrite `myArray` when doing `copyOf()`.","You can simply sort the array and find or remove the two biggest elements. + +``` +int [] myArray = new int[]{14,5,2,16,18,20}; +System.out.println(""The original array is ""+ "" "" +Arrays.toString(myArray)); +Arrays.sort(myArray); +System.out.println(""The sorted array is ""+ "" "" +Arrays.toString(myArray));; + +int fisrtmax = myArray[myArray.length-1]; +int secondmax = myArray[myArray.length-2]; + +System.out.println(""The first biggest number is "" + fisrtmax+ "" The second biggest number is "" + secondmax); + +int [] arrafterremove= Arrays.copyOf(myArray, myArray.length-2); + +System.out.println(""The array after removing the two biggest numbers is "" + Arrays.toString(arrafterremove)); + +``` + +**RUN** + +``` +The original array is [14, 5, 2, 16, 18, 20] +The sorted array is [2, 5, 14, 16, 18, 20] +The first biggest number is 20 The second biggest number is 18 +Array after removing the two biggest numbers is [2, 5, 14, 16] + +```" +30941209,"I have a set of defined JS functions. I want users to pick a subset of these using a comma separated string. Then I want to randomly pick from their subset, and evaluate the function selected. I have this 99% working, except it is not evaluating for some reason. Why does console keep telling me 'undefined is not a function'? + +Take a peek at line 37: + +``` +// 1 User picks a subset of function names as a comma seperated string. +var effectSubset = 'func4, func5, func6'; + +// 2 Available functions + function func1() { + $('html').append('func1'); + } + + function func2() { + $('html').append('func2'); + } + + function func3() { + $('html').append('func3'); + } + + function func4() { + $('html').append('func4'); + } + + function func5() { + $('html').append('func3'); + } + + function func6() { + $('html').append('func4'); + } + +var autoPlay = function () { + // 3 Get the user's subset of functions, turn into array + effectArray = effectSubset.split(','); + // 4 Pick random function from array + var effect = effectArray[Math.floor(Math.random() * effectArray.length)]; + // 5 run the randomly picked function + window[effect](); +} + +// 6 Re-run every second +var playInterval = setInterval(autoPlay, 1000); + +```",2015/06/19,"['https://Stackoverflow.com/questions/30941209', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/422203/']","I could see two things wrong: + +1. Your functions were not assigned to the `window` +2. Your `""effect""` variable contained leading whitespace + +I have corrected the above points here: + +This appears to have resolved the issue you described. + +**Example:** + +``` +window.func1 = function() { + $('html').append('func1'); +} + +``` + +**And:** + +``` +window[effect.trim()](); + +``` + +--- + +**Update** + +As a bonus I fixed your misleading append messages =D + +","You approach is not working because you have a space between the function names +`var effectSubset = 'func4, func5, func6';` After split the variable effect has a space before the name of the functions. + +So the functions being called are `func4`, `func5`, `func6` with a space which do not exist. + +Firstly, its better to have a namespace. + +``` +var effectSubset = 'func4,func5,func6'; // <--- remove spaces here or trim like in other answers +window.myNamespace = {}; + +window.myNamespace.func1 = function() { + $('html').append('func1'); +} +// ..... define other functions like above +window[""myNamespace""][effect](); // <-- this should work + +``` + +Here is a demo ****" +30941209,"I have a set of defined JS functions. I want users to pick a subset of these using a comma separated string. Then I want to randomly pick from their subset, and evaluate the function selected. I have this 99% working, except it is not evaluating for some reason. Why does console keep telling me 'undefined is not a function'? + +Take a peek at line 37: + +``` +// 1 User picks a subset of function names as a comma seperated string. +var effectSubset = 'func4, func5, func6'; + +// 2 Available functions + function func1() { + $('html').append('func1'); + } + + function func2() { + $('html').append('func2'); + } + + function func3() { + $('html').append('func3'); + } + + function func4() { + $('html').append('func4'); + } + + function func5() { + $('html').append('func3'); + } + + function func6() { + $('html').append('func4'); + } + +var autoPlay = function () { + // 3 Get the user's subset of functions, turn into array + effectArray = effectSubset.split(','); + // 4 Pick random function from array + var effect = effectArray[Math.floor(Math.random() * effectArray.length)]; + // 5 run the randomly picked function + window[effect](); +} + +// 6 Re-run every second +var playInterval = setInterval(autoPlay, 1000); + +```",2015/06/19,"['https://Stackoverflow.com/questions/30941209', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/422203/']","I could see two things wrong: + +1. Your functions were not assigned to the `window` +2. Your `""effect""` variable contained leading whitespace + +I have corrected the above points here: + +This appears to have resolved the issue you described. + +**Example:** + +``` +window.func1 = function() { + $('html').append('func1'); +} + +``` + +**And:** + +``` +window[effect.trim()](); + +``` + +--- + +**Update** + +As a bonus I fixed your misleading append messages =D + +","There are two issues: first there are leading whitespaces after you split the input and second, JSFiddle is wrapping your script in an IIFE. The first issue can be solved by either splitting with ' ,' or mapping the resulting array with a trim function. The second issue can be solved by creating an object to assign the functions to. See this [fiddle](http://jsfiddle.net/ftaq8q4m/3/) for a working example. + +``` +// 1 User picks a subset of function names as a comma seperated string. +var effectSubset = 'func4, func5, func6'; + +// 2 Available functions +var funcObj = { + func1: function func1() { + $('html').append('func1'); + }, + + func2: function func2() { + $('html').append('func2'); + }, + + func3: function func3() { + $('html').append('func3'); + }, + + func4: function func4() { + $('html').append('func4'); + }, + + func5: function func5() { + $('html').append('func3'); + }, + + func6: function func6() { + $('html').append('func4'); + } +}; + +var autoPlay = function () { + // 3 Get the user's subset of functions, turn into array + effectArray = effectSubset.split(',').map(function(func) { return func.trim() }); + // 4 Pick random function from array + var effect = effectArray[Math.floor(Math.random() * effectArray.length)]; + // 5 run the randomly picked function + funcObj[effect](); +} + +// 6 Re-run every second +var playInterval = setInterval(autoPlay, 1000); + +```" +30941209,"I have a set of defined JS functions. I want users to pick a subset of these using a comma separated string. Then I want to randomly pick from their subset, and evaluate the function selected. I have this 99% working, except it is not evaluating for some reason. Why does console keep telling me 'undefined is not a function'? + +Take a peek at line 37: + +``` +// 1 User picks a subset of function names as a comma seperated string. +var effectSubset = 'func4, func5, func6'; + +// 2 Available functions + function func1() { + $('html').append('func1'); + } + + function func2() { + $('html').append('func2'); + } + + function func3() { + $('html').append('func3'); + } + + function func4() { + $('html').append('func4'); + } + + function func5() { + $('html').append('func3'); + } + + function func6() { + $('html').append('func4'); + } + +var autoPlay = function () { + // 3 Get the user's subset of functions, turn into array + effectArray = effectSubset.split(','); + // 4 Pick random function from array + var effect = effectArray[Math.floor(Math.random() * effectArray.length)]; + // 5 run the randomly picked function + window[effect](); +} + +// 6 Re-run every second +var playInterval = setInterval(autoPlay, 1000); + +```",2015/06/19,"['https://Stackoverflow.com/questions/30941209', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/422203/']","You approach is not working because you have a space between the function names +`var effectSubset = 'func4, func5, func6';` After split the variable effect has a space before the name of the functions. + +So the functions being called are `func4`, `func5`, `func6` with a space which do not exist. + +Firstly, its better to have a namespace. + +``` +var effectSubset = 'func4,func5,func6'; // <--- remove spaces here or trim like in other answers +window.myNamespace = {}; + +window.myNamespace.func1 = function() { + $('html').append('func1'); +} +// ..... define other functions like above +window[""myNamespace""][effect](); // <-- this should work + +``` + +Here is a demo ****","There are two issues: first there are leading whitespaces after you split the input and second, JSFiddle is wrapping your script in an IIFE. The first issue can be solved by either splitting with ' ,' or mapping the resulting array with a trim function. The second issue can be solved by creating an object to assign the functions to. See this [fiddle](http://jsfiddle.net/ftaq8q4m/3/) for a working example. + +``` +// 1 User picks a subset of function names as a comma seperated string. +var effectSubset = 'func4, func5, func6'; + +// 2 Available functions +var funcObj = { + func1: function func1() { + $('html').append('func1'); + }, + + func2: function func2() { + $('html').append('func2'); + }, + + func3: function func3() { + $('html').append('func3'); + }, + + func4: function func4() { + $('html').append('func4'); + }, + + func5: function func5() { + $('html').append('func3'); + }, + + func6: function func6() { + $('html').append('func4'); + } +}; + +var autoPlay = function () { + // 3 Get the user's subset of functions, turn into array + effectArray = effectSubset.split(',').map(function(func) { return func.trim() }); + // 4 Pick random function from array + var effect = effectArray[Math.floor(Math.random() * effectArray.length)]; + // 5 run the randomly picked function + funcObj[effect](); +} + +// 6 Re-run every second +var playInterval = setInterval(autoPlay, 1000); + +```" +341338,"I have the following Perl scripts (though this applies to Python and other scripting languages): `script1.pl`, `script2.pl`, `script3.pl` + +The way these scripts where written, users execute them with input flags, and the output is a file saved. + +``` +perl script1.pl --i input1.tsv ## this outputs the file `outputs1` +perl script2.pl --i outputs1 ## this outputs the file `outputs2` +perl script3.pl --i outputs2 ## this outputs the file `final_output` + +``` + +Now, I would like to create an executable bash script that allows users to simply work with `input1` and get the output in return `final_output`. + +Here's how I would do this with only one perl script, `execute.sh`: + +``` +#!/bin/sh + +source ~/.bash_profile + +FLAG1=""--i=$1"" + +perl script1.pl $FLAG1 + +``` + +which could be run on the command line `execute.sh input1.tsv` + +For my example with three scripts, how would I pipe the intermediate outputs into the intermediate scripts to created one `execute.sh` script, e.g. `outputs1` into `script2.pl`, then `outputs2` into `scripts3.pl`, etc.? + +Isn't there a way for me to do this without rewriting the perl/python scripts?",2017/01/30,"['https://unix.stackexchange.com/questions/341338', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/115891/']","It seems that the path node\_exporter is not correct. + +``` + ExecStart=/usr/bin/node_exporter + +``` + +I have another path to it on Ubuntu 16.04 + +``` +~# cat /etc/issue +Ubuntu 16.04.3 LTS \n \l + +~# which node_exporter +/usr/sbin/node_exporter + +``` + +If it's not the root of the issue, check your `/var/log/syslog`. It must show the reason of the failure, something similar to: + +``` +Oct 20 12:30:30 prom systemd[8848]: node_exporter.service: Failed at step EXEC spawning /usr/bin/node_exporter: No such file or directory +Oct 20 12:30:30 prom systemd[1]: node_exporter.service: Main process exited, code=exited, status=203/EXEC +Oct 20 12:30:30 prom systemd[1]: node_exporter.service: Unit entered failed state. +Oct 20 12:30:30 prom systemd[1]: node_exporter.service: Failed with result 'exit-code'. +Oct 20 12:30:30 prom systemd[1]: node_exporter.service: Service hold-off time over, scheduling restart. +Oct 20 12:30:30 prom systemd[1]: Stopped Prometheus exporter for machine metrics, written in Go with pluggable metric collectors.. +Oct 20 12:30:30 prom systemd[1]: Started Prometheus exporter for machine metrics, written in Go with pluggable metric collectors.. + +```","Try to launch the command you're passing to `ExecStart` manually to verify whether it runs. + +I got the 203 error as well and apparently it was due to downloading/using the binary for the wrong platform. I was using ""Darwin"" instead of ""Linux"". + +``` + Process: 20340 ExecStart=/usr/local/bin/node_exporter (code=exited, status=203/EXEC) + +$ ls -lah /usr/local/bin/node_exporter +-rwxr-xr-x 1 node_exporter node_exporter 12M Jan 16 16:36 /usr/local/bin/node_exporter +$ /usr/local/bin/node_exporter +-bash: /usr/local/bin/node_exporter: cannot execute binary file: Exec format error + +```" +341338,"I have the following Perl scripts (though this applies to Python and other scripting languages): `script1.pl`, `script2.pl`, `script3.pl` + +The way these scripts where written, users execute them with input flags, and the output is a file saved. + +``` +perl script1.pl --i input1.tsv ## this outputs the file `outputs1` +perl script2.pl --i outputs1 ## this outputs the file `outputs2` +perl script3.pl --i outputs2 ## this outputs the file `final_output` + +``` + +Now, I would like to create an executable bash script that allows users to simply work with `input1` and get the output in return `final_output`. + +Here's how I would do this with only one perl script, `execute.sh`: + +``` +#!/bin/sh + +source ~/.bash_profile + +FLAG1=""--i=$1"" + +perl script1.pl $FLAG1 + +``` + +which could be run on the command line `execute.sh input1.tsv` + +For my example with three scripts, how would I pipe the intermediate outputs into the intermediate scripts to created one `execute.sh` script, e.g. `outputs1` into `script2.pl`, then `outputs2` into `scripts3.pl`, etc.? + +Isn't there a way for me to do this without rewriting the perl/python scripts?",2017/01/30,"['https://unix.stackexchange.com/questions/341338', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/115891/']","It seems that the path node\_exporter is not correct. + +``` + ExecStart=/usr/bin/node_exporter + +``` + +I have another path to it on Ubuntu 16.04 + +``` +~# cat /etc/issue +Ubuntu 16.04.3 LTS \n \l + +~# which node_exporter +/usr/sbin/node_exporter + +``` + +If it's not the root of the issue, check your `/var/log/syslog`. It must show the reason of the failure, something similar to: + +``` +Oct 20 12:30:30 prom systemd[8848]: node_exporter.service: Failed at step EXEC spawning /usr/bin/node_exporter: No such file or directory +Oct 20 12:30:30 prom systemd[1]: node_exporter.service: Main process exited, code=exited, status=203/EXEC +Oct 20 12:30:30 prom systemd[1]: node_exporter.service: Unit entered failed state. +Oct 20 12:30:30 prom systemd[1]: node_exporter.service: Failed with result 'exit-code'. +Oct 20 12:30:30 prom systemd[1]: node_exporter.service: Service hold-off time over, scheduling restart. +Oct 20 12:30:30 prom systemd[1]: Stopped Prometheus exporter for machine metrics, written in Go with pluggable metric collectors.. +Oct 20 12:30:30 prom systemd[1]: Started Prometheus exporter for machine metrics, written in Go with pluggable metric collectors.. + +```","Here is the `/etc/systemd/system/node_exporter.service` + +``` +[Unit] +Description=Node Exporter +Wants=network-online.target +After=network-online.target + +[Service] +User=node_exporter +Group=node_exporter +Type=simple +ExecStart=/usr/local/bin/node_exporter --collector.nfs --collector.nfsd + +[Install] +WantedBy=multi-user.target + +``` + +and make sure the `node_exporter` binary in placed in an expected path." +341338,"I have the following Perl scripts (though this applies to Python and other scripting languages): `script1.pl`, `script2.pl`, `script3.pl` + +The way these scripts where written, users execute them with input flags, and the output is a file saved. + +``` +perl script1.pl --i input1.tsv ## this outputs the file `outputs1` +perl script2.pl --i outputs1 ## this outputs the file `outputs2` +perl script3.pl --i outputs2 ## this outputs the file `final_output` + +``` + +Now, I would like to create an executable bash script that allows users to simply work with `input1` and get the output in return `final_output`. + +Here's how I would do this with only one perl script, `execute.sh`: + +``` +#!/bin/sh + +source ~/.bash_profile + +FLAG1=""--i=$1"" + +perl script1.pl $FLAG1 + +``` + +which could be run on the command line `execute.sh input1.tsv` + +For my example with three scripts, how would I pipe the intermediate outputs into the intermediate scripts to created one `execute.sh` script, e.g. `outputs1` into `script2.pl`, then `outputs2` into `scripts3.pl`, etc.? + +Isn't there a way for me to do this without rewriting the perl/python scripts?",2017/01/30,"['https://unix.stackexchange.com/questions/341338', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/115891/']","It seems that the path node\_exporter is not correct. + +``` + ExecStart=/usr/bin/node_exporter + +``` + +I have another path to it on Ubuntu 16.04 + +``` +~# cat /etc/issue +Ubuntu 16.04.3 LTS \n \l + +~# which node_exporter +/usr/sbin/node_exporter + +``` + +If it's not the root of the issue, check your `/var/log/syslog`. It must show the reason of the failure, something similar to: + +``` +Oct 20 12:30:30 prom systemd[8848]: node_exporter.service: Failed at step EXEC spawning /usr/bin/node_exporter: No such file or directory +Oct 20 12:30:30 prom systemd[1]: node_exporter.service: Main process exited, code=exited, status=203/EXEC +Oct 20 12:30:30 prom systemd[1]: node_exporter.service: Unit entered failed state. +Oct 20 12:30:30 prom systemd[1]: node_exporter.service: Failed with result 'exit-code'. +Oct 20 12:30:30 prom systemd[1]: node_exporter.service: Service hold-off time over, scheduling restart. +Oct 20 12:30:30 prom systemd[1]: Stopped Prometheus exporter for machine metrics, written in Go with pluggable metric collectors.. +Oct 20 12:30:30 prom systemd[1]: Started Prometheus exporter for machine metrics, written in Go with pluggable metric collectors.. + +```","I got this error. Solved as @Saex. + +Reason for getting this error is that I have downloaded the wrong package `node_exporter-1.2.2.darwin-amd64.tar.gz` instead of `node_exporter-1.2.2.linux-amd64.tar.gz` + +``` + node_exporter.service - Node Exporter + Loaded: loaded (/etc/systemd/system/node_exporter.service; enabled; vendor preset: enabled) + Active: failed (Result: exit-code) since Wed 2021-08-18 11:22:44 UTC; 17s ago + Main PID: 3830 (code=exited, status=203/EXEC) + +Aug 18 11:22:44 ip-10-0-101-80 systemd[1]: Started Node Exporter. +Aug 18 11:22:44 ip-10-0-101-80 systemd[3830]: node_exporter.service: Failed to execute command: Exec format error +Aug 18 11:22:44 ip-10-0-101-80 systemd[3830]: node_exporter.service: Failed at step EXEC spawning /opt/node_exporter/node_exporter: Exec> +Aug 18 11:22:44 ip-10-0-101-80 systemd[1]: node_exporter.service: Main process exited, code=exited, status=203/EXEC +Aug 18 11:22:44 ip-10-0-101-80 systemd[1]: node_exporter.service: Failed with result 'exit-code'. + +```" +341338,"I have the following Perl scripts (though this applies to Python and other scripting languages): `script1.pl`, `script2.pl`, `script3.pl` + +The way these scripts where written, users execute them with input flags, and the output is a file saved. + +``` +perl script1.pl --i input1.tsv ## this outputs the file `outputs1` +perl script2.pl --i outputs1 ## this outputs the file `outputs2` +perl script3.pl --i outputs2 ## this outputs the file `final_output` + +``` + +Now, I would like to create an executable bash script that allows users to simply work with `input1` and get the output in return `final_output`. + +Here's how I would do this with only one perl script, `execute.sh`: + +``` +#!/bin/sh + +source ~/.bash_profile + +FLAG1=""--i=$1"" + +perl script1.pl $FLAG1 + +``` + +which could be run on the command line `execute.sh input1.tsv` + +For my example with three scripts, how would I pipe the intermediate outputs into the intermediate scripts to created one `execute.sh` script, e.g. `outputs1` into `script2.pl`, then `outputs2` into `scripts3.pl`, etc.? + +Isn't there a way for me to do this without rewriting the perl/python scripts?",2017/01/30,"['https://unix.stackexchange.com/questions/341338', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/115891/']","I solved the problem like this... + +**Node exporter:** + +```none +ExecStart=/bin/sh -c '/usr/local/bin/node_exporter' + +``` + +**Mysql\_exporter:** + +```none +=/bin/sh -c '/usr/local/bin/mysqld_exporter \ + --config.my-cnf /etc/.mysqld_exporter.cnf \ + --collect.global_status \ + --collect.info_schema.innodb_metrics \ + --collect.auto_increment.columns \ + --collect.info_schema.processlist \ + --collect.binlog_size \ + --collect.info_schema.tablestats \ + --collect.global_variables \ + --collect.info_schema.query_response_time \ + --collect.info_schema.userstats \ + --collect.info_schema.tables \ + --collect.perf_schema.tablelocks \ + --collect.perf_schema.file_events \ + --collect.perf_schema.eventswaits \ + --collect.perf_schema.indexiowaits \ + --collect.perf_schema.tableiowaits \ + --collect.slave_status \ + --web.listen-address=0.0.0.0:9104' + +``` + +**Here is the complete command:** + +``` +sudo vim /etc/systemd/system/mysql_exporter.service + +``` + +**Content for `mysql_exporter.service`:** + +```none + [Unit] + Description=Prometheus MySQL Exporter + After=network.target + + [Service] + Type=simple + Restart=always + ExecStart=/bin/sh -c '/usr/local/bin/mysqld_exporter \ + --config.my-cnf /etc/.mysqld_exporter.cnf \ + --collect.global_status \ + --collect.info_schema.innodb_metrics \ + --collect.auto_increment.columns \ + --collect.info_schema.processlist \ + --collect.binlog_size \ + --collect.info_schema.tablestats \ + --collect.global_variables \ + --collect.info_schema.query_response_time \ + --collect.info_schema.userstats \ + --collect.info_schema.tables \ + --collect.perf_schema.tablelocks \ + --collect.perf_schema.file_events \ + --collect.perf_schema.eventswaits \ + --collect.perf_schema.indexiowaits \ + --collect.perf_schema.tableiowaits \ + --collect.slave_status \ + --web.listen-address=0.0.0.0:9104' + + [Install] + WantedBy=multi-user.target + +``` + +**Node exporter:** + +``` +sudo vim /etc/systemd/system/node_exporter.service + +``` + +**Content for `node_exporter`:** + +```none + [Unit] + Description=Prometheus Node Exporter + After=network.target + User=prometheus + Group=prometheus + + [Service] + Type=simple + Restart=always + ExecStart=/bin/sh -c '/usr/local/bin/node_exporter' + + [Install] + WantedBy=multi-user.target + +```","It seems that the path node\_exporter is not correct. + +``` + ExecStart=/usr/bin/node_exporter + +``` + +I have another path to it on Ubuntu 16.04 + +``` +~# cat /etc/issue +Ubuntu 16.04.3 LTS \n \l + +~# which node_exporter +/usr/sbin/node_exporter + +``` + +If it's not the root of the issue, check your `/var/log/syslog`. It must show the reason of the failure, something similar to: + +``` +Oct 20 12:30:30 prom systemd[8848]: node_exporter.service: Failed at step EXEC spawning /usr/bin/node_exporter: No such file or directory +Oct 20 12:30:30 prom systemd[1]: node_exporter.service: Main process exited, code=exited, status=203/EXEC +Oct 20 12:30:30 prom systemd[1]: node_exporter.service: Unit entered failed state. +Oct 20 12:30:30 prom systemd[1]: node_exporter.service: Failed with result 'exit-code'. +Oct 20 12:30:30 prom systemd[1]: node_exporter.service: Service hold-off time over, scheduling restart. +Oct 20 12:30:30 prom systemd[1]: Stopped Prometheus exporter for machine metrics, written in Go with pluggable metric collectors.. +Oct 20 12:30:30 prom systemd[1]: Started Prometheus exporter for machine metrics, written in Go with pluggable metric collectors.. + +```" +341338,"I have the following Perl scripts (though this applies to Python and other scripting languages): `script1.pl`, `script2.pl`, `script3.pl` + +The way these scripts where written, users execute them with input flags, and the output is a file saved. + +``` +perl script1.pl --i input1.tsv ## this outputs the file `outputs1` +perl script2.pl --i outputs1 ## this outputs the file `outputs2` +perl script3.pl --i outputs2 ## this outputs the file `final_output` + +``` + +Now, I would like to create an executable bash script that allows users to simply work with `input1` and get the output in return `final_output`. + +Here's how I would do this with only one perl script, `execute.sh`: + +``` +#!/bin/sh + +source ~/.bash_profile + +FLAG1=""--i=$1"" + +perl script1.pl $FLAG1 + +``` + +which could be run on the command line `execute.sh input1.tsv` + +For my example with three scripts, how would I pipe the intermediate outputs into the intermediate scripts to created one `execute.sh` script, e.g. `outputs1` into `script2.pl`, then `outputs2` into `scripts3.pl`, etc.? + +Isn't there a way for me to do this without rewriting the perl/python scripts?",2017/01/30,"['https://unix.stackexchange.com/questions/341338', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/115891/']","Try to launch the command you're passing to `ExecStart` manually to verify whether it runs. + +I got the 203 error as well and apparently it was due to downloading/using the binary for the wrong platform. I was using ""Darwin"" instead of ""Linux"". + +``` + Process: 20340 ExecStart=/usr/local/bin/node_exporter (code=exited, status=203/EXEC) + +$ ls -lah /usr/local/bin/node_exporter +-rwxr-xr-x 1 node_exporter node_exporter 12M Jan 16 16:36 /usr/local/bin/node_exporter +$ /usr/local/bin/node_exporter +-bash: /usr/local/bin/node_exporter: cannot execute binary file: Exec format error + +```","I got this error. Solved as @Saex. + +Reason for getting this error is that I have downloaded the wrong package `node_exporter-1.2.2.darwin-amd64.tar.gz` instead of `node_exporter-1.2.2.linux-amd64.tar.gz` + +``` + node_exporter.service - Node Exporter + Loaded: loaded (/etc/systemd/system/node_exporter.service; enabled; vendor preset: enabled) + Active: failed (Result: exit-code) since Wed 2021-08-18 11:22:44 UTC; 17s ago + Main PID: 3830 (code=exited, status=203/EXEC) + +Aug 18 11:22:44 ip-10-0-101-80 systemd[1]: Started Node Exporter. +Aug 18 11:22:44 ip-10-0-101-80 systemd[3830]: node_exporter.service: Failed to execute command: Exec format error +Aug 18 11:22:44 ip-10-0-101-80 systemd[3830]: node_exporter.service: Failed at step EXEC spawning /opt/node_exporter/node_exporter: Exec> +Aug 18 11:22:44 ip-10-0-101-80 systemd[1]: node_exporter.service: Main process exited, code=exited, status=203/EXEC +Aug 18 11:22:44 ip-10-0-101-80 systemd[1]: node_exporter.service: Failed with result 'exit-code'. + +```" +341338,"I have the following Perl scripts (though this applies to Python and other scripting languages): `script1.pl`, `script2.pl`, `script3.pl` + +The way these scripts where written, users execute them with input flags, and the output is a file saved. + +``` +perl script1.pl --i input1.tsv ## this outputs the file `outputs1` +perl script2.pl --i outputs1 ## this outputs the file `outputs2` +perl script3.pl --i outputs2 ## this outputs the file `final_output` + +``` + +Now, I would like to create an executable bash script that allows users to simply work with `input1` and get the output in return `final_output`. + +Here's how I would do this with only one perl script, `execute.sh`: + +``` +#!/bin/sh + +source ~/.bash_profile + +FLAG1=""--i=$1"" + +perl script1.pl $FLAG1 + +``` + +which could be run on the command line `execute.sh input1.tsv` + +For my example with three scripts, how would I pipe the intermediate outputs into the intermediate scripts to created one `execute.sh` script, e.g. `outputs1` into `script2.pl`, then `outputs2` into `scripts3.pl`, etc.? + +Isn't there a way for me to do this without rewriting the perl/python scripts?",2017/01/30,"['https://unix.stackexchange.com/questions/341338', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/115891/']","I solved the problem like this... + +**Node exporter:** + +```none +ExecStart=/bin/sh -c '/usr/local/bin/node_exporter' + +``` + +**Mysql\_exporter:** + +```none +=/bin/sh -c '/usr/local/bin/mysqld_exporter \ + --config.my-cnf /etc/.mysqld_exporter.cnf \ + --collect.global_status \ + --collect.info_schema.innodb_metrics \ + --collect.auto_increment.columns \ + --collect.info_schema.processlist \ + --collect.binlog_size \ + --collect.info_schema.tablestats \ + --collect.global_variables \ + --collect.info_schema.query_response_time \ + --collect.info_schema.userstats \ + --collect.info_schema.tables \ + --collect.perf_schema.tablelocks \ + --collect.perf_schema.file_events \ + --collect.perf_schema.eventswaits \ + --collect.perf_schema.indexiowaits \ + --collect.perf_schema.tableiowaits \ + --collect.slave_status \ + --web.listen-address=0.0.0.0:9104' + +``` + +**Here is the complete command:** + +``` +sudo vim /etc/systemd/system/mysql_exporter.service + +``` + +**Content for `mysql_exporter.service`:** + +```none + [Unit] + Description=Prometheus MySQL Exporter + After=network.target + + [Service] + Type=simple + Restart=always + ExecStart=/bin/sh -c '/usr/local/bin/mysqld_exporter \ + --config.my-cnf /etc/.mysqld_exporter.cnf \ + --collect.global_status \ + --collect.info_schema.innodb_metrics \ + --collect.auto_increment.columns \ + --collect.info_schema.processlist \ + --collect.binlog_size \ + --collect.info_schema.tablestats \ + --collect.global_variables \ + --collect.info_schema.query_response_time \ + --collect.info_schema.userstats \ + --collect.info_schema.tables \ + --collect.perf_schema.tablelocks \ + --collect.perf_schema.file_events \ + --collect.perf_schema.eventswaits \ + --collect.perf_schema.indexiowaits \ + --collect.perf_schema.tableiowaits \ + --collect.slave_status \ + --web.listen-address=0.0.0.0:9104' + + [Install] + WantedBy=multi-user.target + +``` + +**Node exporter:** + +``` +sudo vim /etc/systemd/system/node_exporter.service + +``` + +**Content for `node_exporter`:** + +```none + [Unit] + Description=Prometheus Node Exporter + After=network.target + User=prometheus + Group=prometheus + + [Service] + Type=simple + Restart=always + ExecStart=/bin/sh -c '/usr/local/bin/node_exporter' + + [Install] + WantedBy=multi-user.target + +```","Try to launch the command you're passing to `ExecStart` manually to verify whether it runs. + +I got the 203 error as well and apparently it was due to downloading/using the binary for the wrong platform. I was using ""Darwin"" instead of ""Linux"". + +``` + Process: 20340 ExecStart=/usr/local/bin/node_exporter (code=exited, status=203/EXEC) + +$ ls -lah /usr/local/bin/node_exporter +-rwxr-xr-x 1 node_exporter node_exporter 12M Jan 16 16:36 /usr/local/bin/node_exporter +$ /usr/local/bin/node_exporter +-bash: /usr/local/bin/node_exporter: cannot execute binary file: Exec format error + +```" +341338,"I have the following Perl scripts (though this applies to Python and other scripting languages): `script1.pl`, `script2.pl`, `script3.pl` + +The way these scripts where written, users execute them with input flags, and the output is a file saved. + +``` +perl script1.pl --i input1.tsv ## this outputs the file `outputs1` +perl script2.pl --i outputs1 ## this outputs the file `outputs2` +perl script3.pl --i outputs2 ## this outputs the file `final_output` + +``` + +Now, I would like to create an executable bash script that allows users to simply work with `input1` and get the output in return `final_output`. + +Here's how I would do this with only one perl script, `execute.sh`: + +``` +#!/bin/sh + +source ~/.bash_profile + +FLAG1=""--i=$1"" + +perl script1.pl $FLAG1 + +``` + +which could be run on the command line `execute.sh input1.tsv` + +For my example with three scripts, how would I pipe the intermediate outputs into the intermediate scripts to created one `execute.sh` script, e.g. `outputs1` into `script2.pl`, then `outputs2` into `scripts3.pl`, etc.? + +Isn't there a way for me to do this without rewriting the perl/python scripts?",2017/01/30,"['https://unix.stackexchange.com/questions/341338', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/115891/']","Here is the `/etc/systemd/system/node_exporter.service` + +``` +[Unit] +Description=Node Exporter +Wants=network-online.target +After=network-online.target + +[Service] +User=node_exporter +Group=node_exporter +Type=simple +ExecStart=/usr/local/bin/node_exporter --collector.nfs --collector.nfsd + +[Install] +WantedBy=multi-user.target + +``` + +and make sure the `node_exporter` binary in placed in an expected path.","I got this error. Solved as @Saex. + +Reason for getting this error is that I have downloaded the wrong package `node_exporter-1.2.2.darwin-amd64.tar.gz` instead of `node_exporter-1.2.2.linux-amd64.tar.gz` + +``` + node_exporter.service - Node Exporter + Loaded: loaded (/etc/systemd/system/node_exporter.service; enabled; vendor preset: enabled) + Active: failed (Result: exit-code) since Wed 2021-08-18 11:22:44 UTC; 17s ago + Main PID: 3830 (code=exited, status=203/EXEC) + +Aug 18 11:22:44 ip-10-0-101-80 systemd[1]: Started Node Exporter. +Aug 18 11:22:44 ip-10-0-101-80 systemd[3830]: node_exporter.service: Failed to execute command: Exec format error +Aug 18 11:22:44 ip-10-0-101-80 systemd[3830]: node_exporter.service: Failed at step EXEC spawning /opt/node_exporter/node_exporter: Exec> +Aug 18 11:22:44 ip-10-0-101-80 systemd[1]: node_exporter.service: Main process exited, code=exited, status=203/EXEC +Aug 18 11:22:44 ip-10-0-101-80 systemd[1]: node_exporter.service: Failed with result 'exit-code'. + +```" +341338,"I have the following Perl scripts (though this applies to Python and other scripting languages): `script1.pl`, `script2.pl`, `script3.pl` + +The way these scripts where written, users execute them with input flags, and the output is a file saved. + +``` +perl script1.pl --i input1.tsv ## this outputs the file `outputs1` +perl script2.pl --i outputs1 ## this outputs the file `outputs2` +perl script3.pl --i outputs2 ## this outputs the file `final_output` + +``` + +Now, I would like to create an executable bash script that allows users to simply work with `input1` and get the output in return `final_output`. + +Here's how I would do this with only one perl script, `execute.sh`: + +``` +#!/bin/sh + +source ~/.bash_profile + +FLAG1=""--i=$1"" + +perl script1.pl $FLAG1 + +``` + +which could be run on the command line `execute.sh input1.tsv` + +For my example with three scripts, how would I pipe the intermediate outputs into the intermediate scripts to created one `execute.sh` script, e.g. `outputs1` into `script2.pl`, then `outputs2` into `scripts3.pl`, etc.? + +Isn't there a way for me to do this without rewriting the perl/python scripts?",2017/01/30,"['https://unix.stackexchange.com/questions/341338', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/115891/']","I solved the problem like this... + +**Node exporter:** + +```none +ExecStart=/bin/sh -c '/usr/local/bin/node_exporter' + +``` + +**Mysql\_exporter:** + +```none +=/bin/sh -c '/usr/local/bin/mysqld_exporter \ + --config.my-cnf /etc/.mysqld_exporter.cnf \ + --collect.global_status \ + --collect.info_schema.innodb_metrics \ + --collect.auto_increment.columns \ + --collect.info_schema.processlist \ + --collect.binlog_size \ + --collect.info_schema.tablestats \ + --collect.global_variables \ + --collect.info_schema.query_response_time \ + --collect.info_schema.userstats \ + --collect.info_schema.tables \ + --collect.perf_schema.tablelocks \ + --collect.perf_schema.file_events \ + --collect.perf_schema.eventswaits \ + --collect.perf_schema.indexiowaits \ + --collect.perf_schema.tableiowaits \ + --collect.slave_status \ + --web.listen-address=0.0.0.0:9104' + +``` + +**Here is the complete command:** + +``` +sudo vim /etc/systemd/system/mysql_exporter.service + +``` + +**Content for `mysql_exporter.service`:** + +```none + [Unit] + Description=Prometheus MySQL Exporter + After=network.target + + [Service] + Type=simple + Restart=always + ExecStart=/bin/sh -c '/usr/local/bin/mysqld_exporter \ + --config.my-cnf /etc/.mysqld_exporter.cnf \ + --collect.global_status \ + --collect.info_schema.innodb_metrics \ + --collect.auto_increment.columns \ + --collect.info_schema.processlist \ + --collect.binlog_size \ + --collect.info_schema.tablestats \ + --collect.global_variables \ + --collect.info_schema.query_response_time \ + --collect.info_schema.userstats \ + --collect.info_schema.tables \ + --collect.perf_schema.tablelocks \ + --collect.perf_schema.file_events \ + --collect.perf_schema.eventswaits \ + --collect.perf_schema.indexiowaits \ + --collect.perf_schema.tableiowaits \ + --collect.slave_status \ + --web.listen-address=0.0.0.0:9104' + + [Install] + WantedBy=multi-user.target + +``` + +**Node exporter:** + +``` +sudo vim /etc/systemd/system/node_exporter.service + +``` + +**Content for `node_exporter`:** + +```none + [Unit] + Description=Prometheus Node Exporter + After=network.target + User=prometheus + Group=prometheus + + [Service] + Type=simple + Restart=always + ExecStart=/bin/sh -c '/usr/local/bin/node_exporter' + + [Install] + WantedBy=multi-user.target + +```","Here is the `/etc/systemd/system/node_exporter.service` + +``` +[Unit] +Description=Node Exporter +Wants=network-online.target +After=network-online.target + +[Service] +User=node_exporter +Group=node_exporter +Type=simple +ExecStart=/usr/local/bin/node_exporter --collector.nfs --collector.nfsd + +[Install] +WantedBy=multi-user.target + +``` + +and make sure the `node_exporter` binary in placed in an expected path." +341338,"I have the following Perl scripts (though this applies to Python and other scripting languages): `script1.pl`, `script2.pl`, `script3.pl` + +The way these scripts where written, users execute them with input flags, and the output is a file saved. + +``` +perl script1.pl --i input1.tsv ## this outputs the file `outputs1` +perl script2.pl --i outputs1 ## this outputs the file `outputs2` +perl script3.pl --i outputs2 ## this outputs the file `final_output` + +``` + +Now, I would like to create an executable bash script that allows users to simply work with `input1` and get the output in return `final_output`. + +Here's how I would do this with only one perl script, `execute.sh`: + +``` +#!/bin/sh + +source ~/.bash_profile + +FLAG1=""--i=$1"" + +perl script1.pl $FLAG1 + +``` + +which could be run on the command line `execute.sh input1.tsv` + +For my example with three scripts, how would I pipe the intermediate outputs into the intermediate scripts to created one `execute.sh` script, e.g. `outputs1` into `script2.pl`, then `outputs2` into `scripts3.pl`, etc.? + +Isn't there a way for me to do this without rewriting the perl/python scripts?",2017/01/30,"['https://unix.stackexchange.com/questions/341338', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/115891/']","I solved the problem like this... + +**Node exporter:** + +```none +ExecStart=/bin/sh -c '/usr/local/bin/node_exporter' + +``` + +**Mysql\_exporter:** + +```none +=/bin/sh -c '/usr/local/bin/mysqld_exporter \ + --config.my-cnf /etc/.mysqld_exporter.cnf \ + --collect.global_status \ + --collect.info_schema.innodb_metrics \ + --collect.auto_increment.columns \ + --collect.info_schema.processlist \ + --collect.binlog_size \ + --collect.info_schema.tablestats \ + --collect.global_variables \ + --collect.info_schema.query_response_time \ + --collect.info_schema.userstats \ + --collect.info_schema.tables \ + --collect.perf_schema.tablelocks \ + --collect.perf_schema.file_events \ + --collect.perf_schema.eventswaits \ + --collect.perf_schema.indexiowaits \ + --collect.perf_schema.tableiowaits \ + --collect.slave_status \ + --web.listen-address=0.0.0.0:9104' + +``` + +**Here is the complete command:** + +``` +sudo vim /etc/systemd/system/mysql_exporter.service + +``` + +**Content for `mysql_exporter.service`:** + +```none + [Unit] + Description=Prometheus MySQL Exporter + After=network.target + + [Service] + Type=simple + Restart=always + ExecStart=/bin/sh -c '/usr/local/bin/mysqld_exporter \ + --config.my-cnf /etc/.mysqld_exporter.cnf \ + --collect.global_status \ + --collect.info_schema.innodb_metrics \ + --collect.auto_increment.columns \ + --collect.info_schema.processlist \ + --collect.binlog_size \ + --collect.info_schema.tablestats \ + --collect.global_variables \ + --collect.info_schema.query_response_time \ + --collect.info_schema.userstats \ + --collect.info_schema.tables \ + --collect.perf_schema.tablelocks \ + --collect.perf_schema.file_events \ + --collect.perf_schema.eventswaits \ + --collect.perf_schema.indexiowaits \ + --collect.perf_schema.tableiowaits \ + --collect.slave_status \ + --web.listen-address=0.0.0.0:9104' + + [Install] + WantedBy=multi-user.target + +``` + +**Node exporter:** + +``` +sudo vim /etc/systemd/system/node_exporter.service + +``` + +**Content for `node_exporter`:** + +```none + [Unit] + Description=Prometheus Node Exporter + After=network.target + User=prometheus + Group=prometheus + + [Service] + Type=simple + Restart=always + ExecStart=/bin/sh -c '/usr/local/bin/node_exporter' + + [Install] + WantedBy=multi-user.target + +```","I got this error. Solved as @Saex. + +Reason for getting this error is that I have downloaded the wrong package `node_exporter-1.2.2.darwin-amd64.tar.gz` instead of `node_exporter-1.2.2.linux-amd64.tar.gz` + +``` + node_exporter.service - Node Exporter + Loaded: loaded (/etc/systemd/system/node_exporter.service; enabled; vendor preset: enabled) + Active: failed (Result: exit-code) since Wed 2021-08-18 11:22:44 UTC; 17s ago + Main PID: 3830 (code=exited, status=203/EXEC) + +Aug 18 11:22:44 ip-10-0-101-80 systemd[1]: Started Node Exporter. +Aug 18 11:22:44 ip-10-0-101-80 systemd[3830]: node_exporter.service: Failed to execute command: Exec format error +Aug 18 11:22:44 ip-10-0-101-80 systemd[3830]: node_exporter.service: Failed at step EXEC spawning /opt/node_exporter/node_exporter: Exec> +Aug 18 11:22:44 ip-10-0-101-80 systemd[1]: node_exporter.service: Main process exited, code=exited, status=203/EXEC +Aug 18 11:22:44 ip-10-0-101-80 systemd[1]: node_exporter.service: Failed with result 'exit-code'. + +```" +1589095,"In Algebra (2) I was told that if a polynomial had an even multiplicity for some $x=a$, then the graph touches $y=0$ at $x=a$ but doesn't cross $y=0$. Odd multiplicities go through the $x$-intercept. For example:$$y=x^2\to y=(x-0)(x-0)\to x=0,0$$And you can clearly see the graph ""touches without intersecting"" at $x=0$. + +However, I am confused on how this is proven.",2015/12/26,"['https://math.stackexchange.com/questions/1589095', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/272831/']","Let $P(x) = Q(x)(x-a)^{2n}$ such that $(x-a)\nmid Q(x)$. In a small enough neighbourhood of $a$ (for instance one that contains no roots of $Q(x)$), then $Q(x)$ preserves sign. And $(x-a)^{2n}\geq 0$, therefore, in said neighbourhood, $P(x)$ preserves sign, i.e., the function does not cross the line $y=0$. + +You can find a similar argument of why it happens the other way around for $P(x) = Q(x)(x-a)^{2n+1}$.","Suppose you have $f(x) = (x+6)(x-4)(x-7)^2$. If $x$ is near $7$ then $(x+6)(x-4)$ is near $(7+6)(7-4) =39$, so $f(x)$ is approximately $39(x-7)^2$. Notice that if $x$ is either a little bit more than $7$ or a little bit less, then $(x-7)^2$ is positive, but if $x$ is exactly $7$, then $(x-7)^2$ is $0$. Being positive on either side of that point but exactly $0$ at that point means it touches the axis without crossing over from positive to negative or vice-versa." +27767713,"As a part of an internal project, I have to parse through a dns zone file records. The file looks roughly like this. + +``` + $ORIGIN 0001.test.domain.com. + test-qa CNAME test-qa.0001.test.domain.com. + $ORIGIN test-qa.domain.com. + unit-test01 A 192.168.0.2 + $TTL 60 ; 1 minute + integration-test A 192.168.0.102 + $ORIGIN dev.domain.com. + web A 192.168.10.10 + $TTL 300; 5 minutes + api A 192.168.10.13 + +``` + +Default ttl is 3600, that is, for the above data, + +``` +test-qa CNAME test-qa.0001.test.domain.com. + +``` + +has a ttl of 3600 because it doesn't have a $TTL mentioned anywhere. However, + +``` +unit-test01 A 192.168.0.2 + +``` + +has a ttl of 3600 and + +``` +integration-test A 192.168.0.102 + +``` + +has a ttl of 60 secs. + +I am trying to create a datastructure out of this data above, and I guess a dictionary would be the best possible way to traverse through this data. + +What I did: + +``` +origin = re.compile(""^\$ORIGIN.*"") +ttl = re.compile(""^$TTL.*"") +default_ttl = ""$TTL 3600"" +data_dict = {} +primary_key = None +value = None +for line in data_zones: + if origin.search(line): + line = line.replace(""$ORIGIN "", """") + primary_key = line + elif ttl.search(line): + default_ttl = line + else: + value = line + data_dict[primary_key] = [default_ttl] + data_dict[primary_key][default_ttl] = value + +``` + +I want to convert it into a dictionary, but I get the error + +``` +TypeError: list indices must be integers, not str + +``` + +My sample data structure need to look something like + +``` +0001.test.domain.com.: #This would be the first level Key + ttl:3600: #This would be the second level key + test-qa CNAME test-qa.0001.test.domain.com. #Value + +test-qa.domain.com.: #This would be the first level Key + ttl:3600: #This would be the second level key + unit-test01 A 192.168.0.2 #value + ttl:60: #This would be the second level key + integration-test A 192.168.0.102 #value + +``` + +What am I doing wrong here?",2015/01/04,"['https://Stackoverflow.com/questions/27767713', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3354434/']","Before we look at the detail of the problem, there's a few things that could be cleaned up in this code that would make the error easier to find. Following code quality guidelines make code easier to maintain and understand, in particular - variable names should always be descriptive and tell the reader what the variable is going to represent. A bad variable name doesn't tell the reader anything about what it contains, and a terrible variable name will tell the reader that the variable contains something it doesn't. + +Here we have a variable here called default\_ttl. A casual reader might well make an assumption that this variable is always going to contain the default ttl, but in the code sample above, the variable is overwritten as soon as a ttl is specified in the source data. + +``` +default_ttl = line + +``` + +It might be a lot clearer to specify a default TTL at the top of the code, and then use assign this value to a variable called, say : current\_ttl, whenever a new origin is encountered. + +So at the top of the file we would have : + +``` +DEFAULT_TTL = '$TTL 3600' + +``` + +And every time a new origin is encountered, the current ttl would be reset to the default. + +``` +if origin.search(line): + line = line.replace(""$ORIGIN "", """") + current_ttl = DEFAULT_TTL + +``` + +When a specific TTL is encountered in the source data, the appropriate value can then be assigned to current TTL: + +``` +elif ttl.search(line): + current_ttl = line + +``` + +Once this change is made, the bottom two lines of code would become: + +``` +data_dict[primary_key] = [current_ttl] +data_dict[primary_key][current_ttl] = value + +``` + +The cause of the error is that you are creating a list containing exactly one entry - the current\_ttl, and creating an entry in the data\_dict dictionary containing that list. + +On the next line, you get the list back out of the dictionary, and try and access it using the index current\_ttl. current\_ttl contains a string, and a list can only be accessed using an integer. The interpreter gives you an error message that sums this up succinctly! + +Without major modifications to your code, the quickest clean up is to use a defaultdict for the top level data\_dict: + +``` +from collections import defaultdict +data_dict = defaultdict(dict) + +``` + +So now, whenever we try to refer to a key in data\_dict that does not already exist, a new empty dictionary will be created for us by the defaultdict object and inserted to data\_dict at that key we tried to access. + +The line + +``` +data_dict[primary_key] = [default_ttl] + +``` + +Is now redundant and unnecessary, it can be removed from the code altogether, leaving : + +``` +from collections import defaultdict +origin = re.compile(""^\$ORIGIN.*"") +ttl = re.compile(""^$TTL.*"") +DEFAULT_TTL = ""$TTL 3600"" +data_dict = defaultdict(dict) +primary_key = None +value = None +for line in data_zones.split('\n'): #Split by line not character + if origin.search(line): + line = line.replace(""$ORIGIN "", """") + current_ttl = DEFAULT_TTL + primary_key = line + elif ttl.search(line): + current_ttl = line + else: + value = line + data_dict[primary_key][current_ttl] = value + +```","The line of error is + +``` +data_dict[primary_key][default_ttl] = value + +``` + +Because `data_dict[primary_key]` is a list and not a dictionary object. You can fix this by doing + +``` +data_dict[primary_key] = {default_ttl: value} + +```" +15369,"I'm putting together a gaming rig with an i5 11600k (liquid cooled) and GIGABYTE Z590 mobo... average RAM, GIGABYTE AORUS NVMe Gen4 SSD, beefy PSU... everything is coming along nicely... with the end goal being to be playing on 1440p with in-game settings pretty high. + +But now i need to choose my GPU. I have access to a 3060 Ti or a 3070 Ti for the same price (friendly scalper). I've read that the 3070 will likely cause a CPU bottleneck while the 3060 will be the opposite. I'm pretty new go all this, so I'm not sure I fully understand the issues involved with bottlenecking... or maybe I'm making it more complicated than it needs to be. Is the main problem that the component being bottlenecked will not be able to use 100% of its ""power""... meaning that you're maybe not getting your money's worth out of of that component? + +If that's the case, then I'm thinking I should definitely go with the 3070 Ti since it is costing me the same as the 3060 and will provide some future-proofing or perhaps get me a better resale price (if i ever choose to go that way). Does that sound about right or am I missing something that would actually make the 3060 Ti the better choice (with better performance) in my situation?",2021/10/04,"['https://hardwarerecs.stackexchange.com/questions/15369', 'https://hardwarerecs.stackexchange.com', 'https://hardwarerecs.stackexchange.com/users/20243/']","> +> If I opt for Additional 2.5"" 2 TB 5400RPM SATA Hard Drive, the battery 4 cells 64Whr battery should be selected. +> +> +> + +This is probably because the larger battery takes up the space where a 2.5"" HDD can be installed. + +> +> Does Using both SSD & SATA Hard drive impacts Laptop Performance? +> +> +> + +There is no surprise here, things that run on the SSD run at the SSD speed. Things that run on the HDD run at HDD speed. But since there's more stuff using power in the laptop the battery will be drained quicker. HDDs can conserve power by going to sleep if you make sure they're not being used in the background. If the HDD motor is running often, it will consume a little extra power and shorten the battery life. + +> +> Can someone shed some light on choosing up the hard drives & battery? +> +> +> + +It depends which matters more to you: + +1. Is battery life the most important thing? -- Then get the 6 cell battery. + +You can always plug in a USB hard drive and get extra storage space that way. +2. Is tons of storage space without having to carry an external HDD important? -- Get the SATA HDD and ""normal"" battery. (4 cell batteries are typical)","It doesnt affect performance, as long as nothing is on the hard drive. If you actively use the hard drive, the app that uses the hard drive slows down to hard drive speed. For some tasks (like rendering a video), you can write to the hard drive without performance issues because the bottleneck is somewhere else (cpu)" +7518255,"I wonder, if you open a text file in Python. And then you'd like to search of words containing a number of letters. + +Say you type in 6 different letters (a,b,c,d,e,f) you want to search. +You'd like to find words matching at least 3 letters. +Each letter can only appear once in a word. +And the letter 'a' always has to be containing. + +How should the code look like for this specific kind of search?",2011/09/22,"['https://Stackoverflow.com/questions/7518255', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/959397/']","Here is what I would do if I had to write this: + +I'd have a function that, given a word, would check whether it satisfies the criteria and would return a boolean flag. + +Then I'd have some code that would iterate over all words in the file, present each of them to the function, and print out those for which the function has returned `True`.","``` +words = 'fubar cadre obsequious xray' + +def find_words(src, required=[], letters=[], min_match=3): + required = set(required) + letters = set(letters) + + words = ((word, set(word)) for word in src.split()) + words = (word for word in words if word[1].issuperset(required)) + words = (word for word in words if len(word[1].intersection(letters)) >= min_match) + words = (word[0] for word in words) + return words + +w = find_words(words, required=['a'], letters=['a', 'b', 'c', 'd', 'e', 'f']) +print list(w) + +``` + +**EDIT 1:** I too didn't read the requirements closely enough. To ensure a word contains only 1 instance of a valid letter. + +``` +from collections import Counter + +def valid(word, letters, min_match): + """"""At least min_match, no more than one of any letter"""""" + c = 0 + count = Counter(word) + for letter in letters: + char_count = count.get(letter, 0) + if char_count > 1: + return False + elif char_count == 1: + c += 1 + if c == min_match: + return True + return True + +def find_words(srcfile, required=[], letters=[], min_match=3): + required = set(required) + words = (word for word in srcfile.split()) + words = (word for word in words if set(word).issuperset(required)) + words = (word for word in words if valid(word, letters, min_match)) + return words + +```" +7518255,"I wonder, if you open a text file in Python. And then you'd like to search of words containing a number of letters. + +Say you type in 6 different letters (a,b,c,d,e,f) you want to search. +You'd like to find words matching at least 3 letters. +Each letter can only appear once in a word. +And the letter 'a' always has to be containing. + +How should the code look like for this specific kind of search?",2011/09/22,"['https://Stackoverflow.com/questions/7518255', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/959397/']","Here is what I would do if I had to write this: + +I'd have a function that, given a word, would check whether it satisfies the criteria and would return a boolean flag. + +Then I'd have some code that would iterate over all words in the file, present each of them to the function, and print out those for which the function has returned `True`.","I agree with aix's general plan, but it's perhaps even more general than a 'design pattern,' and I'm not sure how far it gets you, since it boils down to, ""figure out a way to check for what you want to find and then check everything you need to check."" + +Advice about how to find what you want to find: You've entered into one of the most fundamental areas of algorithm research. Though LCS (longest common substring) is better covered, you'll have no problems finding good examples for containment either. The most rigorous discussion of this topic I've seen is on a Google cs wonk's website: . He has something called diff-match-patch which is released and optimized in many different languages, including python, which can be downloaded here: + + +If you'd like to understand more about python and algorithms, magnus hetland has written a great book about python algorithms and his website features some examples within string matching and fuzzy string matching and so on, including the levenshtein distance in a very simple to grasp format. (google for magnus hetland, I don't remember address). + +WIthin the standard library you can look at difflib, which offers many ways to assess similarity of strings. You are looking for containment which is not the same but it is quite related and you could potentially make a set of candidate words that you could compare, depending on your needs. + +Alternatively you could use the new addition to python, Counter, and reconstruct the words you're testing as lists of strings, then make a function that requires counts of 1 or more for each of your tested letters. + +Finally, on to the second part of the aix's approach, 'then apply it to everything you want to test,' I'd suggest you look at itertools. If you have any kind of efficiency constraint, you will want to use generators and a test like the one aix proposes can be most efficiently carried out in python with itertools.ifilter. You have your function that returns True for the values you want to keep, and the **builtin** function bool. So you can just do itertools.ifilter(bool,test\_iterable), which will return all the values that succeed. + +Good luck" +7518255,"I wonder, if you open a text file in Python. And then you'd like to search of words containing a number of letters. + +Say you type in 6 different letters (a,b,c,d,e,f) you want to search. +You'd like to find words matching at least 3 letters. +Each letter can only appear once in a word. +And the letter 'a' always has to be containing. + +How should the code look like for this specific kind of search?",2011/09/22,"['https://Stackoverflow.com/questions/7518255', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/959397/']","Let's see... + +``` +return [x for x in document.split() + if 'a' in x and sum((1 if y in 'abcdef' else 0 for y in x)) >= 3] + +``` + +`split` with no parameters acts as a ""words"" function, splitting on any whitespace and removing words that contain no characters. Then you check if the letter 'a' is in the word. If 'a' is in the word, you use a generator expression that goes over every letter in the word. If the letter is inside of the string of available letters, then it returns a 1 which contributes to the sum. Otherwise, it returns 0. Then if the sum is 3 or greater, it keeps it. A generator is used instead of a list comprehension because sum will accept anything iterable and it stops a temporary list from having to be created (less memory overhead). + +It doesn't have the best access times because of the use of `in` (which on a string should have an O(n) time), but that generally isn't a very big problem unless the data sets are huge. You can optimize that a bit to pack the string into a set and the constant 'abcdef' can easily be a set. I just didn't want to ruin the nice one liner. + +EDIT: Oh, and to improve time on the `if` portion (which is where the inefficiencies are), you could separate it out into a function that iterates over the string once and returns True if the conditions are met. I would have done this, but it ruined my one liner. + +EDIT 2: I didn't see the ""must have 3 different characters"" part. You can't do that in a one liner. You can just take the if portion out into a function. + +``` +def is_valid(word, chars): + count = 0 + for x in word: + if x in chars: + count += 1 + chars.remove(x) + return count >= 3 and 'a' not in chars + +def parse_document(document): + return [x for x in document.split() if is_valid(x, set('abcdef'))] + +``` + +This one shouldn't have any performance problems on real world data sets.","``` +words = 'fubar cadre obsequious xray' + +def find_words(src, required=[], letters=[], min_match=3): + required = set(required) + letters = set(letters) + + words = ((word, set(word)) for word in src.split()) + words = (word for word in words if word[1].issuperset(required)) + words = (word for word in words if len(word[1].intersection(letters)) >= min_match) + words = (word[0] for word in words) + return words + +w = find_words(words, required=['a'], letters=['a', 'b', 'c', 'd', 'e', 'f']) +print list(w) + +``` + +**EDIT 1:** I too didn't read the requirements closely enough. To ensure a word contains only 1 instance of a valid letter. + +``` +from collections import Counter + +def valid(word, letters, min_match): + """"""At least min_match, no more than one of any letter"""""" + c = 0 + count = Counter(word) + for letter in letters: + char_count = count.get(letter, 0) + if char_count > 1: + return False + elif char_count == 1: + c += 1 + if c == min_match: + return True + return True + +def find_words(srcfile, required=[], letters=[], min_match=3): + required = set(required) + words = (word for word in srcfile.split()) + words = (word for word in words if set(word).issuperset(required)) + words = (word for word in words if valid(word, letters, min_match)) + return words + +```" +7518255,"I wonder, if you open a text file in Python. And then you'd like to search of words containing a number of letters. + +Say you type in 6 different letters (a,b,c,d,e,f) you want to search. +You'd like to find words matching at least 3 letters. +Each letter can only appear once in a word. +And the letter 'a' always has to be containing. + +How should the code look like for this specific kind of search?",2011/09/22,"['https://Stackoverflow.com/questions/7518255', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/959397/']","Let's see... + +``` +return [x for x in document.split() + if 'a' in x and sum((1 if y in 'abcdef' else 0 for y in x)) >= 3] + +``` + +`split` with no parameters acts as a ""words"" function, splitting on any whitespace and removing words that contain no characters. Then you check if the letter 'a' is in the word. If 'a' is in the word, you use a generator expression that goes over every letter in the word. If the letter is inside of the string of available letters, then it returns a 1 which contributes to the sum. Otherwise, it returns 0. Then if the sum is 3 or greater, it keeps it. A generator is used instead of a list comprehension because sum will accept anything iterable and it stops a temporary list from having to be created (less memory overhead). + +It doesn't have the best access times because of the use of `in` (which on a string should have an O(n) time), but that generally isn't a very big problem unless the data sets are huge. You can optimize that a bit to pack the string into a set and the constant 'abcdef' can easily be a set. I just didn't want to ruin the nice one liner. + +EDIT: Oh, and to improve time on the `if` portion (which is where the inefficiencies are), you could separate it out into a function that iterates over the string once and returns True if the conditions are met. I would have done this, but it ruined my one liner. + +EDIT 2: I didn't see the ""must have 3 different characters"" part. You can't do that in a one liner. You can just take the if portion out into a function. + +``` +def is_valid(word, chars): + count = 0 + for x in word: + if x in chars: + count += 1 + chars.remove(x) + return count >= 3 and 'a' not in chars + +def parse_document(document): + return [x for x in document.split() if is_valid(x, set('abcdef'))] + +``` + +This one shouldn't have any performance problems on real world data sets.","I agree with aix's general plan, but it's perhaps even more general than a 'design pattern,' and I'm not sure how far it gets you, since it boils down to, ""figure out a way to check for what you want to find and then check everything you need to check."" + +Advice about how to find what you want to find: You've entered into one of the most fundamental areas of algorithm research. Though LCS (longest common substring) is better covered, you'll have no problems finding good examples for containment either. The most rigorous discussion of this topic I've seen is on a Google cs wonk's website: . He has something called diff-match-patch which is released and optimized in many different languages, including python, which can be downloaded here: + + +If you'd like to understand more about python and algorithms, magnus hetland has written a great book about python algorithms and his website features some examples within string matching and fuzzy string matching and so on, including the levenshtein distance in a very simple to grasp format. (google for magnus hetland, I don't remember address). + +WIthin the standard library you can look at difflib, which offers many ways to assess similarity of strings. You are looking for containment which is not the same but it is quite related and you could potentially make a set of candidate words that you could compare, depending on your needs. + +Alternatively you could use the new addition to python, Counter, and reconstruct the words you're testing as lists of strings, then make a function that requires counts of 1 or more for each of your tested letters. + +Finally, on to the second part of the aix's approach, 'then apply it to everything you want to test,' I'd suggest you look at itertools. If you have any kind of efficiency constraint, you will want to use generators and a test like the one aix proposes can be most efficiently carried out in python with itertools.ifilter. You have your function that returns True for the values you want to keep, and the **builtin** function bool. So you can just do itertools.ifilter(bool,test\_iterable), which will return all the values that succeed. + +Good luck" +51610180,"I am trying to create a transition using react and css. I want to add a class to the `span` to create the animation - See example below. + +Does anyone know if the issue is with the css or my javascript. + +```js +class App extends React.Component { + state = { + class: null + }; + + componentDidMount() { + this.setState({ + class: ""active"" + }); + } + + render() { + return ( +
+ +
+ ); + } +} + +const rootElement = document.getElementById(""root""); +ReactDOM.render(, rootElement); +``` + +```css +.progress-bar-container { + border: 0; + height: 4px; + position: relative; + background: red; +} + +.progress-bar { + -webkit-transition: width 2s; /* Safari */ + transition: width 5s; + width: 0%; +} + +.progress-bar.active { + width: 100%; +} +``` + +```html + + +
+```",2018/07/31,"['https://Stackoverflow.com/questions/51610180', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4756106/']","You could use a different approach and append `active` class with `setTimeout` method. + +```js +class App extends React.Component { + state = { + class: null + }; + + componentDidMount() { + setTimeout(() => this.refs.progressBar.classList.add(""active""), 100) + } + + render() { + return ( +
+ +
+ ); + } +} + +const rootElement = document.getElementById(""root""); +ReactDOM.render( < App / > , rootElement); +``` + +```css +.progress-bar-container { + border: 0; + height: 4px; + position: relative; + background: red; +} + +.progress-bar { + position: absolute; + left: 0; + top: 0; + height: 100%; + background: green; + transition: width 5s; + width: 0px; +} + +.progress-bar.active { + width: 100%; +} +``` + +```html + + +
+```","You can use `requestAnimationFrame()` to trigger the transition on mount. I'd presume that doing this is more robust than relying on a `setTimeout()`. + +``` +componentDidMount() { + requestAnimationFrame(() => { + this.setState({ + class: ""active"" + }); + }); +} + +``` + +Source: " +49276120,"I want to open Google Street View Android directly from my app. +Can anyone help me in doing this? + +I have successfully opened the Maps app with Streeview thanks to SO but that's not what I am looking for. + +I actually want to open Streetview camera directly from my app so I can take a panoramic photo. + +My actual task is to develop a camera app that can take panoramic images but I couldn't find anything for that, So I am working on things can be done instead of camera app like cardboard. +Here is the link to the question that I had asked earlier- [App to capture 360 View android](https://stackoverflow.com/questions/49249886/app-to-capture-360-view-android) + +Please help in this!",2018/03/14,"['https://Stackoverflow.com/questions/49276120', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6492719/']","u are using python 3.6 . +so +pip3 install numpy +should be used, make a try .","You need to make sure all the dependent libraries AND the Python file containing your function are all in one zip file in order for it to detect the correct dependencies. + +So essentially, you will need to have Numpy, Panda and your own files all in one zip file before you upload it. Also make sure that your code is referring to the local files (in the same unzipped directory) as dependencies. If you have done that already, the issue is probably how your included libraries gets referenced. Make sure you are able to use the included libraries as a dependency by getting the correct relative path on AWS once it's deployed to Lambda." +49276120,"I want to open Google Street View Android directly from my app. +Can anyone help me in doing this? + +I have successfully opened the Maps app with Streeview thanks to SO but that's not what I am looking for. + +I actually want to open Streetview camera directly from my app so I can take a panoramic photo. + +My actual task is to develop a camera app that can take panoramic images but I couldn't find anything for that, So I am working on things can be done instead of camera app like cardboard. +Here is the link to the question that I had asked earlier- [App to capture 360 View android](https://stackoverflow.com/questions/49249886/app-to-capture-360-view-android) + +Please help in this!",2018/03/14,"['https://Stackoverflow.com/questions/49276120', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6492719/']","u are using python 3.6 . +so +pip3 install numpy +should be used, make a try .","So like Wai kin chung said, you need to use pip3 to install the libraries. + +so to figure out which python version is default you can type: + +``` +which python + +``` + +or + +``` +python -v + +``` + +So in order to install with python3 you need to type: + +``` +python3 -m pip install sklearn, pandas, numpy --user + +``` + +Once that is done, you can make sure that the packages are installed with: + +``` +python3 -m pip freeze + +``` + +This will show all the python libraries installed with your python model. +Once you have the libraries you would want to continue with you regular steps. Of course you would first want to delete everything that you have placed in ~/venv/lib/python3.6/site-packages/\*. + +``` +cd ~/lambda_code +zip -r9 ~/package.zip + +```" +49276120,"I want to open Google Street View Android directly from my app. +Can anyone help me in doing this? + +I have successfully opened the Maps app with Streeview thanks to SO but that's not what I am looking for. + +I actually want to open Streetview camera directly from my app so I can take a panoramic photo. + +My actual task is to develop a camera app that can take panoramic images but I couldn't find anything for that, So I am working on things can be done instead of camera app like cardboard. +Here is the link to the question that I had asked earlier- [App to capture 360 View android](https://stackoverflow.com/questions/49249886/app-to-capture-360-view-android) + +Please help in this!",2018/03/14,"['https://Stackoverflow.com/questions/49276120', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6492719/']","u are using python 3.6 . +so +pip3 install numpy +should be used, make a try .","If you're running this on Windows (like I was), you'll run into an issue with the libraries being compiled on an incompatible OS. + +You can use an Amazon Linux EC2 instance, or a Cloud9 development instance to build your virtualenv as detailed above. + +Or, you could just download the pre-compiled wheel files as discussed on this post: + + +Essentially, you need to go to the project page on and download the files named like the following: + +* For Python 2.7: module-name-version-cp27-cp27mu-manylinux1\_x86\_64.whl +* For Python 3.6: module-name-version-cp36-cp36m-manylinux1\_x86\_64.whl + +Then unzip the .whl files to your project directory and re-zip the contents together with your lambda code." +49276120,"I want to open Google Street View Android directly from my app. +Can anyone help me in doing this? + +I have successfully opened the Maps app with Streeview thanks to SO but that's not what I am looking for. + +I actually want to open Streetview camera directly from my app so I can take a panoramic photo. + +My actual task is to develop a camera app that can take panoramic images but I couldn't find anything for that, So I am working on things can be done instead of camera app like cardboard. +Here is the link to the question that I had asked earlier- [App to capture 360 View android](https://stackoverflow.com/questions/49249886/app-to-capture-360-view-android) + +Please help in this!",2018/03/14,"['https://Stackoverflow.com/questions/49276120', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6492719/']","u are using python 3.6 . +so +pip3 install numpy +should be used, make a try .","Was having a similar problem on Ubuntu 18.04. +Solved the issue by using `python3.7` and `pip3.7`. + +Its important to use `pip3.7` when installing the packages, like `pip3.7 install numpy` or `pip3.7 install numpy --user` + +To install `python3.7` and `pip3.7` on Ubuntu you can use `deadsnakes/ppa` + +``` +sudo add-apt-repository ppa:deadsnakes/ppa +sudo apt-get update +sudo apt-get install python3.7 + +curl https://bootstrap.pypa.io/get-pip.py -o /tmp/get-pip.py +python3.7 /tmp/get-pip.py + +``` + +This solution should also work on Ubuntu 16.04." +37541683,"Well, OpenCv comes with its function findCheckerboardCorners() in C++ which goes like + +``` +bool findChessboardCorners(InputArray image, Size patternSize, +OutputArray corners, +int flags=CALIB_CB_ADAPTIVE_THRESH+CALIB_CB_NORMALIZE_IMAGE ) + +``` + +After using this function for a while, one thing that i understood was that the pattern size must comply with the image to a very good extent, else the algorithm refuses to detect any Chessboard altogether. I was wondering if there were any random image of a chessboard, this function would fail as it is impractical to enter the precise values of the patternSize. Is there a way, the patternSize for this function could be obtained from the image provided. Any help would be appreciated. Thanks.",2016/05/31,"['https://Stackoverflow.com/questions/37541683', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4633925/']","Short answer: you cannot. + +The OpenCV checkerboard detection code assumes that the pattern is uniform (all squares have the same size) and therefore, in order to uniquely locate its position in the image, the following two conditions must be true: + +1. The pattern is entirely visible. +2. The pattern has a known numbers of rows and columns. + +If either 1 or 2 is violated there is no way to know which corner is, say, the ""top left"" one. + +For a more general case, and in particular if you anticipate that the pattern may be partially occluded, you must use a different algorithm and a non-uniform pattern, upon which corners can be uniquely identified. + +There are various way to do that. My favorite pattern is Matsunaga and Kanatani's ""2D barcode"" one, which uses sequences of square lengths with unique crossratios. See the paper [here](https://www.semanticscholar.org/paper/Optimal-Grid-Pattern-for-Automated-Matching-Using-Matsunaga-Kanatani/8c57a5a20eaf9d8d0f16faa2153a80003ef50cdb). In order to match it, once you have sorted the corners into a grid, you can use a simple majority voting algorithm: + +* Precompute the crossratios of all the pattern's consecutive 4-tuples of corners, in both the horizontal and vertical directions. +* Do the above for the detected corners in the grid. +* For every possible horizontal shift + + Over every row + - Accumulate the number of crossratios that agree within a threshold +* Select the horizontal shift with the highest number of agreements. +* Repeat the above for every possible vertical shift, counting crossratios along the columns. +* Repeat the above two steps reversing the order of the crossratios in the vertical and horizontal and vertical direction, separately and jointly, to account for reflections and rotations. + +Placing the detected corners in a grid can be achieved in various ways. There is an often-rediscovered [algorithm](https://somelightprojections.blogspot.com/2016/06/checkerboards.html) that uses topological proximity. The idea is to first associate each corner to all the squares within a small window of it, thus building a corner->squares table, and then traverse it as a graph to build a global table of the offsets of each corner from one another.","The doc for [`findChessboardCorners`](http://docs.opencv.org/3.0.0/d9/d0c/group__calib3d.html#ga93efa9b0aa890de240ca32b11253dd4a) says that + +> +> `patternSize` – Number of inner corners per a chessboard row and +> column +> +> +> + +So `patternSize` is not the size of the chessboard inside the image but the number of inner corners. The number of inner corners does not depend from the size of the chessboard inside the image. + +For example for the following image +[![enter image description here](https://i.stack.imgur.com/4Tnr6.png)](https://i.stack.imgur.com/4Tnr6.png) +`patternSize` should be `cv::Size(7,7)`." +1427602,"Can we show an image in its original size in MATLAB? + +Right now when we are showing, it is exactly fitted to the image window size. However, I want to show the image in its original size. When the image is of larger size, a scroll bar should appear in the image window. This would allow the user to view the image in its original size. + +Any ideas on how to achieve this? Is this possible?",2009/09/15,"['https://Stackoverflow.com/questions/1427602', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']","try: + figure,imshow(your\_image), axis image +This changes the image axis to the original size","There are 3 things to take care of in order to display image in its original size (1:1): + +* The figure size and units. +* The axes size and units. +* The axes data aspect ratio. + +Once all of that are set according to the image size even using MATLAB's `image()` function one could generate 1:1 display of an image. + +Here is the sample code: + +``` +%% Load Data + +mI = imread('7572939538_04e373d8f4_z.jpg'); + +numRows = size(mI, 1); +numCols = size(mI, 2); + +%% Setings + +horMargin = 30; +verMargin = 60; % +> `truesize(fig)` adjusts the display size such that each image pixel covers one screen pixel. If you do not specify a figure, `truesize` adjusts the display size of the current figure. +> +> +>" +1427602,"Can we show an image in its original size in MATLAB? + +Right now when we are showing, it is exactly fitted to the image window size. However, I want to show the image in its original size. When the image is of larger size, a scroll bar should appear in the image window. This would allow the user to view the image in its original size. + +Any ideas on how to achieve this? Is this possible?",2009/09/15,"['https://Stackoverflow.com/questions/1427602', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']","Matlab slider has a problem that it fires callback only on MouseUp and not on MouseMove, so pure matlab implementation would always feels strange. + +Better way - go for Java in Matlab. So you do not have to re-implement whole scroll logics. You can put Java Swing GUI component inside Matlab window, it is not difficult at all. + +Specifically you have to use Swing `JScrollPane` Class. With Matlab `javacomponent()` function you can put it inside matlab window. + +There are tons of examples on the web on how to get image into scroll pane, just browse for `JScrollPane image`. You can use Java classes inside matlab with usual Matlab syntax (no need for `new` keyword, ecc.)","There are 3 things to take care of in order to display image in its original size (1:1): + +* The figure size and units. +* The axes size and units. +* The axes data aspect ratio. + +Once all of that are set according to the image size even using MATLAB's `image()` function one could generate 1:1 display of an image. + +Here is the sample code: + +``` +%% Load Data + +mI = imread('7572939538_04e373d8f4_z.jpg'); + +numRows = size(mI, 1); +numCols = size(mI, 2); + +%% Setings + +horMargin = 30; +verMargin = 60; % +> `truesize(fig)` adjusts the display size such that each image pixel covers one screen pixel. If you do not specify a figure, `truesize` adjusts the display size of the current figure. +> +> +>" +1427602,"Can we show an image in its original size in MATLAB? + +Right now when we are showing, it is exactly fitted to the image window size. However, I want to show the image in its original size. When the image is of larger size, a scroll bar should appear in the image window. This would allow the user to view the image in its original size. + +Any ideas on how to achieve this? Is this possible?",2009/09/15,"['https://Stackoverflow.com/questions/1427602', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']","I believe what you're looking for is the [IMTOOL](http://www.mathworks.com/access/helpdesk/help/toolbox/images/imtool.html) utility (which is a part of the [Image Processing Toolbox](http://www.mathworks.com/products/image/)). It's a MATLAB GUI that allows you to view images in their original size (100% magnification) with horizontal and vertical sliders. + +**EDIT:** + +The above solution will display your image in a new figure window (the IMTOOL GUI). If you don't want the image appearing in a new window, but instead want to adjust its size in a window of your own, it will be more difficult. To adjust the size of the image, which I assume you've displayed on a set of axes using the [IMAGE](http://www.mathworks.com/access/helpdesk/help/techdoc/ref/image.html) command, you will have to adjust a number of [axes properties](http://www.mathworks.com/access/helpdesk/help/techdoc/ref/axes_props.html) for the axes containing the image. The following are the properties you will likely end up modifying: + +* `'Units'`: This can be set to `'inches'`, `'centimeters'`, or `'pixels'`, for example. +* `'Position'`: This controls where the axes are placed in the figure window, in units governed by the `'Units'` property. +* `'DataAspectRatio'/'PlotBoxAspectRatio'`: These control the relative scaling of the axes and the surrounding plot box. +* `'XLim'/'YLim'`: The minimum and maximum values of the axes. + +After getting the size and scaling of the image to display the way you want, parts of the image could be outside the figure window area. Unfortunately, horizontal and vertical sliders *will not* be automatically added. You will have to create these slider controls yourself using the [UICONTROL](http://www.mathworks.com/access/helpdesk/help/techdoc/ref/uicontrol.html) function. You will have to write the callback functions for the slider controls such that they move the axes around in the window. + +If you choose to venture down the above path, here are a few links to GUI design tutorials that may help you: [a slider tutorial on blinkdagger](http://blinkdagger.com/matlab/matlab-gui-tutorial-slider/), [a blog post by Doug Hull](http://blogs.mathworks.com/videos/2009/08/06/gui-tutorials-from-the-file-exchange/), and [a video from Doug on GUIDE basics](http://www.mathworks.com/matlabcentral/fileexchange/7598).","This code from MATLAB's Answers forum creates a window where the image is shown at native resolution (100%), and also gives a ""navigation"" window showing where your viewed section of the image (in the main window) fits into the whole image. + +``` +% Create a scroll panel with a Magnification Box and an Overview tool. +hFig = figure('Toolbar','none',... + 'Menubar','none'); +hIm = imshow('saturn.png'); +hSP = imscrollpanel(hFig,hIm); % Handle to scroll panel. +set(hSP,'Units','normalized',... + 'Position',[0 .1 1 .9]) + +% Add a Magnification Box and an Overview tool. +hMagBox = immagbox(hFig,hIm); +pos = get(hMagBox,'Position'); +set(hMagBox,'Position',[0 0 pos(3) pos(4)]) +imoverview(hIm) + +``` + +([Forum post link](https://au.mathworks.com/matlabcentral/answers/151402-why-isn-t-truesize-working-properly))" +17735526,"I'm playing around with some code in a Kobold2D example project (Orthogonal Tile based Game) and I've noticed: + +``` +@interface TileMapLayer : CCLayer //Map +{ + float tileMapHeightInPixels; //depricated@interface TileMapLayer() +} +@end + +``` + +in the TileMapLayer.h file, and: + +``` +@interface TileMapLayer() +@property (strong) HUDLayer *hud; +@property (strong) CCTMXTiledMap *tileMap; +@property (strong) CCTMXLayer *background; +@property (strong) CCTMXLayer *foreground; +@property (strong) CCTMXLayer *meta; +@property (strong) CCTMXLayer *base; +@property (strong) CCSprite *player; +@property (strong) CCSprite *playerTurret; +@property (assign) int money; +@end + +``` + +in the TileMapLay.m file. + +I've always thought that `.h` files hold interfaces and `.m` files store implementations + +Can someone please explain their purpose (started from the basics, I'm still learning Objective C) and what the difference in purpose between the 2 examples above?",2013/07/18,"['https://Stackoverflow.com/questions/17735526', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']",What you put in a header and implementation file is entirely up to you. They all get concatenated by the preprocessor before compilation anyway. It's convention to put external interfaces that other compilation units might want to use into header files. The person who wrote your example code intends to keep all of those properties defined in the `.m` file private - that is they're intended to not be directly accessed by other code in the system.,Things defined in .h can be used by any .m files as long as the .m includes the .h. But things defined in .m can only be used in current .m file. +17735526,"I'm playing around with some code in a Kobold2D example project (Orthogonal Tile based Game) and I've noticed: + +``` +@interface TileMapLayer : CCLayer //Map +{ + float tileMapHeightInPixels; //depricated@interface TileMapLayer() +} +@end + +``` + +in the TileMapLayer.h file, and: + +``` +@interface TileMapLayer() +@property (strong) HUDLayer *hud; +@property (strong) CCTMXTiledMap *tileMap; +@property (strong) CCTMXLayer *background; +@property (strong) CCTMXLayer *foreground; +@property (strong) CCTMXLayer *meta; +@property (strong) CCTMXLayer *base; +@property (strong) CCSprite *player; +@property (strong) CCSprite *playerTurret; +@property (assign) int money; +@end + +``` + +in the TileMapLay.m file. + +I've always thought that `.h` files hold interfaces and `.m` files store implementations + +Can someone please explain their purpose (started from the basics, I'm still learning Objective C) and what the difference in purpose between the 2 examples above?",2013/07/18,"['https://Stackoverflow.com/questions/17735526', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']","First notice that `.m` are Objective-C files (which can have both Objective-C and C) and `.c` are plain C files which can only contain C code. Both employ the `.h` extension for the header. + +Regarding Objective-C, the `.m` file does `@interface TileMapLayer()` to declare a class *extension*. A class *extension* can add ivars and properties to a Class that was already declared in the `.h` file. An extension is only viewable from within its own `.m` file. It doesn't make much sense to declare an extension inside an `.h` file, but I guess you could if you wanted. + +Regarding purpose, a recommended practice is declaring the minimum amount of properties needed in the `.h` in order to keep the interface lean and clean. For properties that are only needed inside the class, you can declare them in the extension on the `.m` file. My personal preference is to avoid explicitly declaring and using ivars at all (unless I'm overriding a property setter or getter), because that way on the implementation I can tell at first glance which variables are local to the function or object properties. The overhead is usually negligible and I prefer to code for readability than to prematurely optimize. With the recently introduced auto-synthesized properties this saves a lot of boilerplate code as well. + +A strategy that I also recommend is thinking carefully which properties should be modifiable from outside the object or not. Declare the non-modifiable properties as `readonly` in the `.h` files. Then, you can re-declare them as `readwrite` in the `.m` *extension* for operations from the object itself. This ensures that you or your colleagues don't commit the mistake and modify a `readonly` property that is not supposed to change from outside the object. In a sense it helps you in keeping the logic of the object inside it. I would try to avoid the trap of declaring everything `readwrite` (the default), because then it usually comes to bite you back later.",Things defined in .h can be used by any .m files as long as the .m includes the .h. But things defined in .m can only be used in current .m file. +28699,"The description in the book describes touching the right hand in front of the left foot while the right leg goes up, then says to repeat it with the left hand going down, and that you've completed one rep when you've done that. Then, it says to switch legs. So, when doing ladders (1 rep, then 2 reps, then 3 reps, etc), is one to do the right leg twice as one rep, then do left twice, right twice as the second two reps, and so on? Or is ""one rep"" supposed to be twice on the right and twice on the left? + +I would consult his website, but [the forum](https://www.marklauren.com/forum/) seems to perpetually be down.",2016/01/19,"['https://fitness.stackexchange.com/questions/28699', 'https://fitness.stackexchange.com', 'https://fitness.stackexchange.com/users/8039/']","Do not regret this break from your weightlifting and take the opportunity to become an even better weightlifter. + +The trainers I have had, most often has used about half of the workout for yoga exercises to improve flexibility, range, mobility and core strength. +Exercises like over-the-head-squats demands extremely high flexibility. + +You can highly improve quality of your squats by doing air squats in front of a mirror. + +You can improve your core strength and stability far beyond what you think is possible just by doing functional training and calisthenics - without any equipment. + +If you can afford a little for a smaller device, I will definitely recommend you a cheap suspension-trainer aka TRX (cheap ones are as good as the expensive ones), which you easily can attach to a door, and sliding exercises like this: +You can just use floor-cloths for sliding exercises. I use to do so. + +If you dare to try advanced exercises, Switch ball can take your weightlifting to the next level, but I recommends proper instructions. + +If you have room for more than that, then get inspiration from crossfit and use sandbags (or water bags), tires, logs, etc. as weights.","Training is in essence applying force to a resistance. How that resistance looks like is just limited to your imagination. + +* The World is your gym (phrase stolen from Ross Enamait) +go out and train outside in fresh air, you can do pull-ups, chin-ups, dips on trees or monkey bars on playgrounds, using heavy stones, barrels or kegs for overhead lifting or deadlifts or big logs. +Running up hills for conditioning is an challenging task... too. +* You are your own Gym (phrase stolen from a title of a bodyweight training program od a farmer navy seal - Mark Lauren) you can do bodyweight exercises in addition or just alone, there are some outstanding programs outhere. I recommend: Never Gymless-Ross Enamait, YAYOG - Mark Lauren or Convict Conditioning by Paul Wade. +* Make your own gym: +Depending on your Budget and available space for training you could build some of the tools on your own, here is some Information on custom created tools like bulgarian bags, sandbags, gymnastic rings, trx bands and kettle-dumbells. + + +now go do something..." +28699,"The description in the book describes touching the right hand in front of the left foot while the right leg goes up, then says to repeat it with the left hand going down, and that you've completed one rep when you've done that. Then, it says to switch legs. So, when doing ladders (1 rep, then 2 reps, then 3 reps, etc), is one to do the right leg twice as one rep, then do left twice, right twice as the second two reps, and so on? Or is ""one rep"" supposed to be twice on the right and twice on the left? + +I would consult his website, but [the forum](https://www.marklauren.com/forum/) seems to perpetually be down.",2016/01/19,"['https://fitness.stackexchange.com/questions/28699', 'https://fitness.stackexchange.com', 'https://fitness.stackexchange.com/users/8039/']","Do not regret this break from your weightlifting and take the opportunity to become an even better weightlifter. + +The trainers I have had, most often has used about half of the workout for yoga exercises to improve flexibility, range, mobility and core strength. +Exercises like over-the-head-squats demands extremely high flexibility. + +You can highly improve quality of your squats by doing air squats in front of a mirror. + +You can improve your core strength and stability far beyond what you think is possible just by doing functional training and calisthenics - without any equipment. + +If you can afford a little for a smaller device, I will definitely recommend you a cheap suspension-trainer aka TRX (cheap ones are as good as the expensive ones), which you easily can attach to a door, and sliding exercises like this: +You can just use floor-cloths for sliding exercises. I use to do so. + +If you dare to try advanced exercises, Switch ball can take your weightlifting to the next level, but I recommends proper instructions. + +If you have room for more than that, then get inspiration from crossfit and use sandbags (or water bags), tires, logs, etc. as weights.","If you consider yourself handy then you could consider building some weightlifting equipment yourself. It is cheap and surprisingly simple. + +Although I do recommend that you do buy the barbell since making one out of wood or other common materials would be considerably weaker or larger if you try to maintain the same strength. + +[Buff Dudes](https://www.youtube.com/channel/UCKf0UqBiCQI4Ol0To9V0pKQ) have a Youtube channel where sometimes *Buff Dad* has tutorials on how to make Gym Equipment. [This](https://www.youtube.com/watch?v=6dy5eyMDt3c) is an example for a power rack. I've found that the procedure is quite simple and doesn't require any advanced tools. The material is mostly wood so it is very cheap. + +As for weight plates, there are again many tutorials on Youtube ([this one](https://www.youtube.com/watch?v=EpwewKou_R0) for example) where people show you how to make weight plates from concrete. It's about $5 for a 25kg bag of concrete, so you could make ~30kg (some water is retained from curing, I'm not sure how much) of weight plates for only the cost of a bag and a mould which would be less than $5. + +Although it would take a considerable amount of time you could build yourself a home gym for a couple of hundred dollars." +28699,"The description in the book describes touching the right hand in front of the left foot while the right leg goes up, then says to repeat it with the left hand going down, and that you've completed one rep when you've done that. Then, it says to switch legs. So, when doing ladders (1 rep, then 2 reps, then 3 reps, etc), is one to do the right leg twice as one rep, then do left twice, right twice as the second two reps, and so on? Or is ""one rep"" supposed to be twice on the right and twice on the left? + +I would consult his website, but [the forum](https://www.marklauren.com/forum/) seems to perpetually be down.",2016/01/19,"['https://fitness.stackexchange.com/questions/28699', 'https://fitness.stackexchange.com', 'https://fitness.stackexchange.com/users/8039/']","Training is in essence applying force to a resistance. How that resistance looks like is just limited to your imagination. + +* The World is your gym (phrase stolen from Ross Enamait) +go out and train outside in fresh air, you can do pull-ups, chin-ups, dips on trees or monkey bars on playgrounds, using heavy stones, barrels or kegs for overhead lifting or deadlifts or big logs. +Running up hills for conditioning is an challenging task... too. +* You are your own Gym (phrase stolen from a title of a bodyweight training program od a farmer navy seal - Mark Lauren) you can do bodyweight exercises in addition or just alone, there are some outstanding programs outhere. I recommend: Never Gymless-Ross Enamait, YAYOG - Mark Lauren or Convict Conditioning by Paul Wade. +* Make your own gym: +Depending on your Budget and available space for training you could build some of the tools on your own, here is some Information on custom created tools like bulgarian bags, sandbags, gymnastic rings, trx bands and kettle-dumbells. + + +now go do something...","Lifting>family + +but really, you might be able to find a place to do chinups in a park or on a tree or something, it's one of the best exercises to do. Maybe you can buy a metal bar from a hardware store and make a chinup station yourself. Dips are also great. Other than that you can start a running routine." +28699,"The description in the book describes touching the right hand in front of the left foot while the right leg goes up, then says to repeat it with the left hand going down, and that you've completed one rep when you've done that. Then, it says to switch legs. So, when doing ladders (1 rep, then 2 reps, then 3 reps, etc), is one to do the right leg twice as one rep, then do left twice, right twice as the second two reps, and so on? Or is ""one rep"" supposed to be twice on the right and twice on the left? + +I would consult his website, but [the forum](https://www.marklauren.com/forum/) seems to perpetually be down.",2016/01/19,"['https://fitness.stackexchange.com/questions/28699', 'https://fitness.stackexchange.com', 'https://fitness.stackexchange.com/users/8039/']","If you consider yourself handy then you could consider building some weightlifting equipment yourself. It is cheap and surprisingly simple. + +Although I do recommend that you do buy the barbell since making one out of wood or other common materials would be considerably weaker or larger if you try to maintain the same strength. + +[Buff Dudes](https://www.youtube.com/channel/UCKf0UqBiCQI4Ol0To9V0pKQ) have a Youtube channel where sometimes *Buff Dad* has tutorials on how to make Gym Equipment. [This](https://www.youtube.com/watch?v=6dy5eyMDt3c) is an example for a power rack. I've found that the procedure is quite simple and doesn't require any advanced tools. The material is mostly wood so it is very cheap. + +As for weight plates, there are again many tutorials on Youtube ([this one](https://www.youtube.com/watch?v=EpwewKou_R0) for example) where people show you how to make weight plates from concrete. It's about $5 for a 25kg bag of concrete, so you could make ~30kg (some water is retained from curing, I'm not sure how much) of weight plates for only the cost of a bag and a mould which would be less than $5. + +Although it would take a considerable amount of time you could build yourself a home gym for a couple of hundred dollars.","Get a pullup/chinup bar. You can get one for about $20. + +Buy a couple of parallel bars where you can do dips. If you have a couple of sturdy chairs, they will do. + +Pullups, chinups, dips, pushups, planks, bodyweight squats are all great exercises that could make up for a very decent routine." +28699,"The description in the book describes touching the right hand in front of the left foot while the right leg goes up, then says to repeat it with the left hand going down, and that you've completed one rep when you've done that. Then, it says to switch legs. So, when doing ladders (1 rep, then 2 reps, then 3 reps, etc), is one to do the right leg twice as one rep, then do left twice, right twice as the second two reps, and so on? Or is ""one rep"" supposed to be twice on the right and twice on the left? + +I would consult his website, but [the forum](https://www.marklauren.com/forum/) seems to perpetually be down.",2016/01/19,"['https://fitness.stackexchange.com/questions/28699', 'https://fitness.stackexchange.com', 'https://fitness.stackexchange.com/users/8039/']","If you consider yourself handy then you could consider building some weightlifting equipment yourself. It is cheap and surprisingly simple. + +Although I do recommend that you do buy the barbell since making one out of wood or other common materials would be considerably weaker or larger if you try to maintain the same strength. + +[Buff Dudes](https://www.youtube.com/channel/UCKf0UqBiCQI4Ol0To9V0pKQ) have a Youtube channel where sometimes *Buff Dad* has tutorials on how to make Gym Equipment. [This](https://www.youtube.com/watch?v=6dy5eyMDt3c) is an example for a power rack. I've found that the procedure is quite simple and doesn't require any advanced tools. The material is mostly wood so it is very cheap. + +As for weight plates, there are again many tutorials on Youtube ([this one](https://www.youtube.com/watch?v=EpwewKou_R0) for example) where people show you how to make weight plates from concrete. It's about $5 for a 25kg bag of concrete, so you could make ~30kg (some water is retained from curing, I'm not sure how much) of weight plates for only the cost of a bag and a mould which would be less than $5. + +Although it would take a considerable amount of time you could build yourself a home gym for a couple of hundred dollars.",[Gymnastic Strength Training](https://www.gymnasticbodies.com/) is a perfect option for you in my opinion. It is very well designed program with tons of progressions and requires almost negligible equipment. +28699,"The description in the book describes touching the right hand in front of the left foot while the right leg goes up, then says to repeat it with the left hand going down, and that you've completed one rep when you've done that. Then, it says to switch legs. So, when doing ladders (1 rep, then 2 reps, then 3 reps, etc), is one to do the right leg twice as one rep, then do left twice, right twice as the second two reps, and so on? Or is ""one rep"" supposed to be twice on the right and twice on the left? + +I would consult his website, but [the forum](https://www.marklauren.com/forum/) seems to perpetually be down.",2016/01/19,"['https://fitness.stackexchange.com/questions/28699', 'https://fitness.stackexchange.com', 'https://fitness.stackexchange.com/users/8039/']","Do not regret this break from your weightlifting and take the opportunity to become an even better weightlifter. + +The trainers I have had, most often has used about half of the workout for yoga exercises to improve flexibility, range, mobility and core strength. +Exercises like over-the-head-squats demands extremely high flexibility. + +You can highly improve quality of your squats by doing air squats in front of a mirror. + +You can improve your core strength and stability far beyond what you think is possible just by doing functional training and calisthenics - without any equipment. + +If you can afford a little for a smaller device, I will definitely recommend you a cheap suspension-trainer aka TRX (cheap ones are as good as the expensive ones), which you easily can attach to a door, and sliding exercises like this: +You can just use floor-cloths for sliding exercises. I use to do so. + +If you dare to try advanced exercises, Switch ball can take your weightlifting to the next level, but I recommends proper instructions. + +If you have room for more than that, then get inspiration from crossfit and use sandbags (or water bags), tires, logs, etc. as weights.","Get a pullup/chinup bar. You can get one for about $20. + +Buy a couple of parallel bars where you can do dips. If you have a couple of sturdy chairs, they will do. + +Pullups, chinups, dips, pushups, planks, bodyweight squats are all great exercises that could make up for a very decent routine." +28699,"The description in the book describes touching the right hand in front of the left foot while the right leg goes up, then says to repeat it with the left hand going down, and that you've completed one rep when you've done that. Then, it says to switch legs. So, when doing ladders (1 rep, then 2 reps, then 3 reps, etc), is one to do the right leg twice as one rep, then do left twice, right twice as the second two reps, and so on? Or is ""one rep"" supposed to be twice on the right and twice on the left? + +I would consult his website, but [the forum](https://www.marklauren.com/forum/) seems to perpetually be down.",2016/01/19,"['https://fitness.stackexchange.com/questions/28699', 'https://fitness.stackexchange.com', 'https://fitness.stackexchange.com/users/8039/']","Do not regret this break from your weightlifting and take the opportunity to become an even better weightlifter. + +The trainers I have had, most often has used about half of the workout for yoga exercises to improve flexibility, range, mobility and core strength. +Exercises like over-the-head-squats demands extremely high flexibility. + +You can highly improve quality of your squats by doing air squats in front of a mirror. + +You can improve your core strength and stability far beyond what you think is possible just by doing functional training and calisthenics - without any equipment. + +If you can afford a little for a smaller device, I will definitely recommend you a cheap suspension-trainer aka TRX (cheap ones are as good as the expensive ones), which you easily can attach to a door, and sliding exercises like this: +You can just use floor-cloths for sliding exercises. I use to do so. + +If you dare to try advanced exercises, Switch ball can take your weightlifting to the next level, but I recommends proper instructions. + +If you have room for more than that, then get inspiration from crossfit and use sandbags (or water bags), tires, logs, etc. as weights.","Lifting>family + +but really, you might be able to find a place to do chinups in a park or on a tree or something, it's one of the best exercises to do. Maybe you can buy a metal bar from a hardware store and make a chinup station yourself. Dips are also great. Other than that you can start a running routine." +28699,"The description in the book describes touching the right hand in front of the left foot while the right leg goes up, then says to repeat it with the left hand going down, and that you've completed one rep when you've done that. Then, it says to switch legs. So, when doing ladders (1 rep, then 2 reps, then 3 reps, etc), is one to do the right leg twice as one rep, then do left twice, right twice as the second two reps, and so on? Or is ""one rep"" supposed to be twice on the right and twice on the left? + +I would consult his website, but [the forum](https://www.marklauren.com/forum/) seems to perpetually be down.",2016/01/19,"['https://fitness.stackexchange.com/questions/28699', 'https://fitness.stackexchange.com', 'https://fitness.stackexchange.com/users/8039/']","Get a pullup/chinup bar. You can get one for about $20. + +Buy a couple of parallel bars where you can do dips. If you have a couple of sturdy chairs, they will do. + +Pullups, chinups, dips, pushups, planks, bodyweight squats are all great exercises that could make up for a very decent routine.","Lifting>family + +but really, you might be able to find a place to do chinups in a park or on a tree or something, it's one of the best exercises to do. Maybe you can buy a metal bar from a hardware store and make a chinup station yourself. Dips are also great. Other than that you can start a running routine." +28699,"The description in the book describes touching the right hand in front of the left foot while the right leg goes up, then says to repeat it with the left hand going down, and that you've completed one rep when you've done that. Then, it says to switch legs. So, when doing ladders (1 rep, then 2 reps, then 3 reps, etc), is one to do the right leg twice as one rep, then do left twice, right twice as the second two reps, and so on? Or is ""one rep"" supposed to be twice on the right and twice on the left? + +I would consult his website, but [the forum](https://www.marklauren.com/forum/) seems to perpetually be down.",2016/01/19,"['https://fitness.stackexchange.com/questions/28699', 'https://fitness.stackexchange.com', 'https://fitness.stackexchange.com/users/8039/']","If you consider yourself handy then you could consider building some weightlifting equipment yourself. It is cheap and surprisingly simple. + +Although I do recommend that you do buy the barbell since making one out of wood or other common materials would be considerably weaker or larger if you try to maintain the same strength. + +[Buff Dudes](https://www.youtube.com/channel/UCKf0UqBiCQI4Ol0To9V0pKQ) have a Youtube channel where sometimes *Buff Dad* has tutorials on how to make Gym Equipment. [This](https://www.youtube.com/watch?v=6dy5eyMDt3c) is an example for a power rack. I've found that the procedure is quite simple and doesn't require any advanced tools. The material is mostly wood so it is very cheap. + +As for weight plates, there are again many tutorials on Youtube ([this one](https://www.youtube.com/watch?v=EpwewKou_R0) for example) where people show you how to make weight plates from concrete. It's about $5 for a 25kg bag of concrete, so you could make ~30kg (some water is retained from curing, I'm not sure how much) of weight plates for only the cost of a bag and a mould which would be less than $5. + +Although it would take a considerable amount of time you could build yourself a home gym for a couple of hundred dollars.","Training is in essence applying force to a resistance. How that resistance looks like is just limited to your imagination. + +* The World is your gym (phrase stolen from Ross Enamait) +go out and train outside in fresh air, you can do pull-ups, chin-ups, dips on trees or monkey bars on playgrounds, using heavy stones, barrels or kegs for overhead lifting or deadlifts or big logs. +Running up hills for conditioning is an challenging task... too. +* You are your own Gym (phrase stolen from a title of a bodyweight training program od a farmer navy seal - Mark Lauren) you can do bodyweight exercises in addition or just alone, there are some outstanding programs outhere. I recommend: Never Gymless-Ross Enamait, YAYOG - Mark Lauren or Convict Conditioning by Paul Wade. +* Make your own gym: +Depending on your Budget and available space for training you could build some of the tools on your own, here is some Information on custom created tools like bulgarian bags, sandbags, gymnastic rings, trx bands and kettle-dumbells. + + +now go do something..." +28699,"The description in the book describes touching the right hand in front of the left foot while the right leg goes up, then says to repeat it with the left hand going down, and that you've completed one rep when you've done that. Then, it says to switch legs. So, when doing ladders (1 rep, then 2 reps, then 3 reps, etc), is one to do the right leg twice as one rep, then do left twice, right twice as the second two reps, and so on? Or is ""one rep"" supposed to be twice on the right and twice on the left? + +I would consult his website, but [the forum](https://www.marklauren.com/forum/) seems to perpetually be down.",2016/01/19,"['https://fitness.stackexchange.com/questions/28699', 'https://fitness.stackexchange.com', 'https://fitness.stackexchange.com/users/8039/']",[Gymnastic Strength Training](https://www.gymnasticbodies.com/) is a perfect option for you in my opinion. It is very well designed program with tons of progressions and requires almost negligible equipment.,"Lifting>family + +but really, you might be able to find a place to do chinups in a park or on a tree or something, it's one of the best exercises to do. Maybe you can buy a metal bar from a hardware store and make a chinup station yourself. Dips are also great. Other than that you can start a running routine." +25834234,"I have a `p:datagrid` that contain some offers + +inside the `p:datagrid` there is a `p:commandLink` that will pass offer and redirect to onther page + +this is my xhtml + +``` + + + + + + + + +``` + +this is my bean + +``` +@SessionScoped +public class NavigationBean implements Serializable { + public String ToMore() { + return ""/more.xhtml?faces-redirect=true""; + } +} + +``` + +The problem is when click on the commandLink it only refresh the page",2014/09/14,"['https://Stackoverflow.com/questions/25834234', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3982495/']","(Copied from Answer, so (c) @naifsami) + +I Solved the problem by workarround idea by using p:remotecommand outside the table and call the remotecommand from inside the table + +``` + + + + + + + + +``` + +my bean + +``` +public String ToMore() { + String offerid=""""; + FacesContext context = FacesContext.getCurrentInstance(); + Map map = context.getExternalContext().getRequestParameterMap(); + offerid=(String) map.get(""n""); + offer1= newOfferServices.OfferByNumber(Integer.parseInt(offerid)); + setOffer(offer1); + return ""/more.xhtml?faces-redirect=true""; + } + +```","You should get the desired result by navigating through the outcome attribute. + +```html + + + + +```" +68377604,Im just beginner in Swift Development. I don't know how to remove the .isSelected when the user choose the other button,2021/07/14,"['https://Stackoverflow.com/questions/68377604', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/15285622/']","Looking at the pattern that you tried, you could match using a capture group for the part after the first curly. + +``` +\{(\{.*?}}) + +``` + +And replace with + +``` +{​$1 + +``` + +See a [regex demo](https://regex101.com/r/XJ9wdP/1) and a [Java demo](https://ideone.com/tdRXau) + +Example code + +``` +String regex = ""\\{(\\{.*?\\}\\})""; +String string = ""{{ interface_ID }} THERE SHOU{{interface_ID}}LD BE CODE HERE: {{interface_ID}}""; + +Pattern pattern = Pattern.compile(regex); +Matcher matcher = pattern.matcher(string); + +System.out.println(matcher.replaceAll(""{​$1"")); + +``` + +Output + +``` +{​{ interface_ID }} THERE SHOU{​{interface_ID}}LD BE CODE HERE: {​{interface_ID}} + +```","``` +Pattern CURLY_BRACKETS_PLACEHOLDER = Pattern.compile(""\\{\\{(.*?)\\}\\}""); +Matcher m = CURLY_BRACKETS_PLACEHOLDER.matcher(htmlString); +while(m.find()) { + String script = m.group(1); + String scriptWithPlaceholder = ""{{""+script+""}}""; + String replacementToken = ""{""+ ZERO_WIDTH_SPACE_CHARACTER +""{""+script+""}}""; + htmlString = htmlString.replace(scriptWithPlaceholder, replacementToken); +} +return htmlString; + +```" +181623,"Does the first syllable rhyme with “glow” or with “how”? It is no use appealing to the Hindi for “Little Frog” or anything else, since Kipling confessed to making it up of whole cloth, as I discovered after asking a local Hindi speaker who drew a total blank. The question comes down to what sound Kipling meant to suggest by the spelling “ow,” which is hard to figure out, given that homograph pairs like “row” (quarrel vs. line of something) and “bow” (loopy knot or gesture of deference) straddle the difference in question. I know Disney’s film made the first syllable rhyme with “glow,” but I concede to Disney no authority in the matter whatsoever. I used to have access to an LP phonograph disk of Boris Karloff reading aloud, which would be better as authority, but alas I cannot remember how he pronounced the name.",2014/07/01,"['https://english.stackexchange.com/questions/181623', 'https://english.stackexchange.com', 'https://english.stackexchange.com/users/76878/']","It actually appears that the way it is pronounced may be different. + +The Name [Mowgli](http://en.m.wikipedia.org/wiki/Mowgli#The_Name_Mowgli): + +> +> In the stories, the name Mowgli is said to mean ""frog"". Kipling made up the name, and it ""does not mean 'frog' in any language other than the language of the forest."" +> +> +> Kipling stated that the first syllable of ""Mowgli"" should rhyme with ""cow"" and is pronounced this way in Britain, while in America and India it is almost always pronounced to rhyme with ""go"". +> +> +>","Andrew Leach left a comment linking to a [Kipling Society web page](http://www.kiplingsociety.co.uk/rg_junglebook_names.htm) that says + +> +> *This list of names, their meanings, and pronunciation, was provided by Rudyard Kipling as an Author's Note for the definitive Sussex Edition of his works (Vol. X11, pages 471-8).* +> +> +> + +[...] + +> +> MOWGLI [...] is a name I made up. It does not mean. ‘frog’ in any language that I know of. It is pronounced *Mowglee* (accent on the *Mow*, which rhymes with 'cow'). +> +> +>" +41160023,"I don't get it why is this not working properly: + +[Fiddle](https://jsfiddle.net/ze5tsgy9/1/) + +I just want to show the tax amount but it gets `false` results. + +``` +// calculate brutto and tax +$(document).on('keyup paste', '#netto', function() { + var brutto = $(""#brutto"").val(); + var netto = $(""#netto"").val(); + $(""#brutto"").val(netto * 1.19); + $(""#tax"").val(brutto - netto); +}); + +```",2016/12/15,"['https://Stackoverflow.com/questions/41160023', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2502731/']","Please try following code : + +``` +// calculate brutto and tax +$(document).on('keyup paste', '#netto', function () { + + var brutto = $(""#brutto"").val(); + var netto = $(""#netto"").val(); + + $(""#brutto"").val(netto * 1.19); + + var brutto1 = $(""#brutto"").val(); + + $(""#tax"").val(brutto1 - netto); + +``` + +}); + +In your code the value of brutto is not updated in variable after new value (natto \* 1.19), so you gets false result. + +Thanks...","You need to validate the value of `brutto` element is a number before performing operation. the `+` operator is use to convert input to a number. + +``` +$(document).on('keyup paste', '#netto', function() { + var brutto = +$(""#brutto"").val() || 1; + var netto = +$(""#netto"").val() || 1; + brutto = netto * 1.19; + $(""#brutto"").val(brutto); + $(""#tax"").val(brutto - netto); +}); + +``` + +This will also be useful since the element is readonly. +[Updated Fiddle](https://jsfiddle.net/satpalsingh/ze5tsgy9/5/)" +41160023,"I don't get it why is this not working properly: + +[Fiddle](https://jsfiddle.net/ze5tsgy9/1/) + +I just want to show the tax amount but it gets `false` results. + +``` +// calculate brutto and tax +$(document).on('keyup paste', '#netto', function() { + var brutto = $(""#brutto"").val(); + var netto = $(""#netto"").val(); + $(""#brutto"").val(netto * 1.19); + $(""#tax"").val(brutto - netto); +}); + +```",2016/12/15,"['https://Stackoverflow.com/questions/41160023', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2502731/']","The problem is that you get the brutto value before filling it, the solution is to get `var brutto` after you calculate `$(""#brutto"").val(netto * 1.19)`: + +```js +// calculate brutto and tax +$(document).on('keyup paste', '#netto', function() { + var netto = +$(""#netto"").val(); + $(""#brutto"").val(netto * 1.19); + var brutto = +$(""#brutto"").val(); + $(""#tax"").val(brutto - netto); +}); +``` + +```html + +
+ + +
+
+ + +
+
+ + +
+```","You need to validate the value of `brutto` element is a number before performing operation. the `+` operator is use to convert input to a number. + +``` +$(document).on('keyup paste', '#netto', function() { + var brutto = +$(""#brutto"").val() || 1; + var netto = +$(""#netto"").val() || 1; + brutto = netto * 1.19; + $(""#brutto"").val(brutto); + $(""#tax"").val(brutto - netto); +}); + +``` + +This will also be useful since the element is readonly. +[Updated Fiddle](https://jsfiddle.net/satpalsingh/ze5tsgy9/5/)" +41160023,"I don't get it why is this not working properly: + +[Fiddle](https://jsfiddle.net/ze5tsgy9/1/) + +I just want to show the tax amount but it gets `false` results. + +``` +// calculate brutto and tax +$(document).on('keyup paste', '#netto', function() { + var brutto = $(""#brutto"").val(); + var netto = $(""#netto"").val(); + $(""#brutto"").val(netto * 1.19); + $(""#tax"").val(brutto - netto); +}); + +```",2016/12/15,"['https://Stackoverflow.com/questions/41160023', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2502731/']","Please try following code : + +``` +// calculate brutto and tax +$(document).on('keyup paste', '#netto', function () { + + var brutto = $(""#brutto"").val(); + var netto = $(""#netto"").val(); + + $(""#brutto"").val(netto * 1.19); + + var brutto1 = $(""#brutto"").val(); + + $(""#tax"").val(brutto1 - netto); + +``` + +}); + +In your code the value of brutto is not updated in variable after new value (natto \* 1.19), so you gets false result. + +Thanks...","Parse you strings to int, change the event to a input type event: + +``` + $(document).on('input', '#netto', function () { + + var brutto = parseInt($(""#brutto"").val()); + var netto = parseInt($(""#netto"").val()); + + $(""#brutto"").val(netto * 1.19); + $(""#tax"").val((netto * 1.19) - netto ); + +}); + +``` + +better if you go with a input type number so you don't have problems with invalid values + + +or: + + if you want to get rid of NaN when its empty" +41160023,"I don't get it why is this not working properly: + +[Fiddle](https://jsfiddle.net/ze5tsgy9/1/) + +I just want to show the tax amount but it gets `false` results. + +``` +// calculate brutto and tax +$(document).on('keyup paste', '#netto', function() { + var brutto = $(""#brutto"").val(); + var netto = $(""#netto"").val(); + $(""#brutto"").val(netto * 1.19); + $(""#tax"").val(brutto - netto); +}); + +```",2016/12/15,"['https://Stackoverflow.com/questions/41160023', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2502731/']","The problem is that you get the brutto value before filling it, the solution is to get `var brutto` after you calculate `$(""#brutto"").val(netto * 1.19)`: + +```js +// calculate brutto and tax +$(document).on('keyup paste', '#netto', function() { + var netto = +$(""#netto"").val(); + $(""#brutto"").val(netto * 1.19); + var brutto = +$(""#brutto"").val(); + $(""#tax"").val(brutto - netto); +}); +``` + +```html + +
+ + +
+
+ + +
+
+ + +
+```","Parse you strings to int, change the event to a input type event: + +``` + $(document).on('input', '#netto', function () { + + var brutto = parseInt($(""#brutto"").val()); + var netto = parseInt($(""#netto"").val()); + + $(""#brutto"").val(netto * 1.19); + $(""#tax"").val((netto * 1.19) - netto ); + +}); + +``` + +better if you go with a input type number so you don't have problems with invalid values + + +or: + + if you want to get rid of NaN when its empty" +41160023,"I don't get it why is this not working properly: + +[Fiddle](https://jsfiddle.net/ze5tsgy9/1/) + +I just want to show the tax amount but it gets `false` results. + +``` +// calculate brutto and tax +$(document).on('keyup paste', '#netto', function() { + var brutto = $(""#brutto"").val(); + var netto = $(""#netto"").val(); + $(""#brutto"").val(netto * 1.19); + $(""#tax"").val(brutto - netto); +}); + +```",2016/12/15,"['https://Stackoverflow.com/questions/41160023', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2502731/']","The problem is that you get the brutto value before filling it, the solution is to get `var brutto` after you calculate `$(""#brutto"").val(netto * 1.19)`: + +```js +// calculate brutto and tax +$(document).on('keyup paste', '#netto', function() { + var netto = +$(""#netto"").val(); + $(""#brutto"").val(netto * 1.19); + var brutto = +$(""#brutto"").val(); + $(""#tax"").val(brutto - netto); +}); +``` + +```html + +
+ + +
+
+ + +
+
+ + +
+```","Please try following code : + +``` +// calculate brutto and tax +$(document).on('keyup paste', '#netto', function () { + + var brutto = $(""#brutto"").val(); + var netto = $(""#netto"").val(); + + $(""#brutto"").val(netto * 1.19); + + var brutto1 = $(""#brutto"").val(); + + $(""#tax"").val(brutto1 - netto); + +``` + +}); + +In your code the value of brutto is not updated in variable after new value (natto \* 1.19), so you gets false result. + +Thanks..." +53911308,"In order to release my App in the Play Store, I had to change the `TargetSdkVersion` from `23` to `26`. +Before I changed it, the App worked perfectly! +Now the App crashes on start. +I figured out, that the problem was at these two lines: + +``` +prefs = getSharedPreferences(""de.bs.quicknoteblock.Notes"", Context.MODE_WORLD_WRITEABLE); + editor = prefs.edit(); + +``` + +Now my Question is, how I can use `SharedPreferences` with `Api-Level 26`",2018/12/24,"['https://Stackoverflow.com/questions/53911308', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10828450/']","`Context.MODE_WORLD_WRITEABLE` is deprecated, replace it with `Context.MODE_PRIVATE`","hi I think your problem is the SharedPreferences code please test this way + +> +> (maybe should change Context.MODE\_WORLD\_WRITEABLE to +> Context.MODE\_PRIVATE is work ! ) +> +> +> + +first please download this source code and add your project , [download](http://ufile.io/hapau) + +so after add you can use SharedPreferences so esay sample code : + +``` + // class A --- > save text in SharedPreferences + + new AppPreferenceTools(context, ""Share"") .savePreferences(""test"",""simple text""); + + // class B ---> read text as SharedPreferences + +String text = new AppPreferenceTools(context, ""Share"").getName(""test"",defultSTR); + +```" +66720402,"I'm trying to retrieve the most recent article on a blog. My current code below does not output anything. + +``` +{% for article in blogs['myblog'].articles.last %} + {{ article.title }} +{% endfor %} + +```",2021/03/20,"['https://Stackoverflow.com/questions/66720402', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13262682/']","You don't need a loop in order to access the last item. + +``` +{% assign article = blogs['myblog'].articles.last %} + +``` + +This will set `article` to the last item. You can then use it as expected. + +``` +{{ article.title }} + +``` + +Docs: ","It can be done like this using [forloop.last](https://shopify.dev/docs/themes/liquid/reference/objects/for-loops#forloop-last): + +``` +{% for article in blogs['myblog'].articles %} + {% if forloop.last == true %} + {{ article.title }} + {% endif %} +{% endfor %} + +``` + +This assumes that `blogs` is a variable. Otherwise, try replacing `blogs['myblog'].articles` with `blog.articles`." +47354108,"Could you please advise how + +``` +sudo su - userb + +``` + +translates into ansible ? + +More specifically, I would like to login to linux server X as `usera` then become `userb` (with the command above), and then execute all the tasks defined in the playbook as `userb` + +The following are configuration options in `ansible.cfg`: + +``` +sudo_user = root +#ask_sudo_pass = True +#ask_pass = True +#remote_user = root +#become=True +#become_method=sudo +#become_user=root +#become_ask_pass=False + +``` + +An example task would be: + +``` +- name: ""Create the version directory of app"" + remote_user: userb + file: path=""{{ app_dir }}/{{ app_version }}"" state=directory owner=userb group=xxx + +``` + +EDIT: please note that no sudo password is provided in order to become `userb` + +``` +usera@serverX:~> sudo su - userb +Last login: Fri Nov 17 15:46:48 CET 2017 on pts/1 +-bash-4.2$ + +```",2017/11/17,"['https://Stackoverflow.com/questions/47354108', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4035529/']","I do not believe this is possible without adding some extra state and interfaces to your BlockingQueue. + +Proof goes something like this. You want to wait until the reading thread is blocked on `pop`. But there is no way to distinguish between that and the thread being about to execute the `pop`. This remains true no matter what you put just before or after the call to `pop` itself. + +If you really want to fix this with 100% reliability, you need to add some state inside the queue, guarded by the queue's mutex, that means ""someone is waiting"". The `pop` call then has to update that state just before it atomically releases the mutex and goes to sleep on the internal condition variable. The `push` thread can obtain the mutex and wait until ""someone is waiting"". To avoid a busy loop here, you will want to use the condition variable again. + +All of this machinery is nearly as complicated as the queue itself, so maybe you will want to test it, too... This sort of multi-threaded code is where concepts like ""code coverage"" -- and arguably even unit testing itself -- break down a bit. There are just too many possible interleavings of operations. + +In practice, I would probably go with your original approach of sleeping.","You can use a `std::condition_variable` to accomplish this. The help page of cppreference.com actually shows a very nice cosumer-producer example which should be exactly what you are looking for: + +EDIT: Actually the german version of cppreference.com has an even better example :-) " +47354108,"Could you please advise how + +``` +sudo su - userb + +``` + +translates into ansible ? + +More specifically, I would like to login to linux server X as `usera` then become `userb` (with the command above), and then execute all the tasks defined in the playbook as `userb` + +The following are configuration options in `ansible.cfg`: + +``` +sudo_user = root +#ask_sudo_pass = True +#ask_pass = True +#remote_user = root +#become=True +#become_method=sudo +#become_user=root +#become_ask_pass=False + +``` + +An example task would be: + +``` +- name: ""Create the version directory of app"" + remote_user: userb + file: path=""{{ app_dir }}/{{ app_version }}"" state=directory owner=userb group=xxx + +``` + +EDIT: please note that no sudo password is provided in order to become `userb` + +``` +usera@serverX:~> sudo su - userb +Last login: Fri Nov 17 15:46:48 CET 2017 on pts/1 +-bash-4.2$ + +```",2017/11/17,"['https://Stackoverflow.com/questions/47354108', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4035529/']","``` +template +struct async_queue { + T pop() { + auto l = lock(); + ++wait_count; + cv.wait( l, [&]{ return !data.empty(); } ); + --wait_count; + auto r = std::move(data.front()); + data.pop_front(); + return r; + } + void push(T in) { + { + auto l = lock(); + data.push_back( std::move(in) ); + } + cv.notify_one(); + } + void push_many(std::initializer_list in) { + { + auto l = lock(); + for (auto&& x: in) + data.push_back( x ); + } + cv.notify_all(); + } + std::size_t readers_waiting() { + return wait_count; + } + std::size_t data_waiting() const { + auto l = lock(); + return data.size(); + } +private: + std::queue data; + std::condition_variable cv; + mutable std::mutex m; + std::atomic wait_count{0}; + auto lock() const { return std::unique_lock(m); } + +}; + +``` + +or somesuch. + +In the push thread, busy wait on `readers_waiting` until it passes 1. + +At which point you have the lock and are within `cv.wait` before the lock is unlocked. Do a `push`. + +In theory an infinitely slow reader thread could have gotten into `cv.wait` and still be evaluating the first lambda by the time you call `push`, but an infinitely slow reader thread is no different than a blocked one... + +This does, however, deal with slow thread startup and the like. + +Using `readers_waiting` and `data_waiting` for anything other than debugging is usually code smell.","You can use a `std::condition_variable` to accomplish this. The help page of cppreference.com actually shows a very nice cosumer-producer example which should be exactly what you are looking for: + +EDIT: Actually the german version of cppreference.com has an even better example :-) " +51161348,"I am in the process of translating some MATLAB code into Python. There is one line that is giving me a bit of trouble: + +``` +[q,f_dummy,exitflag, output] = quadprog(H,f,-A,zeros(p*N,1),E,qm,[],[],q0,options); + +``` + +I looked up the documentation in MATLAB to find that the quadprog function is used for optimization (particularly minimization). + +I attempted to find a similar function in Python (using numpy) and there does not seem to be any. + +Is there a better way to translate this line of code into Python? Or are there other packages that can be used? Do I need to make a new function that accomplishes the same task? + +Thanks for your time and help!",2018/07/03,"['https://Stackoverflow.com/questions/51161348', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9645799/']","There is a library called [CVXOPT](https://scaron.info/blog/quadratic-programming-in-python.html) that has quadratic programming in it. + +``` +def quadprog_solve_qp(P, q, G=None, h=None, A=None, b=None): + qp_G = .5 * (P + P.T) # make sure P is symmetric + qp_a = -q + if A is not None: + qp_C = -numpy.vstack([A, G]).T + qp_b = -numpy.hstack([b, h]) + meq = A.shape[0] + else: # no equality constraint + qp_C = -G.T + qp_b = -h + meq = 0 + return quadprog.solve_qp(qp_G, qp_a, qp_C, qp_b, meq)[0] + +```","[OSQP](https://osqp.org) is a specialized free QP solver based on ADMM. I have adapted the [OSQP documentation demo](http://osqp.org/docs/examples/demo.html) and the OSQP call in the [qpsolvers repository](https://github.com/stephane-caron/qpsolvers/blob/master/qpsolvers/osqp_.py) for your problem. + +Note that matrices `H` and `G` are supposed to be sparse in [CSC format](http://www.scipy-lectures.org/advanced/scipy_sparse/csc_matrix.html). Here is the script + +``` +import numpy as np +import scipy.sparse as spa +import osqp + +def quadprog(P, q, G=None, h=None, A=None, b=None, + initvals=None, verbose=True): + l = -np.inf * np.ones(len(h)) + if A is not None: + qp_A = spa.vstack([G, A]).tocsc() + qp_l = np.hstack([l, b]) + qp_u = np.hstack([h, b]) + else: # no equality constraint + qp_A = G + qp_l = l + qp_u = h + model = osqp.OSQP() + model.setup(P=P, q=q, + A=qp_A, l=qp_l, u=qp_u, verbose=verbose) + if initvals is not None: + model.warm_start(x=initvals) + results = model.solve() + return results.x, results.info.status + +# Generate problem data +n = 2 # Variables +H = spa.csc_matrix([[4, 1], [1, 2]]) +f = np.array([1, 1]) +G = spa.csc_matrix([[1, 0], [0, 1]]) +h = np.array([0.7, 0.7]) +A = spa.csc_matrix([[1, 1]]) +b = np.array([1.]) + +# Initial point +q0 = np.ones(n) + +x, status = quadprog(H, f, G, h, A, b, initvals=q0, verbose=True) + +```" +51161348,"I am in the process of translating some MATLAB code into Python. There is one line that is giving me a bit of trouble: + +``` +[q,f_dummy,exitflag, output] = quadprog(H,f,-A,zeros(p*N,1),E,qm,[],[],q0,options); + +``` + +I looked up the documentation in MATLAB to find that the quadprog function is used for optimization (particularly minimization). + +I attempted to find a similar function in Python (using numpy) and there does not seem to be any. + +Is there a better way to translate this line of code into Python? Or are there other packages that can be used? Do I need to make a new function that accomplishes the same task? + +Thanks for your time and help!",2018/07/03,"['https://Stackoverflow.com/questions/51161348', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9645799/']","There is a library called [CVXOPT](https://scaron.info/blog/quadratic-programming-in-python.html) that has quadratic programming in it. + +``` +def quadprog_solve_qp(P, q, G=None, h=None, A=None, b=None): + qp_G = .5 * (P + P.T) # make sure P is symmetric + qp_a = -q + if A is not None: + qp_C = -numpy.vstack([A, G]).T + qp_b = -numpy.hstack([b, h]) + meq = A.shape[0] + else: # no equality constraint + qp_C = -G.T + qp_b = -h + meq = 0 + return quadprog.solve_qp(qp_G, qp_a, qp_C, qp_b, meq)[0] + +```","I will start by mentioning that *quadratic programming* problems are a subset of *convex optimization* problems which are a subset of *optimization* problems. + +There are multiple python packages which solve quadratic programming problems, notably + +1. [cvxopt](https://cvxopt.org/userguide/coneprog.html#quadratic-programming) -- which solves all kinds of *convex optimization* problems (including quadratic programming problems). This is a python version of the previous [cvx MATLAB package](http://cvxr.com/cvx/). +2. [quadprog](https://github.com/rmcgibbo/quadprog) -- this is exclusively for quadratic programming problems but doesn't seem to have much documentation. +3. [scipy.optimize.minimize](https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize.html) -- this is a very general minimizer which can solve quadratic programming problems, as well as other *optimization* problems (convex and non-convex). + +You might also benefit from looking at the answers to [this stackoverflow post](https://stackoverflow.com/questions/17009774/quadratic-program-qp-solver-that-only-depends-on-numpy-scipy) which has more details and references. + +Note: The code snippet in user1911226' answer appears to come from this blog post: + +which compares some of these quadratic programming packages. I can't comment on their answer, but they claim to be mentioning the cvxopt solution, but the code is actually for the quadprog solution." +51161348,"I am in the process of translating some MATLAB code into Python. There is one line that is giving me a bit of trouble: + +``` +[q,f_dummy,exitflag, output] = quadprog(H,f,-A,zeros(p*N,1),E,qm,[],[],q0,options); + +``` + +I looked up the documentation in MATLAB to find that the quadprog function is used for optimization (particularly minimization). + +I attempted to find a similar function in Python (using numpy) and there does not seem to be any. + +Is there a better way to translate this line of code into Python? Or are there other packages that can be used? Do I need to make a new function that accomplishes the same task? + +Thanks for your time and help!",2018/07/03,"['https://Stackoverflow.com/questions/51161348', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9645799/']","There is a library called [CVXOPT](https://scaron.info/blog/quadratic-programming-in-python.html) that has quadratic programming in it. + +``` +def quadprog_solve_qp(P, q, G=None, h=None, A=None, b=None): + qp_G = .5 * (P + P.T) # make sure P is symmetric + qp_a = -q + if A is not None: + qp_C = -numpy.vstack([A, G]).T + qp_b = -numpy.hstack([b, h]) + meq = A.shape[0] + else: # no equality constraint + qp_C = -G.T + qp_b = -h + meq = 0 + return quadprog.solve_qp(qp_G, qp_a, qp_C, qp_b, meq)[0] + +```","You could use the [`solve_qp`](https://scaron.info/doc/qpsolvers/quadratic-programming.html#qpsolvers.solve_qp) function from [qpsolvers](https://github.com/stephane-caron/qpsolvers). It can be installed, along with a starter kit of open source solvers, by `pip install qpsolvers[open_source_solvers]`. Then you can replace your line with: + +```py +from qpsolvers import solve_qp + +solver = ""proxqp"" # or ""osqp"", ""quadprog"", ""cvxopt"", ... +x = solve_qp(H, f, G, h, A, b, initvals=q_0, solver=solver, **options) + +``` + +There are many solvers available in Python, each coming with their pros and cons. Make sure you try [different values](https://github.com/stephane-caron/qpsolvers#solvers) for the `solver` keyword argument to find the one that fits your problem best. + +Here is a standalone example based on your question and the other comments: + +```py +import numpy as np + +from qpsolvers import solve_qp + +H = np.array([[4.0, 1.0], [1.0, 2.0]]) +f = np.array([1.0, 1]) +G = np.array([[1.0, 0.0], [0.0, 1.0]]) +h = np.array([0.7, 0.7]) +A = np.array([[1.0, 1.0]]) +b = np.array([1.0]) +q_0 = np.array([1.0, 1.0]) + +solver = ""cvxopt"" # or ""osqp"", ""proxqp"", ""quadprog"", ... +options = {""verbose"": True} +x = solve_qp(H, f, G, h, A, b, initvals=q_0, solver=solver, **options) + +```" +51161348,"I am in the process of translating some MATLAB code into Python. There is one line that is giving me a bit of trouble: + +``` +[q,f_dummy,exitflag, output] = quadprog(H,f,-A,zeros(p*N,1),E,qm,[],[],q0,options); + +``` + +I looked up the documentation in MATLAB to find that the quadprog function is used for optimization (particularly minimization). + +I attempted to find a similar function in Python (using numpy) and there does not seem to be any. + +Is there a better way to translate this line of code into Python? Or are there other packages that can be used? Do I need to make a new function that accomplishes the same task? + +Thanks for your time and help!",2018/07/03,"['https://Stackoverflow.com/questions/51161348', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9645799/']","[OSQP](https://osqp.org) is a specialized free QP solver based on ADMM. I have adapted the [OSQP documentation demo](http://osqp.org/docs/examples/demo.html) and the OSQP call in the [qpsolvers repository](https://github.com/stephane-caron/qpsolvers/blob/master/qpsolvers/osqp_.py) for your problem. + +Note that matrices `H` and `G` are supposed to be sparse in [CSC format](http://www.scipy-lectures.org/advanced/scipy_sparse/csc_matrix.html). Here is the script + +``` +import numpy as np +import scipy.sparse as spa +import osqp + +def quadprog(P, q, G=None, h=None, A=None, b=None, + initvals=None, verbose=True): + l = -np.inf * np.ones(len(h)) + if A is not None: + qp_A = spa.vstack([G, A]).tocsc() + qp_l = np.hstack([l, b]) + qp_u = np.hstack([h, b]) + else: # no equality constraint + qp_A = G + qp_l = l + qp_u = h + model = osqp.OSQP() + model.setup(P=P, q=q, + A=qp_A, l=qp_l, u=qp_u, verbose=verbose) + if initvals is not None: + model.warm_start(x=initvals) + results = model.solve() + return results.x, results.info.status + +# Generate problem data +n = 2 # Variables +H = spa.csc_matrix([[4, 1], [1, 2]]) +f = np.array([1, 1]) +G = spa.csc_matrix([[1, 0], [0, 1]]) +h = np.array([0.7, 0.7]) +A = spa.csc_matrix([[1, 1]]) +b = np.array([1.]) + +# Initial point +q0 = np.ones(n) + +x, status = quadprog(H, f, G, h, A, b, initvals=q0, verbose=True) + +```","You could use the [`solve_qp`](https://scaron.info/doc/qpsolvers/quadratic-programming.html#qpsolvers.solve_qp) function from [qpsolvers](https://github.com/stephane-caron/qpsolvers). It can be installed, along with a starter kit of open source solvers, by `pip install qpsolvers[open_source_solvers]`. Then you can replace your line with: + +```py +from qpsolvers import solve_qp + +solver = ""proxqp"" # or ""osqp"", ""quadprog"", ""cvxopt"", ... +x = solve_qp(H, f, G, h, A, b, initvals=q_0, solver=solver, **options) + +``` + +There are many solvers available in Python, each coming with their pros and cons. Make sure you try [different values](https://github.com/stephane-caron/qpsolvers#solvers) for the `solver` keyword argument to find the one that fits your problem best. + +Here is a standalone example based on your question and the other comments: + +```py +import numpy as np + +from qpsolvers import solve_qp + +H = np.array([[4.0, 1.0], [1.0, 2.0]]) +f = np.array([1.0, 1]) +G = np.array([[1.0, 0.0], [0.0, 1.0]]) +h = np.array([0.7, 0.7]) +A = np.array([[1.0, 1.0]]) +b = np.array([1.0]) +q_0 = np.array([1.0, 1.0]) + +solver = ""cvxopt"" # or ""osqp"", ""proxqp"", ""quadprog"", ... +options = {""verbose"": True} +x = solve_qp(H, f, G, h, A, b, initvals=q_0, solver=solver, **options) + +```" +51161348,"I am in the process of translating some MATLAB code into Python. There is one line that is giving me a bit of trouble: + +``` +[q,f_dummy,exitflag, output] = quadprog(H,f,-A,zeros(p*N,1),E,qm,[],[],q0,options); + +``` + +I looked up the documentation in MATLAB to find that the quadprog function is used for optimization (particularly minimization). + +I attempted to find a similar function in Python (using numpy) and there does not seem to be any. + +Is there a better way to translate this line of code into Python? Or are there other packages that can be used? Do I need to make a new function that accomplishes the same task? + +Thanks for your time and help!",2018/07/03,"['https://Stackoverflow.com/questions/51161348', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9645799/']","I will start by mentioning that *quadratic programming* problems are a subset of *convex optimization* problems which are a subset of *optimization* problems. + +There are multiple python packages which solve quadratic programming problems, notably + +1. [cvxopt](https://cvxopt.org/userguide/coneprog.html#quadratic-programming) -- which solves all kinds of *convex optimization* problems (including quadratic programming problems). This is a python version of the previous [cvx MATLAB package](http://cvxr.com/cvx/). +2. [quadprog](https://github.com/rmcgibbo/quadprog) -- this is exclusively for quadratic programming problems but doesn't seem to have much documentation. +3. [scipy.optimize.minimize](https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize.html) -- this is a very general minimizer which can solve quadratic programming problems, as well as other *optimization* problems (convex and non-convex). + +You might also benefit from looking at the answers to [this stackoverflow post](https://stackoverflow.com/questions/17009774/quadratic-program-qp-solver-that-only-depends-on-numpy-scipy) which has more details and references. + +Note: The code snippet in user1911226' answer appears to come from this blog post: + +which compares some of these quadratic programming packages. I can't comment on their answer, but they claim to be mentioning the cvxopt solution, but the code is actually for the quadprog solution.","You could use the [`solve_qp`](https://scaron.info/doc/qpsolvers/quadratic-programming.html#qpsolvers.solve_qp) function from [qpsolvers](https://github.com/stephane-caron/qpsolvers). It can be installed, along with a starter kit of open source solvers, by `pip install qpsolvers[open_source_solvers]`. Then you can replace your line with: + +```py +from qpsolvers import solve_qp + +solver = ""proxqp"" # or ""osqp"", ""quadprog"", ""cvxopt"", ... +x = solve_qp(H, f, G, h, A, b, initvals=q_0, solver=solver, **options) + +``` + +There are many solvers available in Python, each coming with their pros and cons. Make sure you try [different values](https://github.com/stephane-caron/qpsolvers#solvers) for the `solver` keyword argument to find the one that fits your problem best. + +Here is a standalone example based on your question and the other comments: + +```py +import numpy as np + +from qpsolvers import solve_qp + +H = np.array([[4.0, 1.0], [1.0, 2.0]]) +f = np.array([1.0, 1]) +G = np.array([[1.0, 0.0], [0.0, 1.0]]) +h = np.array([0.7, 0.7]) +A = np.array([[1.0, 1.0]]) +b = np.array([1.0]) +q_0 = np.array([1.0, 1.0]) + +solver = ""cvxopt"" # or ""osqp"", ""proxqp"", ""quadprog"", ... +options = {""verbose"": True} +x = solve_qp(H, f, G, h, A, b, initvals=q_0, solver=solver, **options) + +```" +3554426,"I've started using [Code Contracts](http://msdn.microsoft.com/en-us/devlabs/dd491992.aspx) in all new code I'm writing, such as in a framework library I'm building to help bootstrap [IoC](http://en.wikipedia.org/wiki/Inversion_of_control), [O/RM](http://en.wikipedia.org/wiki/Object-relational_mapping), etc., in an ASP.NET MVC application. I've written a simple build script for this framework library that looks like the following: + +``` +@echo off +echo. +echo Cleaning build output (removing 'obj' and 'bin' folders)... +for /f ""tokens=*"" %%G in ('dir /b /ad /s bin') do rmdir /s /q ""%%G"" +for /f ""tokens=*"" %%G in ('dir /b /ad /s obj') do rmdir /s /q ""%%G"" +rmdir /s /q build +echo. +echo Starting the build... +call ""%VS100COMNTOOLS%\vsvars32.bat"" +msbuild Integration.build /target:Build +echo. +echo Done! +pause + +``` + +This doesn't work. What I end up with in my `build` folder if I run this is, for whatever reason, assemblies that aren't fully rewritten by `ccrewrite` alongside `.pdb.original`, `.rewritten` and `.csproj.FileListAbsolute.txt` files that litter the output directory. + +What does work is first building the solution in Visual Studio 2010, commenting out line 3 through 7 in the batch file and running it again. I then end up with properly rewritten assemblies and no `.pdb.original` nor `.rewritten` files. + +What I've deduced from this is that Visual Studio 2010 somehow triggers the Code Contract rewriter properly so the resulting assemblies from the Visual Studio 2010 build is re-used by the command-line MSBuild call, so what my batch script basically does is just copying files to the `build` directory. Rather useless, in other words. + +I've read [this](https://stackoverflow.com/questions/1209166/why-is-ccrewrite-exe-not-doing-anything-from-the-command-line), but Jon's problem seems different from mine since `ccrewrite` is obviously doing *something*, but it's just not completing the rewriting for whatever reason. The `Integration.build` file builds the correct configuration (that has Code Contracts enabled in the `.csproj` files) and everything else looks right, it just doesn't work properly. + +So, I'm wondering: How do I run MSBuild the way Visual Studio 2010 is where `ccrewrite` does what it's supposed to and doesn't litter my output directory with `.rewritten` and `.pdb.original` files? Does anyone have a perfect example of how an MSBuild file doing proper Code Contracts rewriting looks like?",2010/08/24,"['https://Stackoverflow.com/questions/3554426', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/61818/']","If you attach a handler to the MouseLeftButtonDown event on the ListView it will only fire when areas outside of a ListViewItem are clicked. Any clicks inside the items will be handled by the items themselves to drive the ListView's selection behavior. + +You can make changes to the clickable areas by adjusting the Background ({x:Null} is not clickable, anything else is) and Margin of the ListViewItems by setting an ItemContainerStyle on the ListView. Also make sure that you are not using a null Background on the ListView itself (White is the default, Transparent works too).","`ListBoxItem` control handles clicks on ListBox. You should either: + +* use `PreviewMouseDown` event on ListBox +* Add event handler in code via `myListBox.AddHandler` method + +See **[How to Attach to MouseDown Event on ListBox](http://www.wpfnewbie.com/2010/07/22/how-to-attach-to-mousedown-event-on-listbox/)** for explanation and code examples." +3554426,"I've started using [Code Contracts](http://msdn.microsoft.com/en-us/devlabs/dd491992.aspx) in all new code I'm writing, such as in a framework library I'm building to help bootstrap [IoC](http://en.wikipedia.org/wiki/Inversion_of_control), [O/RM](http://en.wikipedia.org/wiki/Object-relational_mapping), etc., in an ASP.NET MVC application. I've written a simple build script for this framework library that looks like the following: + +``` +@echo off +echo. +echo Cleaning build output (removing 'obj' and 'bin' folders)... +for /f ""tokens=*"" %%G in ('dir /b /ad /s bin') do rmdir /s /q ""%%G"" +for /f ""tokens=*"" %%G in ('dir /b /ad /s obj') do rmdir /s /q ""%%G"" +rmdir /s /q build +echo. +echo Starting the build... +call ""%VS100COMNTOOLS%\vsvars32.bat"" +msbuild Integration.build /target:Build +echo. +echo Done! +pause + +``` + +This doesn't work. What I end up with in my `build` folder if I run this is, for whatever reason, assemblies that aren't fully rewritten by `ccrewrite` alongside `.pdb.original`, `.rewritten` and `.csproj.FileListAbsolute.txt` files that litter the output directory. + +What does work is first building the solution in Visual Studio 2010, commenting out line 3 through 7 in the batch file and running it again. I then end up with properly rewritten assemblies and no `.pdb.original` nor `.rewritten` files. + +What I've deduced from this is that Visual Studio 2010 somehow triggers the Code Contract rewriter properly so the resulting assemblies from the Visual Studio 2010 build is re-used by the command-line MSBuild call, so what my batch script basically does is just copying files to the `build` directory. Rather useless, in other words. + +I've read [this](https://stackoverflow.com/questions/1209166/why-is-ccrewrite-exe-not-doing-anything-from-the-command-line), but Jon's problem seems different from mine since `ccrewrite` is obviously doing *something*, but it's just not completing the rewriting for whatever reason. The `Integration.build` file builds the correct configuration (that has Code Contracts enabled in the `.csproj` files) and everything else looks right, it just doesn't work properly. + +So, I'm wondering: How do I run MSBuild the way Visual Studio 2010 is where `ccrewrite` does what it's supposed to and doesn't litter my output directory with `.rewritten` and `.pdb.original` files? Does anyone have a perfect example of how an MSBuild file doing proper Code Contracts rewriting looks like?",2010/08/24,"['https://Stackoverflow.com/questions/3554426', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/61818/']","If you attach a handler to the MouseLeftButtonDown event on the ListView it will only fire when areas outside of a ListViewItem are clicked. Any clicks inside the items will be handled by the items themselves to drive the ListView's selection behavior. + +You can make changes to the clickable areas by adjusting the Background ({x:Null} is not clickable, anything else is) and Margin of the ListViewItems by setting an ItemContainerStyle on the ListView. Also make sure that you are not using a null Background on the ListView itself (White is the default, Transparent works too).","I found if I had previously single clicked on an item in the listview (and thereby selecting it), then next double clicked on the empty space in the listview the undesired result of having the previously selected item being actioned as if it had been double clicked on (rather then the empty space). To get around this I used the following code (vb.net): + +``` +Private Sub ListView1_MouseLeftButtonDown(sender As Object, e As MouseButtonEventArgs) Handles ListView1.MouseLeftButtonDown + + ListView1.SelectedIndex = -1 + +End Sub + +``` + +with this code in place double clicking on the empty space de-selects any previously selected items and has the desired effect of nothing appearing to happen for the user when they double click in an empty area." +55584078,"I would like to report progress from a long running PLINQ query. + +I can't really find any native LINQ method that allows me to do this (as was [implemented](https://learn.microsoft.com/en-us/dotnet/standard/parallel-programming/how-to-cancel-a-plinq-query) for [cancellation](https://learn.microsoft.com/en-us/dotnet/api/system.linq.parallelenumerable.withcancellation?view=netframework-4.7.2)). + +I have read [this article](http://blog.functionalfun.net/2008/07/reporting-progress-during-linq-queries.html) that shows a neat extension function for a regular serialized query. + +I have been testing the behavior using the below code. + +```c# +var progress = new BehaviorSubject(0); +DateTime start = DateTime.Now; +progress.Subscribe(x => { Console.WriteLine(x); }); +Enumerable.Range(1,1000000) + //.WithProgressReporting(i => progress.OnNext(i)) //Beginning Progress + .AsParallel() + .AsOrdered() + //.WithProgressReporting(i => progress.OnNext(i)) //Middle Progress reporting + .Select(v => { Thread.Sleep(1); return v * v; }) + //.WithProgressReporting(i => progress.OnNext(i)) //End Progress Reporting + .ToList(); +Console.WriteLine(""Completed in: "" + (DateTime.Now - start).TotalSeconds + "" seconds""); + +``` + +Edit: + +Reporting progress from the **middle** using the `IEnumerable` extension removes the parallelism. + +Reporting from the **end** does not report any progress while the parallel calculations are being computed then quickly reports all the progress at the very end. I assume this is progress of compiling of the results from the parallel computation into a list. + +I originally thought the progress reporting from **beginning** was causing the the LINQ to run unparallelized. After sleeping on this, and reading comments from [Peter Duniho](https://stackoverflow.com/questions/55584078/how-can-i-report-progress-from-a-plinq-query#comment97866126_55584078), I see that it is actually working as parallel, but I am getting so many progress reports that handling so many is causing my test/application to slow significantly. + +Is there a way that is parallel/thread safe to report progress from a PLINQ in increments that allow a user to know progress is being made without having a significant impact on the method runtime?",2019/04/09,"['https://Stackoverflow.com/questions/55584078', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7371817/']","This answer might not be as elegant, but it gets the job done. + +When using PLINQ, there are multiple threads processing your collection, so using those threads to **report** progress results in multiple (and out-of-order) progress reports like 0% 1% 5% 4% 3% etc... + +Instead, we can use those multiple threads to **update** a shared variable storing the progress. In my example, it's a local variable `completed`. We then spawn another thread using `Task.Run()` to report on that progress variable at 0.5s intervals. + +Extension class: + +``` +static class Extensions + public static ParallelQuery WithProgressReporting(this ParallelQuery sequence, Action increment) + { + return sequence.Select(x => + { + increment?.Invoke(); + return x; + }); + } +} + +``` + +Code: + +``` +static void Main(string[] args) + { + long completed = 0; + Task.Run(() => + { + while (completed < 100000) + { + Console.WriteLine((completed * 100 / 100000) + ""%""); + Thread.Sleep(500); + } + }); + DateTime start = DateTime.Now; + var output = Enumerable.Range(1, 100000) + .AsParallel() + .WithProgressReporting(()=>Interlocked.Increment(ref completed)) + .Select(v => { Thread.Sleep(1); return v * v; }) + .ToList(); + Console.WriteLine(""Completed in: "" + (DateTime.Now - start).TotalSeconds + "" seconds""); + Console.ReadKey(); + } + +```","This extension can be positioned either at the start or at the end of the LINQ query. If positioned at the start will start reporting progress immediately, but will erroneously report 100% before the job is done. If positioned at the end will report accurately the end of the query, but will delay reporting progress until the first item of the source has completed. + +``` +public static ParallelQuery WithProgressReporting( + this ParallelQuery source, + long itemsCount, IProgress progress) +{ + int countShared = 0; + return source.Select(item => + { + int countLocal = Interlocked.Increment(ref countShared); + progress.Report(countLocal / (double)itemsCount); + return item; + }); +} + +``` + +Usage example: + +``` +// The Progress captures the current SynchronizationContext at construction. +var progress = new Progress(); +progress.ProgressChanged += (object sender, double e) => +{ + Console.WriteLine($""Progress: {e:0%}""); +}; + +var numbers = Enumerable.Range(1, 10); + +var sum = numbers + .AsParallel() + .WithDegreeOfParallelism(3) + .WithMergeOptions(ParallelMergeOptions.NotBuffered) + .Select(n => { Thread.Sleep(500); return n; }) // Simulate some heavy computation + .WithProgressReporting(10, progress) // <--- the extension method + .Sum(); + +Console.WriteLine($""Sum: {sum}""); + +``` + +Output: + +[![Query output](https://i.stack.imgur.com/gZjY9.png)](https://i.stack.imgur.com/gZjY9.png) + +There is some jumping because sometimes the worker threads are preempting each other. + +The [`System.Progress`](https://learn.microsoft.com/en-us/dotnet/api/system.progress-1?view=netframework-4.7.2) class has the nice feature that invokes the `ProgressChanged` event at the captured context (usually the UI thread), so the UI controls can be updated safely. On the other hand in a Console Application the event is invoked on the ThreadPool, that will probably be fully utilized by the parallel query, so the event will fire with some delay (the ThreadPool spawns new threads every 500 msec). This is the reason I limited the parallelism to 3 in the example, to keep a free thread for the reporting of the progress (I have a quad core machine)." +39831170,"I'm using C# and windows forms, i have a group box with 20 labels in it (10 in the top row and 10 in the bottom row). + +I want to set Text property of these labels based on their location coordinates in the group box. Y co-ordinate of all labels in same row remains same and only X co-ordinate changes. + +``` +Example locations: + +label1.Location is (6,16), label2.Location is (33,16) ... label10.Location is (150,16) + +label11.Location is (6,43), label12.Location is (33,43) ... label20.Location is (150,43) + +``` + +Now originally the label.Text is set as `label_[int a]_[int b]` where `int a` is a number between 1 and 10 to show its ""column"" number and `int b` is a either 1 *OR* 2 for its ""row"" number. + +Now this all works great but I need 60 group boxes each with 20 labels in it and renaming each one is quite a pain, that's why id like to do it this way. + +The reason its set out like this is because every ""column"" gets only 1 number in EITHER the top OR bottom row. + +Now my 1st question is; +Is it possible to set the text property by its location property? + +2ndly, can the stackoverflow hive mind think of a better/efficient way to do this? + +NOTE: +i have tried loading the labels into a List to try use a loop but that creates complications with selecting the appropriate label. + +i'm trying to develop a single method that can be used separately on each groupbox. + +now while this all makes sense in my mind, i don't immediately see what other information i can provide.",2016/10/03,"['https://Stackoverflow.com/questions/39831170', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6691757/']","This sounds like a good candidate for a User Control to me. + +Design a user control with the groupbox and labels. +Expose the operations you need externally. Possibly a good moment to set naming conventions to something more meaningful to you. + +Another way could be to generate the labels from code instead of design time like @Kevin says. Crate a method which takes you groupbox and other values you need. Then set label name and location as you want (look at the designer file).","I guess can try a foreach to GroupBox.Controls,and you can check their names inside this foreach too. example: + +``` +foreach(Label lbl in groupBox1.Controls +{ + if (lbl.Name.Contains(""[int_a]_[int_b]"")) + { + lbl.Text = ""Label Text""; + } +} + +``` + +I guess this gives you a base to what you're needing" +957172,"Can someone please help me out with a query? In Microsoft SQL Server, I have the following query, which executes fine: + +``` +SELECT * FROM ControlPoint +INNER JOIN Project ON ControlPoint.ProjectID = Project.ProjectID +INNER JOIN Site ON Site.SiteID = Project.SiteID +WHERE Project.ProjectName LIKE '%Flood%' + +``` + +My problem is, when I try to execute this on Microsoft Access, it gives me some kind of syntax error. It's been forever since I've used Access, but if I remember right, I think the joins need to be in parenthesis or something. Any help would be useful!",2009/06/05,"['https://Stackoverflow.com/questions/957172', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/98094/']","Access uses different wildcard patterns. + +In your case, it will be - LIKE '?Flood?' (replace question mark with asterisk). + +I don't know formatting codes to apply here so that it shows it correctly. + +See the link for details - ","Use this sintax in access never fails + +(this is an example) + +select \* from customer, adress +where customer.id = adress.customerId" +957172,"Can someone please help me out with a query? In Microsoft SQL Server, I have the following query, which executes fine: + +``` +SELECT * FROM ControlPoint +INNER JOIN Project ON ControlPoint.ProjectID = Project.ProjectID +INNER JOIN Site ON Site.SiteID = Project.SiteID +WHERE Project.ProjectName LIKE '%Flood%' + +``` + +My problem is, when I try to execute this on Microsoft Access, it gives me some kind of syntax error. It's been forever since I've used Access, but if I remember right, I think the joins need to be in parenthesis or something. Any help would be useful!",2009/06/05,"['https://Stackoverflow.com/questions/957172', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/98094/']","You will need some parentheses in addition to changing the wild cards: + +``` +SELECT * FROM (ControlPoint +INNER JOIN Project ON ControlPoint.ProjectID = Project.ProjectID) +INNER JOIN Site ON Site.SiteID = Project.SiteID +WHERE Project.ProjectName LIKE '*Flood*' + +``` + +Note that the asterisk is used in the Access query window and with DAO, percent is used with ADO.","Use this sintax in access never fails + +(this is an example) + +select \* from customer, adress +where customer.id = adress.customerId" +957172,"Can someone please help me out with a query? In Microsoft SQL Server, I have the following query, which executes fine: + +``` +SELECT * FROM ControlPoint +INNER JOIN Project ON ControlPoint.ProjectID = Project.ProjectID +INNER JOIN Site ON Site.SiteID = Project.SiteID +WHERE Project.ProjectName LIKE '%Flood%' + +``` + +My problem is, when I try to execute this on Microsoft Access, it gives me some kind of syntax error. It's been forever since I've used Access, but if I remember right, I think the joins need to be in parenthesis or something. Any help would be useful!",2009/06/05,"['https://Stackoverflow.com/questions/957172', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/98094/']","The syntax error is caused because access uses "" instead of ' as the string delimiter. As previously mentioned you will also need to change the % wildcards to \*","Use this sintax in access never fails + +(this is an example) + +select \* from customer, adress +where customer.id = adress.customerId" +957172,"Can someone please help me out with a query? In Microsoft SQL Server, I have the following query, which executes fine: + +``` +SELECT * FROM ControlPoint +INNER JOIN Project ON ControlPoint.ProjectID = Project.ProjectID +INNER JOIN Site ON Site.SiteID = Project.SiteID +WHERE Project.ProjectName LIKE '%Flood%' + +``` + +My problem is, when I try to execute this on Microsoft Access, it gives me some kind of syntax error. It's been forever since I've used Access, but if I remember right, I think the joins need to be in parenthesis or something. Any help would be useful!",2009/06/05,"['https://Stackoverflow.com/questions/957172', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/98094/']","You will need some parentheses in addition to changing the wild cards: + +``` +SELECT * FROM (ControlPoint +INNER JOIN Project ON ControlPoint.ProjectID = Project.ProjectID) +INNER JOIN Site ON Site.SiteID = Project.SiteID +WHERE Project.ProjectName LIKE '*Flood*' + +``` + +Note that the asterisk is used in the Access query window and with DAO, percent is used with ADO.","Access uses different wildcard patterns. + +In your case, it will be - LIKE '?Flood?' (replace question mark with asterisk). + +I don't know formatting codes to apply here so that it shows it correctly. + +See the link for details - " +957172,"Can someone please help me out with a query? In Microsoft SQL Server, I have the following query, which executes fine: + +``` +SELECT * FROM ControlPoint +INNER JOIN Project ON ControlPoint.ProjectID = Project.ProjectID +INNER JOIN Site ON Site.SiteID = Project.SiteID +WHERE Project.ProjectName LIKE '%Flood%' + +``` + +My problem is, when I try to execute this on Microsoft Access, it gives me some kind of syntax error. It's been forever since I've used Access, but if I remember right, I think the joins need to be in parenthesis or something. Any help would be useful!",2009/06/05,"['https://Stackoverflow.com/questions/957172', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/98094/']","You will need some parentheses in addition to changing the wild cards: + +``` +SELECT * FROM (ControlPoint +INNER JOIN Project ON ControlPoint.ProjectID = Project.ProjectID) +INNER JOIN Site ON Site.SiteID = Project.SiteID +WHERE Project.ProjectName LIKE '*Flood*' + +``` + +Note that the asterisk is used in the Access query window and with DAO, percent is used with ADO.","The syntax error is caused because access uses "" instead of ' as the string delimiter. As previously mentioned you will also need to change the % wildcards to \*" +32011014,"Consider the following macro: + +``` +#define FOO(a,b) (--a)* 8 + (--b); + +``` + +Now + +``` +int graph[8][8] = { 0 }; +int *graph_p = &(graph[0][0]); +int *p = graph_p + FOO(2, 3); + +``` + +Why do I get the error: + +> +> IntelliSense: expression must be a modifiable lvalue +> +> +>",2015/08/14,"['https://Stackoverflow.com/questions/32011014', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5211135/']","It's because you are passing an *integer constant* to function-like macro `FOO(a, b)`, that applies pre-increment `--` operator to its arguments. + +The result of this macro expansion looks as: + +``` +int *p = graph_p + (--2)* 8 + (--3);; + +``` + +which is illegal in C, as operator requires a *modifiable lvalue* as its operand. + +Another issues here are, that you should put parantheses around macro's replacement and do not place semicolon at the end: + +``` +#define FOO(a,b) ((--a)* 8 + (--b)) + +```","The line + +``` +int *p = graph_p + FOO(2, 3); + +``` + +will be replaced at compile time by the defined macro as + +``` +int *p = graph_p + (--2)* 8 + (--3);; + +``` + +the operand of prefix `--` must be an lvalue. `2` and `3` are integer constants and it can't be an operand of prefix `--` operator." +32011014,"Consider the following macro: + +``` +#define FOO(a,b) (--a)* 8 + (--b); + +``` + +Now + +``` +int graph[8][8] = { 0 }; +int *graph_p = &(graph[0][0]); +int *p = graph_p + FOO(2, 3); + +``` + +Why do I get the error: + +> +> IntelliSense: expression must be a modifiable lvalue +> +> +>",2015/08/14,"['https://Stackoverflow.com/questions/32011014', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5211135/']","The line + +``` +int *p = graph_p + FOO(2, 3); + +``` + +will be replaced at compile time by the defined macro as + +``` +int *p = graph_p + (--2)* 8 + (--3);; + +``` + +the operand of prefix `--` must be an lvalue. `2` and `3` are integer constants and it can't be an operand of prefix `--` operator.","`FOO(2,3)` translates to `(--2)* 8 + (--3)` + +You can only increment/decrement an lvalue, not a number." +32011014,"Consider the following macro: + +``` +#define FOO(a,b) (--a)* 8 + (--b); + +``` + +Now + +``` +int graph[8][8] = { 0 }; +int *graph_p = &(graph[0][0]); +int *p = graph_p + FOO(2, 3); + +``` + +Why do I get the error: + +> +> IntelliSense: expression must be a modifiable lvalue +> +> +>",2015/08/14,"['https://Stackoverflow.com/questions/32011014', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5211135/']","The line + +``` +int *p = graph_p + FOO(2, 3); + +``` + +will be replaced at compile time by the defined macro as + +``` +int *p = graph_p + (--2)* 8 + (--3);; + +``` + +the operand of prefix `--` must be an lvalue. `2` and `3` are integer constants and it can't be an operand of prefix `--` operator.","Try this: + +``` +Int * p=(int * )(graph-p+FOO(2,3)); + +```" +32011014,"Consider the following macro: + +``` +#define FOO(a,b) (--a)* 8 + (--b); + +``` + +Now + +``` +int graph[8][8] = { 0 }; +int *graph_p = &(graph[0][0]); +int *p = graph_p + FOO(2, 3); + +``` + +Why do I get the error: + +> +> IntelliSense: expression must be a modifiable lvalue +> +> +>",2015/08/14,"['https://Stackoverflow.com/questions/32011014', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5211135/']","It's because you are passing an *integer constant* to function-like macro `FOO(a, b)`, that applies pre-increment `--` operator to its arguments. + +The result of this macro expansion looks as: + +``` +int *p = graph_p + (--2)* 8 + (--3);; + +``` + +which is illegal in C, as operator requires a *modifiable lvalue* as its operand. + +Another issues here are, that you should put parantheses around macro's replacement and do not place semicolon at the end: + +``` +#define FOO(a,b) ((--a)* 8 + (--b)) + +```","`FOO(2,3)` translates to `(--2)* 8 + (--3)` + +You can only increment/decrement an lvalue, not a number." +32011014,"Consider the following macro: + +``` +#define FOO(a,b) (--a)* 8 + (--b); + +``` + +Now + +``` +int graph[8][8] = { 0 }; +int *graph_p = &(graph[0][0]); +int *p = graph_p + FOO(2, 3); + +``` + +Why do I get the error: + +> +> IntelliSense: expression must be a modifiable lvalue +> +> +>",2015/08/14,"['https://Stackoverflow.com/questions/32011014', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5211135/']","It's because you are passing an *integer constant* to function-like macro `FOO(a, b)`, that applies pre-increment `--` operator to its arguments. + +The result of this macro expansion looks as: + +``` +int *p = graph_p + (--2)* 8 + (--3);; + +``` + +which is illegal in C, as operator requires a *modifiable lvalue* as its operand. + +Another issues here are, that you should put parantheses around macro's replacement and do not place semicolon at the end: + +``` +#define FOO(a,b) ((--a)* 8 + (--b)) + +```","Try this: + +``` +Int * p=(int * )(graph-p+FOO(2,3)); + +```" +51500657,"Is it possible to get substring from right hand hand(Reverse) direction using `substring()` in JAVA. +Example. + Suppose `String S=""abcdef""`, + Can I get Substring ""fedc"" using `S.substring(S.length()-1,3)` ? +If it is not correct, please suggest me how to get Substring from right hand end(Reverse direction)??",2018/07/24,"['https://Stackoverflow.com/questions/51500657', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10128375/']","You could reverse the string and use `substring`. Unfortunately `String` does not have that, but `StringBuilder` has it e.g. + +``` +new StringBuilder(""abcdef"").reverse().toString().substring(0,4); + +```","You can reverse the string and find the substring + +``` +// reverse +String s = ""abcdef""; +StringBuilder builder = new StringBuilder(s); +String substring = builder.reverse().substring(0,3); + +```" +51500657,"Is it possible to get substring from right hand hand(Reverse) direction using `substring()` in JAVA. +Example. + Suppose `String S=""abcdef""`, + Can I get Substring ""fedc"" using `S.substring(S.length()-1,3)` ? +If it is not correct, please suggest me how to get Substring from right hand end(Reverse direction)??",2018/07/24,"['https://Stackoverflow.com/questions/51500657', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10128375/']","You could reverse the string and use `substring`. Unfortunately `String` does not have that, but `StringBuilder` has it e.g. + +``` +new StringBuilder(""abcdef"").reverse().toString().substring(0,4); + +```","Java doesn't support extension methods like C# does, so I would build a function for this. This way you can control how much of the reverse substring you want with a parameter. + +``` +public class StackOverflow { + public static void main(String[] args) { + String data = ""abcdef""; + for (int i = 0; i < data.length(); i++) { + System.out.println(reverseSubstring(data, i+1)); + } + } + + public static String reverseSubstring(String data, int length) { + return new StringBuilder(data).reverse().substring(0, length); + } +} + +``` + +Result: + +``` +f +fe +fed +fedc +fedcb +fedcba + +``` + +UPDATE +------ + +Another approach is to create a wrapper class to String. This way you can call a class method like how you're asking in your question with the example `S.substring(S.length()-1,3)`. This will also allow you to still have all the `String` methods after using the wrapper's `get()` method. + +String Wrapper +-------------- + +``` +public class MyString { + private String theString; + + public MyString(String s) { + theString = s; + } + + public String get() { + return theString; + } + + public String reverseSubstring(int length) { + return new StringBuilder(theString).reverse().substring(0, length); + } +} + +``` + +Usage +----- + +``` +public class StackOverflow { + public static void main(String[] args) { + MyString data = new MyString(""abcdef""); + for (int i = 0; i < data.get().length(); i++) { + System.out.println(data.reverseSubstring(i+1)); + } + } +} + +``` + +Results: + +``` +f +fe +fed +fedc +fedcb +fedcba + +```" +39452720,"I created a vagrant box using `vagrant package` , uploaded it and released it. + +Then I did `vagrant init /` which created a Vagrantfile. I even appended the box version to the Vagrantfile. + +Next I did `vagrant up --provider virtualbox`. This tries to get the box locally and then when it can't find it, i get the error: + +``` +The box you're attempting to add doesn't support the provider +you requested. Please find an alternate box or use an alternate +provider. Double-check your requested provider to verify you didn't +simply misspell it. + +If you're adding a box from HashiCorp's Atlas, make sure the box is +released. + +``` + +I have given virtualbox as the provider and virtual box works fine with other boxes I use.",2016/09/12,"['https://Stackoverflow.com/questions/39452720', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5955578/']",What I figured was that due to some reason vagrant had got corrupted. So doing a fresh install of vagrant did the trick.,"Upgrading vagrant version through installing `.deb` version worked for me (download through vagrant website: - choose tab ""Debian"" and install the package)" +39452720,"I created a vagrant box using `vagrant package` , uploaded it and released it. + +Then I did `vagrant init /` which created a Vagrantfile. I even appended the box version to the Vagrantfile. + +Next I did `vagrant up --provider virtualbox`. This tries to get the box locally and then when it can't find it, i get the error: + +``` +The box you're attempting to add doesn't support the provider +you requested. Please find an alternate box or use an alternate +provider. Double-check your requested provider to verify you didn't +simply misspell it. + +If you're adding a box from HashiCorp's Atlas, make sure the box is +released. + +``` + +I have given virtualbox as the provider and virtual box works fine with other boxes I use.",2016/09/12,"['https://Stackoverflow.com/questions/39452720', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5955578/']",What I figured was that due to some reason vagrant had got corrupted. So doing a fresh install of vagrant did the trick.,"I suffered for 2 hours but I don't want anyone to suffer ;) + +1 - **access the terminal (sudo) and, remove vagrant files** + +$ rm -rf /opt/vagrant + +$ rm -f /usr/bin/vagrant + +2 - **then install it again as it has probably been corrupted.** + +$ curl -O + +3 - **install vagrant** + +$ sudo apt install ./vagrant\_2.2.9\_x86\_64.deb + +4 - **confirm by viewing the installed vagrant version** + +& vagrant --version + +*be happy*" +39452720,"I created a vagrant box using `vagrant package` , uploaded it and released it. + +Then I did `vagrant init /` which created a Vagrantfile. I even appended the box version to the Vagrantfile. + +Next I did `vagrant up --provider virtualbox`. This tries to get the box locally and then when it can't find it, i get the error: + +``` +The box you're attempting to add doesn't support the provider +you requested. Please find an alternate box or use an alternate +provider. Double-check your requested provider to verify you didn't +simply misspell it. + +If you're adding a box from HashiCorp's Atlas, make sure the box is +released. + +``` + +I have given virtualbox as the provider and virtual box works fine with other boxes I use.",2016/09/12,"['https://Stackoverflow.com/questions/39452720', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5955578/']","Make sure you have virtualbox installed if you are using ubuntu. + + `sudo apt install virtualbox-qt`","Upgrading vagrant version through installing `.deb` version worked for me (download through vagrant website: - choose tab ""Debian"" and install the package)" +39452720,"I created a vagrant box using `vagrant package` , uploaded it and released it. + +Then I did `vagrant init /` which created a Vagrantfile. I even appended the box version to the Vagrantfile. + +Next I did `vagrant up --provider virtualbox`. This tries to get the box locally and then when it can't find it, i get the error: + +``` +The box you're attempting to add doesn't support the provider +you requested. Please find an alternate box or use an alternate +provider. Double-check your requested provider to verify you didn't +simply misspell it. + +If you're adding a box from HashiCorp's Atlas, make sure the box is +released. + +``` + +I have given virtualbox as the provider and virtual box works fine with other boxes I use.",2016/09/12,"['https://Stackoverflow.com/questions/39452720', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5955578/']","Make sure you have virtualbox installed if you are using ubuntu. + + `sudo apt install virtualbox-qt`","I suffered for 2 hours but I don't want anyone to suffer ;) + +1 - **access the terminal (sudo) and, remove vagrant files** + +$ rm -rf /opt/vagrant + +$ rm -f /usr/bin/vagrant + +2 - **then install it again as it has probably been corrupted.** + +$ curl -O + +3 - **install vagrant** + +$ sudo apt install ./vagrant\_2.2.9\_x86\_64.deb + +4 - **confirm by viewing the installed vagrant version** + +& vagrant --version + +*be happy*" +39452720,"I created a vagrant box using `vagrant package` , uploaded it and released it. + +Then I did `vagrant init /` which created a Vagrantfile. I even appended the box version to the Vagrantfile. + +Next I did `vagrant up --provider virtualbox`. This tries to get the box locally and then when it can't find it, i get the error: + +``` +The box you're attempting to add doesn't support the provider +you requested. Please find an alternate box or use an alternate +provider. Double-check your requested provider to verify you didn't +simply misspell it. + +If you're adding a box from HashiCorp's Atlas, make sure the box is +released. + +``` + +I have given virtualbox as the provider and virtual box works fine with other boxes I use.",2016/09/12,"['https://Stackoverflow.com/questions/39452720', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5955578/']","Upgrading vagrant version through installing `.deb` version worked for me (download through vagrant website: - choose tab ""Debian"" and install the package)","I suffered for 2 hours but I don't want anyone to suffer ;) + +1 - **access the terminal (sudo) and, remove vagrant files** + +$ rm -rf /opt/vagrant + +$ rm -f /usr/bin/vagrant + +2 - **then install it again as it has probably been corrupted.** + +$ curl -O + +3 - **install vagrant** + +$ sudo apt install ./vagrant\_2.2.9\_x86\_64.deb + +4 - **confirm by viewing the installed vagrant version** + +& vagrant --version + +*be happy*" +5043,"I started wondering about this when I realized most websites I visit have white backgrounds, and I know that the screen is usually responsible for most of the battery usage. Since I can't change the background in those sites, I might at least switch my wallpaper to a black one. + +Most (all?) phones need back-lighting to brighten the screen when needed. Since that back-lighting consumes battery, **is it correct to state that a white screen consumes energy at a faster rate than a black one?** *(assuming the same brightness level in the settings)* + +I'm assuming that a white screen needs stronger back-lighting, but I don't know if it's the case.",2011/01/21,"['https://android.stackexchange.com/questions/5043', 'https://android.stackexchange.com', 'https://android.stackexchange.com/users/1926/']","On OLED, AMOLED and Super AMOLED screens: [Yes](http://techlogg.com/2010/12/ips-vs-amoled-vs-slcd-smartphone-displays-explained/1877) + +LCD screens: [No](http://techlogg.com/2010/05/black-vs-white-screen-power-consumption-24-more-monitors-tested/17)","This depends on the screen technology. + +For instance, (it was said that) Android 2.3 Gingerbread has dark theme since Google's latest flagship device Nexus S uses (Super) AMOLED display which consumes less energy when displaying dark color since AMOLED produces its own light and darker color emits less photons. Contrasts with LCD display which uses a backlight (a fixed number of photons) and the LCD crystals filters those colors it needs. The crystals on an LCD displays though, actually consume slightly less power when displaying white since it takes more power to strain the crystal to block more light. + +Screen color does not affect the backlighting. There are certain display technologies in TVs that tries to give dynamic backlighting by dimming the screen when displaying darker image. I'm not aware of any device that actually ships with that type of screen though." +5043,"I started wondering about this when I realized most websites I visit have white backgrounds, and I know that the screen is usually responsible for most of the battery usage. Since I can't change the background in those sites, I might at least switch my wallpaper to a black one. + +Most (all?) phones need back-lighting to brighten the screen when needed. Since that back-lighting consumes battery, **is it correct to state that a white screen consumes energy at a faster rate than a black one?** *(assuming the same brightness level in the settings)* + +I'm assuming that a white screen needs stronger back-lighting, but I don't know if it's the case.",2011/01/21,"['https://android.stackexchange.com/questions/5043', 'https://android.stackexchange.com', 'https://android.stackexchange.com/users/1926/']","This depends on the screen technology. + +For instance, (it was said that) Android 2.3 Gingerbread has dark theme since Google's latest flagship device Nexus S uses (Super) AMOLED display which consumes less energy when displaying dark color since AMOLED produces its own light and darker color emits less photons. Contrasts with LCD display which uses a backlight (a fixed number of photons) and the LCD crystals filters those colors it needs. The crystals on an LCD displays though, actually consume slightly less power when displaying white since it takes more power to strain the crystal to block more light. + +Screen color does not affect the backlighting. There are certain display technologies in TVs that tries to give dynamic backlighting by dimming the screen when displaying darker image. I'm not aware of any device that actually ships with that type of screen though.","If your screen has an older standard lcd then this doesn't help at all. The backlight is still shining behind all those darkened pixels. You just can't see it. + +If you have oled, amoled, super amoled, LED lcd, or I think even plasma then it does help to darken the screen because the light is generated specifically where it is needed. + +BTW there are fire fox plugins that reformat whatever page you are on to be dark. I don't remember the names, but I needed it when I was living in a studio apartment with my girlfriend and I was up all night on my computer while she was trying to sleep 20 feet away in the same room." +5043,"I started wondering about this when I realized most websites I visit have white backgrounds, and I know that the screen is usually responsible for most of the battery usage. Since I can't change the background in those sites, I might at least switch my wallpaper to a black one. + +Most (all?) phones need back-lighting to brighten the screen when needed. Since that back-lighting consumes battery, **is it correct to state that a white screen consumes energy at a faster rate than a black one?** *(assuming the same brightness level in the settings)* + +I'm assuming that a white screen needs stronger back-lighting, but I don't know if it's the case.",2011/01/21,"['https://android.stackexchange.com/questions/5043', 'https://android.stackexchange.com', 'https://android.stackexchange.com/users/1926/']","On OLED, AMOLED and Super AMOLED screens: [Yes](http://techlogg.com/2010/12/ips-vs-amoled-vs-slcd-smartphone-displays-explained/1877) + +LCD screens: [No](http://techlogg.com/2010/05/black-vs-white-screen-power-consumption-24-more-monitors-tested/17)","If your screen has an older standard lcd then this doesn't help at all. The backlight is still shining behind all those darkened pixels. You just can't see it. + +If you have oled, amoled, super amoled, LED lcd, or I think even plasma then it does help to darken the screen because the light is generated specifically where it is needed. + +BTW there are fire fox plugins that reformat whatever page you are on to be dark. I don't remember the names, but I needed it when I was living in a studio apartment with my girlfriend and I was up all night on my computer while she was trying to sleep 20 feet away in the same room." +5043,"I started wondering about this when I realized most websites I visit have white backgrounds, and I know that the screen is usually responsible for most of the battery usage. Since I can't change the background in those sites, I might at least switch my wallpaper to a black one. + +Most (all?) phones need back-lighting to brighten the screen when needed. Since that back-lighting consumes battery, **is it correct to state that a white screen consumes energy at a faster rate than a black one?** *(assuming the same brightness level in the settings)* + +I'm assuming that a white screen needs stronger back-lighting, but I don't know if it's the case.",2011/01/21,"['https://android.stackexchange.com/questions/5043', 'https://android.stackexchange.com', 'https://android.stackexchange.com/users/1926/']","On OLED, AMOLED and Super AMOLED screens: [Yes](http://techlogg.com/2010/12/ips-vs-amoled-vs-slcd-smartphone-displays-explained/1877) + +LCD screens: [No](http://techlogg.com/2010/05/black-vs-white-screen-power-consumption-24-more-monitors-tested/17)","Hey, I just ran a load of test to figure this out. They are vaguely scientific tests! I figured out that I was saving 20% battery by switching to dark wallpaper and dark themed apps. Have a look through my write up, you should be able to work out the saving on your phone: + +" +5043,"I started wondering about this when I realized most websites I visit have white backgrounds, and I know that the screen is usually responsible for most of the battery usage. Since I can't change the background in those sites, I might at least switch my wallpaper to a black one. + +Most (all?) phones need back-lighting to brighten the screen when needed. Since that back-lighting consumes battery, **is it correct to state that a white screen consumes energy at a faster rate than a black one?** *(assuming the same brightness level in the settings)* + +I'm assuming that a white screen needs stronger back-lighting, but I don't know if it's the case.",2011/01/21,"['https://android.stackexchange.com/questions/5043', 'https://android.stackexchange.com', 'https://android.stackexchange.com/users/1926/']","Hey, I just ran a load of test to figure this out. They are vaguely scientific tests! I figured out that I was saving 20% battery by switching to dark wallpaper and dark themed apps. Have a look through my write up, you should be able to work out the saving on your phone: + +","If your screen has an older standard lcd then this doesn't help at all. The backlight is still shining behind all those darkened pixels. You just can't see it. + +If you have oled, amoled, super amoled, LED lcd, or I think even plasma then it does help to darken the screen because the light is generated specifically where it is needed. + +BTW there are fire fox plugins that reformat whatever page you are on to be dark. I don't remember the names, but I needed it when I was living in a studio apartment with my girlfriend and I was up all night on my computer while she was trying to sleep 20 feet away in the same room." +3475856,"$\int\_{x^2+y^2+z^2\le 2(x+y+z)}(x^2+y^2+z^2)\sin z dxdydz$ + +Can you give me a hint how to start?",2019/12/14,"['https://math.stackexchange.com/questions/3475856', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/653945/']","Let us restate, also introducing notations, so that there is nothing more to prove at the end. + +> +> Given is a triangle $\Delta ABC$. We consider intermediate points $A',A''\in BC$, $B',B''\in CA$, $C',C''\in AB$, so that +> $$ +> \frac{A'C}{BC} = +> \frac{B'A}{CA} = +> \frac{C'B}{AB} = +> \frac 13= +> \frac{BA''}{BC} = +> \frac{CB''}{CA} = +> \frac{AC''}{AB} +> \ . +> $$ +> The **equidistant** parallels +> +> +> * to $AA'$ through $B,A'',A',C$ (one of them being $AA'$, +> * to $BB'$ through $C,B'',B',A$ (one of them being $BB'$, +> +> +> determine the points $X,X';Y,Y';Z,Z';S,T,U$ as in the following figure: +> [![The 1:3:3 triangle, net construction](https://i.stack.imgur.com/yRKdy.png)](https://i.stack.imgur.com/yRKdy.png) +> We have also drawn the mid points $\alpha$, $\beta$, $\gamma$ of the sides of $\Delta ABC$ as orientation, but we do not need them.(Except for the Bonus.) +> +> +> **1.st Claim:** The following quadrilaterals are congruent parallelograms: +> $AZ'US$, +> $Z'ZBU$, +> $YSTY'$, +> $SUX'T$, +> $Y'TXC$. +> +> +> **2.nd Claim:** The following segments are parallel: +> $$ +> AY\ \|\ +> ZS\ \|\ +> SY'\ \|\ +> ZU\ \|\ +> UT\ \|\ +> TC\ \|\ +> BX'\ \|\ +> X'X\ \ . +> $$ +> +> +> In particular +> +> +> * the points $Z',C'',S,Y'$ (and $\beta$) are colinear, +> * the points $Z,C',U,T,C$ are colinear, +> * the points $B,X',X$ are colinear, +> +> +> so that we can draw solid lines instead of the dotted lines: +> [![The 1:3:3 triangle](https://i.stack.imgur.com/LDDWD.png)](https://i.stack.imgur.com/LDDWD.png) +> +> +> + +The question in the OP follows now easily from the above construction. (The key word is *equidistant parallels* in all three directions.) + +**Proof:** The first claim is clear, since we have two directions with three equidistant parallels in each one. The equidistance is insured by the fact that a intersecting line is delimited in equal segments, here explicitly $BA''=A''A'=A'C$ and $CB''=B''B'=B'A$. + +For the second claim, we use the first one and succesively compare triangles built with one side parallel and congruent to $AZ'$, and an other one parallel and congruent to $AS$. We have for instance $\Delta AZ'S\equiv \Delta SYA$, because $AZ'$ is (via $US$) parallel and congruent to $SY$, adn $AS$ is a common side. This gives $AY\| Z'S$. (Congruence also holds for the two segments.) +With a similar argument we add one by one the other segments in the parallel chain. + +$\square$ + +--- + +*Bonus:* $\beta$ is for instance on $SY'$ and in fact its mid point, because it is the mid point of the one diagonal $AC$ in the parallelogram $ATCY$, so also of the other diagonal $YT$, which is also one diagonal in the parallelogram $YSTY'$. + +--- + +*Note:* If we start with a lattice defined by two directions, make a choice of points $A,B,C$ as in the picture, and vectorially (for instance) also immediately accept that the ""third direction works"", there is nothing to be shown. But the question in the OP reduces to exactly this aspect. Also the above proof is easy, the only complicated thing is to make sentences that construct, and fix the known data step by step.","Two things : + +1) About the equality of the lengths you are asking for, see the recent question [Proof that each of the three cevians is divided in the ratio $1:3:3$](https://math.stackexchange.com/q/3350495) (with, among the answers, one of mine). + +2) About the proportion ($1/7$) of areas : + +Let $A,a$ be the resp. areas of the big and small (red) triangle. + +In your second figure, the sum of the areas of the 12 (purple) copies of the initial triangle is $12a$. + +This sum can be computed in a second manner by recognizing 3 parallelograms (one of them is $ABCD$) whose total area is the double of the area of the big triangle **minus the area of the small triangle**, giving the equation : + +$$12a=2(A-a)$$ + +which amounts to : + +> +> $$a=\tfrac17A$$ +> +> +> + +Remarks : + +1) The given figure can be connected to one of the figures one finds in this [reference](https://en.wikipedia.org/wiki/Goldberg%E2%80%93Coxeter_construction). + +2) A generalization of the $1/7$ triangle is [Routh theorem](https://en.wikipedia.org/wiki/Routh%27s_theorem)." +23575,"Back in the 90's I remember watching a late-night movie on one of the networks. + +The story took place in an arid, post-apocaliptic future. The plot revolved around a little girl who befriended a cyborg killing machine. The cyborg killing machine spent the movie blasting apart a gang of evil cyborgs to protect her, and it seems like he died in the end. + +It had an old west or samurai vibe to it, and it seemed pretty good for the timeslot it was in. Any ideas what this film might be?",2012/09/18,"['https://scifi.stackexchange.com/questions/23575', 'https://scifi.stackexchange.com', 'https://scifi.stackexchange.com/users/8590/']","Is it by any chance [Screamers](http://www.imdb.com/title/tt0114367/)? + +The main character is a human soldier (or mercenary, can't remember exactly). He travels trough an arid, desolated post-apocalyptic planet and saves a little girl from cyborg killing machines, and she follows him 'till the end of the movie, when he dies.","I think it might be the film [Cyborg](http://www.imdb.com/title/tt0097138/). + +> +> Gibson Rickenbacker is a hired fighter living in a plague-ravaged apocalyptic America where a plague has infested most of the United States and the rest of the world. In New York City, Gibson encounters a woman named Pearl Prophet. Pearl reveals to Gibson that she is a cyborg who is carrying vital-information for a group of scientists in Atlanta who are working on a cure to the plague and Pearl hires Gibson to escort her back to Atlanta. But Pearl is kidnapped by ""Pirates"" a murderous gang led by Fender Tremolo, who wants the cure for themselves and they decide to take Pearl to Atlanta themselves. Gibson, joined by a young woman named Nady Simmons, goes in pursuit of Fender and his gang, as Gibson sets out to rescue Pearl, stop Fender and his gang from reaching Atlanta and defeat Fender who slaughtered Gibson's family. (From IMDB) +> +> +>" +23575,"Back in the 90's I remember watching a late-night movie on one of the networks. + +The story took place in an arid, post-apocaliptic future. The plot revolved around a little girl who befriended a cyborg killing machine. The cyborg killing machine spent the movie blasting apart a gang of evil cyborgs to protect her, and it seems like he died in the end. + +It had an old west or samurai vibe to it, and it seemed pretty good for the timeslot it was in. Any ideas what this film might be?",2012/09/18,"['https://scifi.stackexchange.com/questions/23575', 'https://scifi.stackexchange.com', 'https://scifi.stackexchange.com/users/8590/']","S. Albano, in case you haven't already found the movie, the one you're looking for is [Knights (1993)](http://www.imdb.com/title/tt0107333/ ""Knights (1993)"") + +From [Wikipedia](https://en.wikipedia.org/wiki/Knights_(film)): + +> +> The cyborg Gabriel was created to destroy all other cyborgs. He later rescues Nea by killing the cyborg Simon. Gabriel trains Nea to become a cyborg killer and help him. They continue to kill cyborgs until Gabriel is torn in half by one of his targets and taken to the cyborg camp. Nea follows Jacob and challenges the cyborg leader Job to a fight. Finding Gabriel, she straps him to her back and they battle cyborgs until Gabriel can attach a dead cyborg's legs to himself. They pursue Job, but before they can catch him, the Master Builder captures Nea's brother, taking him to Cyborg City. During a battle, Job tells Gabriel that the cyborg population can't be stopped. Job dies moments later. Gabriel and Nea ride off in search of her brother. +> +> +> + +**Trailer**","Is it by any chance [Screamers](http://www.imdb.com/title/tt0114367/)? + +The main character is a human soldier (or mercenary, can't remember exactly). He travels trough an arid, desolated post-apocalyptic planet and saves a little girl from cyborg killing machines, and she follows him 'till the end of the movie, when he dies." +23575,"Back in the 90's I remember watching a late-night movie on one of the networks. + +The story took place in an arid, post-apocaliptic future. The plot revolved around a little girl who befriended a cyborg killing machine. The cyborg killing machine spent the movie blasting apart a gang of evil cyborgs to protect her, and it seems like he died in the end. + +It had an old west or samurai vibe to it, and it seemed pretty good for the timeslot it was in. Any ideas what this film might be?",2012/09/18,"['https://scifi.stackexchange.com/questions/23575', 'https://scifi.stackexchange.com', 'https://scifi.stackexchange.com/users/8590/']","S. Albano, in case you haven't already found the movie, the one you're looking for is [Knights (1993)](http://www.imdb.com/title/tt0107333/ ""Knights (1993)"") + +From [Wikipedia](https://en.wikipedia.org/wiki/Knights_(film)): + +> +> The cyborg Gabriel was created to destroy all other cyborgs. He later rescues Nea by killing the cyborg Simon. Gabriel trains Nea to become a cyborg killer and help him. They continue to kill cyborgs until Gabriel is torn in half by one of his targets and taken to the cyborg camp. Nea follows Jacob and challenges the cyborg leader Job to a fight. Finding Gabriel, she straps him to her back and they battle cyborgs until Gabriel can attach a dead cyborg's legs to himself. They pursue Job, but before they can catch him, the Master Builder captures Nea's brother, taking him to Cyborg City. During a battle, Job tells Gabriel that the cyborg population can't be stopped. Job dies moments later. Gabriel and Nea ride off in search of her brother. +> +> +> + +**Trailer**","I think it might be the film [Cyborg](http://www.imdb.com/title/tt0097138/). + +> +> Gibson Rickenbacker is a hired fighter living in a plague-ravaged apocalyptic America where a plague has infested most of the United States and the rest of the world. In New York City, Gibson encounters a woman named Pearl Prophet. Pearl reveals to Gibson that she is a cyborg who is carrying vital-information for a group of scientists in Atlanta who are working on a cure to the plague and Pearl hires Gibson to escort her back to Atlanta. But Pearl is kidnapped by ""Pirates"" a murderous gang led by Fender Tremolo, who wants the cure for themselves and they decide to take Pearl to Atlanta themselves. Gibson, joined by a young woman named Nady Simmons, goes in pursuit of Fender and his gang, as Gibson sets out to rescue Pearl, stop Fender and his gang from reaching Atlanta and defeat Fender who slaughtered Gibson's family. (From IMDB) +> +> +>" +10908070,"I have a dataset with minute by minute GPS coordinates recorded by a persons cellphone. I.e. the dataset has 1440 rows with LON/LAT values. Based on the data I would like a point estimate (lon/lat value) of where the participants home is. Let's assume that home is the single location where they spend most of their time in a given 24h interval. Furthermore, the GPS sensor most of the time has quite high accuracy, however sometimes it is completely off resulting in gigantic outliers. + +I think the best way to go about this is to treat it as a point process and use 2D density estimation to find the peak. Is there a native way to do this in R? I looked into kde2d (MASS) but this didn't really seem to do the trick. Kde2d creates a 25x25 grid of the data range with density values. However, in my data, the person can easily travel 100 miles or more per day, so these blocks are generally too large of an estimate. I could narrow them down and use a much larger grid but I am sure there must be a better way to get a point estimate.",2012/06/06,"['https://Stackoverflow.com/questions/10908070', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/318752/']","There are ""time spent"" functions in the `trip` package (I'm the author). You can create objects from the track data that understand the underlying track process over time, and simply process the points assuming straight line segments between fixes. If ""home"" is where the largest value pixel is, i.e. when you break up all the segments based on the time duration and sum them into cells, then it's easy to find it. A ""time spent"" grid from the `tripGrid` function is a `SpatialGridDataFrame` with the standard `sp` package classes, and a trip object can be composed of one or many tracks. + +Using `rgdal` you can easily transform coordinates to an appropriate map projection if lon/lat is not appropriate for your extent, but it makes no difference to the grid/time-spent calculation of line segments. + +There is a simple `speedfilter` to remove fixes that imply movement that is too fast, but that is very simplistic and can introduce new problems, in general updating or filtering tracks for unlikely movement can be very complicated. (In my experience a basic time spent gridding gets you as good an estimate as many sophisticated models that just open up new complications). The filter works with Cartesian or long/lat coordinates, using tools in `sp` to calculate distances (long/lat is reliable, whereas a poor map projection choice can introduce problems - over short distances like humans on land it's probably no big deal). + +(The function `tripGrid` calculates the exact components of the straight line segments using `pixellate.psp`, but that detail is hidden in the implementation). + +In terms of data preparation, `trip` is strict about a sensible sequence of times and will prevent you from creating an object if the data have duplicates, are out of order, etc. There is an example of reading data from a text file in `?trip`, and a very simple example with (really) dummy data is: + +``` +library(trip) +d <- data.frame(x = 1:10, y = rnorm(10), tms = Sys.time() + 1:10, id = gl(1, 5)) +coordinates(d) <- ~x+y +tr <- trip(d, c(""tms"", ""id"")) +g <- tripGrid(tr) + +pt <- coordinates(g)[which.max(g$z), ] +image(g, col = c(""transparent"", heat.colors(16))) +lines(tr, col = ""black"") +points(pt[1], pt[2], pch = ""+"", cex = 2) + +``` + +That dummy track has no overlapping regions, but it shows that finding the max point in ""time spent"" is simple enough.","How about using the location that minimises the sum squared distance to all the events? This might be close to the supremum of any kernel smoothing if my brain is working right. + +If your data comprises two clusters (home and work) then I think the location will be in the biggest cluster rather than between them. Its not the same as the simple mean of the x and y coordinates. + +For an uncertainty on that, jitter your data by whatever your positional uncertainty is (would be great if you had that value from the GPS, otherwise guess - 50 metres?) and recompute. Do that 100 times, do a kernel smoothing of those locations and find the 95% contour. + +Not rigorous, and I need to experiment with this minimum distance/kernel supremum thing..." +10908070,"I have a dataset with minute by minute GPS coordinates recorded by a persons cellphone. I.e. the dataset has 1440 rows with LON/LAT values. Based on the data I would like a point estimate (lon/lat value) of where the participants home is. Let's assume that home is the single location where they spend most of their time in a given 24h interval. Furthermore, the GPS sensor most of the time has quite high accuracy, however sometimes it is completely off resulting in gigantic outliers. + +I think the best way to go about this is to treat it as a point process and use 2D density estimation to find the peak. Is there a native way to do this in R? I looked into kde2d (MASS) but this didn't really seem to do the trick. Kde2d creates a 25x25 grid of the data range with density values. However, in my data, the person can easily travel 100 miles or more per day, so these blocks are generally too large of an estimate. I could narrow them down and use a much larger grid but I am sure there must be a better way to get a point estimate.",2012/06/06,"['https://Stackoverflow.com/questions/10908070', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/318752/']","There are ""time spent"" functions in the `trip` package (I'm the author). You can create objects from the track data that understand the underlying track process over time, and simply process the points assuming straight line segments between fixes. If ""home"" is where the largest value pixel is, i.e. when you break up all the segments based on the time duration and sum them into cells, then it's easy to find it. A ""time spent"" grid from the `tripGrid` function is a `SpatialGridDataFrame` with the standard `sp` package classes, and a trip object can be composed of one or many tracks. + +Using `rgdal` you can easily transform coordinates to an appropriate map projection if lon/lat is not appropriate for your extent, but it makes no difference to the grid/time-spent calculation of line segments. + +There is a simple `speedfilter` to remove fixes that imply movement that is too fast, but that is very simplistic and can introduce new problems, in general updating or filtering tracks for unlikely movement can be very complicated. (In my experience a basic time spent gridding gets you as good an estimate as many sophisticated models that just open up new complications). The filter works with Cartesian or long/lat coordinates, using tools in `sp` to calculate distances (long/lat is reliable, whereas a poor map projection choice can introduce problems - over short distances like humans on land it's probably no big deal). + +(The function `tripGrid` calculates the exact components of the straight line segments using `pixellate.psp`, but that detail is hidden in the implementation). + +In terms of data preparation, `trip` is strict about a sensible sequence of times and will prevent you from creating an object if the data have duplicates, are out of order, etc. There is an example of reading data from a text file in `?trip`, and a very simple example with (really) dummy data is: + +``` +library(trip) +d <- data.frame(x = 1:10, y = rnorm(10), tms = Sys.time() + 1:10, id = gl(1, 5)) +coordinates(d) <- ~x+y +tr <- trip(d, c(""tms"", ""id"")) +g <- tripGrid(tr) + +pt <- coordinates(g)[which.max(g$z), ] +image(g, col = c(""transparent"", heat.colors(16))) +lines(tr, col = ""black"") +points(pt[1], pt[2], pch = ""+"", cex = 2) + +``` + +That dummy track has no overlapping regions, but it shows that finding the max point in ""time spent"" is simple enough.","In response to spacedman - I am pretty sure least squares won't work. Least squares is best known for bowing to the demands of outliers, without much weighting to things that are ""nearby"". This is the opposite of what is desired. + +The bisquare estimator would probably work better, in my opinion - but I have never used it. I think it also requires some tuning. + +It's more or less like a least squares estimator for a certain distance from 0, and then the weighting is constant beyond that. So once a point becomes an outlier, it's penalty is constant. We don't want outliers to weigh more and more and more as we move away from them, we would rather weigh them constant, and let the optimization focus on better fitting the things in the vicinity of the cluster." +10908070,"I have a dataset with minute by minute GPS coordinates recorded by a persons cellphone. I.e. the dataset has 1440 rows with LON/LAT values. Based on the data I would like a point estimate (lon/lat value) of where the participants home is. Let's assume that home is the single location where they spend most of their time in a given 24h interval. Furthermore, the GPS sensor most of the time has quite high accuracy, however sometimes it is completely off resulting in gigantic outliers. + +I think the best way to go about this is to treat it as a point process and use 2D density estimation to find the peak. Is there a native way to do this in R? I looked into kde2d (MASS) but this didn't really seem to do the trick. Kde2d creates a 25x25 grid of the data range with density values. However, in my data, the person can easily travel 100 miles or more per day, so these blocks are generally too large of an estimate. I could narrow them down and use a much larger grid but I am sure there must be a better way to get a point estimate.",2012/06/06,"['https://Stackoverflow.com/questions/10908070', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/318752/']","How about using the location that minimises the sum squared distance to all the events? This might be close to the supremum of any kernel smoothing if my brain is working right. + +If your data comprises two clusters (home and work) then I think the location will be in the biggest cluster rather than between them. Its not the same as the simple mean of the x and y coordinates. + +For an uncertainty on that, jitter your data by whatever your positional uncertainty is (would be great if you had that value from the GPS, otherwise guess - 50 metres?) and recompute. Do that 100 times, do a kernel smoothing of those locations and find the 95% contour. + +Not rigorous, and I need to experiment with this minimum distance/kernel supremum thing...","In response to spacedman - I am pretty sure least squares won't work. Least squares is best known for bowing to the demands of outliers, without much weighting to things that are ""nearby"". This is the opposite of what is desired. + +The bisquare estimator would probably work better, in my opinion - but I have never used it. I think it also requires some tuning. + +It's more or less like a least squares estimator for a certain distance from 0, and then the weighting is constant beyond that. So once a point becomes an outlier, it's penalty is constant. We don't want outliers to weigh more and more and more as we move away from them, we would rather weigh them constant, and let the optimization focus on better fitting the things in the vicinity of the cluster." +13075,"I played a game today where I feel that I had a nice positional advantage (the computer supports my opinion) but I only managed to draw it in the end. This is the position that I consider to be critical: + +``` +[fen ""2bq1r2/1r1np1kp/pp4p1/2pP1pP1/2P1NQ2/3B3P/PP3P2/R3R1K1 w - - 0 1""] + +``` + +I am playing White. Here Black played has just played ...f5 and my following moves were Ng3 and h4 (after Rf7). I still had some advantage at that point according to the computer but I lost it a couple of moves later after some inaccuracies. **What plan should I have followed? What are White ideas to win in this position?**",2015/12/13,"['https://chess.stackexchange.com/questions/13075', 'https://chess.stackexchange.com', 'https://chess.stackexchange.com/users/8751/']","Black is very weak on the black squares, on the e file, his e pawn is very weak and his knight and bishop are short of good squares because of his cramped position. + +You should try and get your knight to f4 and double your rooks on the e file. I would start with Nc3. This also helps against Black's obvious plan to undermine your center and give himself more space with b5. You may need to play a4 at some stage to control b5 but your immediate priority should be to double on the e file. Once you control the e file you want to either win his e pawn or invade on the e file. + +At the same time your queen can exert more control over black squares in his position, either from h6 or maybe along the long diagonal from b2 or c3.","You should try for a breakthrough on the h file. You will eventually play h5, but you might want to move your king to g2 and double rooks on the file before you push the pawn. Your pieces have better lateral mobility than Black's, which is why you should be thinking of moving your rooks to one end of the board, and finding a way to break through." +13075,"I played a game today where I feel that I had a nice positional advantage (the computer supports my opinion) but I only managed to draw it in the end. This is the position that I consider to be critical: + +``` +[fen ""2bq1r2/1r1np1kp/pp4p1/2pP1pP1/2P1NQ2/3B3P/PP3P2/R3R1K1 w - - 0 1""] + +``` + +I am playing White. Here Black played has just played ...f5 and my following moves were Ng3 and h4 (after Rf7). I still had some advantage at that point according to the computer but I lost it a couple of moves later after some inaccuracies. **What plan should I have followed? What are White ideas to win in this position?**",2015/12/13,"['https://chess.stackexchange.com/questions/13075', 'https://chess.stackexchange.com', 'https://chess.stackexchange.com/users/8751/']","Black is very weak on the black squares, on the e file, his e pawn is very weak and his knight and bishop are short of good squares because of his cramped position. + +You should try and get your knight to f4 and double your rooks on the e file. I would start with Nc3. This also helps against Black's obvious plan to undermine your center and give himself more space with b5. You may need to play a4 at some stage to control b5 but your immediate priority should be to double on the e file. Once you control the e file you want to either win his e pawn or invade on the e file. + +At the same time your queen can exert more control over black squares in his position, either from h6 or maybe along the long diagonal from b2 or c3.","As stated, White is clearly better here, but it's hard to say if White can force a win in the long run against best play. I like the idea with Nc3 in Brian Towers response a lot, but I'm not sure the idea outlined in that answer is enough to win by itself. + +I think that you should combine different ideas. As suggested, working on the h-file is not something to scoff at. Combine a pawn march to h6 with a well-timed Qc3, and Black is completely tied down. + +Use pressure on the e-file to restrict Black even further. Play a4 at the right time to prevent counterplay; or play a3 followed by b4 to break up Black's pawn structure on the queenside! As long as a black pawn is on e7, it will be very difficult to coordinate Black's pieces to deal with the resulting pressure. + +The more I look at it, the more I like the a3-b4 idea. It's hard to see how Black copes with the pressure. Black may be forced to give up the e7 pawn for nothing." +13075,"I played a game today where I feel that I had a nice positional advantage (the computer supports my opinion) but I only managed to draw it in the end. This is the position that I consider to be critical: + +``` +[fen ""2bq1r2/1r1np1kp/pp4p1/2pP1pP1/2P1NQ2/3B3P/PP3P2/R3R1K1 w - - 0 1""] + +``` + +I am playing White. Here Black played has just played ...f5 and my following moves were Ng3 and h4 (after Rf7). I still had some advantage at that point according to the computer but I lost it a couple of moves later after some inaccuracies. **What plan should I have followed? What are White ideas to win in this position?**",2015/12/13,"['https://chess.stackexchange.com/questions/13075', 'https://chess.stackexchange.com', 'https://chess.stackexchange.com/users/8751/']","As stated, White is clearly better here, but it's hard to say if White can force a win in the long run against best play. I like the idea with Nc3 in Brian Towers response a lot, but I'm not sure the idea outlined in that answer is enough to win by itself. + +I think that you should combine different ideas. As suggested, working on the h-file is not something to scoff at. Combine a pawn march to h6 with a well-timed Qc3, and Black is completely tied down. + +Use pressure on the e-file to restrict Black even further. Play a4 at the right time to prevent counterplay; or play a3 followed by b4 to break up Black's pawn structure on the queenside! As long as a black pawn is on e7, it will be very difficult to coordinate Black's pieces to deal with the resulting pressure. + +The more I look at it, the more I like the a3-b4 idea. It's hard to see how Black copes with the pressure. Black may be forced to give up the e7 pawn for nothing.","You should try for a breakthrough on the h file. You will eventually play h5, but you might want to move your king to g2 and double rooks on the file before you push the pawn. Your pieces have better lateral mobility than Black's, which is why you should be thinking of moving your rooks to one end of the board, and finding a way to break through." +7486389,"Is there any way to call one class's ArrayList onto another class? In class A ArrayList is there, I need to use that ArrayList in class B, Class A is having `AsyncTask` in that I have the Arraylist so I need that in side AsynTask's Arraylist in another class. + +In class A: + +``` +public Class A{ + public class HomeTask extends AsyncTask { + onPreexecute(){} + doInbackground(){} + postexecute(){} + + Arraylist joblist(); //------------ My data is here; + } +} + +``` + +second class: + +``` +Class B +{ + // I need to use that arraylist here +} + +```",2011/09/20,"['https://Stackoverflow.com/questions/7486389', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/954839/']","If you set the language in a view, the error messages will be printed in the selected language: + +``` + from django.utils.translation import activate + activate('de') + +```","if you use \_ in your form messages the message will be displayed in the right lang! but if you want to check which lang is running in the template you can use: + +``` +{% if LANGUAGE_CODE != ""ch"" %} + +{% endif %} + +``` + +for more info about using \_ in your form, check this out: " +7486389,"Is there any way to call one class's ArrayList onto another class? In class A ArrayList is there, I need to use that ArrayList in class B, Class A is having `AsyncTask` in that I have the Arraylist so I need that in side AsynTask's Arraylist in another class. + +In class A: + +``` +public Class A{ + public class HomeTask extends AsyncTask { + onPreexecute(){} + doInbackground(){} + postexecute(){} + + Arraylist joblist(); //------------ My data is here; + } +} + +``` + +second class: + +``` +Class B +{ + // I need to use that arraylist here +} + +```",2011/09/20,"['https://Stackoverflow.com/questions/7486389', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/954839/']","**Some quick explanation first:** + +Your form field errors come from + +``` +raise forms.ValidationError(_(""My Error Message"")) + +``` + +In Django (possibly in other places also), it is common to see this: + +``` +from django.utils.translation import ugettext_lazy as _ + +``` + +This turns the `_` into a `ugettext_lazy`, i.e. the code above is REALLY: + +``` +raise forms.ValidationError(ugettext_lazy(""My Error Message"")) + +``` + +but to avoid typing ugettext\_lazy (or your translation function) over and over again, we simply map it to `_`. + +**Answer to your question** + +Finally, to answer your question on whether the errors can be shown in Chinese (or other languages). This depends on whether the validation error message is passed into django.utils.translation.ugettext. In the example above, the ""My Error Message"" would be displayed in Chinese translated if the user's LANGUAGE\_CODE is zh-tw or zh-cn. + +Below is an example where there would be no translation: + +``` +raise forms.ValidationError(""My Error Message"") + +``` + +I highly recommend reading: as there is additional work you will need to do to get the translations to show up properly.","if you use \_ in your form messages the message will be displayed in the right lang! but if you want to check which lang is running in the template you can use: + +``` +{% if LANGUAGE_CODE != ""ch"" %} + +{% endif %} + +``` + +for more info about using \_ in your form, check this out: " +5081853,"A client has asked me to connect to their SVN server to upload (sync) my file changes rather than use FTP. I simply want to connect to the SVN server. + +Every tutorial I read has something to do with installing SVN server on my local machine - I don't want to install a server, I want to connect to one, pull down the files, replace with my changes, and push them back up. Can someone tell me how to do this? Or is there are very very very basic tutorial out there that explains how? I had never used SVN before this. + +I'm using Ubuntu 10. + +Thanks, +Chris",2011/02/22,"['https://Stackoverflow.com/questions/5081853', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/628815/']","Basically you need to install subversion first: + +``` +sudo apt-get install subversion + +``` + +Then you need to checkout the SVN repository, add your files and commit; that looks similar to this: + +``` +svn co http://some.url/to/the/repository +cd repository-folder +cp ../files/from/otherfolder . +svn add the/new/files +svn commit + +```","I'd suggest reading through and the next 4-5 pages of that chapter/section to get a good primer on using SVN as a client. + +You want to check out a working copy to your local machine: + +`svn checkout my-working-copy` + +This will let you modify files on your local machine, and commit them back up to the repository. Make sure to svn update before you svn commit!" +5873516,"I don't get it. I usually install third party software into */usr/local* so libraries are installed into /usr/local/lib and never had problems linking to these libraries. But now it suddenly no longer works: + +``` +$ gcc -lkaytils -o test test.c +/usr/bin/ld.gold.real: error: cannot find -lkaytils +/usr/bin/ld.gold.real: /tmp/ccXwCkYk.o: in function main:test.c(.text+0x15): +error: undefined reference to 'strCreate' +collect2: ld returned 1 exit status + +``` + +When I add the parameter `-L/usr/local/lib` than it works but I never had to use this before. Header files in */usr/local/include* are found without adding `-I/usr/local/include`. + +I'm using Debian GNU/Linux 6 (Squeeze) which has an entry for */usr/local/lib* in */etc/ld.so.conf.d/libc.conf* by default and the ldconfig cache knows the library I'm trying to use: + +``` +k@vincent:~$ ldconfig -p | grep kaytils + libkaytils.so.0 (libc6,x86-64) => /usr/local/lib/libkaytils.so.0 + libkaytils.so (libc6,x86-64) => /usr/local/lib/libkaytils.so + +``` + +So what the heck is going on here? Where can I check which library paths are searched by gcc by default? Maybe something is wrong there.",2011/05/03,"['https://Stackoverflow.com/questions/5873516', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/274473/']","gcc -print-search-dirs will tell you what path the compiler checks. /usr/local/lib is simply not among them, so your compile time linker (in this case the new gold ld from binutils) doesn't find the library while the dynamic one (ld-linux.so which reads the cache written by ldconfig) does. Presumably the builds you've done previously added -L/usr/local/lib as necessary in their makefiles (usually done by a ./configure script), or you installed binaries.","This is probably an issue of environment variables - you have something set that's including /usr/local/include but not /usr/local/lib + +From the GCC mapage on environment variables + +``` + CPATH specifies a list of directories to be searched as if speci‐ + fied with -I, but after any paths given with -I options on the com‐ + mand line. This environment variable is used regardless of which + language is being preprocessed. + +``` + +and + +``` + The value of LIBRARY_PATH is a colon-separated list of directories, + much like PATH. When configured as a native compiler, GCC tries + the directories thus specified when searching for special linker + files, if it can’t find them using GCC_EXEC_PREFIX. Linking using + GCC also uses these directories when searching for ordinary + libraries for the -l option (but directories specified with -L come + first). + +``` + +try ""printenv"" to see what you have set" +55464578,"Consider the following code: + +``` +struct A { + virtual A& operator+=(const A& other) noexcept = 0; +}; + +void foo_inner(int *p) noexcept { *p += *p; } +void foo_virtual_inner(A *p) noexcept { *p += *p; } + +void foo(int *p) noexcept +{ + return foo_inner(p); +} + +struct Aint : public A { + int i; + A& operator+=(const A& other) noexcept override final + { +// No devirtualization of foo_virtual with: + i += dynamic_cast(other).i; +// ... nor with: +// i += reinterpret_cast(other).i; + return *this; + } +}; + +void foo_virtual(Aint *p) noexcept +{ + return foo_virtual_inner(p); +} + +``` + +As far as I can tell, both `foo()` and `foo_virtual()` should compile to the same object code. The compiler has all the information it needs to de-virtualize the call to `operator+=` in `foo_virtual_inner()`, when it's called from `foo_virtual`. But - [neither GCC 8.3, nor MSVC 19.10, nor clang 8 do this](https://godbolt.org/z/l0vdFG). Naturally I used the maximum optimization flag (`-O3` or `/Ox`). + +Why? Is this a bug, or am I missing something? + +--- + +clang 8 output: + +``` +foo(int*): # @foo(int*) + shl dword ptr [rdi] + ret +foo_virtual(Aint*): # @foo_virtual(Aint*) + mov rax, qword ptr [rdi] + mov rax, qword ptr [rax] + mov rsi, rdi + jmp rax # TAILCALL + +``` + +GCC 8.3 output: + +``` +foo(int*): + sal DWORD PTR [rdi] + ret +foo_virtual(Aint*): + mov rax, QWORD PTR [rdi] + mov rax, QWORD PTR [rax] + cmp rax, OFFSET FLAT:Aint::operator+=(A const&) + jne .L19 + push rbx + xor ecx, ecx + mov edx, OFFSET FLAT:typeinfo for Aint + mov esi, OFFSET FLAT:typeinfo for A + mov rbx, rdi + call __dynamic_cast + test rax, rax + je .L20 + mov eax, DWORD PTR [rax+8] + add DWORD PTR [rbx+8], eax + pop rbx + ret +.L19: + mov rsi, rdi + jmp rax +foo_virtual(Aint*) [clone .cold.1]: +.L20: + call __cxa_bad_cast + +``` + +MSVC 19.10 output: + +``` +p$ = 8 +void foo(int * __ptr64) PROC ; foo + mov eax, DWORD PTR [rcx] + add eax, eax + mov DWORD PTR [rcx], eax + ret 0 +void foo(int * __ptr64) ENDP ; foo + +p$ = 8 +void foo_virtual(Aint * __ptr64) PROC ; foo_virtual + mov rax, QWORD PTR [rcx] + mov rdx, rcx + rex_jmp QWORD PTR [rax] +void foo_virtual(Aint * __ptr64) ENDP + +``` + +PS - What's the explanation for all of that typeinfo business in the compiled code under GCC?",2019/04/01,"['https://Stackoverflow.com/questions/55464578', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1593077/']","GCC guesses that Aint \*p points to instance of Aint \*p (but does not think this is guaranteed to happen) and therefore it devirtualises speculatively the call to operator+= and the typeinfo checking is an inlined copy of it. +-fno-devirtualize-speculatively leads to same code as Clang and MSVC produces. + +``` +_Z11foo_virtualP4Aint: +.LFB4: + .cfi_startproc + movq (%rdi), %rax + movq %rdi, %rsi + movq (%rax), %rax + jmp *%rax + +```","Following @JanHubicka's answer, I've filed a bug against GCC: + + + +and it's being worked on (!)." +55464578,"Consider the following code: + +``` +struct A { + virtual A& operator+=(const A& other) noexcept = 0; +}; + +void foo_inner(int *p) noexcept { *p += *p; } +void foo_virtual_inner(A *p) noexcept { *p += *p; } + +void foo(int *p) noexcept +{ + return foo_inner(p); +} + +struct Aint : public A { + int i; + A& operator+=(const A& other) noexcept override final + { +// No devirtualization of foo_virtual with: + i += dynamic_cast(other).i; +// ... nor with: +// i += reinterpret_cast(other).i; + return *this; + } +}; + +void foo_virtual(Aint *p) noexcept +{ + return foo_virtual_inner(p); +} + +``` + +As far as I can tell, both `foo()` and `foo_virtual()` should compile to the same object code. The compiler has all the information it needs to de-virtualize the call to `operator+=` in `foo_virtual_inner()`, when it's called from `foo_virtual`. But - [neither GCC 8.3, nor MSVC 19.10, nor clang 8 do this](https://godbolt.org/z/l0vdFG). Naturally I used the maximum optimization flag (`-O3` or `/Ox`). + +Why? Is this a bug, or am I missing something? + +--- + +clang 8 output: + +``` +foo(int*): # @foo(int*) + shl dword ptr [rdi] + ret +foo_virtual(Aint*): # @foo_virtual(Aint*) + mov rax, qword ptr [rdi] + mov rax, qword ptr [rax] + mov rsi, rdi + jmp rax # TAILCALL + +``` + +GCC 8.3 output: + +``` +foo(int*): + sal DWORD PTR [rdi] + ret +foo_virtual(Aint*): + mov rax, QWORD PTR [rdi] + mov rax, QWORD PTR [rax] + cmp rax, OFFSET FLAT:Aint::operator+=(A const&) + jne .L19 + push rbx + xor ecx, ecx + mov edx, OFFSET FLAT:typeinfo for Aint + mov esi, OFFSET FLAT:typeinfo for A + mov rbx, rdi + call __dynamic_cast + test rax, rax + je .L20 + mov eax, DWORD PTR [rax+8] + add DWORD PTR [rbx+8], eax + pop rbx + ret +.L19: + mov rsi, rdi + jmp rax +foo_virtual(Aint*) [clone .cold.1]: +.L20: + call __cxa_bad_cast + +``` + +MSVC 19.10 output: + +``` +p$ = 8 +void foo(int * __ptr64) PROC ; foo + mov eax, DWORD PTR [rcx] + add eax, eax + mov DWORD PTR [rcx], eax + ret 0 +void foo(int * __ptr64) ENDP ; foo + +p$ = 8 +void foo_virtual(Aint * __ptr64) PROC ; foo_virtual + mov rax, QWORD PTR [rcx] + mov rdx, rcx + rex_jmp QWORD PTR [rax] +void foo_virtual(Aint * __ptr64) ENDP + +``` + +PS - What's the explanation for all of that typeinfo business in the compiled code under GCC?",2019/04/01,"['https://Stackoverflow.com/questions/55464578', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1593077/']","GCC guesses that Aint \*p points to instance of Aint \*p (but does not think this is guaranteed to happen) and therefore it devirtualises speculatively the call to operator+= and the typeinfo checking is an inlined copy of it. +-fno-devirtualize-speculatively leads to same code as Clang and MSVC produces. + +``` +_Z11foo_virtualP4Aint: +.LFB4: + .cfi_startproc + movq (%rdi), %rax + movq %rdi, %rsi + movq (%rax), %rax + jmp *%rax + +```","The compiler can't assume that an Aint\* actually points to an Aint object until it sees some operation that would have undefined semantics otherwise, like referring to one of its non-static members. Otherwise it could be the result of reinterpret\_cast from some other pointer type waiting to be reinterpret\_casted back to that type. + +It seems to me that the standard conversion to A\* should be such an operation, but AFAICT the standard doesn't currently say that. Wording to that effect would need to consider converting to a non-virtual base of an object under construction, which is deliberately allowed." +55464578,"Consider the following code: + +``` +struct A { + virtual A& operator+=(const A& other) noexcept = 0; +}; + +void foo_inner(int *p) noexcept { *p += *p; } +void foo_virtual_inner(A *p) noexcept { *p += *p; } + +void foo(int *p) noexcept +{ + return foo_inner(p); +} + +struct Aint : public A { + int i; + A& operator+=(const A& other) noexcept override final + { +// No devirtualization of foo_virtual with: + i += dynamic_cast(other).i; +// ... nor with: +// i += reinterpret_cast(other).i; + return *this; + } +}; + +void foo_virtual(Aint *p) noexcept +{ + return foo_virtual_inner(p); +} + +``` + +As far as I can tell, both `foo()` and `foo_virtual()` should compile to the same object code. The compiler has all the information it needs to de-virtualize the call to `operator+=` in `foo_virtual_inner()`, when it's called from `foo_virtual`. But - [neither GCC 8.3, nor MSVC 19.10, nor clang 8 do this](https://godbolt.org/z/l0vdFG). Naturally I used the maximum optimization flag (`-O3` or `/Ox`). + +Why? Is this a bug, or am I missing something? + +--- + +clang 8 output: + +``` +foo(int*): # @foo(int*) + shl dword ptr [rdi] + ret +foo_virtual(Aint*): # @foo_virtual(Aint*) + mov rax, qword ptr [rdi] + mov rax, qword ptr [rax] + mov rsi, rdi + jmp rax # TAILCALL + +``` + +GCC 8.3 output: + +``` +foo(int*): + sal DWORD PTR [rdi] + ret +foo_virtual(Aint*): + mov rax, QWORD PTR [rdi] + mov rax, QWORD PTR [rax] + cmp rax, OFFSET FLAT:Aint::operator+=(A const&) + jne .L19 + push rbx + xor ecx, ecx + mov edx, OFFSET FLAT:typeinfo for Aint + mov esi, OFFSET FLAT:typeinfo for A + mov rbx, rdi + call __dynamic_cast + test rax, rax + je .L20 + mov eax, DWORD PTR [rax+8] + add DWORD PTR [rbx+8], eax + pop rbx + ret +.L19: + mov rsi, rdi + jmp rax +foo_virtual(Aint*) [clone .cold.1]: +.L20: + call __cxa_bad_cast + +``` + +MSVC 19.10 output: + +``` +p$ = 8 +void foo(int * __ptr64) PROC ; foo + mov eax, DWORD PTR [rcx] + add eax, eax + mov DWORD PTR [rcx], eax + ret 0 +void foo(int * __ptr64) ENDP ; foo + +p$ = 8 +void foo_virtual(Aint * __ptr64) PROC ; foo_virtual + mov rax, QWORD PTR [rcx] + mov rdx, rcx + rex_jmp QWORD PTR [rax] +void foo_virtual(Aint * __ptr64) ENDP + +``` + +PS - What's the explanation for all of that typeinfo business in the compiled code under GCC?",2019/04/01,"['https://Stackoverflow.com/questions/55464578', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1593077/']","Following @JanHubicka's answer, I've filed a bug against GCC: + + + +and it's being worked on (!).","The compiler can't assume that an Aint\* actually points to an Aint object until it sees some operation that would have undefined semantics otherwise, like referring to one of its non-static members. Otherwise it could be the result of reinterpret\_cast from some other pointer type waiting to be reinterpret\_casted back to that type. + +It seems to me that the standard conversion to A\* should be such an operation, but AFAICT the standard doesn't currently say that. Wording to that effect would need to consider converting to a non-virtual base of an object under construction, which is deliberately allowed." +53561760,"I feel dumb as it seems so easy. But I am stuck with this one: + +I built a scraper which gets me the titles of jobs. +Works great but it includes the h1 tags. E.g. it saves the title of a job as: + +""<*h1>Marketing Manager<*/h1>"" +I do not know why he does not just take the value within the h1 tag. + +But secondly, I just tried to strip the tags away by stripping the first 4 and last 5 characters of the title (title(4..-5). Unfortunately no function like strip seems to work (the error tells me its some weird nokogiri class that cannot be stripped). + +So here is my code, hopefully someone knows a smart solution for my problem: + +``` +company_career_urls.each do |url| + puts ""gets job url"" + # get the specific job url + html_file = open(url).read + html_doc = Nokogiri::HTML(html_file) + i = 0 + Vacancy.where(:companyname => ""Lillydoo"").destroy_all + html_doc.search('.job-list-button a').each do |element| + i = i+1 + if i > 7 + else + job_url = element.attribute('href').value + puts job_url + #get the job name and description + html_file = open(job_url).read + html_doc = Nokogiri::HTML(html_file) + job_description = html_doc.search('.inner ul') + job_title = html_doc.search('.job-detail-desc h1') #this line seems to be the problem + # job_title = job_title_html[4..-6] + puts job_title + + resource_type = ""image"" + type = ""upload"" + version = 1234567890 + public_id = ""wv7l1o6xwimtfvx2oxdw"" + format = ""jpg"" + signature = Cloudinary::Utils.api_sign_request({:public_id=>public_id, + :version=>version}, Cloudinary.config.api_secret) + photo = ""#{resource_type}/#{type}/v#{version}/#{public_id}.#{format}##{signature}"" + vacancy = Vacancy.create(title: job_title, companyname: 'Lillydoo', jobdescription: job_description, photo: photo) + end + end + +```",2018/11/30,"['https://Stackoverflow.com/questions/53561760', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10075876/']","This gives you a bunch of elements: + +``` +job_title = html_doc.search('.job-detail-desc h1') + +``` + +This gives you the text of the first one: + +``` +job_title = html_doc.at('.job-detail-desc h1').text + +```","For HTML, a rule of thumb is that documents have `html` and `body` tags, and fragments usually do not. Try to use the `DocumentFragment` class because the text is not a valid HTML or XML document. + +``` +html_doc = Nokogiri::HTML::DocumentFragment.parse(html_file) + +```" +53561760,"I feel dumb as it seems so easy. But I am stuck with this one: + +I built a scraper which gets me the titles of jobs. +Works great but it includes the h1 tags. E.g. it saves the title of a job as: + +""<*h1>Marketing Manager<*/h1>"" +I do not know why he does not just take the value within the h1 tag. + +But secondly, I just tried to strip the tags away by stripping the first 4 and last 5 characters of the title (title(4..-5). Unfortunately no function like strip seems to work (the error tells me its some weird nokogiri class that cannot be stripped). + +So here is my code, hopefully someone knows a smart solution for my problem: + +``` +company_career_urls.each do |url| + puts ""gets job url"" + # get the specific job url + html_file = open(url).read + html_doc = Nokogiri::HTML(html_file) + i = 0 + Vacancy.where(:companyname => ""Lillydoo"").destroy_all + html_doc.search('.job-list-button a').each do |element| + i = i+1 + if i > 7 + else + job_url = element.attribute('href').value + puts job_url + #get the job name and description + html_file = open(job_url).read + html_doc = Nokogiri::HTML(html_file) + job_description = html_doc.search('.inner ul') + job_title = html_doc.search('.job-detail-desc h1') #this line seems to be the problem + # job_title = job_title_html[4..-6] + puts job_title + + resource_type = ""image"" + type = ""upload"" + version = 1234567890 + public_id = ""wv7l1o6xwimtfvx2oxdw"" + format = ""jpg"" + signature = Cloudinary::Utils.api_sign_request({:public_id=>public_id, + :version=>version}, Cloudinary.config.api_secret) + photo = ""#{resource_type}/#{type}/v#{version}/#{public_id}.#{format}##{signature}"" + vacancy = Vacancy.create(title: job_title, companyname: 'Lillydoo', jobdescription: job_description, photo: photo) + end + end + +```",2018/11/30,"['https://Stackoverflow.com/questions/53561760', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10075876/']","The issue you're having is that `job_title` is not a simple string; it's a set of node object(s) that match the search. When you print it with `puts`, Ruby is calling `#to_s` on the node set and outputting the ""HTML source"" of all the nodes. + +What you need to do is to isolate the node you want an then extract its text content using `#content` (or `#text`). Here's an example: + +``` +require 'nokogiri' + +CONTENT = <<'EOT' + + +

Test Heading

+ + +EOT + +html_doc = Nokogiri::HTML(CONTENT) + +# this returns a set of all matching nodes +nodes = html_doc.css('h1') +puts nodes.class # --> ""Nokogiri::XML::NodeSet"" +puts nodes # --> ""

Test Heading

"" + +# if you know you will only have one, use at_css +node = html_doc.at_css('h1') +puts node.class # --> ""Nokogiri::XML::Element"" +puts node # --> ""

Test Heading

"" + +# to get just the text content inside the node +puts node.content # --> ""Test Heading"" + +``` + +See ","For HTML, a rule of thumb is that documents have `html` and `body` tags, and fragments usually do not. Try to use the `DocumentFragment` class because the text is not a valid HTML or XML document. + +``` +html_doc = Nokogiri::HTML::DocumentFragment.parse(html_file) + +```" +46169229,"I've seen a lot of nice solutions here about how to work with ArrayList and HashMaps, but the point is I still can't solve my problem. + +So, the idea is there are few people that drink beer, wine and cola. So, it looks like that (for example): + +``` +Steve wine +Steve cola +Ben cola +Frank wine +Ben cola +Ben cola +Frank wine + +``` + +In the end I need to count how many glasses of each drink each of them drank. So, the answer should look like that: + +``` +Steve wine 1 +Steve cola 1 +Ben cola 3 +Frank wine 2 + +``` + +My idea was to put to create an object Person(String name, String drink). Then I put all the persons to ArrayList. After that I have created HashMap and wanted to add there a new Person if key doesn't exist, and to increment to 1 if key already exists. + +``` + Map map = new HashMap(); + + for (Person p : persons) + { + if (map.containsKey(p)) { + map.put(p, map.get(p)+1); + } else { + map.put(p,1); + } + } + +``` + +It doesn't work. It just returns me the result like this: + +``` + Steve wine 1 + Steve cola 1 + Ben cola 1 + Frank wine 1 + Ben cola 1 + Ben cola 1 + Frank wine 1 + +``` + +So, as I understand that should be some other trick here. Maybe you could also tell any other ideas of how to count the glasses of the drinks instead of using HashMap? +Many thanks!",2017/09/12,"['https://Stackoverflow.com/questions/46169229', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8258820/']","Key should be unique in hash map or Dictionary (C#). This case while inserting key itself need to combine name and drink. Giving the solution in C# here. Hope it helps. + +``` +public class Person +{ + public string Name { get; set; } + public string Drink { get; set; } +} + +class Program +{ + static void Main(string[] args) + { + List persons = new List(); + persons.Add(new Person() { Name = ""Steve"", Drink = ""Tea"" }); + persons.Add(new Person() { Name = ""Bell"", Drink = ""Milk"" }); + persons.Add(new Person() { Name = ""Bell"", Drink = ""Milk"" }); + persons.Add(new Person() { Name = ""Bell"", Drink = ""Milk"" }); + persons.Add(new Person() { Name = ""Steve"", Drink = ""Milk"" }); + Dictionary output = new Dictionary(); + foreach(var p in persons) + { + string key = p.Name + "":"" + p.Drink; + if(output.ContainsKey(key)) + { + output[key]++; + } + else + { + output.Add(key,1); + } + } + foreach(var k in output) + { + string[] split = k.Key.Split(':'); + Console.WriteLine(string.Format(""{0} {1} {2}"", split[0],split[1],k.Value.ToString())); + } + } +} + +```","First I would recommend you to take care of your namings. What is really the key in your case is an order not a person (since Steve cola and Steve wine is different you shouldn't name it as person). + +After that: containsKey will use the hashcode method which will be inherited from the Object class if you don't override it in your class. The Object class's hashcode probably will provide different hashcode for your instances so you should override it in your class e.g. you can create an acceptable hashcode method if you concat the name and beverage (which is your unique identifier for an order) and invoke a hashcode method on that string." +46169229,"I've seen a lot of nice solutions here about how to work with ArrayList and HashMaps, but the point is I still can't solve my problem. + +So, the idea is there are few people that drink beer, wine and cola. So, it looks like that (for example): + +``` +Steve wine +Steve cola +Ben cola +Frank wine +Ben cola +Ben cola +Frank wine + +``` + +In the end I need to count how many glasses of each drink each of them drank. So, the answer should look like that: + +``` +Steve wine 1 +Steve cola 1 +Ben cola 3 +Frank wine 2 + +``` + +My idea was to put to create an object Person(String name, String drink). Then I put all the persons to ArrayList. After that I have created HashMap and wanted to add there a new Person if key doesn't exist, and to increment to 1 if key already exists. + +``` + Map map = new HashMap(); + + for (Person p : persons) + { + if (map.containsKey(p)) { + map.put(p, map.get(p)+1); + } else { + map.put(p,1); + } + } + +``` + +It doesn't work. It just returns me the result like this: + +``` + Steve wine 1 + Steve cola 1 + Ben cola 1 + Frank wine 1 + Ben cola 1 + Ben cola 1 + Frank wine 1 + +``` + +So, as I understand that should be some other trick here. Maybe you could also tell any other ideas of how to count the glasses of the drinks instead of using HashMap? +Many thanks!",2017/09/12,"['https://Stackoverflow.com/questions/46169229', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8258820/']","You are making a mistake by storing `Person` Object as a Key. + +You must store the person name, a String as Key and it will work fine. + +``` + Map map = new HashMap<>(); + + for (Person p : persons) + { + if (map.containsKey(p.getName())) { + map.put(p.getName(), map.get(p)+1); + } else { + map.put(p.getName(),1); + } + } + +```","You have to override equals and hashCode method in Person class. Below is the sample code: + +``` +class Person { + + private String name; + private String drink; + + public Person(String name, String drink) { + super(); + this.name = name; + this.drink = drink; + } + + @Override + public int hashCode() { + + return this.getName().hashCode(); + } + + @Override + public boolean equals(Object obj) { + + if (obj == this) + return true; + + if (!(obj instanceof Person)) { + return false; + } + Person person = (Person) obj; + + return person.getName().equals(this.name); + } + ....getters and setters + ....toString method +} + +``` + +After this, if you try to run your code it will work for sure for me output for below code was + +``` + Map map = new HashMap<>(); + + for (Person p : persons) + { + if (map.containsKey(p)) { + map.put(p, map.get(p)+1); + } else { + map.put(p,1); + } + } + + for(Map.Entry person : map.entrySet()){ + System.out.println(person.getKey()+"" ""+person.getValue()); + } + +``` + +Output: + +``` +Person [name=Steve, drink=wine] 2 +Person [name=Ben, drink=cola] 3 +Person [name=Frank, drink=wine] 2 + +``` + +Hope it will help you." +46169229,"I've seen a lot of nice solutions here about how to work with ArrayList and HashMaps, but the point is I still can't solve my problem. + +So, the idea is there are few people that drink beer, wine and cola. So, it looks like that (for example): + +``` +Steve wine +Steve cola +Ben cola +Frank wine +Ben cola +Ben cola +Frank wine + +``` + +In the end I need to count how many glasses of each drink each of them drank. So, the answer should look like that: + +``` +Steve wine 1 +Steve cola 1 +Ben cola 3 +Frank wine 2 + +``` + +My idea was to put to create an object Person(String name, String drink). Then I put all the persons to ArrayList. After that I have created HashMap and wanted to add there a new Person if key doesn't exist, and to increment to 1 if key already exists. + +``` + Map map = new HashMap(); + + for (Person p : persons) + { + if (map.containsKey(p)) { + map.put(p, map.get(p)+1); + } else { + map.put(p,1); + } + } + +``` + +It doesn't work. It just returns me the result like this: + +``` + Steve wine 1 + Steve cola 1 + Ben cola 1 + Frank wine 1 + Ben cola 1 + Ben cola 1 + Frank wine 1 + +``` + +So, as I understand that should be some other trick here. Maybe you could also tell any other ideas of how to count the glasses of the drinks instead of using HashMap? +Many thanks!",2017/09/12,"['https://Stackoverflow.com/questions/46169229', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8258820/']",Overwrite hashcode and equals method in your Person class,"You are making a mistake by storing `Person` Object as a Key. + +You must store the person name, a String as Key and it will work fine. + +``` + Map map = new HashMap<>(); + + for (Person p : persons) + { + if (map.containsKey(p.getName())) { + map.put(p.getName(), map.get(p)+1); + } else { + map.put(p.getName(),1); + } + } + +```" +46169229,"I've seen a lot of nice solutions here about how to work with ArrayList and HashMaps, but the point is I still can't solve my problem. + +So, the idea is there are few people that drink beer, wine and cola. So, it looks like that (for example): + +``` +Steve wine +Steve cola +Ben cola +Frank wine +Ben cola +Ben cola +Frank wine + +``` + +In the end I need to count how many glasses of each drink each of them drank. So, the answer should look like that: + +``` +Steve wine 1 +Steve cola 1 +Ben cola 3 +Frank wine 2 + +``` + +My idea was to put to create an object Person(String name, String drink). Then I put all the persons to ArrayList. After that I have created HashMap and wanted to add there a new Person if key doesn't exist, and to increment to 1 if key already exists. + +``` + Map map = new HashMap(); + + for (Person p : persons) + { + if (map.containsKey(p)) { + map.put(p, map.get(p)+1); + } else { + map.put(p,1); + } + } + +``` + +It doesn't work. It just returns me the result like this: + +``` + Steve wine 1 + Steve cola 1 + Ben cola 1 + Frank wine 1 + Ben cola 1 + Ben cola 1 + Frank wine 1 + +``` + +So, as I understand that should be some other trick here. Maybe you could also tell any other ideas of how to count the glasses of the drinks instead of using HashMap? +Many thanks!",2017/09/12,"['https://Stackoverflow.com/questions/46169229', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8258820/']","If you can use Java 8 streams here is one clever solution : + +``` + List people = Arrays.asList(new Person(""Steve"", ""wine""), new Person(""Steve"", ""cola""), + new Person(""Ben"", ""cola""), new Person(""Ben"", ""cola""), new Person(""Steve"", ""wine""), + new Person(""Steve"", ""wine"")); + + Map map = people.stream() + .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); + +``` + +**Edit :** +To decrease the code you can import the methods statically like this: + +``` +import static java.util.stream.Collectors.groupingBy; +import static java.util.stream.Collectors.counting; +import static java.util.function.Function.identity; + +``` + +and then the code look like this: + +``` +Map map = people + .stream() + .collect(groupingBy(identity(), counting())); + +```",Overwrite hashcode and equals method in your Person class +46169229,"I've seen a lot of nice solutions here about how to work with ArrayList and HashMaps, but the point is I still can't solve my problem. + +So, the idea is there are few people that drink beer, wine and cola. So, it looks like that (for example): + +``` +Steve wine +Steve cola +Ben cola +Frank wine +Ben cola +Ben cola +Frank wine + +``` + +In the end I need to count how many glasses of each drink each of them drank. So, the answer should look like that: + +``` +Steve wine 1 +Steve cola 1 +Ben cola 3 +Frank wine 2 + +``` + +My idea was to put to create an object Person(String name, String drink). Then I put all the persons to ArrayList. After that I have created HashMap and wanted to add there a new Person if key doesn't exist, and to increment to 1 if key already exists. + +``` + Map map = new HashMap(); + + for (Person p : persons) + { + if (map.containsKey(p)) { + map.put(p, map.get(p)+1); + } else { + map.put(p,1); + } + } + +``` + +It doesn't work. It just returns me the result like this: + +``` + Steve wine 1 + Steve cola 1 + Ben cola 1 + Frank wine 1 + Ben cola 1 + Ben cola 1 + Frank wine 1 + +``` + +So, as I understand that should be some other trick here. Maybe you could also tell any other ideas of how to count the glasses of the drinks instead of using HashMap? +Many thanks!",2017/09/12,"['https://Stackoverflow.com/questions/46169229', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8258820/']",Overwrite hashcode and equals method in your Person class,"You have to override equals and hashCode method in Person class. Below is the sample code: + +``` +class Person { + + private String name; + private String drink; + + public Person(String name, String drink) { + super(); + this.name = name; + this.drink = drink; + } + + @Override + public int hashCode() { + + return this.getName().hashCode(); + } + + @Override + public boolean equals(Object obj) { + + if (obj == this) + return true; + + if (!(obj instanceof Person)) { + return false; + } + Person person = (Person) obj; + + return person.getName().equals(this.name); + } + ....getters and setters + ....toString method +} + +``` + +After this, if you try to run your code it will work for sure for me output for below code was + +``` + Map map = new HashMap<>(); + + for (Person p : persons) + { + if (map.containsKey(p)) { + map.put(p, map.get(p)+1); + } else { + map.put(p,1); + } + } + + for(Map.Entry person : map.entrySet()){ + System.out.println(person.getKey()+"" ""+person.getValue()); + } + +``` + +Output: + +``` +Person [name=Steve, drink=wine] 2 +Person [name=Ben, drink=cola] 3 +Person [name=Frank, drink=wine] 2 + +``` + +Hope it will help you." +46169229,"I've seen a lot of nice solutions here about how to work with ArrayList and HashMaps, but the point is I still can't solve my problem. + +So, the idea is there are few people that drink beer, wine and cola. So, it looks like that (for example): + +``` +Steve wine +Steve cola +Ben cola +Frank wine +Ben cola +Ben cola +Frank wine + +``` + +In the end I need to count how many glasses of each drink each of them drank. So, the answer should look like that: + +``` +Steve wine 1 +Steve cola 1 +Ben cola 3 +Frank wine 2 + +``` + +My idea was to put to create an object Person(String name, String drink). Then I put all the persons to ArrayList. After that I have created HashMap and wanted to add there a new Person if key doesn't exist, and to increment to 1 if key already exists. + +``` + Map map = new HashMap(); + + for (Person p : persons) + { + if (map.containsKey(p)) { + map.put(p, map.get(p)+1); + } else { + map.put(p,1); + } + } + +``` + +It doesn't work. It just returns me the result like this: + +``` + Steve wine 1 + Steve cola 1 + Ben cola 1 + Frank wine 1 + Ben cola 1 + Ben cola 1 + Frank wine 1 + +``` + +So, as I understand that should be some other trick here. Maybe you could also tell any other ideas of how to count the glasses of the drinks instead of using HashMap? +Many thanks!",2017/09/12,"['https://Stackoverflow.com/questions/46169229', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8258820/']",Overwrite hashcode and equals method in your Person class,"Key should be unique in hash map or Dictionary (C#). This case while inserting key itself need to combine name and drink. Giving the solution in C# here. Hope it helps. + +``` +public class Person +{ + public string Name { get; set; } + public string Drink { get; set; } +} + +class Program +{ + static void Main(string[] args) + { + List persons = new List(); + persons.Add(new Person() { Name = ""Steve"", Drink = ""Tea"" }); + persons.Add(new Person() { Name = ""Bell"", Drink = ""Milk"" }); + persons.Add(new Person() { Name = ""Bell"", Drink = ""Milk"" }); + persons.Add(new Person() { Name = ""Bell"", Drink = ""Milk"" }); + persons.Add(new Person() { Name = ""Steve"", Drink = ""Milk"" }); + Dictionary output = new Dictionary(); + foreach(var p in persons) + { + string key = p.Name + "":"" + p.Drink; + if(output.ContainsKey(key)) + { + output[key]++; + } + else + { + output.Add(key,1); + } + } + foreach(var k in output) + { + string[] split = k.Key.Split(':'); + Console.WriteLine(string.Format(""{0} {1} {2}"", split[0],split[1],k.Value.ToString())); + } + } +} + +```" +46169229,"I've seen a lot of nice solutions here about how to work with ArrayList and HashMaps, but the point is I still can't solve my problem. + +So, the idea is there are few people that drink beer, wine and cola. So, it looks like that (for example): + +``` +Steve wine +Steve cola +Ben cola +Frank wine +Ben cola +Ben cola +Frank wine + +``` + +In the end I need to count how many glasses of each drink each of them drank. So, the answer should look like that: + +``` +Steve wine 1 +Steve cola 1 +Ben cola 3 +Frank wine 2 + +``` + +My idea was to put to create an object Person(String name, String drink). Then I put all the persons to ArrayList. After that I have created HashMap and wanted to add there a new Person if key doesn't exist, and to increment to 1 if key already exists. + +``` + Map map = new HashMap(); + + for (Person p : persons) + { + if (map.containsKey(p)) { + map.put(p, map.get(p)+1); + } else { + map.put(p,1); + } + } + +``` + +It doesn't work. It just returns me the result like this: + +``` + Steve wine 1 + Steve cola 1 + Ben cola 1 + Frank wine 1 + Ben cola 1 + Ben cola 1 + Frank wine 1 + +``` + +So, as I understand that should be some other trick here. Maybe you could also tell any other ideas of how to count the glasses of the drinks instead of using HashMap? +Many thanks!",2017/09/12,"['https://Stackoverflow.com/questions/46169229', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8258820/']","If you can use Java 8 streams here is one clever solution : + +``` + List people = Arrays.asList(new Person(""Steve"", ""wine""), new Person(""Steve"", ""cola""), + new Person(""Ben"", ""cola""), new Person(""Ben"", ""cola""), new Person(""Steve"", ""wine""), + new Person(""Steve"", ""wine"")); + + Map map = people.stream() + .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); + +``` + +**Edit :** +To decrease the code you can import the methods statically like this: + +``` +import static java.util.stream.Collectors.groupingBy; +import static java.util.stream.Collectors.counting; +import static java.util.function.Function.identity; + +``` + +and then the code look like this: + +``` +Map map = people + .stream() + .collect(groupingBy(identity(), counting())); + +```","First I would recommend you to take care of your namings. What is really the key in your case is an order not a person (since Steve cola and Steve wine is different you shouldn't name it as person). + +After that: containsKey will use the hashcode method which will be inherited from the Object class if you don't override it in your class. The Object class's hashcode probably will provide different hashcode for your instances so you should override it in your class e.g. you can create an acceptable hashcode method if you concat the name and beverage (which is your unique identifier for an order) and invoke a hashcode method on that string." +46169229,"I've seen a lot of nice solutions here about how to work with ArrayList and HashMaps, but the point is I still can't solve my problem. + +So, the idea is there are few people that drink beer, wine and cola. So, it looks like that (for example): + +``` +Steve wine +Steve cola +Ben cola +Frank wine +Ben cola +Ben cola +Frank wine + +``` + +In the end I need to count how many glasses of each drink each of them drank. So, the answer should look like that: + +``` +Steve wine 1 +Steve cola 1 +Ben cola 3 +Frank wine 2 + +``` + +My idea was to put to create an object Person(String name, String drink). Then I put all the persons to ArrayList. After that I have created HashMap and wanted to add there a new Person if key doesn't exist, and to increment to 1 if key already exists. + +``` + Map map = new HashMap(); + + for (Person p : persons) + { + if (map.containsKey(p)) { + map.put(p, map.get(p)+1); + } else { + map.put(p,1); + } + } + +``` + +It doesn't work. It just returns me the result like this: + +``` + Steve wine 1 + Steve cola 1 + Ben cola 1 + Frank wine 1 + Ben cola 1 + Ben cola 1 + Frank wine 1 + +``` + +So, as I understand that should be some other trick here. Maybe you could also tell any other ideas of how to count the glasses of the drinks instead of using HashMap? +Many thanks!",2017/09/12,"['https://Stackoverflow.com/questions/46169229', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8258820/']","You are making a mistake by storing `Person` Object as a Key. + +You must store the person name, a String as Key and it will work fine. + +``` + Map map = new HashMap<>(); + + for (Person p : persons) + { + if (map.containsKey(p.getName())) { + map.put(p.getName(), map.get(p)+1); + } else { + map.put(p.getName(),1); + } + } + +```","Overriding **equals** and **hascode** method in your **Person** class is the solution for your problem. + +assuming you have Person class with parameter **name** and **drink** , then you could use some IDE like eclipse to generate hashcode and equals method for you + +see below code: + +``` +public class Person { + private String name; + private String drink; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDrink() { + return drink; + } + + public void setDrink(String drink) { + this.drink = drink; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((drink == null) ? 0 : drink.hashCode()); + result = prime * result + ((name == null) ? 0 : name.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Person other = (Person) obj; + if (drink == null) { + if (other.drink != null) + return false; + } else if (!drink.equals(other.drink)) + return false; + if (name == null) { + if (other.name != null) + return false; + } else if (!name.equals(other.name)) + return false; + return true; + } +} + +```" +46169229,"I've seen a lot of nice solutions here about how to work with ArrayList and HashMaps, but the point is I still can't solve my problem. + +So, the idea is there are few people that drink beer, wine and cola. So, it looks like that (for example): + +``` +Steve wine +Steve cola +Ben cola +Frank wine +Ben cola +Ben cola +Frank wine + +``` + +In the end I need to count how many glasses of each drink each of them drank. So, the answer should look like that: + +``` +Steve wine 1 +Steve cola 1 +Ben cola 3 +Frank wine 2 + +``` + +My idea was to put to create an object Person(String name, String drink). Then I put all the persons to ArrayList. After that I have created HashMap and wanted to add there a new Person if key doesn't exist, and to increment to 1 if key already exists. + +``` + Map map = new HashMap(); + + for (Person p : persons) + { + if (map.containsKey(p)) { + map.put(p, map.get(p)+1); + } else { + map.put(p,1); + } + } + +``` + +It doesn't work. It just returns me the result like this: + +``` + Steve wine 1 + Steve cola 1 + Ben cola 1 + Frank wine 1 + Ben cola 1 + Ben cola 1 + Frank wine 1 + +``` + +So, as I understand that should be some other trick here. Maybe you could also tell any other ideas of how to count the glasses of the drinks instead of using HashMap? +Many thanks!",2017/09/12,"['https://Stackoverflow.com/questions/46169229', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8258820/']","You have to override equals and hashCode method in Person class. Below is the sample code: + +``` +class Person { + + private String name; + private String drink; + + public Person(String name, String drink) { + super(); + this.name = name; + this.drink = drink; + } + + @Override + public int hashCode() { + + return this.getName().hashCode(); + } + + @Override + public boolean equals(Object obj) { + + if (obj == this) + return true; + + if (!(obj instanceof Person)) { + return false; + } + Person person = (Person) obj; + + return person.getName().equals(this.name); + } + ....getters and setters + ....toString method +} + +``` + +After this, if you try to run your code it will work for sure for me output for below code was + +``` + Map map = new HashMap<>(); + + for (Person p : persons) + { + if (map.containsKey(p)) { + map.put(p, map.get(p)+1); + } else { + map.put(p,1); + } + } + + for(Map.Entry person : map.entrySet()){ + System.out.println(person.getKey()+"" ""+person.getValue()); + } + +``` + +Output: + +``` +Person [name=Steve, drink=wine] 2 +Person [name=Ben, drink=cola] 3 +Person [name=Frank, drink=wine] 2 + +``` + +Hope it will help you.","First I would recommend you to take care of your namings. What is really the key in your case is an order not a person (since Steve cola and Steve wine is different you shouldn't name it as person). + +After that: containsKey will use the hashcode method which will be inherited from the Object class if you don't override it in your class. The Object class's hashcode probably will provide different hashcode for your instances so you should override it in your class e.g. you can create an acceptable hashcode method if you concat the name and beverage (which is your unique identifier for an order) and invoke a hashcode method on that string." +46169229,"I've seen a lot of nice solutions here about how to work with ArrayList and HashMaps, but the point is I still can't solve my problem. + +So, the idea is there are few people that drink beer, wine and cola. So, it looks like that (for example): + +``` +Steve wine +Steve cola +Ben cola +Frank wine +Ben cola +Ben cola +Frank wine + +``` + +In the end I need to count how many glasses of each drink each of them drank. So, the answer should look like that: + +``` +Steve wine 1 +Steve cola 1 +Ben cola 3 +Frank wine 2 + +``` + +My idea was to put to create an object Person(String name, String drink). Then I put all the persons to ArrayList. After that I have created HashMap and wanted to add there a new Person if key doesn't exist, and to increment to 1 if key already exists. + +``` + Map map = new HashMap(); + + for (Person p : persons) + { + if (map.containsKey(p)) { + map.put(p, map.get(p)+1); + } else { + map.put(p,1); + } + } + +``` + +It doesn't work. It just returns me the result like this: + +``` + Steve wine 1 + Steve cola 1 + Ben cola 1 + Frank wine 1 + Ben cola 1 + Ben cola 1 + Frank wine 1 + +``` + +So, as I understand that should be some other trick here. Maybe you could also tell any other ideas of how to count the glasses of the drinks instead of using HashMap? +Many thanks!",2017/09/12,"['https://Stackoverflow.com/questions/46169229', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8258820/']",Overwrite hashcode and equals method in your Person class,"``` +int count = Collections.frequency(""your collection"", ""Your Value""); + +``` + +I meant to say like that: + +``` +ArrayList list = new ArrayList<>(); +list.add(""Steve wine""); +list.add(""Steve cola""); +list.add(""Ben cola""); +list.add(""Frank wine""); +list.add(""Ben cola""); +list.add(""Ben cola""); +list.add(""Frank wine""); + +System.out.println(Collections.frequency(list, ""Steve wine"")); + +System.out.println(Collections.frequency(list, ""Ben cola"")); + +```" +2677956,"So basically what I'm working with is a database full of phone numbers. + +if I get one of those users from that phone database and they sign up to my website I want to automatically associate the number from the database that is already present, how would I go about linking those 2 tables together once a user signs up?",2010/04/20,"['https://Stackoverflow.com/questions/2677956', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/301252/']","Assuming that you have phone number table and users table you need to store the primary keys of both table together + +You can do it: + +* In a user table, but then you will be able to link only one phone number to a user (and later if you will have to add more then one phone you might end up adding fields like phone\_number\_1, phone\_number\_2, etc... which is quite horrible) +* In a phone number table, but then you will be able to link only one user to a phone number (same problem may arise as in point one) +* In a separate table, but then you will have to use a join every time you need to get a user or phone number + +The right choice depends on the relationships between the data that you are trying to model.","So, the database would be structured using composition. Keep a `phone_numbers` table w/ `phone_number_id`, the `users` table w/ `user_id`, and then a `customer_phone_numbers` table that maps user\_ids to phone\_number\_ids. Then your PHP code would do something like this: + +``` +save(); // save normal user data +$phoneNumbers = array(); +foreach($user->getPhoneNumbers() as $phoneNumber) { + $phoneId = getPhoneNumberId($phoneNumber); // get the phone number, or save a new record if necessary, and return that number + $phoneNumbers[] = $phoneId; +} + +$user->savePhoneNumbers( $phoneNumbers ); // adds or removes phone numbers as necessary + +``` + +--- + +EDIT: Based on your feedback, it doesn't sound so much like you are just looking for a way to associate the data. If I understand you correctly, the user will sign up for your website via their phone, then later register on the website. You want to combine the two registrations when this happens. + +Are users creating a complete profile from their phone? Do you have a process in place to verify that the phone number provided by the user is actually theirs? + +If the user is not creating a full profile via the phone, it sounds like there are two types of ""profiles"" being stored, a complete website profile, and a telephone profile. This way, you would have a phone profile w/ a `phone_profile_id` and a regular user record w/ a `user_id`. Then, let users verify their telephone information and associate them to a `phone_profile_id` using a composition table as above. + +Is that a little closer? + +Thanks, +Joe" +47883939,"I need to generate a `TSQL` query like this: + +``` +IF @GenderOfEmployee IS NOT NULL + CASE @GenderOfEmployee = 1 + THEN INSERT INTO @NotAllowedGenderOfJobPost (TagID) values (139) + ELSE INSERT INTO @NotAllowedGenderOfJobPost (TagID) values (138) + END; + +``` + +I mean I want have a `CASE` statement in `IF` statement. + +Is it possible? + +Consider I don't want other similar ways to provide that query. + +Thanks for your advanced help.",2017/12/19,"['https://Stackoverflow.com/questions/47883939', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']","Change like this + +``` +IF @GenderOfEmployee IS NOT NULL +BEGIN + INSERT INTO @NotAllowedGenderOfJobPost (TagID) SELECT CASE WHEN @GenderOfEmployee = 1 + THEN 139 + ELSE 138 + END +END; + +```","There is no need for a `select` to insert the result of a `case` expression: + +``` +declare @NotAllowedGenderOfJobPost as Table ( TagId Int ); +declare @GenderOfEmployee as Int = NULL; + +-- Try NULL. +if @GenderOfEmployee is not NULL + insert into @NotAllowedGenderOfJobPost (TagId ) values + ( case when @GenderOfEmployee = 1 then 139 else 138 end ); +select * from @NotAllowedGenderOfJobPost; + +-- Try 0. +set @GenderOfEmployee = 0; +if @GenderOfEmployee is not NULL + insert into @NotAllowedGenderOfJobPost (TagId ) values + ( case when @GenderOfEmployee = 1 then 139 else 138 end ); +select * from @NotAllowedGenderOfJobPost; + +-- Try 1. +set @GenderOfEmployee = 1; +if @GenderOfEmployee is not NULL + insert into @NotAllowedGenderOfJobPost (TagId ) values + ( case when @GenderOfEmployee = 1 then 139 else 138 end ); +select * from @NotAllowedGenderOfJobPost; + +```" +53849604,how to make regex for number from -100 to 100? Thanks in advance,2018/12/19,"['https://Stackoverflow.com/questions/53849604', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9328454/']","You can use a regex range generator, such as + +I think this regular expression will do it: + +``` +/^-?([0-9]|[1-8][0-9]|9[0-9]|100)$/ + +```","use for checking your regex. + +and use `(?:\b|-)([1-9]{1,2}[0]?|100)\b` expression to print numbers from -100 to 100" +39895319,"I am looking at making a navbar like this in android: +[Scketch of navbar](http://i.stack.imgur.com/NsRSO.png) + +Everything is straight forward beside the months. +I want to be able to scroll through the months by dragging or by clicking a month. +I also want the current month to be the one centered on start. + +Any suggestions on how to make this is welcome.",2016/10/06,"['https://Stackoverflow.com/questions/39895319', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5326910/']","Coverted the above comment as answer. Hope it solves your problem. + +Use TabLayout with **app:tabMode=”scrollable”**. You'll find the implementation and code under the topic **Scrollable Tabs** [here](http://www.androidhive.info/2015/09/android-material-design-working-with-tabs/).","``` +ActionBar mActionBar = getActionBar(); +mActionBar.setDisplayShowHomeEnabled(false); +mActionBar.setDisplayShowTitleEnabled(false); +LayoutInflater mInflater = LayoutInflater.from(this); +View mCustomView = mInflater.inflate(R.layout.custom_actionbar, null); +mActionBar.setCustomView(mCustomView); +mActionBar.setDisplayShowCustomEnabled(true); + +``` + +make Horizontal scrollview in custom layout." +43918993,"I get the following error installing sasl in my Bluemix app: + +``` + Installing collected packages: sasl, thrift-sasl + Running setup.py install for sasl: started + Running setup.py install for sasl: finished with status 'error' + Command ""/app/.heroku/python/bin/python -u -c ""import setuptools, tokenize;__file__='/tmp/pip-build-9mi8225r/sasl/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))"" install --record /tmp/pip-3l4o04ga-record/install-record.txt --single-version-externally-managed --compile"" failed with error code 1 in /tmp/pip-build-9mi8225r/sasl/ + running install + running build_py + creating build + creating build/lib.linux-x86_64-3.5 + creating build/lib.linux-x86_64-3.5/sasl + copying sasl/__init__.py -> build/lib.linux-x86_64-3.5/sasl + running egg_info + writing dependency_links to sasl.egg-info/dependency_links.txt + writing top-level names to sasl.egg-info/top_level.txt + warning: manifest_maker: standard file '-c' not found + + reading manifest file 'sasl.egg-info/SOURCES.txt' + writing manifest file 'sasl.egg-info/SOURCES.txt' + copying sasl/saslwrapper.cpp -> build/lib.linux-x86_64-3.5/sasl + copying sasl/saslwrapper.pyx -> build/lib.linux-x86_64-3.5/sasl + building 'sasl.saslwrapper' extension + creating build/temp.linux-x86_64-3.5 + creating build/temp.linux-x86_64-3.5/sasl + gcc -pthread -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -Isasl -I/app/.heroku/python/include/python3.5m -c sasl/saslwrapper.cpp -o build/temp.linux-x86_64-3.5/sasl/saslwrapper.o + sasl/saslwrapper.h:22:23: fatal error: sasl/sasl.h: No such file or directory + #include + ^ + compilation terminated. + +``` + +I'm using the buildpack: `python 1.5.5` + +My runtime.txt contains: `python-3.5.0` + +How can I install the necessary headers in the buildpack? + +--- + +**Update:** + +It looks as though the latest cloud foundry stack has the sasl library: . + +How can I use this stack on Bluemix?",2017/05/11,"['https://Stackoverflow.com/questions/43918993', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1033422/']","Maybe you should install some system libraries before you can install **sasl** refer to + +> +> This library contains C++ code, and will require some additional +> system libraries installed. +> +> +> *Debian/Ubuntu* +> +> +> apt-get install python-dev libsasl2-dev gcc +> +> +> *CentOS/RHEL* +> +> +> yum install gcc-c++ python-devel.x86\_64 +> cyrus-sasl-devel.x86\_64 +> +> +>","The solution for me was to use pure-sasl and install imypla and thrift\_sasl from application code rather than my requirements.txt: + +``` +try: + import impyla +except ImportError: + print(""Installing missing impyla"") + import pip + pip.main(['install', '--no-deps', 'impyla']) + +try: + import thrift_sasl +except ImportError: + print(""Installing missing thrift_sasl"") + import pip + # need a patched version of thrift_sasl. see https://github.com/cloudera/impyla/issues/238 + pip.main(['install', '--no-deps', 'git+https://github.com/snowch/thrift_sasl']) + +``` + +I added this code to a view in my flask application: " +43918993,"I get the following error installing sasl in my Bluemix app: + +``` + Installing collected packages: sasl, thrift-sasl + Running setup.py install for sasl: started + Running setup.py install for sasl: finished with status 'error' + Command ""/app/.heroku/python/bin/python -u -c ""import setuptools, tokenize;__file__='/tmp/pip-build-9mi8225r/sasl/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))"" install --record /tmp/pip-3l4o04ga-record/install-record.txt --single-version-externally-managed --compile"" failed with error code 1 in /tmp/pip-build-9mi8225r/sasl/ + running install + running build_py + creating build + creating build/lib.linux-x86_64-3.5 + creating build/lib.linux-x86_64-3.5/sasl + copying sasl/__init__.py -> build/lib.linux-x86_64-3.5/sasl + running egg_info + writing dependency_links to sasl.egg-info/dependency_links.txt + writing top-level names to sasl.egg-info/top_level.txt + warning: manifest_maker: standard file '-c' not found + + reading manifest file 'sasl.egg-info/SOURCES.txt' + writing manifest file 'sasl.egg-info/SOURCES.txt' + copying sasl/saslwrapper.cpp -> build/lib.linux-x86_64-3.5/sasl + copying sasl/saslwrapper.pyx -> build/lib.linux-x86_64-3.5/sasl + building 'sasl.saslwrapper' extension + creating build/temp.linux-x86_64-3.5 + creating build/temp.linux-x86_64-3.5/sasl + gcc -pthread -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -Isasl -I/app/.heroku/python/include/python3.5m -c sasl/saslwrapper.cpp -o build/temp.linux-x86_64-3.5/sasl/saslwrapper.o + sasl/saslwrapper.h:22:23: fatal error: sasl/sasl.h: No such file or directory + #include + ^ + compilation terminated. + +``` + +I'm using the buildpack: `python 1.5.5` + +My runtime.txt contains: `python-3.5.0` + +How can I install the necessary headers in the buildpack? + +--- + +**Update:** + +It looks as though the latest cloud foundry stack has the sasl library: . + +How can I use this stack on Bluemix?",2017/05/11,"['https://Stackoverflow.com/questions/43918993', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1033422/']","The solution for me was to use pure-sasl and install imypla and thrift\_sasl from application code rather than my requirements.txt: + +``` +try: + import impyla +except ImportError: + print(""Installing missing impyla"") + import pip + pip.main(['install', '--no-deps', 'impyla']) + +try: + import thrift_sasl +except ImportError: + print(""Installing missing thrift_sasl"") + import pip + # need a patched version of thrift_sasl. see https://github.com/cloudera/impyla/issues/238 + pip.main(['install', '--no-deps', 'git+https://github.com/snowch/thrift_sasl']) + +``` + +I added this code to a view in my flask application: ","I was having similar error - + +``` +In file included from sasl/saslwrapper.cpp:254:0: +sasl/saslwrapper.h:22:23: fatal error: sasl/sasl.h: No such file or directory +#include + ^ +compilation terminated. +error: command 'gcc' failed with exit status 1 + +``` + +Try this thread it was helpful for me +[I can't install python-ldap](https://stackoverflow.com/questions/4768446/i-cant-install-python-ldap)" +43918993,"I get the following error installing sasl in my Bluemix app: + +``` + Installing collected packages: sasl, thrift-sasl + Running setup.py install for sasl: started + Running setup.py install for sasl: finished with status 'error' + Command ""/app/.heroku/python/bin/python -u -c ""import setuptools, tokenize;__file__='/tmp/pip-build-9mi8225r/sasl/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))"" install --record /tmp/pip-3l4o04ga-record/install-record.txt --single-version-externally-managed --compile"" failed with error code 1 in /tmp/pip-build-9mi8225r/sasl/ + running install + running build_py + creating build + creating build/lib.linux-x86_64-3.5 + creating build/lib.linux-x86_64-3.5/sasl + copying sasl/__init__.py -> build/lib.linux-x86_64-3.5/sasl + running egg_info + writing dependency_links to sasl.egg-info/dependency_links.txt + writing top-level names to sasl.egg-info/top_level.txt + warning: manifest_maker: standard file '-c' not found + + reading manifest file 'sasl.egg-info/SOURCES.txt' + writing manifest file 'sasl.egg-info/SOURCES.txt' + copying sasl/saslwrapper.cpp -> build/lib.linux-x86_64-3.5/sasl + copying sasl/saslwrapper.pyx -> build/lib.linux-x86_64-3.5/sasl + building 'sasl.saslwrapper' extension + creating build/temp.linux-x86_64-3.5 + creating build/temp.linux-x86_64-3.5/sasl + gcc -pthread -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -Isasl -I/app/.heroku/python/include/python3.5m -c sasl/saslwrapper.cpp -o build/temp.linux-x86_64-3.5/sasl/saslwrapper.o + sasl/saslwrapper.h:22:23: fatal error: sasl/sasl.h: No such file or directory + #include + ^ + compilation terminated. + +``` + +I'm using the buildpack: `python 1.5.5` + +My runtime.txt contains: `python-3.5.0` + +How can I install the necessary headers in the buildpack? + +--- + +**Update:** + +It looks as though the latest cloud foundry stack has the sasl library: . + +How can I use this stack on Bluemix?",2017/05/11,"['https://Stackoverflow.com/questions/43918993', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1033422/']","Maybe you should install some system libraries before you can install **sasl** refer to + +> +> This library contains C++ code, and will require some additional +> system libraries installed. +> +> +> *Debian/Ubuntu* +> +> +> apt-get install python-dev libsasl2-dev gcc +> +> +> *CentOS/RHEL* +> +> +> yum install gcc-c++ python-devel.x86\_64 +> cyrus-sasl-devel.x86\_64 +> +> +>","I was having similar error - + +``` +In file included from sasl/saslwrapper.cpp:254:0: +sasl/saslwrapper.h:22:23: fatal error: sasl/sasl.h: No such file or directory +#include + ^ +compilation terminated. +error: command 'gcc' failed with exit status 1 + +``` + +Try this thread it was helpful for me +[I can't install python-ldap](https://stackoverflow.com/questions/4768446/i-cant-install-python-ldap)" +18342961,"I have a copy text button that I'm using ZeroClipboard with in order to copy certain text on the page. It works in Chrome and IE but it doesn't copy text in Firefox and the `complete` event is never fired. + +My JavaScript for setting up the button looks something like this: + +``` +ZeroClipboard.setDefaults({ + moviePath: '/js/zeroclipboard/ZeroClipboard.swf', + allowScriptAccess: 'always', + forceHandCursor: true +}); + +function enableCopyButton(container) { + var button = container.find('.text-copy'), + source = container.find('.text'), + clip = new ZeroClipboard(button); + + clip.setText(source.val()); + + clip.on('load', function (client) { + console.log('ZeroClipboard loaded.'); + + client.on('complete', function (client, args) { + console.log('Text copied: ' + args.text); + }); + }); + + clip.on('noFlash', function () { + console.error('No Flash installed!'); + }); + clip.on('wrongFlash', function () { + console.error('Wrong Flash installed!'); + }); +} + +``` + +The console ends up showing `""ZeroClipboard loaded.""` and nothing else. No errors are thrown, and I've confirmed that `ZeroClipboard.swf` is being loaded and placed on the page. The `mousedown` and `mouseup` events are being fired, as well. The page this is running on is using a valid SSL certificate, and all assets on the page are loaded via HTTPS. + +The library's demo page on GitHub works fine in FireFox, so I suspect it's something I'm doing.",2013/08/20,"['https://Stackoverflow.com/questions/18342961', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/784368/']","I'm not sure if this would help, but recently I have been working on using zeroclipboard for more than a month. Sometimes it works but sometimes it fails due to some very tiny things(maybe because I'm very new to javascript and html stuff)...and I understand the upset very well... + +In your case, have you ever tried this event before? +Instead using clip.setText(source.val()) alone, move it inside a 'dataRequested' event like this: + +``` +clip.on('dataRequested', function(client, args) { + client.setText(source.val()); +}); + +``` + +Then after clicking on the button, see if the complete event gets fired. + +BTW, I'm wondering if your 'noflash' or 'wrongflash' got fired normally? In my case, if users don't have flash installed, the event is still not fired...not sure what's wrong with it... + +Anyways, good luck :)","My dev environment: + +* .NET 4.5 +* ASP.NET MVC4 with Razor engine +* jQuery + +Here is what I did to get Copy to Clipboard to work across 5 browsers: + +* FF 23 +* IE 10 +* Chrome 29 +* Safari 5.1.7 +* Opera 16 + +My scenario: +The text I want to copy to clipboard is generated an put in a Div along with html breaks (br). +For the Copy, I needed to remove these html breaks and replace them with /r/n. +The copy is via a Button click. + +Not this might not be the best way to code this up but it worked for me. + +Grab latest ZeroClipboard from [github](https://github.com/zeroclipboard/zeroclipboard) + +In my .cshtml file, I define the button and div and include the ZeroClipboard.min.js file. + +``` + + +
+ +``` + +Javascript portion: + +``` + + + +```" +18342961,"I have a copy text button that I'm using ZeroClipboard with in order to copy certain text on the page. It works in Chrome and IE but it doesn't copy text in Firefox and the `complete` event is never fired. + +My JavaScript for setting up the button looks something like this: + +``` +ZeroClipboard.setDefaults({ + moviePath: '/js/zeroclipboard/ZeroClipboard.swf', + allowScriptAccess: 'always', + forceHandCursor: true +}); + +function enableCopyButton(container) { + var button = container.find('.text-copy'), + source = container.find('.text'), + clip = new ZeroClipboard(button); + + clip.setText(source.val()); + + clip.on('load', function (client) { + console.log('ZeroClipboard loaded.'); + + client.on('complete', function (client, args) { + console.log('Text copied: ' + args.text); + }); + }); + + clip.on('noFlash', function () { + console.error('No Flash installed!'); + }); + clip.on('wrongFlash', function () { + console.error('Wrong Flash installed!'); + }); +} + +``` + +The console ends up showing `""ZeroClipboard loaded.""` and nothing else. No errors are thrown, and I've confirmed that `ZeroClipboard.swf` is being loaded and placed on the page. The `mousedown` and `mouseup` events are being fired, as well. The page this is running on is using a valid SSL certificate, and all assets on the page are loaded via HTTPS. + +The library's demo page on GitHub works fine in FireFox, so I suspect it's something I'm doing.",2013/08/20,"['https://Stackoverflow.com/questions/18342961', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/784368/']","I'm not sure if this would help, but recently I have been working on using zeroclipboard for more than a month. Sometimes it works but sometimes it fails due to some very tiny things(maybe because I'm very new to javascript and html stuff)...and I understand the upset very well... + +In your case, have you ever tried this event before? +Instead using clip.setText(source.val()) alone, move it inside a 'dataRequested' event like this: + +``` +clip.on('dataRequested', function(client, args) { + client.setText(source.val()); +}); + +``` + +Then after clicking on the button, see if the complete event gets fired. + +BTW, I'm wondering if your 'noflash' or 'wrongflash' got fired normally? In my case, if users don't have flash installed, the event is still not fired...not sure what's wrong with it... + +Anyways, good luck :)","Latest version of zeroclipboard uses event.stopImmediatePropagation which not exists in firefox before version 28.0, it fails with error: + +``` +event.stopImmediatePropagation is not a function + +``` + +You can see browser comparison here: + + + +I use this polifil to add missing functionality: + +" +15178165,"I would like to know if there is any IDE or Eclipse Plugin that supports mixed mode debugging. As I searched the term mixed mode, found lot of references debugging VM languages alongside with native code. + +But I referring to a feature that is similar to the one available in compiled languages such as C where an user can see both C source line along side with the corresponding assembly line and will be able to step in even at assembly level. (please excuse If I had made a nomenclature mistake by calling the feature as mixed mode) + +In other words I am looking for a following features while debugging java: + +1. Ability to the java source code and the corresponding byte codes during program execution +2. Ability to see JVM PC registers and Operand stacks +3. Ability to view other JVM specific data structures (for example constant pools) + +This is to understand how the Java source code maps to byte codes and how the various JVM associated data structures are affected while stepping in.",2013/03/02,"['https://Stackoverflow.com/questions/15178165', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1391837/']","I'm a DSL developer and have sort of run into this same issue a number of times. + +The only tool i've found has been the [Dr. Garbage](http://www.drgarbage.com/bytecode-visualizer/) tools. + +At the current moment, they don't seem to be the best maintained, but they do work with appropriate versions of eclipse.","You don't need debugger to understand how Java code maps to compiled native code. You can use `-XX:+PrintCompilation` JVM flag. See mode info on that in [Stephen Colebourne's blog post](http://blog.joda.org/2011/08/printcompilation-jvm-flag.html) and more detail in Kris Mok [reply to that post](https://gist.github.com/rednaxelafx/1165804#file_notes.md). + +You may also find [HotSpot Internals Wiki](https://wikis.oracle.com/display/HotSpotInternals/Home) useful." +1864869,"Sorry, my English is poor, but I have a question. It is usual to find the definition of subgroup as: ""We define a subgroup $H$ of a group $G$ to be a nonempty subset $H$ of $G$ such that when the group operation of $G$ is restricted to $H$, $H$ is a group in its own right"". But it is known that $A=\left\{\begin{pmatrix}a & a\\a& a\end{pmatrix} \mbox{ with } a \in R \mbox{ and } a\neq 0 \right\}$ is a group with the usual product of matrices but it is not a subgroup of $M\_{2\times2}$. Do you know another examples of subsets like this? + +**Edit:** I'll try to change a little the question: In the set of matrices $M\_{2\times2}$ there are subsets which are groups in regard to the usual matrix product but have a different neutral element. An example would be the group of all nonsingular matrices over $\mathbb R$, $GL(2,\mathbb R)$ and $H=\left\{\begin{pmatrix}a & a\\a& a\end{pmatrix} \mbox{ with } a \in \mathbb R \mbox{ and } a\neq 0 \right\}$. Do you know of other examples of subsets (groups) with elements of the same nature, that given the same operation have a different neutral element?",2016/07/19,"['https://math.stackexchange.com/questions/1864869', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/85966/']","> +> Can two function be Big-O of each other? +> +> +> + +The answer is yes. + +One may take $f(n)=n$ and $g(n)=2n+1$, as $ n \to \infty$, one has +$$ +\left|\frac{f(n)}{g(n)}\right|=\frac{n}{2n+1}\le \frac12 \implies f=O(g) +$$ and +$$ +\left|\frac{g(n)}{f(n)}\right|=\frac{2n+1}{n}\le 3 \implies g=O(f). +$$","**Is it possible?** Yes. A simple example: $f=g$. + +**What does it imply**? This is equivalent to saying that $f=\Theta(g)$. To see why: + +If $f=O(g)$, there exists $c>0$ and $N \geq 0$ such that +$$ +\forall n \geq N, \qquad f(n) \leq c\cdot g(n) \tag{1} +$$ + +If $g=O(f)$, there exists $c'>0$ and $N' \geq 0$ such that +$$ +\forall n \geq N', \qquad g(n) \leq c'\cdot f(n) \tag{2} +$$ + +Combining (1) and (2), and choosing $M\stackrel{\rm def}{=}\max(N,N')$, $\alpha\stackrel{\rm def}{=}\frac{1}{c} > 0$, $\beta \stackrel{\rm def}{=} c'$, we get that there exist $M\geq 0$, constants $\alpha,\beta>0$ such that +$$ +\forall n \geq M, \qquad \alpha f(n) \leq g(n) \leq \beta f(n) \tag{3} +$$ +which by definition means $f=\Theta(g)$. This should answer both your questions." +1864869,"Sorry, my English is poor, but I have a question. It is usual to find the definition of subgroup as: ""We define a subgroup $H$ of a group $G$ to be a nonempty subset $H$ of $G$ such that when the group operation of $G$ is restricted to $H$, $H$ is a group in its own right"". But it is known that $A=\left\{\begin{pmatrix}a & a\\a& a\end{pmatrix} \mbox{ with } a \in R \mbox{ and } a\neq 0 \right\}$ is a group with the usual product of matrices but it is not a subgroup of $M\_{2\times2}$. Do you know another examples of subsets like this? + +**Edit:** I'll try to change a little the question: In the set of matrices $M\_{2\times2}$ there are subsets which are groups in regard to the usual matrix product but have a different neutral element. An example would be the group of all nonsingular matrices over $\mathbb R$, $GL(2,\mathbb R)$ and $H=\left\{\begin{pmatrix}a & a\\a& a\end{pmatrix} \mbox{ with } a \in \mathbb R \mbox{ and } a\neq 0 \right\}$. Do you know of other examples of subsets (groups) with elements of the same nature, that given the same operation have a different neutral element?",2016/07/19,"['https://math.stackexchange.com/questions/1864869', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/85966/']","> +> Can two function be Big-O of each other? +> +> +> + +The answer is yes. + +One may take $f(n)=n$ and $g(n)=2n+1$, as $ n \to \infty$, one has +$$ +\left|\frac{f(n)}{g(n)}\right|=\frac{n}{2n+1}\le \frac12 \implies f=O(g) +$$ and +$$ +\left|\frac{g(n)}{f(n)}\right|=\frac{2n+1}{n}\le 3 \implies g=O(f). +$$","The following are equivalent: + +1. $f(n) = O(g(n))$ and $g(n) = O(f(n))$ +2. $f(n) = \Omega(g(n))$ and $g(n) = \Omega(f(n))$ (using the definition from computational complexity theory, not the one from analytic number theory) +3. $f(n) = \Theta(g(n))$." +1864869,"Sorry, my English is poor, but I have a question. It is usual to find the definition of subgroup as: ""We define a subgroup $H$ of a group $G$ to be a nonempty subset $H$ of $G$ such that when the group operation of $G$ is restricted to $H$, $H$ is a group in its own right"". But it is known that $A=\left\{\begin{pmatrix}a & a\\a& a\end{pmatrix} \mbox{ with } a \in R \mbox{ and } a\neq 0 \right\}$ is a group with the usual product of matrices but it is not a subgroup of $M\_{2\times2}$. Do you know another examples of subsets like this? + +**Edit:** I'll try to change a little the question: In the set of matrices $M\_{2\times2}$ there are subsets which are groups in regard to the usual matrix product but have a different neutral element. An example would be the group of all nonsingular matrices over $\mathbb R$, $GL(2,\mathbb R)$ and $H=\left\{\begin{pmatrix}a & a\\a& a\end{pmatrix} \mbox{ with } a \in \mathbb R \mbox{ and } a\neq 0 \right\}$. Do you know of other examples of subsets (groups) with elements of the same nature, that given the same operation have a different neutral element?",2016/07/19,"['https://math.stackexchange.com/questions/1864869', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/85966/']","**Is it possible?** Yes. A simple example: $f=g$. + +**What does it imply**? This is equivalent to saying that $f=\Theta(g)$. To see why: + +If $f=O(g)$, there exists $c>0$ and $N \geq 0$ such that +$$ +\forall n \geq N, \qquad f(n) \leq c\cdot g(n) \tag{1} +$$ + +If $g=O(f)$, there exists $c'>0$ and $N' \geq 0$ such that +$$ +\forall n \geq N', \qquad g(n) \leq c'\cdot f(n) \tag{2} +$$ + +Combining (1) and (2), and choosing $M\stackrel{\rm def}{=}\max(N,N')$, $\alpha\stackrel{\rm def}{=}\frac{1}{c} > 0$, $\beta \stackrel{\rm def}{=} c'$, we get that there exist $M\geq 0$, constants $\alpha,\beta>0$ such that +$$ +\forall n \geq M, \qquad \alpha f(n) \leq g(n) \leq \beta f(n) \tag{3} +$$ +which by definition means $f=\Theta(g)$. This should answer both your questions.","The following are equivalent: + +1. $f(n) = O(g(n))$ and $g(n) = O(f(n))$ +2. $f(n) = \Omega(g(n))$ and $g(n) = \Omega(f(n))$ (using the definition from computational complexity theory, not the one from analytic number theory) +3. $f(n) = \Theta(g(n))$." +52294,"I am a Linux user with a frequent need to ssh into remote computers and keep my session there running while disconnecting. And then later connect back to it from the same or a different 'client' computers. There are a number of programs, *terminal multiplexers*, that solves this problem. I frequently use gnu screen, tmux, etc. + +However, they all seem designed around the idea of taking over rendering of the text surface available to them to do a form of 'screen management'. In doing so they override tasks normally handled by the terminal window on the client computer (i.e., the xterm, gnome terminal, etc. from which I am running the ssh). This means that once I start the multiplexer, I can no longer use, e.g., the scrollbar to access the scrollback history, or the search menu of my graphical terminal. I can no longer mouse mark and drag in the window and have it scroll back by itself, etc. Instead, these terminal multiplexer provide their own keyboard-based user interfaces to handle such tasks. I would much prefer if I could keep using the UI of my client terminal as usual. + +Hence, is there a terminal multiplexer that provides the function of a virtual tty, which one can attach and detach from at will, but when one is connected it simply just outputs all text into the console ""the normal way""? I.e., without doing any form of ""screen management""? (I'm imagining that it could still keep a log of recent history internally, so that when one connects, it can spit out this log to provide context to a newly connected client.) + +(Answers that point to ways to configure well-known multiplexers to do this are of course acceptable.)",2018/09/21,"['https://softwarerecs.stackexchange.com/questions/52294', 'https://softwarerecs.stackexchange.com', 'https://softwarerecs.stackexchange.com/users/40595/']","You might want to clarify what Kind oft ""remote desktop"" you want: + +1. Mirror the screen, i.e. interact with the user session which is currently active on the physical screen. +2. Open a New session exclusively for the remote user. + +1.) is the target oft VNC, but also TeamViewer and the likes. It is useful for remote assistance, but not well suited for remote working. 2.) is RDP, and NX as well, IIRC. This is useful for (multiple) remote workers. + +Back in the days, remote working in UNIX was very common, with thin Clients connected to a central Workstation. After all, that's what the X window system client server model was made for. This is now very uncommon. If you're looking for some remote assistance tool (case 1), then I think VNC+SSH is still the best option. If you're looking for something like windows remote desktop services, then I am afraid there is none.","Even today tunneling an X session over SSH works just fine. + +On a Mac, you can install the X server from the apple store, Linux/BSD you have it native, and for Windows there are X servers in the app store, or other commercial offerings, or you can use `cygwin-x`" +52294,"I am a Linux user with a frequent need to ssh into remote computers and keep my session there running while disconnecting. And then later connect back to it from the same or a different 'client' computers. There are a number of programs, *terminal multiplexers*, that solves this problem. I frequently use gnu screen, tmux, etc. + +However, they all seem designed around the idea of taking over rendering of the text surface available to them to do a form of 'screen management'. In doing so they override tasks normally handled by the terminal window on the client computer (i.e., the xterm, gnome terminal, etc. from which I am running the ssh). This means that once I start the multiplexer, I can no longer use, e.g., the scrollbar to access the scrollback history, or the search menu of my graphical terminal. I can no longer mouse mark and drag in the window and have it scroll back by itself, etc. Instead, these terminal multiplexer provide their own keyboard-based user interfaces to handle such tasks. I would much prefer if I could keep using the UI of my client terminal as usual. + +Hence, is there a terminal multiplexer that provides the function of a virtual tty, which one can attach and detach from at will, but when one is connected it simply just outputs all text into the console ""the normal way""? I.e., without doing any form of ""screen management""? (I'm imagining that it could still keep a log of recent history internally, so that when one connects, it can spit out this log to provide context to a newly connected client.) + +(Answers that point to ways to configure well-known multiplexers to do this are of course acceptable.)",2018/09/21,"['https://softwarerecs.stackexchange.com/questions/52294', 'https://softwarerecs.stackexchange.com', 'https://softwarerecs.stackexchange.com/users/40595/']","I think X2Go fits your requirements, based on NX3. + +I use it and while it's not perfect, it's the best I've found so far. + +It may be in your distro's repository. X support only, no Wayland. + +Uses ssh, logs in to existing sessions or creates new sessions using remote system accounts, and has a cool ""seamless"" application mode for running a remote program in a local window. + +Problems I've encountered are mostly with keymaps. i.e. in session mode, some keys don't register correctly for me.","You might want to clarify what Kind oft ""remote desktop"" you want: + +1. Mirror the screen, i.e. interact with the user session which is currently active on the physical screen. +2. Open a New session exclusively for the remote user. + +1.) is the target oft VNC, but also TeamViewer and the likes. It is useful for remote assistance, but not well suited for remote working. 2.) is RDP, and NX as well, IIRC. This is useful for (multiple) remote workers. + +Back in the days, remote working in UNIX was very common, with thin Clients connected to a central Workstation. After all, that's what the X window system client server model was made for. This is now very uncommon. If you're looking for some remote assistance tool (case 1), then I think VNC+SSH is still the best option. If you're looking for something like windows remote desktop services, then I am afraid there is none." +52294,"I am a Linux user with a frequent need to ssh into remote computers and keep my session there running while disconnecting. And then later connect back to it from the same or a different 'client' computers. There are a number of programs, *terminal multiplexers*, that solves this problem. I frequently use gnu screen, tmux, etc. + +However, they all seem designed around the idea of taking over rendering of the text surface available to them to do a form of 'screen management'. In doing so they override tasks normally handled by the terminal window on the client computer (i.e., the xterm, gnome terminal, etc. from which I am running the ssh). This means that once I start the multiplexer, I can no longer use, e.g., the scrollbar to access the scrollback history, or the search menu of my graphical terminal. I can no longer mouse mark and drag in the window and have it scroll back by itself, etc. Instead, these terminal multiplexer provide their own keyboard-based user interfaces to handle such tasks. I would much prefer if I could keep using the UI of my client terminal as usual. + +Hence, is there a terminal multiplexer that provides the function of a virtual tty, which one can attach and detach from at will, but when one is connected it simply just outputs all text into the console ""the normal way""? I.e., without doing any form of ""screen management""? (I'm imagining that it could still keep a log of recent history internally, so that when one connects, it can spit out this log to provide context to a newly connected client.) + +(Answers that point to ways to configure well-known multiplexers to do this are of course acceptable.)",2018/09/21,"['https://softwarerecs.stackexchange.com/questions/52294', 'https://softwarerecs.stackexchange.com', 'https://softwarerecs.stackexchange.com/users/40595/']","I think X2Go fits your requirements, based on NX3. + +I use it and while it's not perfect, it's the best I've found so far. + +It may be in your distro's repository. X support only, no Wayland. + +Uses ssh, logs in to existing sessions or creates new sessions using remote system accounts, and has a cool ""seamless"" application mode for running a remote program in a local window. + +Problems I've encountered are mostly with keymaps. i.e. in session mode, some keys don't register correctly for me.","Even today tunneling an X session over SSH works just fine. + +On a Mac, you can install the X server from the apple store, Linux/BSD you have it native, and for Windows there are X servers in the app store, or other commercial offerings, or you can use `cygwin-x`" +33053891,"I'm working with this tutorial which uses lambda expressions. + +[Spring Boot - Bookmarks](http://spring.io/guides/tutorials/bookmarks/) + +But IntelliJ says always: `cannot resolve method()`. + +What do I have to check? + +``` +this.accountRepository.findByUsername(userId).orElseThrow(() -> new UserNotFoundException(userId)); + +```",2015/10/10,"['https://Stackoverflow.com/questions/33053891', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2715720/']","It looks like your IntelliJ or your project is not setup to use Java 8. + +1. Open **Project Structure** +2. Look into **Project Settings | Project**, the value of **Project SDK** should be 1.8 +3. Look into **Platform Settings | SDK**, there should be 1.8 listed + +It should look something like this: + +[![enter image description here](https://i.stack.imgur.com/jaAE9.png)](https://i.stack.imgur.com/jaAE9.png)","You need to change the ""Project language level"" to ""8 - Lambdas, type annotations etc."". You can find this option in ""Project Settings"" -> ""Project""" +33053891,"I'm working with this tutorial which uses lambda expressions. + +[Spring Boot - Bookmarks](http://spring.io/guides/tutorials/bookmarks/) + +But IntelliJ says always: `cannot resolve method()`. + +What do I have to check? + +``` +this.accountRepository.findByUsername(userId).orElseThrow(() -> new UserNotFoundException(userId)); + +```",2015/10/10,"['https://Stackoverflow.com/questions/33053891', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2715720/']","It looks like your IntelliJ or your project is not setup to use Java 8. + +1. Open **Project Structure** +2. Look into **Project Settings | Project**, the value of **Project SDK** should be 1.8 +3. Look into **Platform Settings | SDK**, there should be 1.8 listed + +It should look something like this: + +[![enter image description here](https://i.stack.imgur.com/jaAE9.png)](https://i.stack.imgur.com/jaAE9.png)","In addition to the answers above look into you pom.xml file. Source and target should be 1.8 or higher. e.g. + +``` + + UTF-8 + 1.8 + 1.8 + + +```" +33053891,"I'm working with this tutorial which uses lambda expressions. + +[Spring Boot - Bookmarks](http://spring.io/guides/tutorials/bookmarks/) + +But IntelliJ says always: `cannot resolve method()`. + +What do I have to check? + +``` +this.accountRepository.findByUsername(userId).orElseThrow(() -> new UserNotFoundException(userId)); + +```",2015/10/10,"['https://Stackoverflow.com/questions/33053891', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2715720/']","You need to change the ""Project language level"" to ""8 - Lambdas, type annotations etc."". You can find this option in ""Project Settings"" -> ""Project""","In addition to the answers above look into you pom.xml file. Source and target should be 1.8 or higher. e.g. + +``` + + UTF-8 + 1.8 + 1.8 + + +```" +11232845,"I used some relative url in my project like ``, but our consultant insist to ask me change every url to `~/images/...`, and because they are html control, I have to add `runat=""server""` tag for each one, So my question is that is it necessary? I have couple master page, it makes all the js link and css link unreached. Thanks",2012/06/27,"['https://Stackoverflow.com/questions/11232845', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1202242/']","A control can live in any subfolder and be referenced by many different pages in many different subfolders. `../` will not work in every case. + +For that reason, you shuold resolve the URLs: + +``` +ResolveUrl(""~/images/myimage.jpg"") + +``` + +And, no, you don't have to add `runat=""server""`, you could do it like so: + +``` +"" .../> + +```","It depends greatly on context. Using relative URLs works fine as long as the location of the dependent resources isn't expected to change. Turning all of your image tags into controls does give you the benefit of using ""~"" (App Root) but it also adds overhead to processing on the server. + +Your consultant is likely trying to protect you from a common problem. All your relative links work fine in development (""http://localhost/site"") but break when you move to production (""http://www.yourdomain.com/somelocation/"")." +11232845,"I used some relative url in my project like ``, but our consultant insist to ask me change every url to `~/images/...`, and because they are html control, I have to add `runat=""server""` tag for each one, So my question is that is it necessary? I have couple master page, it makes all the js link and css link unreached. Thanks",2012/06/27,"['https://Stackoverflow.com/questions/11232845', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1202242/']","A control can live in any subfolder and be referenced by many different pages in many different subfolders. `../` will not work in every case. + +For that reason, you shuold resolve the URLs: + +``` +ResolveUrl(""~/images/myimage.jpg"") + +``` + +And, no, you don't have to add `runat=""server""`, you could do it like so: + +``` +"" .../> + +```","Not sure which ASP version you're working in, but I use `@Url.Content(""~/relativepath"")` for ASP4 using MVC3 w/Razor + +or ``" +32505666,"I'm developing a package and want to import all of the `dplyr` functions, so I added + +`#' @import dplyr` + +To my function and which generated a namespace which looks like this: + +``` +`# Generated by roxygen2 (4.1.1): do not edit by hand + +export(process_text) +export(quick_match) +import(dplyr)` + +``` + +But then when I load the package using `devtools::load_all()` I get an error: + +> +> the dplyr functions are not availiable. +> +> +> + +What am I doing wrong?",2015/09/10,"['https://Stackoverflow.com/questions/32505666', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1499416/']","You also need to import it in your DESCRIPTION file. Something like this: + +``` +Package: +Version: +Date: +Title: +Author: <author> +Maintainer: <maintainer> +Depends: + R (>= 2.13.0) +Imports: + dplyr +Description: <description> +License: GPL (>= 2) + +```","Turns out that you need the package to be listed in the Depends as well as the Imports section of the DESCRIPTION file. The following resolved the issue for me. + +``` + Package: stringmatch +Title: Q-Gram filtering for approximate string matching +Version: 0.0.0.9000 +Authors@R: +Description: An implementation of q-gram filtering for fast levenstein distance matching +Depends:R (>= 3.2.2), + dplyr +Imports: + dplyr, + +```" +25306180,"I want to change z order of some views during animation + +On Androids above 4.1.2 it works just fine, and on androids below 4.1.2 the Z order doesnt change, the top view remains on top. + +This is what i am trying. + +``` +myView.bringToFront(); +((View)myView.getParent()).invalidate(); + +``` + +How to make it work on older devices ?",2014/08/14,"['https://Stackoverflow.com/questions/25306180', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2136812/']","``` + /** + * Change the view's z order in the tree, so it's on top of other sibling + * views. This ordering change may affect layout, if the parent container + * uses an order-dependent layout scheme (e.g., LinearLayout). Prior + * to {@link android.os.Build.VERSION_CODES#KITKAT} this + * method should be followed by calls to {@link #requestLayout()} and + * {@link View#invalidate()} on the view's parent to force the parent to redraw + * with the new child ordering. + * + * @see ViewGroup#bringChildToFront(View) + */ + public void bringToFront() { + if (mParent != null) { + mParent.bringChildToFront(this); + } + } + +``` + +according to this I was simply missing the line + +``` +((View)myView.getParent()).requestLayout(); + +``` + +and it worked!","According to this I was simply missing the line + +This Simple line work for you + +``` +yourView.bringToFront(); + +```" +25306180,"I want to change z order of some views during animation + +On Androids above 4.1.2 it works just fine, and on androids below 4.1.2 the Z order doesnt change, the top view remains on top. + +This is what i am trying. + +``` +myView.bringToFront(); +((View)myView.getParent()).invalidate(); + +``` + +How to make it work on older devices ?",2014/08/14,"['https://Stackoverflow.com/questions/25306180', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2136812/']","I tried all that. A RelativeLayout was supposed to be on top of a Button but it just didn't want to obey. + +In the end I solved it by adding `android:elevation=""2dp""` to the RelativeLayout. + +The elevation value is only used in API level 21 and higher. In my case everything below the API level 21 was fine and everything above wasn't. + +Hope this might help someone :)","I hope this will be useful for somebody. +None of the above solutions worked for me. Why? Because my view that I wanted to be in the frond had an elevation smaller than other view. So the view with bigger elevation was always in front, no matter what." +25306180,"I want to change z order of some views during animation + +On Androids above 4.1.2 it works just fine, and on androids below 4.1.2 the Z order doesnt change, the top view remains on top. + +This is what i am trying. + +``` +myView.bringToFront(); +((View)myView.getParent()).invalidate(); + +``` + +How to make it work on older devices ?",2014/08/14,"['https://Stackoverflow.com/questions/25306180', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2136812/']","I tried all that. A RelativeLayout was supposed to be on top of a Button but it just didn't want to obey. + +In the end I solved it by adding `android:elevation=""2dp""` to the RelativeLayout. + +The elevation value is only used in API level 21 and higher. In my case everything below the API level 21 was fine and everything above wasn't. + +Hope this might help someone :)","For Api's 21 or above There is an xml attribute known as `translateZ` which lets you define the elevation level on the view. + +You can pretty much use that too. + +> +> android:translateZ=""30dp"" +> +> +> + +\*APIs >=21" +25306180,"I want to change z order of some views during animation + +On Androids above 4.1.2 it works just fine, and on androids below 4.1.2 the Z order doesnt change, the top view remains on top. + +This is what i am trying. + +``` +myView.bringToFront(); +((View)myView.getParent()).invalidate(); + +``` + +How to make it work on older devices ?",2014/08/14,"['https://Stackoverflow.com/questions/25306180', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2136812/']","For Api's 21 or above There is an xml attribute known as `translateZ` which lets you define the elevation level on the view. + +You can pretty much use that too. + +> +> android:translateZ=""30dp"" +> +> +> + +\*APIs >=21","According to this I was simply missing the line + +This Simple line work for you + +``` +yourView.bringToFront(); + +```" +25306180,"I want to change z order of some views during animation + +On Androids above 4.1.2 it works just fine, and on androids below 4.1.2 the Z order doesnt change, the top view remains on top. + +This is what i am trying. + +``` +myView.bringToFront(); +((View)myView.getParent()).invalidate(); + +``` + +How to make it work on older devices ?",2014/08/14,"['https://Stackoverflow.com/questions/25306180', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2136812/']","``` + /** + * Change the view's z order in the tree, so it's on top of other sibling + * views. This ordering change may affect layout, if the parent container + * uses an order-dependent layout scheme (e.g., LinearLayout). Prior + * to {@link android.os.Build.VERSION_CODES#KITKAT} this + * method should be followed by calls to {@link #requestLayout()} and + * {@link View#invalidate()} on the view's parent to force the parent to redraw + * with the new child ordering. + * + * @see ViewGroup#bringChildToFront(View) + */ + public void bringToFront() { + if (mParent != null) { + mParent.bringChildToFront(this); + } + } + +``` + +according to this I was simply missing the line + +``` +((View)myView.getParent()).requestLayout(); + +``` + +and it worked!","If the parent view is a relativelayout, then it might work or it might not work. I tried `bringToFront`, `requestLayout`, and `removeView; addView`, but no luck. My solution was to put everything inside a framelayout. What I needed on top was moved the buttom of the framelayout with visibility invisible, and then in code it was made visible." +25306180,"I want to change z order of some views during animation + +On Androids above 4.1.2 it works just fine, and on androids below 4.1.2 the Z order doesnt change, the top view remains on top. + +This is what i am trying. + +``` +myView.bringToFront(); +((View)myView.getParent()).invalidate(); + +``` + +How to make it work on older devices ?",2014/08/14,"['https://Stackoverflow.com/questions/25306180', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2136812/']","I hope this will be useful for somebody. +None of the above solutions worked for me. Why? Because my view that I wanted to be in the frond had an elevation smaller than other view. So the view with bigger elevation was always in front, no matter what.","For Api's 21 or above There is an xml attribute known as `translateZ` which lets you define the elevation level on the view. + +You can pretty much use that too. + +> +> android:translateZ=""30dp"" +> +> +> + +\*APIs >=21" +25306180,"I want to change z order of some views during animation + +On Androids above 4.1.2 it works just fine, and on androids below 4.1.2 the Z order doesnt change, the top view remains on top. + +This is what i am trying. + +``` +myView.bringToFront(); +((View)myView.getParent()).invalidate(); + +``` + +How to make it work on older devices ?",2014/08/14,"['https://Stackoverflow.com/questions/25306180', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2136812/']","I hope this will be useful for somebody. +None of the above solutions worked for me. Why? Because my view that I wanted to be in the frond had an elevation smaller than other view. So the view with bigger elevation was always in front, no matter what.","According to this I was simply missing the line + +This Simple line work for you + +``` +yourView.bringToFront(); + +```" +25306180,"I want to change z order of some views during animation + +On Androids above 4.1.2 it works just fine, and on androids below 4.1.2 the Z order doesnt change, the top view remains on top. + +This is what i am trying. + +``` +myView.bringToFront(); +((View)myView.getParent()).invalidate(); + +``` + +How to make it work on older devices ?",2014/08/14,"['https://Stackoverflow.com/questions/25306180', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2136812/']","``` + /** + * Change the view's z order in the tree, so it's on top of other sibling + * views. This ordering change may affect layout, if the parent container + * uses an order-dependent layout scheme (e.g., LinearLayout). Prior + * to {@link android.os.Build.VERSION_CODES#KITKAT} this + * method should be followed by calls to {@link #requestLayout()} and + * {@link View#invalidate()} on the view's parent to force the parent to redraw + * with the new child ordering. + * + * @see ViewGroup#bringChildToFront(View) + */ + public void bringToFront() { + if (mParent != null) { + mParent.bringChildToFront(this); + } + } + +``` + +according to this I was simply missing the line + +``` +((View)myView.getParent()).requestLayout(); + +``` + +and it worked!","I hope this will be useful for somebody. +None of the above solutions worked for me. Why? Because my view that I wanted to be in the frond had an elevation smaller than other view. So the view with bigger elevation was always in front, no matter what." +25306180,"I want to change z order of some views during animation + +On Androids above 4.1.2 it works just fine, and on androids below 4.1.2 the Z order doesnt change, the top view remains on top. + +This is what i am trying. + +``` +myView.bringToFront(); +((View)myView.getParent()).invalidate(); + +``` + +How to make it work on older devices ?",2014/08/14,"['https://Stackoverflow.com/questions/25306180', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2136812/']","I hope this will be useful for somebody. +None of the above solutions worked for me. Why? Because my view that I wanted to be in the frond had an elevation smaller than other view. So the view with bigger elevation was always in front, no matter what.","If the parent view is a relativelayout, then it might work or it might not work. I tried `bringToFront`, `requestLayout`, and `removeView; addView`, but no luck. My solution was to put everything inside a framelayout. What I needed on top was moved the buttom of the framelayout with visibility invisible, and then in code it was made visible." +25306180,"I want to change z order of some views during animation + +On Androids above 4.1.2 it works just fine, and on androids below 4.1.2 the Z order doesnt change, the top view remains on top. + +This is what i am trying. + +``` +myView.bringToFront(); +((View)myView.getParent()).invalidate(); + +``` + +How to make it work on older devices ?",2014/08/14,"['https://Stackoverflow.com/questions/25306180', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2136812/']","If the parent view is a relativelayout, then it might work or it might not work. I tried `bringToFront`, `requestLayout`, and `removeView; addView`, but no luck. My solution was to put everything inside a framelayout. What I needed on top was moved the buttom of the framelayout with visibility invisible, and then in code it was made visible.","According to this I was simply missing the line + +This Simple line work for you + +``` +yourView.bringToFront(); + +```" +17133430,"I have a UTF-8 text file which starts with this line: + +``` +<HEAD><META name=GENERATOR content=""MSHTML 10.00.9200.16521""><body> + +``` + +When I read this file with `TFile.ReadAllText` with TEncoding.UTF8: + +``` +MyStr := TFile.ReadAllText(ThisFileNamePath, TEncoding.UTF8); + +``` + +then the first 3 characters of the text file are omitted, so MyStr results in: + +``` +'AD><META name=GENERATOR content=""MSHTML 10.00.9200.16521""><body>...' + +``` + +However, when I read this file with `TFile.ReadAllText` without TEncoding.UTF8: + +``` +MyStr := TFile.ReadAllText(ThisFileNamePath); + +``` + +then the file is read completely and correctly: + +``` +<HEAD><META name=GENERATOR content=""MSHTML 10.00.9200.16521""><body>... + +``` + +Does `TFile.ReadAllText` have a bug?",2013/06/16,"['https://Stackoverflow.com/questions/17133430', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1580348/']","The first three bytes are skipped because the RTL code assumes that the file contains a UTF-8 BOM. Clearly your file does not. + +The `TUTF8Encoding` class implements a `GetPreamble` method that specifies the `UTF-8` BOM. And `ReadAllBytes` skips the preamble specified by the encoding that you pass. + +One simple solution would be to read the file into a byte array and then use `TEncoding.UTF8.GetString` to decode it into a string. + +``` +var + Bytes: TBytes; + Str: string; +.... +Bytes := TFile.ReadAllBytes(FileName); +Str := TEncoding.UTF8.GetString(Bytes); + +``` + +An more comprehensive alternative would be to make a `TEncoding` instance that ignored the UTF-8 BOM. + +``` +type + TUTF8EncodingWithoutBOM = class(TUTF8Encoding) + public + function Clone: TEncoding; override; + function GetPreamble: TBytes; override; + end; + +function TUTF8EncodingWithoutBOM.Clone: TEncoding; +begin + Result := TUTF8EncodingWithoutBOM.Create; +end; + +function TUTF8EncodingWithoutBOM.GetPreamble: TBytes; +begin + Result := nil; +end; + +``` + +Instantiate one of these (you only need one instance per process) and pass it to `TFile.ReadAllText`. + +The advantage of using a singleton instance of `TUTF8EncodingWithoutBOM` is that you can use it anywhere that expects a `TEncoding`.","Actually the value you pass to ReadAllText is not the Default Encoding (when you check how it's implemented), it's an enforced encoding if you pass something other than Nil. Internally it calls other method of TEncoding that does have an extra default encoding parameter (for when the foundEncoding var parameter is set to nil and no encoding could be detected) + +I was trying to make methods to work with Stream, based on the TFile.ReadAllText code and ended up with this, note the ""DefaultEncoding=nil"" (=nil so that no extra overloaded method needed) I use and the ""ForceDefaultEncoding=false"" (to say we always want to use that encoding) + +``` +function ReadAllBytes(const Stream: TStream): TBytes; +begin + var LFileSize := Stream.Size; + {$IFDEF CPU32BITS} + if LFileSize > MaxInt then + raise EInOutError.CreateRes(@SFileTooLong); + {$ENDIF} + SetLength(Result, LFileSize); + Stream.ReadBuffer(result, Length(result)); +end; + +function ReadAllText(const Stream: TStream; const DefaultEncoding: TEncoding = nil; const ForceDefaultEncoding: Boolean = false): string; +var FoundEncoding: TEncoding; +begin + if ForceDefaultEncoding then + FoundEncoding := DefaultEncoding; + var Buff := ReadAllBytes(Stream); + var BOMLength := TEncoding.GetBufferEncoding(Buff, FoundEncoding, DefaultEncoding); + result := FoundEncoding.GetString(Buff, BOMLength, Length(Buff) - BOMLength); +end; + +```" +2109,"**Background** + +I'm building a project Gantt, involving multiple teams. In the past I've had a good experience with a Gantt as a means of planning a project but not so much as a means of tracking a project's progress. + +I'm trying to figure out what would be the best way to reflect the integration points and dependencies between teams and then track it as easily as possible. + +**Current approach** + +Right now, what I have in mind is creating tasks for teams' activities and after each task that indicates a delivery to another team I creating a milestone, with the task as its predecessor. The receiving team's task depends on the milestone. + +Example: + +``` +==== [Team A develops] + +-> * [Team A development complete] + +-> ==== [Team B develops] + +``` + +The downside of this approach is that the Gantt gets cluttered with a lot of milestones. The upside is that I get more control down the road around team delivery tracking and an easier way to filter the deliveries of each of the teams. Also, a side benefit is to avoid messing with weird task updates, splits, etc. I would ask for updates to estimated delivery dates. + +I'd be happy to hear your thoughts and ideas around this issue. How would you approach this?",2011/05/08,"['https://pm.stackexchange.com/questions/2109', 'https://pm.stackexchange.com', 'https://pm.stackexchange.com/users/44/']","You do not need to use milestones to show the task relationships. In your schedule, once you have determined the sequence of work, based on BOTH hard and soft logic, link them. Link them using FS, SS, FF, with the appropriate leads and lags as appropriate. Baseline it and go. + +This should provide you with the control you need.","I tend to use milestones to mark key meetings or approvals of work. If there is some sort of formal cut-over process, make it a milestone." +2109,"**Background** + +I'm building a project Gantt, involving multiple teams. In the past I've had a good experience with a Gantt as a means of planning a project but not so much as a means of tracking a project's progress. + +I'm trying to figure out what would be the best way to reflect the integration points and dependencies between teams and then track it as easily as possible. + +**Current approach** + +Right now, what I have in mind is creating tasks for teams' activities and after each task that indicates a delivery to another team I creating a milestone, with the task as its predecessor. The receiving team's task depends on the milestone. + +Example: + +``` +==== [Team A develops] + +-> * [Team A development complete] + +-> ==== [Team B develops] + +``` + +The downside of this approach is that the Gantt gets cluttered with a lot of milestones. The upside is that I get more control down the road around team delivery tracking and an easier way to filter the deliveries of each of the teams. Also, a side benefit is to avoid messing with weird task updates, splits, etc. I would ask for updates to estimated delivery dates. + +I'd be happy to hear your thoughts and ideas around this issue. How would you approach this?",2011/05/08,"['https://pm.stackexchange.com/questions/2109', 'https://pm.stackexchange.com', 'https://pm.stackexchange.com/users/44/']","I've used (and like) a section at the top of the schedule for milestones. This keeps the key milestones visible and easily reportable. + +If you really want to use milestones to show links between teams, I would suggest first that the teams -really- be separate teams and not just different roles. For teams that each manage their own schedule, I have found milestone linking like you are describing moderately helpful. Here is how I have done it + +Warning - this requires a -ton- of overhead to maintain, I strongly suggest you really understand why this level of tracking is needed... + +Give each team their own project file. Each project file has three major ""sections"" + +* **Published Milestones** - List of milestones from the local schedule file that are reported up and to other projects +* **External Milestones** -List of milestones from other teams or external sources. +* **Schedule** - where the actual tasks are for the team + +You then control a master schedule that takes each team's schedule and ""creates the links"" between their milestones. That is, you need to use the ""Published Milestones"" to drive the ""External Milestones"" across all of the teams' project files. This is time consuming and for five teams takes a good few days to set up, plus the communication needed to ensure everyone understands the structure. +Each week (or whatever your timeframe is for managing the schedule) you need to pull in the teams' projects into the master, observe the links changing, and resolve the issues. + +Again, I can't stress enough that this requires a -huge- commitment to the project schedule. I wouldn't attempt this without some of the teams each having their own PM who understands this and can help you work with it. +If you can live without a Gantt chart, you might just keep a list of Excel milestones that can be used to communicate across the teams and trust each team to update the milestone list. This gives you 90% of the benefit with 2% of the effort.","I tend to use milestones to mark key meetings or approvals of work. If there is some sort of formal cut-over process, make it a milestone." +2109,"**Background** + +I'm building a project Gantt, involving multiple teams. In the past I've had a good experience with a Gantt as a means of planning a project but not so much as a means of tracking a project's progress. + +I'm trying to figure out what would be the best way to reflect the integration points and dependencies between teams and then track it as easily as possible. + +**Current approach** + +Right now, what I have in mind is creating tasks for teams' activities and after each task that indicates a delivery to another team I creating a milestone, with the task as its predecessor. The receiving team's task depends on the milestone. + +Example: + +``` +==== [Team A develops] + +-> * [Team A development complete] + +-> ==== [Team B develops] + +``` + +The downside of this approach is that the Gantt gets cluttered with a lot of milestones. The upside is that I get more control down the road around team delivery tracking and an easier way to filter the deliveries of each of the teams. Also, a side benefit is to avoid messing with weird task updates, splits, etc. I would ask for updates to estimated delivery dates. + +I'd be happy to hear your thoughts and ideas around this issue. How would you approach this?",2011/05/08,"['https://pm.stackexchange.com/questions/2109', 'https://pm.stackexchange.com', 'https://pm.stackexchange.com/users/44/']","Actually, I like how you're planning it. I think part of the problem is that you're now focusing on the aesthetics of the gantt chart as opposed to what it's being used for. Who cares if it 'looks' cluttered? The only real question is - does it make sense to you, and can you quickly and easily see and find the information you need?","I tend to use milestones to mark key meetings or approvals of work. If there is some sort of formal cut-over process, make it a milestone." +2109,"**Background** + +I'm building a project Gantt, involving multiple teams. In the past I've had a good experience with a Gantt as a means of planning a project but not so much as a means of tracking a project's progress. + +I'm trying to figure out what would be the best way to reflect the integration points and dependencies between teams and then track it as easily as possible. + +**Current approach** + +Right now, what I have in mind is creating tasks for teams' activities and after each task that indicates a delivery to another team I creating a milestone, with the task as its predecessor. The receiving team's task depends on the milestone. + +Example: + +``` +==== [Team A develops] + +-> * [Team A development complete] + +-> ==== [Team B develops] + +``` + +The downside of this approach is that the Gantt gets cluttered with a lot of milestones. The upside is that I get more control down the road around team delivery tracking and an easier way to filter the deliveries of each of the teams. Also, a side benefit is to avoid messing with weird task updates, splits, etc. I would ask for updates to estimated delivery dates. + +I'd be happy to hear your thoughts and ideas around this issue. How would you approach this?",2011/05/08,"['https://pm.stackexchange.com/questions/2109', 'https://pm.stackexchange.com', 'https://pm.stackexchange.com/users/44/']","You do not need to use milestones to show the task relationships. In your schedule, once you have determined the sequence of work, based on BOTH hard and soft logic, link them. Link them using FS, SS, FF, with the appropriate leads and lags as appropriate. Baseline it and go. + +This should provide you with the control you need.","How about tracking deliveries between teams and as a separate list? This list would be managed by the program office. Each party would need to mutually agree upon what each delivery will contain and when it will be made. Once they sign up these agreements would be as binding as schedule milestones. This list would be used in addition to a master schedule - it does not replace a schedule. + +The number and status of these hand-offs also makes a useful metric. The practice provides teams a way to ask for and get attention for things they need from one another." +2109,"**Background** + +I'm building a project Gantt, involving multiple teams. In the past I've had a good experience with a Gantt as a means of planning a project but not so much as a means of tracking a project's progress. + +I'm trying to figure out what would be the best way to reflect the integration points and dependencies between teams and then track it as easily as possible. + +**Current approach** + +Right now, what I have in mind is creating tasks for teams' activities and after each task that indicates a delivery to another team I creating a milestone, with the task as its predecessor. The receiving team's task depends on the milestone. + +Example: + +``` +==== [Team A develops] + +-> * [Team A development complete] + +-> ==== [Team B develops] + +``` + +The downside of this approach is that the Gantt gets cluttered with a lot of milestones. The upside is that I get more control down the road around team delivery tracking and an easier way to filter the deliveries of each of the teams. Also, a side benefit is to avoid messing with weird task updates, splits, etc. I would ask for updates to estimated delivery dates. + +I'd be happy to hear your thoughts and ideas around this issue. How would you approach this?",2011/05/08,"['https://pm.stackexchange.com/questions/2109', 'https://pm.stackexchange.com', 'https://pm.stackexchange.com/users/44/']","I've used (and like) a section at the top of the schedule for milestones. This keeps the key milestones visible and easily reportable. + +If you really want to use milestones to show links between teams, I would suggest first that the teams -really- be separate teams and not just different roles. For teams that each manage their own schedule, I have found milestone linking like you are describing moderately helpful. Here is how I have done it + +Warning - this requires a -ton- of overhead to maintain, I strongly suggest you really understand why this level of tracking is needed... + +Give each team their own project file. Each project file has three major ""sections"" + +* **Published Milestones** - List of milestones from the local schedule file that are reported up and to other projects +* **External Milestones** -List of milestones from other teams or external sources. +* **Schedule** - where the actual tasks are for the team + +You then control a master schedule that takes each team's schedule and ""creates the links"" between their milestones. That is, you need to use the ""Published Milestones"" to drive the ""External Milestones"" across all of the teams' project files. This is time consuming and for five teams takes a good few days to set up, plus the communication needed to ensure everyone understands the structure. +Each week (or whatever your timeframe is for managing the schedule) you need to pull in the teams' projects into the master, observe the links changing, and resolve the issues. + +Again, I can't stress enough that this requires a -huge- commitment to the project schedule. I wouldn't attempt this without some of the teams each having their own PM who understands this and can help you work with it. +If you can live without a Gantt chart, you might just keep a list of Excel milestones that can be used to communicate across the teams and trust each team to update the milestone list. This gives you 90% of the benefit with 2% of the effort.","You do not need to use milestones to show the task relationships. In your schedule, once you have determined the sequence of work, based on BOTH hard and soft logic, link them. Link them using FS, SS, FF, with the appropriate leads and lags as appropriate. Baseline it and go. + +This should provide you with the control you need." +2109,"**Background** + +I'm building a project Gantt, involving multiple teams. In the past I've had a good experience with a Gantt as a means of planning a project but not so much as a means of tracking a project's progress. + +I'm trying to figure out what would be the best way to reflect the integration points and dependencies between teams and then track it as easily as possible. + +**Current approach** + +Right now, what I have in mind is creating tasks for teams' activities and after each task that indicates a delivery to another team I creating a milestone, with the task as its predecessor. The receiving team's task depends on the milestone. + +Example: + +``` +==== [Team A develops] + +-> * [Team A development complete] + +-> ==== [Team B develops] + +``` + +The downside of this approach is that the Gantt gets cluttered with a lot of milestones. The upside is that I get more control down the road around team delivery tracking and an easier way to filter the deliveries of each of the teams. Also, a side benefit is to avoid messing with weird task updates, splits, etc. I would ask for updates to estimated delivery dates. + +I'd be happy to hear your thoughts and ideas around this issue. How would you approach this?",2011/05/08,"['https://pm.stackexchange.com/questions/2109', 'https://pm.stackexchange.com', 'https://pm.stackexchange.com/users/44/']","You do not need to use milestones to show the task relationships. In your schedule, once you have determined the sequence of work, based on BOTH hard and soft logic, link them. Link them using FS, SS, FF, with the appropriate leads and lags as appropriate. Baseline it and go. + +This should provide you with the control you need.","Actually, I like how you're planning it. I think part of the problem is that you're now focusing on the aesthetics of the gantt chart as opposed to what it's being used for. Who cares if it 'looks' cluttered? The only real question is - does it make sense to you, and can you quickly and easily see and find the information you need?" +2109,"**Background** + +I'm building a project Gantt, involving multiple teams. In the past I've had a good experience with a Gantt as a means of planning a project but not so much as a means of tracking a project's progress. + +I'm trying to figure out what would be the best way to reflect the integration points and dependencies between teams and then track it as easily as possible. + +**Current approach** + +Right now, what I have in mind is creating tasks for teams' activities and after each task that indicates a delivery to another team I creating a milestone, with the task as its predecessor. The receiving team's task depends on the milestone. + +Example: + +``` +==== [Team A develops] + +-> * [Team A development complete] + +-> ==== [Team B develops] + +``` + +The downside of this approach is that the Gantt gets cluttered with a lot of milestones. The upside is that I get more control down the road around team delivery tracking and an easier way to filter the deliveries of each of the teams. Also, a side benefit is to avoid messing with weird task updates, splits, etc. I would ask for updates to estimated delivery dates. + +I'd be happy to hear your thoughts and ideas around this issue. How would you approach this?",2011/05/08,"['https://pm.stackexchange.com/questions/2109', 'https://pm.stackexchange.com', 'https://pm.stackexchange.com/users/44/']","I've used (and like) a section at the top of the schedule for milestones. This keeps the key milestones visible and easily reportable. + +If you really want to use milestones to show links between teams, I would suggest first that the teams -really- be separate teams and not just different roles. For teams that each manage their own schedule, I have found milestone linking like you are describing moderately helpful. Here is how I have done it + +Warning - this requires a -ton- of overhead to maintain, I strongly suggest you really understand why this level of tracking is needed... + +Give each team their own project file. Each project file has three major ""sections"" + +* **Published Milestones** - List of milestones from the local schedule file that are reported up and to other projects +* **External Milestones** -List of milestones from other teams or external sources. +* **Schedule** - where the actual tasks are for the team + +You then control a master schedule that takes each team's schedule and ""creates the links"" between their milestones. That is, you need to use the ""Published Milestones"" to drive the ""External Milestones"" across all of the teams' project files. This is time consuming and for five teams takes a good few days to set up, plus the communication needed to ensure everyone understands the structure. +Each week (or whatever your timeframe is for managing the schedule) you need to pull in the teams' projects into the master, observe the links changing, and resolve the issues. + +Again, I can't stress enough that this requires a -huge- commitment to the project schedule. I wouldn't attempt this without some of the teams each having their own PM who understands this and can help you work with it. +If you can live without a Gantt chart, you might just keep a list of Excel milestones that can be used to communicate across the teams and trust each team to update the milestone list. This gives you 90% of the benefit with 2% of the effort.","How about tracking deliveries between teams and as a separate list? This list would be managed by the program office. Each party would need to mutually agree upon what each delivery will contain and when it will be made. Once they sign up these agreements would be as binding as schedule milestones. This list would be used in addition to a master schedule - it does not replace a schedule. + +The number and status of these hand-offs also makes a useful metric. The practice provides teams a way to ask for and get attention for things they need from one another." +2109,"**Background** + +I'm building a project Gantt, involving multiple teams. In the past I've had a good experience with a Gantt as a means of planning a project but not so much as a means of tracking a project's progress. + +I'm trying to figure out what would be the best way to reflect the integration points and dependencies between teams and then track it as easily as possible. + +**Current approach** + +Right now, what I have in mind is creating tasks for teams' activities and after each task that indicates a delivery to another team I creating a milestone, with the task as its predecessor. The receiving team's task depends on the milestone. + +Example: + +``` +==== [Team A develops] + +-> * [Team A development complete] + +-> ==== [Team B develops] + +``` + +The downside of this approach is that the Gantt gets cluttered with a lot of milestones. The upside is that I get more control down the road around team delivery tracking and an easier way to filter the deliveries of each of the teams. Also, a side benefit is to avoid messing with weird task updates, splits, etc. I would ask for updates to estimated delivery dates. + +I'd be happy to hear your thoughts and ideas around this issue. How would you approach this?",2011/05/08,"['https://pm.stackexchange.com/questions/2109', 'https://pm.stackexchange.com', 'https://pm.stackexchange.com/users/44/']","Actually, I like how you're planning it. I think part of the problem is that you're now focusing on the aesthetics of the gantt chart as opposed to what it's being used for. Who cares if it 'looks' cluttered? The only real question is - does it make sense to you, and can you quickly and easily see and find the information you need?","How about tracking deliveries between teams and as a separate list? This list would be managed by the program office. Each party would need to mutually agree upon what each delivery will contain and when it will be made. Once they sign up these agreements would be as binding as schedule milestones. This list would be used in addition to a master schedule - it does not replace a schedule. + +The number and status of these hand-offs also makes a useful metric. The practice provides teams a way to ask for and get attention for things they need from one another." +2109,"**Background** + +I'm building a project Gantt, involving multiple teams. In the past I've had a good experience with a Gantt as a means of planning a project but not so much as a means of tracking a project's progress. + +I'm trying to figure out what would be the best way to reflect the integration points and dependencies between teams and then track it as easily as possible. + +**Current approach** + +Right now, what I have in mind is creating tasks for teams' activities and after each task that indicates a delivery to another team I creating a milestone, with the task as its predecessor. The receiving team's task depends on the milestone. + +Example: + +``` +==== [Team A develops] + +-> * [Team A development complete] + +-> ==== [Team B develops] + +``` + +The downside of this approach is that the Gantt gets cluttered with a lot of milestones. The upside is that I get more control down the road around team delivery tracking and an easier way to filter the deliveries of each of the teams. Also, a side benefit is to avoid messing with weird task updates, splits, etc. I would ask for updates to estimated delivery dates. + +I'd be happy to hear your thoughts and ideas around this issue. How would you approach this?",2011/05/08,"['https://pm.stackexchange.com/questions/2109', 'https://pm.stackexchange.com', 'https://pm.stackexchange.com/users/44/']","I've used (and like) a section at the top of the schedule for milestones. This keeps the key milestones visible and easily reportable. + +If you really want to use milestones to show links between teams, I would suggest first that the teams -really- be separate teams and not just different roles. For teams that each manage their own schedule, I have found milestone linking like you are describing moderately helpful. Here is how I have done it + +Warning - this requires a -ton- of overhead to maintain, I strongly suggest you really understand why this level of tracking is needed... + +Give each team their own project file. Each project file has three major ""sections"" + +* **Published Milestones** - List of milestones from the local schedule file that are reported up and to other projects +* **External Milestones** -List of milestones from other teams or external sources. +* **Schedule** - where the actual tasks are for the team + +You then control a master schedule that takes each team's schedule and ""creates the links"" between their milestones. That is, you need to use the ""Published Milestones"" to drive the ""External Milestones"" across all of the teams' project files. This is time consuming and for five teams takes a good few days to set up, plus the communication needed to ensure everyone understands the structure. +Each week (or whatever your timeframe is for managing the schedule) you need to pull in the teams' projects into the master, observe the links changing, and resolve the issues. + +Again, I can't stress enough that this requires a -huge- commitment to the project schedule. I wouldn't attempt this without some of the teams each having their own PM who understands this and can help you work with it. +If you can live without a Gantt chart, you might just keep a list of Excel milestones that can be used to communicate across the teams and trust each team to update the milestone list. This gives you 90% of the benefit with 2% of the effort.","Actually, I like how you're planning it. I think part of the problem is that you're now focusing on the aesthetics of the gantt chart as opposed to what it's being used for. Who cares if it 'looks' cluttered? The only real question is - does it make sense to you, and can you quickly and easily see and find the information you need?" +354242,"I want to `\foreach` on a list and create task (via package [`tasks`](https://www.ctan.org/pkg/tasks)) inside a question. A MWE: + +``` +\documentclass{article} +\usepackage[magyar]{babel} +\usepackage[utf8x]{inputenc} +\usepackage{t1enc} +\usepackage{exsheets} +\usepackage{pgffor} +\usepackage{fp} +\def\pontlist{ +2/3/1/4/, +5/1/-4/3/, +2/7/11/10/, +4/-3/5/7/, +-4/4/5/-7/, +-4/-4/4/4/, +3/7/-3/10/, +-1/-2/3/4/, +-1/3/-2/1/ +} +\newcommand{\felezopont}[4]{ + \FPeval{\resx}{round( ( (#1)+(#3) )/2,1)} + \FPeval{\resy}{round( ( (#2)+(#4) )/2,1)} + \task $A(#1;#2)$, $B(#3;#4)$ + {$(\resx;\resy)$} +} +\begin{document} +\begin{question} + Határozd meg a következő pontpárok felezőpontját! + \begin{tasks} + \foreach \ax/\ay/\bx/\by in \pontlist { + \felezopont{\ax}{\ay}{\bx}{\by} + } + \end{tasks} +\end{question} +\end{document} + +``` + +Without `\begin{tasks} ... \end{tasks}` works well but the use of `tasks` environment causes an error: + +``` +! LaTeX Error: Something's wrong--perhaps a missing \item. + +See the LaTeX manual or LaTeX Companion for explanation. +Type H <return> for immediate help. + ... + +l.33 \end{question} + +``` + +What do I use wrong?",2017/02/16,"['https://tex.stackexchange.com/questions/354242', 'https://tex.stackexchange.com', 'https://tex.stackexchange.com/users/8836/']","It is a question of whether your text font has such a character. If you look in the log file you will find + +> +> `Missing character: There is no π (U+03C0) in font [lmroman12-regular]:+tlig;!` +> +> +> + +In your case pi represents a mathematical entity and in normal text with unicode input you can use + +``` + This is $π$. + +``` + +if you load the package `unicode-math`. + +The `siunitx` package provides a direct interpretation of `\pi` in numbers so you can write + +``` +\SI{\pi/2}{\radian} + +``` + +If you insert the pi character, even with `unicode-math` it will complain with + +> +> `! Invalid token 'π' in numerical input.` +> +> +> + +in the log file.","This typesets pi and gives an error message when using \SI. SI does not recognize pi as the number 3.14159.... + +``` +\documentclass[12pt,a4paper]{article} +\usepackage[utf8]{inputenc} +\usepackage{fontspec} +\setmainfont{DejaVu Serif} +\usepackage{siunitx} %Einheiten + +\begin{document} + This is π. + \SI{π/2}{\radian} %Here latex hangs up +\end{document} + +```" +354242,"I want to `\foreach` on a list and create task (via package [`tasks`](https://www.ctan.org/pkg/tasks)) inside a question. A MWE: + +``` +\documentclass{article} +\usepackage[magyar]{babel} +\usepackage[utf8x]{inputenc} +\usepackage{t1enc} +\usepackage{exsheets} +\usepackage{pgffor} +\usepackage{fp} +\def\pontlist{ +2/3/1/4/, +5/1/-4/3/, +2/7/11/10/, +4/-3/5/7/, +-4/4/5/-7/, +-4/-4/4/4/, +3/7/-3/10/, +-1/-2/3/4/, +-1/3/-2/1/ +} +\newcommand{\felezopont}[4]{ + \FPeval{\resx}{round( ( (#1)+(#3) )/2,1)} + \FPeval{\resy}{round( ( (#2)+(#4) )/2,1)} + \task $A(#1;#2)$, $B(#3;#4)$ + {$(\resx;\resy)$} +} +\begin{document} +\begin{question} + Határozd meg a következő pontpárok felezőpontját! + \begin{tasks} + \foreach \ax/\ay/\bx/\by in \pontlist { + \felezopont{\ax}{\ay}{\bx}{\by} + } + \end{tasks} +\end{question} +\end{document} + +``` + +Without `\begin{tasks} ... \end{tasks}` works well but the use of `tasks` environment causes an error: + +``` +! LaTeX Error: Something's wrong--perhaps a missing \item. + +See the LaTeX manual or LaTeX Companion for explanation. +Type H <return> for immediate help. + ... + +l.33 \end{question} + +``` + +What do I use wrong?",2017/02/16,"['https://tex.stackexchange.com/questions/354242', 'https://tex.stackexchange.com', 'https://tex.stackexchange.com/users/8836/']","It is a question of whether your text font has such a character. If you look in the log file you will find + +> +> `Missing character: There is no π (U+03C0) in font [lmroman12-regular]:+tlig;!` +> +> +> + +In your case pi represents a mathematical entity and in normal text with unicode input you can use + +``` + This is $π$. + +``` + +if you load the package `unicode-math`. + +The `siunitx` package provides a direct interpretation of `\pi` in numbers so you can write + +``` +\SI{\pi/2}{\radian} + +``` + +If you insert the pi character, even with `unicode-math` it will complain with + +> +> `! Invalid token 'π' in numerical input.` +> +> +> + +in the log file.","TeX only loops if you respond to the error message + +``` +!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! +! +! siunitx error: ""invalid-token-in-number"" +! +! Invalid token 'π' in numerical input. +! +! See the siunitx documentation for further information. +! +! For immediate help type H <return>. +!............................................... + +l.7 \SI{π/2}{\radian} + %Here latex hangs up +? + +``` + +with a return and then do the same again on the following error. (Or equivalently if you choose to run in scrollmode automatically ignoring all errors) + +If you do carry on it eventually will end up expanding `\q_no_value` which expands to itself and tex then loops. (You should never reach such a ""quark"" in an error free document, but after an error more or less any behaviour is possible)." +23231397,"I want to find out which widget is in a given direction in GTK+, i.e. doing what the ""move-focus"" signal does, but without actually changing the focus. What I have in mind is a function that takes a GtkWidget \* and a GtkDirectionType and returns the GtkWidget in the given direction (if any). + +What I want this for is to ultimately enumerate the widgets inside a specific GtkFrame in my UI definition, in order from left to right. I.e. basically create a list of widgets from leftmost to rightmost, inside my GtkFrame (or in the general case, inside any container). + +I've tried to search the GTK documentation but haven't found anything that doesn't also change focus.",2014/04/22,"['https://Stackoverflow.com/questions/23231397', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3332264/']","Failing any other approach, the way I'm going forward with is to copy a selected set of static functions from the library implementation of GtkContainer and put them in a file in my own application, modifying them to suit my needs. + +More specifically, the function gtk\_container\_focus\_sort\_left\_right() and any local functions that it depends on. This includes the GCompareFunc left\_right\_compare() and get\_allocation\_coords().","Assuming the directions you care about are ""Forward"" and ""Backward"", it sounds like you want to use [`gtk_container_get_focus_chain()`](https://developer.gnome.org/gtk3/stable/GtkContainer.html#gtk-container-get-focus-chain) on the frame: it does pretty much what it says on the tin: you get a list of widgets in order of focus when tabbing." +41768980,"I'm currently using SQL server 2008 R2(SP1) and SQL server 2008 (SP3) and the applications using these servers are storing the credentials in a plain text json file. My issue is I need to store user credentials as access is only allowed to authorized users. + +How should I go about this? Could I sub out the credentials with the hashed version?",2017/01/20,"['https://Stackoverflow.com/questions/41768980', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5537602/']","You can create alert window outside your application by using WindowManager api + +[What is WindowManager in android?](https://stackoverflow.com/questions/19846541/what-is-windowmanager-in-android) + +Code Snippet + +``` +WindowManager.LayoutParams p = new WindowManager.LayoutParams( +// Shrink the window to wrap the content rather than filling the screen +WindowManager.LayoutParams.WRAP_CONTENT, +WindowManager.LayoutParams.WRAP_CONTENT, +// Display it on top of other application windows, but only for the current user +WindowManager.LayoutParams.TYPE_SYSTEM_ALERT, +// Don't let it grab the input focus +WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, +// Make the underlying application window visible through any transparent parts +PixelFormat.TRANSLUCENT); +// Define the position of the window within the screen +p.gravity = Gravity.TOP | Gravity.RIGHT; +p.x = 0; +p.y = 100; + +WindowManager windowManager = (WindowManager)getSystemService(WINDOW_SERVICE); +windowManager.addView(myView, p); + +``` + +Add this to manifest + +`<uses-permission android:name=""android.permission.SYSTEM_ALERT_WINDOW""/>` + +For Auto close message you can use handler to dimiss after delta of time.","make a consistent alarm manager service class, and research on alert.dialogue activity. After displaying message through box check this link below + +[Execute function after 5 seconds in Android](https://stackoverflow.com/questions/31041884/execute-function-after-5-seconds-in-android) + +and call finish(); function to close your message box." +15210996,"I am getting the result set from the controller to the jsp page where I have a table. + +I inserted all the data coming from resultset to the of that table. + +**The problem I am having is that data is coming in only one column.** What I want to do is just limit the data to 5 in each column (5 in col 1, 5 in col 2, 5 in col3 of the same row). + +Associated ID's: + +``` +AKR +AK +AKRBS +AKRB +AKBS +AKRB +AKRBS +AKRBSW +AK +AKRE + +``` + +and so on.....",2013/03/04,"['https://Stackoverflow.com/questions/15210996', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1847801/']","The syntax error is irrelevant in the long run. + +In Android your *must* start an Activity with an Intent. (See [this Developer's Guide article](https://developer.android.com/guide/components/activities.html#StartingAnActivity).) When you want to start Game use: + +``` +Intent intent = new Intent(this, Game.class); +startActivity(intent); + +``` + +--- + +Also you declare `KEY_DIFFICULTY` as `final` (unchangeable): + +``` +public static final String KEY_DIFFICULTY = ""org.example.sudoku.difficulty""; + +``` + +So your if-else block will never be true in any of these cases: + +``` +if (KEY_DIFFICULTY == String.valueOf(1)) + +``` + +*And* to compare Strings in Java you *must* use `equals()`, `==` will give inaccurate results. ([How do I compare strings in Java?](https://stackoverflow.com/q/513832/1267661)) + +--- + +If you want to pass the level of difficulty from one Activity to another use the Intent's extras, a `public` class variable, or another approach found in: [How do I pass data between Activities in Android application?](https://stackoverflow.com/q/2091465/1267661) + +--- + +**Addition** + +You just added more code to your question and you have circular logic. + +``` +- When you create RandomMathQuestionGenerator object, you will create a Game object + - When you create Game object, you will create a RandomMathQuestionGenerator object + - When you create RandomMathQuestionGenerator object, you will create a Game object + - When you create Game object, you will create a RandomMathQuestionGenerator object + - When you create RandomMathQuestionGenerator object, you will create a Game object + - When you create Game object, you will create a RandomMathQuestionGenerator object + - When you create RandomMathQuestionGenerator object, you will create a Game object + - When you create Game object, you will create a RandomMathQuestionGenerator object + - ... + +``` + +This will only stop when your app throws a StackOverflowException.","``` +number = num.Game(value); + +``` + +I don't see a method `Game(int value)` in your `Game` class. You need to create this method in your class: + +``` +public int Game(int value){ + //code +} + +``` + +I am also not sure you can name a method the same name as your class. I assume the fact it has a return value in the signature, it would be valid, but it would be bad practice to have a method name the same as your class anyway." +15210996,"I am getting the result set from the controller to the jsp page where I have a table. + +I inserted all the data coming from resultset to the of that table. + +**The problem I am having is that data is coming in only one column.** What I want to do is just limit the data to 5 in each column (5 in col 1, 5 in col 2, 5 in col3 of the same row). + +Associated ID's: + +``` +AKR +AK +AKRBS +AKRB +AKBS +AKRB +AKRBS +AKRBSW +AK +AKRE + +``` + +and so on.....",2013/03/04,"['https://Stackoverflow.com/questions/15210996', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1847801/']","The syntax error is irrelevant in the long run. + +In Android your *must* start an Activity with an Intent. (See [this Developer's Guide article](https://developer.android.com/guide/components/activities.html#StartingAnActivity).) When you want to start Game use: + +``` +Intent intent = new Intent(this, Game.class); +startActivity(intent); + +``` + +--- + +Also you declare `KEY_DIFFICULTY` as `final` (unchangeable): + +``` +public static final String KEY_DIFFICULTY = ""org.example.sudoku.difficulty""; + +``` + +So your if-else block will never be true in any of these cases: + +``` +if (KEY_DIFFICULTY == String.valueOf(1)) + +``` + +*And* to compare Strings in Java you *must* use `equals()`, `==` will give inaccurate results. ([How do I compare strings in Java?](https://stackoverflow.com/q/513832/1267661)) + +--- + +If you want to pass the level of difficulty from one Activity to another use the Intent's extras, a `public` class variable, or another approach found in: [How do I pass data between Activities in Android application?](https://stackoverflow.com/q/2091465/1267661) + +--- + +**Addition** + +You just added more code to your question and you have circular logic. + +``` +- When you create RandomMathQuestionGenerator object, you will create a Game object + - When you create Game object, you will create a RandomMathQuestionGenerator object + - When you create RandomMathQuestionGenerator object, you will create a Game object + - When you create Game object, you will create a RandomMathQuestionGenerator object + - When you create RandomMathQuestionGenerator object, you will create a Game object + - When you create Game object, you will create a RandomMathQuestionGenerator object + - When you create RandomMathQuestionGenerator object, you will create a Game object + - When you create Game object, you will create a RandomMathQuestionGenerator object + - ... + +``` + +This will only stop when your app throws a StackOverflowException.","Case - In `<init>` +------------------ + +Here's my modified proposed code for `RandomMathQuestionGenerator`: + +``` +public class RandomMathQuestionGenerator { + private Game num; + private int number; + + public RandomMathQuestionGenerator() { + num = new Game(); + number = num.value; + // Existing code here + } + // Existing code here +} + +``` + +Case - In method code +--------------------- + +``` +Game num = new Game(); +int number = num.value; + +``` + +Here's what's wrong: + +* `public Game` - `public` is a *field* modifier, not a *variable* modifier, and is invalid in the middle of method code. Note that `final` is a valid modifier - it means that re-assigning the variable is a compile error. +* Creating number with a placeholder value, then assigning to it - that `0` will never be used +* num does not have a method Game, and value is not defined in this code. value is a property of Game objects, of which num is one. I **strongly** recommend renaming this variable - maybe `gameInst` would work. + +Summary +------- + +(in progress)" +15136935,"What will be the C++ equivalemt command for below mentioned php command: + +``` +$command = shell_exec(""sqlldr {$connect_string} control={$ctl_file_name} log={$log_file_name}""); + +```",2013/02/28,"['https://Stackoverflow.com/questions/15136935', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2107491/']","So based on your comments a solution that would work would be to use popen(3): + +``` +#include <cstdio> +#include <iostream> +#include <string> + +int main() +{ + // Set file names based on your input etc... just using dummies below + std::string + ctrlFileName = ""file1"", + logFileName = ""file2"", + cmd = ""sqlldr usr/pwd@LT45 control="" + ctrlFileName + "" log="" + logFileName ; + + std::cout << ""Executing Command: "" << cmd << std::endl ; + + FILE* pipe = popen(cmd.c_str(), ""r""); + + if (pipe == NULL) + { + return -1; + } + + char buffer[128]; + std::string result = """"; + + while(!feof(pipe)) + { + if(fgets(buffer, 128, pipe) != NULL) + { + result += buffer; + } + } + + std::cout << ""Results: "" << std::endl << result << std::endl ; + + pclose(pipe); +} + +```","Try `forkpty`, you get a file descriptor which you can use to read from the other pseudoterminal." +1731818,"This is one of those ""there's gotta be a better way"" questions. Let me set up the problem, then I'll give you my hacked solution, and perhaps you can suggest a better solution. Thanks! + +Lets take this little tidbit of PL/SQL + +``` +DECLARE + TYPE foo_record IS RECORD (foo%type, bar%type); + TYPE foo_records IS TABLE OF foo_record INDEX BY PLS_INTEGER; + arr_foos foo_records; + + CURSOR monkeys is SELECT primates FROM zoo; + row_monkey monkeys%rowtype; +BEGIN + FOR row_monkey IN monkeys loop + /* + at this point in each iteration I need to have the associative array + arr_foos in its original state. if this were java, I'd declare it + right here and its scope would be limited to this iteration. However, + this is not java, so the scope of the array is effectively global and + I can't have one iteration's data meddle with the next. + */ + null; + END LOOP; +END; + +``` + +Does that make sense? I basically need to reset it to something. If it was a number that starts at zero, I could just say number:=0; at the top of every iteration and be done with it. But this is not a number, it's a type that I can just reset with a clean :=0. + +Anyway, onto my hack: + +``` +DECLARE + TYPE foo_record IS RECORD (foo%type, bar%type); + TYPE foo_records IS TABLE OF foo_record INDEX BY PLS_INTEGER; + arr_foos foo_records; + arr_foos_reset foo_records; + + CURSOR monkeys is SELECT primates FROM zoo; + row_monkey monkeys%rowtype; +BEGIN + FOR row_monkey IN monkeys loop + arr_foos := arr_foos_reset; + null; + END LOOP; +END; + +``` + +I figured that if I can manage to preserve a member of the same type in an original state, then I can just set the working variable back to whatever the value is of the original. And, surprisingly enough, it works (I think.) But there's gotta be a better way. Can anyone help? + +T'anks!",2009/11/13,"['https://Stackoverflow.com/questions/1731818', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1181/']","The easiest way: + +``` +arr_foos.Delete(); + +``` + +Other way is to declare the variable inside the `FOR` loop. This way it will be recreated for each pass. + +Like this: + +``` +DECLARE + TYPE foo_record IS RECORD (foo%type, bar%type); + TYPE foo_records IS TABLE OF foo_record INDEX BY PLS_INTEGER; + + CURSOR monkeys is SELECT primates FROM zoo; + row_monkey monkeys%rowtype; +BEGIN + FOR row_monkey IN monkeys loop + DECLARE + arr_foos foo_records; + BEGIN + null; + END; + END LOOP; +END; + +```","Are you going to read data from zoo table into a collection? Then there's a better way: + +``` +DECLARE + type foos_ts is table of zoo.foo%type index by pls_integer; + foos foos_t; +BEGIN + select foo + bulk collect into foos + from zoo; + ... +END; + +``` + +Bulk collect automatically clears the collection before fetching, and it works faster then reading row-by-row in loop. Unfortunately, it does'n work with records, so you'll need several PL/SQL tables for each of field. + +You can find additional information here: [Retrieving Query Results into Collections with the BULK COLLECT Clause](http://download.oracle.com/docs/cd/B10501_01/appdev.920/a96624/05_colls.htm#28329)" +23235122,"I'm making Json format data editor with Qt treeview and Qt Json support. +I wanna pass QJsonObject or QJsonArray reference parameter to function. + +This works: + +``` +void makeJsonData(QJsonObject &obj) { + obj.insert(""key"", 1234); +} + +//call makeJsonData() +QJsonObject jobj; +makeJsonData(jobj); +int keysize = jobj.keys().size(); //1, OK. + +``` + +But not with this: + +``` +//QJsonValue, because it can handle both QJsonObject and QJsonArray +void makeJsonData(QJsonValue &obj) { + obj.toObject().insert(""key"", 1234); //obj is QJsonObject +} + +//call makeJsonData() +QJsonObject jobj; +makeJsonData(QJsonValue::fromVariant(jobj)); //fromVariant() to cast QJsonObject to QJsonValue +int keysize = jobj.keys().size(); //0, Fail. + +``` + +It looks like QJsonValue::toObject() just copies parameter.. +How can I use reference of both QJsonObject and QJsonArray with one parameter type?",2014/04/23,"['https://Stackoverflow.com/questions/23235122', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1391099/']","There are a couple ways I see to solve your problem: + +**Option 1** (as mentioned in my comment) + +A dynamic cast can be used like so: + +``` +bool makeJsonData(void* obj) { + QJsonObject* asObj = dynamic_cast<QJsonObject*>(obj); + QJsonArray* asArray = dynamic_cast<QJsonArray*>(obj); + + if (asObj) { + //do what you would if it were an object + } + else if (asArray) { + //do what you would if it were an array + } + else { + //cast fail. Returning false to tell the caller that they passed bad data + //an alternate (probably better) would be to throw an exception + return false; + } +} + +``` + +**Option 2** + +I honestly feel that this business with `void*` is the wrong way to do it. Doing `void*` stuff is almost always a code smell (it removes compile-time checks that save us from stepping on their own feet) and in this case I think that the way you are doing this needs work. Also, `dynamic_cast` requires [RTTI](http://en.wikipedia.org/wiki/Run-time_type_information) which may not always be turned on (compiler support, performance issues, etc). + +I took a look at the Qt headers on my machine and as far as I can tell, `QJsonObject` and `QJsonArray` don't really inherit from anything, so going down the route of changing the `void*` to a base type in order to keep a semblance of type checking won't quite work. + +What I would do would be this: + +* Make two separate methods. One for handling arrays and one for handling objects. They have different methods and different things you can do, so this makes sense to me. You could even keep the same name so that they are overloaded. +* Have another method with your common stuff in it. I assume that your function is trying to add some data to either the array or object that is passed. Make a method that *creates* the data (i.e. `QJsonObject createJsonData()`) and call it inside both of your methods mentioned above. + +The idea is to keep code repetition down while still preserving type checking. The time you spend making the one extra method to handle both cases could be far less than the time you will spend debugging code after accidentally passing in something to a `void*` pointer that you never meant to pass. + +**Option 3** + +Alternately, you could use `QJsonValue`, change the return type of the function to `QJsonValue`, and make it return the new object without modifying the original. Further, the `QJsonValue` class has those fun `isArray`/`isObject` methods that you could use to do something like mentioned earlier. An example: + +``` +QJsonValue makeJsonData(const QJsonValue& val) { + if (val.isObject()) { + QJsonObject obj = val.toObject(); + //do your stuff, modifying obj as you please (perhaps calling another method so that this can have less repetition + return QJsonValue(obj); + } + else if (val.isArray()) { + QJsonArray arr = val.toArray(); + //do your stuff, modifying arr as you please (perhaps calling another method so that this can have less repetition + return QJsonValue(arr); + } + else { + throw ""Invalid Value Type""; + } +} + +``` + +I honestly prefer this pattern, but I know there are reasons for going the way you have mentioned such as avoiding gratuitous memory allocations.","You may need to add this: + +``` +#include <QJsonArray> + +```" +40441026,"My bootstrap navbar that i got from the bootstrap jumbotron example won't collapse. If it is that i dont have the right javascript, css or Jquery links pls send me the right ones. I am kinda new to the navbar thing so i really need some help. Thank you! + Here is my code: + +``` +<nav class=""navbar navbar-inverse navbar-static-top""> + <div class=""container""> + <div class=""navbar-header""> + <button type=""button"" class=""navbar-toggle collapsed"" data-toggle=""collapse"" data-target="".nav-collapse"" aria-expanded=""false"" aria-controls=""navbar""> + <span class=""sr-only"">Toggle navigation</span> + <span class=""icon-bar""></span> + <span class=""icon-bar""></span> + <span class=""icon-bar""></span> + </button> + <a class=""navbar-brand"" href=""#"">Project name</a> + </div> + <div id=""navbar"" class=""navbar-collapse collapse""> + <ul class=""nav navbar-nav""> + <li class=""active""><a href=""#"">Home</a></li> + <li><a href=""#about"">About</a></li> + <li><a href=""#contact"">Contact</a></li> + <li class=""dropdown""> + <a href=""#"" class=""dropdown-toggle"" data-toggle=""dropdown"" role=""button"" aria-haspopup=""true"" aria-expanded=""false"">Dropdown <span class=""caret""></span></a> + <ul class=""dropdown-menu""> + <li><a href=""#"">Action</a></li> + <li><a href=""#"">Another action</a></li> + <li><a href=""#"">Something else here</a></li> + <li role=""separator"" class=""divider""></li> + <li class=""dropdown-header"">Nav header</li> + <li><a href=""#"">Separated link</a></li> + <li><a href=""#"">One more separated link</a></li> + </ul> + </li> + </ul> + <ul class=""nav navbar-nav navbar-right""> + <li><a href=""../navbar/"">Default</a></li> + <li><a href=""./"">Static top <span class=""sr-only"">(current)</span></a></li> + <li><a href=""../navbar-fixed-top/"">Fixed top</a></li> + </ul> + </div><!--/.nav-collapse --> + </div> +</nav> + +```",2016/11/05,"['https://Stackoverflow.com/questions/40441026', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6355698/']","Just figured out, since the object of the shape `(362L,)` is really a pandas series, I just need to change it to dataframe, like this: + +``` +pd.DataFrame(df) + +``` + +That's it!","use + +``` +df.iloc[:, 0].apply(pd.Series) + +```" +32995441,"So I have a table (table A) with a list of drivers and the races they entered and their finishing position + +Fields are + +``` +Date of race +Driver id +Finishing position + +``` + +I want to create a left join query where I can have the above 3 fields and then then joined on them the previous race that the driver entered and its date , finishing position + +So a table that has the headers below………… + +``` +Date of race | Driver id | Finishing position | prev race date | prev race id | prev finishing position + +``` + +I want it to only return the previous and not races prior to the last race + +I want to use the date and or driver id as my variable that I will use to input prior to running query. + +Any support or thoughts would be grateful + +FYI - i am using SSMS 2008",2015/10/07,"['https://Stackoverflow.com/questions/32995441', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5094247/']","You could try multiple (say, 1000) values per INSERT: + +``` +START TRANSACTION; +CREATE TABLE foo (a INTEGER, b STRING); +INSERT INTO foo VALUES (1, 'a'), (2, 'b'), (3, 'c'); +COMMIT; + +``` + +But really, bulk load with `COPY INTO` is generally a much better idea...","<https://www.nuget.org/packages/MonetDb.Mapi> + +``` +int count; +string tableName; // ""\""MyTable\"""" +string columns; // '""' + string.Join(""\"", \"""", columnArray) + '""' + +dbCommand.Execute($""COPY {count} RECORDS INTO {tableName} FROM STDIN ({columns}) DELIMITERS ',','\\n','\\'';""); + +string records; // string.Join('\n', recArrayOfArray.Select(x => string.Join("","" x)) +dbCommand.Execute(records); + +```" +10037932,"I'm trying to access the JSON response from the Bing API using Knockout.js. Below is my javascript code and the corresponding Knockoutjs bindings I'm using in the html. I also included a screenshot of the object I'm trying to access. From the object I need to get Thumbnail.Url and assign that value to the HREF attributes on the page. Can someone spot what I've done wrong? I think the problem is likely in my attr bindings. + +JS + +``` +function bindModel(data) { +var viewModel = ko.mapping.fromJSON(data); +ko.applyBindings(viewModel); + +} + +$.ajax({ + url: fullUri, + type: 'post', + dataType: 'jsonp', + jsonp: true, + jsonpCallback: 'searchDone', + success: function(data, textStatus, jqXHR){ + console.log(data); + bindModel(data); + } +}) + +``` + +HTML + +``` + <ul class=""thumbnails"" data-bind=""foreach: Image.Results""> + <li class=""span2""><img data-bind=""attr: {href: Thumbnail.Url}""></img></li> + </ul> + +``` + +CONSOLE SCREENSHOT + +![enter image description here](https://i.stack.imgur.com/I6yez.png)",2012/04/06,"['https://Stackoverflow.com/questions/10037932', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/549273/']","Couple of things. + +If you are binding the object in your console directly then you will need to be referencing from the property `SearchResponse` since that would be the first property in your viewModel. + +Also an image tag is normally self closing, minor gripe, it does however not use `href` instead you should be setting `src`. + +The correct markup would be. + +``` +<ul class=""thumbnails"" data-bind=""foreach: SearchResponse.Image.Results""> + <li class=""span2""><img data-bind=""attr: {src: Thumbnail.Url}"" /></li> +</ul> + +``` + +Your use of the mapping plugin I believe should be using fromJS since I'm pretty sure jquery will take care of parsing the json string into an object so your data value is not a raw string anymore at this point. + +The correct bind method would therefore be. + +``` +function bindModel(data) { + viewModel = ko.mapping.fromJS(data); + console.log(viewModel); + ko.applyBindings(viewModel); +} + +``` + +Here's a fiddle. + +<http://jsfiddle.net/madcapnmckay/udDGP/> + +Hope this helps.",`img` tags use `src` instead of `href`. You would want to do `attr: { src: Thumbnail.Url }` +40451226,"I have one page where I've put three tabs. After clicking on each tab, the related text gets changed. I want to put three images for each of the tab so when a user clicks the tab, the image should get changed. +Sharing the theme link: + +<https://www.themographics.com/wordpress/docdirect/> + +Here's how the text gets changed on tabs with each click.. Sharing JS + +//Swap Titles + +``` +jQuery(document).on('click','.current-directory',function(){ + jQuery(this).parents('ul').find('li').removeClass('active'); + jQuery(this).addClass('active'); + var dir_name = jQuery(this).data('dir_name'); + var id = jQuery(this).data('id'); + jQuery(this).parents('.tg-banner-content').find('em.current_directory').html(dir_name); + + if( Z_Editor.elements[id] ) { + var load_subcategories = wp.template( 'load-subcategories' ); + var data = []; + data['childrens'] = Z_Editor.elements[id]; + data['parent'] = dir_name; + var _options = load_subcategories(data); + jQuery( '.subcats' ).html(_options); + } + + }); + + //Prepare Subcatgories + jQuery(document).on('change','.directory_type', function (event) { + var id = jQuery('option:selected', this).attr('id'); + var dir_name = jQuery(this).find(':selected').data('dir_name'); + + if( jQuery( '.dynamic-title' ).length ){ + jQuery( '.dynamic-title' ).html(dir_name); + } + + if( Z_Editor.elements[id] ) { + var load_subcategories = wp.template( 'load-subcategories' ); + var data = []; + data['childrens'] = Z_Editor.elements[id]; + data['parent'] = dir_name; + var _options = load_subcategories(data); + jQuery( '.subcats' ).html(_options); + } + }); + +``` + +Here's thee CSS which I tried to modify but I'm only able to add one image to the background, which is static. I want to add 3 images that should change with the text. +Here's the CSS + +``` +.tg-homebanner{position: relative;} +.tg-homebanner figure{ + width: 100%; + float: left; + margin: 0; + z-index: 1; + position: relative; +} +.tg-homebanner figure img{ + display: block; + width: 100%; + /*min-height: 650px;*/ +} +.tg-banner-content{ + position: absolute; + top: 0; + left: 0; + width: 100%; + height: 100%; + z-index: 2; + background: rgba(0, 0, 0, 0.9); +} +/*Here I've made changes and successfully added a background image, but the problem is I want to put 3 images that should be changed with each click*/ + +.tg-banner-content .form-searchdoctors .tg-btn{color: #fff;} +.tg-homebanner .tg-searchform .tg-btn{color: #fff;} +.tg-homebanner .tg-location-map{height: 800px;} +.tg-mapbox .tg-location-map{ + height: 100%; + position: absolute; +} +.show-search{ + position: absolute; + height: 100%; + width: 70px; + right: 0; + top: 0; + background: rgba(0, 0, 0, 0.5); + color: #fff; + font-size: 24px; + text-align: center; + display: none; + cursor: pointer; +} +.show-search i{ + position: relative; + top: 50%; +} + +``` + +Here's the changes I've made as mentioned above: + +``` +.tg-banner-content{ + position: absolute; + top: 0; + left: 0; + width: 100%; + height: 100%; + z-index: 2; + background: url('URL OF MY IMAGE') center center no-repeat; + background-size: cover; + content: ''; + position: absolute; + top: 0; + right: 0; + bottom: 0; + left: 0; + background-image:linear-gradient(to bottom right,#002f4b,#dc20000); + opacity: 1; +} + +``` + +But it only puts a single background image that doesn't change with clicks.",2016/11/06,"['https://Stackoverflow.com/questions/40451226', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5997920/']","Add the following line to your **.htaccess**, so the server can recognize svg files from your css file (background: url(""images/CC\_logo.svg"") no-repeat center top;), Insert this line: + +``` +RewriteRule !\.(js|ico|gif|jpg|jpeg|svg|bmp|png|css|pdf|swf|mp3|mp4|3gp|flv|avi|rm|mpeg|wmv|xml|doc|docx|xls|xlsx|csv|ppt|pptx|zip|rar|mov)$ index.php + +``` + +No need to have so many rules as above but depends on what you need for the format you would like to have on your site, but for your current question here, please make sure there is ""**svg**"" in the rule of your .htaccess file. + +It works, try it! :)",Make sure that your SVG was exported properly. I've found problems with Photoshop images exported as SVGs but I've never had an issue with Illustrator files exported as SVGs. +66035511,"I get the title and the text below when I try and fail to build an .aab file using flutter build appbundle: + +> +> java.util.concurrent.ExecutionException: java.lang.RuntimeException: jarsignerfailed with exit code 1 : +> jarsigner: Certificate chain not found for: keystore. keystore must reference a valid KeyStore key entry containing a private key and corresponding public key certificate chain. +> +> +> + +I had to reset my signing key. The google developer support had me generate a new .jks file with the following command line which I ran from within my project folder: + +``` +keytool -genkeypair -alias upload -keyalg RSA -keysize 2048 -validity 9125 -keystore keystore.jks + +``` + +He then instructed me to convert this file into a .pem file using this command: + +``` +keytool -export -rfc -alias upload -file upload_certificate.pem -keystore keystore.jks + +``` + +I then emailed him the upload\_certificate.pem file. I immediately noticed that the keystore.jks file was red in the sidebar and I get this upon clicking on it: + +""The file 'keystore.jks' is not associated with any file type. Please define the association:"" + +The .pem file is also red, but clicking on it shows the text that makes up the key. + +Do I need to reset the signing key again and do something different? Is there a way to fix the issue causing this error?",2021/02/03,"['https://Stackoverflow.com/questions/66035511', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7311347/']","As dumb as this may sound, I spent 24 hours on this and all I had to was enter `flutter clean`","You have `keyAlias=keystore` in your key.properties while it looks like the alias you created is named `upload` (see in your `keytool export` command). + +Repleace with `keyAlias=upload` and that should work if your password is correct." +728190,"I am having problem with the find and grep commands. I want to find the files which are `*.doc` and match the pattern `Danish` from that file with grep command. I am using -exec to combine them but it give an error i do not know what is that. It said that the `-exec` argument is missing. + +![screen shot](https://i.stack.imgur.com/HWKSw.jpg)",2016/02/01,"['https://askubuntu.com/questions/728190', 'https://askubuntu.com', 'https://askubuntu.com/users/500055/']","You have to escape the `;`: + +``` +find -iname .... -exec echo {} \; + +``` + +Will do what you want.","Unless you put a backslash before the `;`, the shell will interpret that as a command separator, not as an argument to `find` command." +135,What should I be aware of when buying a zoom lens (other than that it will fit my camera)? What specs should I pay close attention to?,2010/07/15,"['https://photo.stackexchange.com/questions/135', 'https://photo.stackexchange.com', 'https://photo.stackexchange.com/users/54/']","One consideration (this is a generalization, but most generalizations are based on some facts) is that usually the longer the zoom range, the quality of the image will suffer. As an example, the mega-zooms (28-300mm for example) will usually result in softer images (especially at either end of the zoom range) than a lens with a narrower zoom range (such as 24-70mm). + +In any case, look for real-world reviews and photo samples before making a purchase. + +I really like the lens [review section of FredMiranda.com](http://www.fredmiranda.com/reviews/) for getting real-world reviews.","1. The zoom factor of course +2. Aperture, if aperture value is low you will either be able to take better photo in darkness and/or do blur effect in lower focus distance +3. Min. focus distance, you will not be able to take a correct shoot if subject is closer than this distance +4. Weight depending of your need you might not want something too heavy + +Each time you want to buy a lens, try to find some review on Internet !" +135,What should I be aware of when buying a zoom lens (other than that it will fit my camera)? What specs should I pay close attention to?,2010/07/15,"['https://photo.stackexchange.com/questions/135', 'https://photo.stackexchange.com', 'https://photo.stackexchange.com/users/54/']","1. The zoom factor of course +2. Aperture, if aperture value is low you will either be able to take better photo in darkness and/or do blur effect in lower focus distance +3. Min. focus distance, you will not be able to take a correct shoot if subject is closer than this distance +4. Weight depending of your need you might not want something too heavy + +Each time you want to buy a lens, try to find some review on Internet !","If you know someone with the lens you are interested in, or a similar one, borrow and use it if you can. That goes way beyond reviews!" +135,What should I be aware of when buying a zoom lens (other than that it will fit my camera)? What specs should I pay close attention to?,2010/07/15,"['https://photo.stackexchange.com/questions/135', 'https://photo.stackexchange.com', 'https://photo.stackexchange.com/users/54/']","1. The zoom factor of course +2. Aperture, if aperture value is low you will either be able to take better photo in darkness and/or do blur effect in lower focus distance +3. Min. focus distance, you will not be able to take a correct shoot if subject is closer than this distance +4. Weight depending of your need you might not want something too heavy + +Each time you want to buy a lens, try to find some review on Internet !",I'm a big fan of Thom Hogan's lens reviews. <http://bythom.com/nikon.htm> +135,What should I be aware of when buying a zoom lens (other than that it will fit my camera)? What specs should I pay close attention to?,2010/07/15,"['https://photo.stackexchange.com/questions/135', 'https://photo.stackexchange.com', 'https://photo.stackexchange.com/users/54/']","One consideration (this is a generalization, but most generalizations are based on some facts) is that usually the longer the zoom range, the quality of the image will suffer. As an example, the mega-zooms (28-300mm for example) will usually result in softer images (especially at either end of the zoom range) than a lens with a narrower zoom range (such as 24-70mm). + +In any case, look for real-world reviews and photo samples before making a purchase. + +I really like the lens [review section of FredMiranda.com](http://www.fredmiranda.com/reviews/) for getting real-world reviews.","If you know someone with the lens you are interested in, or a similar one, borrow and use it if you can. That goes way beyond reviews!" +135,What should I be aware of when buying a zoom lens (other than that it will fit my camera)? What specs should I pay close attention to?,2010/07/15,"['https://photo.stackexchange.com/questions/135', 'https://photo.stackexchange.com', 'https://photo.stackexchange.com/users/54/']","One consideration (this is a generalization, but most generalizations are based on some facts) is that usually the longer the zoom range, the quality of the image will suffer. As an example, the mega-zooms (28-300mm for example) will usually result in softer images (especially at either end of the zoom range) than a lens with a narrower zoom range (such as 24-70mm). + +In any case, look for real-world reviews and photo samples before making a purchase. + +I really like the lens [review section of FredMiranda.com](http://www.fredmiranda.com/reviews/) for getting real-world reviews.",I'm a big fan of Thom Hogan's lens reviews. <http://bythom.com/nikon.htm> +135,What should I be aware of when buying a zoom lens (other than that it will fit my camera)? What specs should I pay close attention to?,2010/07/15,"['https://photo.stackexchange.com/questions/135', 'https://photo.stackexchange.com', 'https://photo.stackexchange.com/users/54/']","If you know someone with the lens you are interested in, or a similar one, borrow and use it if you can. That goes way beyond reviews!",I'm a big fan of Thom Hogan's lens reviews. <http://bythom.com/nikon.htm> +14582431,"Did anyone managed to use @Convert annotation with DataNucleus? Do you have a working example or a documentation link? + +I tried to implement it this way + +``` +... +@Convert(converter = MyAttributeConverter.class) +private String[] aField; +... + +``` + +`MyAttributeConverter` implements `javax.persistence.jpa21.AttributeConverter<String[], String>`. + +When I run the DataNucleus Enhancer I get this error + +``` +WARN [main] (Log4JLogger.java:96) - Class ""XXX"" has an annotation ""javax.persistence.jpa21.Convert"" specified with property ""converter"" yet this is invalid. Please check the specification for that annotation class. Errors were encountered when loading the specified MetaData files and classes. See the nested exceptions for details +ERROR [main] (Log4JLogger.java:125) - DataNucleus Enhancer completed with an error. Please review the enhancer log for full details. Some classes may have been enhanced but some caused errors Errors were encountered when loading the specified MetaData files and classes. See the nested exceptions for details org.datanucleus.exceptions.NucleusUserException: Errors were encountered when loading the specified MetaData files and classes. See the nested exceptions for details + at org.datanucleus.metadata.MetaDataManager.loadClasses(MetaDataManager.java:536) + ... + +``` + +According to DataNucleus documentation seems fine: <http://www.datanucleus.org/products/accessplatform/jpa/annotations.html#Convert>, though googling I found an issue report in which things are a little bit different: <http://www.datanucleus.org/servlet/jira/browse/NUCJPA-164>. + +I'm using DataNucleus 3.1.3.",2013/01/29,"['https://Stackoverflow.com/questions/14582431', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1210071/']","Turn on [logging](http://docs.aws.amazon.com/AmazonS3/latest/dev/LogFormat.html) for the S3 bucket, then (optionally) send the client directly to the bucket. + +The log format includes ""Bytes Sent"" as well as ""Object Size"" and a number of other goodies including the remote IP, referring page, and request URI with query string. + +Logs are not real-time of course, but you'll find a new log dropped into your bucket every few minutes. Retrieve it, parse it, store the interesting content if you want to, and then delete it if you don't want to pay monthly storage costs on the logs.","Keep the request URLs the same, pointing to your EC2 instance. But instead of proxying the content from S3 to the client through your EC2 instance, have your EC2 instance redirect the user to the S3 URL. + +Use an expiring signed URL for the redirect. Your EC2 instance can create the appropriate URL on each request, expiring in a few minutes. That way there's time for the client to fetch the S3 resource but bookmarking it won't work because it will have expired when they try it later. So they always have to go to your EC2 instance to get the resource, allowing you to control and log access, but you don't have to proxy the content itself." +58184449,"In `moodle 3.6` the `enrol_manual_enrol_user` does not work every time! + +``` +{ + ""exception"": ""moodle_exception"", + ""errorcode"": ""wsusercannotassign"", + ""message"": ""You don't have the permission to assign this role (383) to this user (2) in this course(28)."" +} + +```",2019/10/01,"['https://Stackoverflow.com/questions/58184449', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8031441/']","I fell in the same error message. + +If someone faced it, the permission to give to your integration user is: +moodle/role:assign + +That solve the ""wsusercannotassign"" problem.","It took me two days to find a way to solve this problem. + +In my case the web service user had all required privileges to enroll a user. The confusing thing was that the same web service user was able to create a new moodle user via the API. + +After checking all those role specific right (""allow roles assignments"", ""allow role overrides"", ""allow role switches"") multiple times I found one relevant hint in a tutorial: the user who wants to enroll another user to a course has to be member of this course (?!?). + +So I put my web service user to each course I have and gave him in addition the ""trainer""-role. And now enrollment works even via the API." +2626838,"Let $a\_{n} = 2^{-\frac {n}{2}}(1+i)^{n} \frac {1+n}{n}$ for n$ \in \mathbb N.$ + +In order to prove the $i$ is a point of accumulation of the sequence ${a\_{n}}$, I realize that I need to construct/find a subsequence $a\_{l}$ where $l \in \mathbb N$. I am perplexed with regards to $(1+i)^n$ as it does not seem to maintain an $i$ for any such $a\_{l}$. + +Am I on the right track? Any help would be greatly appreciated.",2018/01/29,"['https://math.stackexchange.com/questions/2626838', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/512018/']","You can first integrate by parts for $X > \pi$ + +> +> $$ +> \int\_{\pi}^{X}\frac{\cos\left(x\right)}{x}\text{d}x=\left[\frac{\sin\left(x\right)}{x}\right]^{X}\_{\pi}+\int\_{\pi}^{X}\frac{\sin\left(x\right)}{x^2}\text{d}x +> $$ +> +> +> + +Then you can apply your inequality +$$ +\left|\frac{\sin\left(X\right)}{X}\right| \leq \frac{1}{X} \underset{X \rightarrow +\infty}{\rightarrow}0 +$$ +and then +$$ +\left|\frac{\sin\left(x\right)}{x^2}\right| \leq \frac{1}{x^2} +$$ +which is integrable on $\left[\pi, +\infty\right[$. Letting $X \rightarrow +\infty$ gives you the convergence of the first integral because the three terms you find that one is constant, one tends to a constant and the last tends to $0$.","$\sum\_\limits{n=2}^{\infty} \int\_{(n-\frac 12)\pi}^{(n+\frac 12)\pi} \frac {\cos x}{x} dx$ produces an alternating series. + +if $a\_n$ is an alternating series + +$\sum\_\limits{n=1}^{\infty} a\_n$ converges if: + +$\lim\_\limits{n\to \infty}a\_n = 0$ and for some $N, n>N \implies|a\_{n+1}| < |a\_n|$" +2626838,"Let $a\_{n} = 2^{-\frac {n}{2}}(1+i)^{n} \frac {1+n}{n}$ for n$ \in \mathbb N.$ + +In order to prove the $i$ is a point of accumulation of the sequence ${a\_{n}}$, I realize that I need to construct/find a subsequence $a\_{l}$ where $l \in \mathbb N$. I am perplexed with regards to $(1+i)^n$ as it does not seem to maintain an $i$ for any such $a\_{l}$. + +Am I on the right track? Any help would be greatly appreciated.",2018/01/29,"['https://math.stackexchange.com/questions/2626838', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/512018/']","**Hint:** +$$ +\begin{align} +\int\_\pi^\infty\frac{\cos(x)}{x}\,\mathrm{d}x +&=\sum\_{k=1}^\infty\int\_{(2k-1)\pi}^{(2k+1)\pi}\frac{\cos(x)}{x}\,\mathrm{d}x\\ +&=\sum\_{k=1}^\infty\int\_{-\pi}^\pi\frac{\cos(x)}{x+2k\pi}\,\mathrm{d}x\\ +&=\sum\_{k=1}^\infty\int\_0^\pi\left[\frac{\cos(x)}{x+2k\pi}-\frac{\cos(x)}{x+(2k-1)\pi}\right]\mathrm{d}x\\ +&=-\pi\sum\_{k=1}^\infty\int\_0^\pi\frac{\cos(x)}{(x+2k\pi)(x+(2k-1)\pi)}\,\mathrm{d}x\\ +\end{align} +$$ +and +$$ +\left|\,\frac{\cos(x)}{(x+2k\pi)(x+(2k-1)\pi)}\,\right|\le\frac1{2k(2k-1)\pi^2} +$$","$\sum\_\limits{n=2}^{\infty} \int\_{(n-\frac 12)\pi}^{(n+\frac 12)\pi} \frac {\cos x}{x} dx$ produces an alternating series. + +if $a\_n$ is an alternating series + +$\sum\_\limits{n=1}^{\infty} a\_n$ converges if: + +$\lim\_\limits{n\to \infty}a\_n = 0$ and for some $N, n>N \implies|a\_{n+1}| < |a\_n|$" +2626838,"Let $a\_{n} = 2^{-\frac {n}{2}}(1+i)^{n} \frac {1+n}{n}$ for n$ \in \mathbb N.$ + +In order to prove the $i$ is a point of accumulation of the sequence ${a\_{n}}$, I realize that I need to construct/find a subsequence $a\_{l}$ where $l \in \mathbb N$. I am perplexed with regards to $(1+i)^n$ as it does not seem to maintain an $i$ for any such $a\_{l}$. + +Am I on the right track? Any help would be greatly appreciated.",2018/01/29,"['https://math.stackexchange.com/questions/2626838', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/512018/']","You can first integrate by parts for $X > \pi$ + +> +> $$ +> \int\_{\pi}^{X}\frac{\cos\left(x\right)}{x}\text{d}x=\left[\frac{\sin\left(x\right)}{x}\right]^{X}\_{\pi}+\int\_{\pi}^{X}\frac{\sin\left(x\right)}{x^2}\text{d}x +> $$ +> +> +> + +Then you can apply your inequality +$$ +\left|\frac{\sin\left(X\right)}{X}\right| \leq \frac{1}{X} \underset{X \rightarrow +\infty}{\rightarrow}0 +$$ +and then +$$ +\left|\frac{\sin\left(x\right)}{x^2}\right| \leq \frac{1}{x^2} +$$ +which is integrable on $\left[\pi, +\infty\right[$. Letting $X \rightarrow +\infty$ gives you the convergence of the first integral because the three terms you find that one is constant, one tends to a constant and the last tends to $0$.","$$\int\_{\pi}^{+\infty}\frac{\cos x}{x}\,dx $$ +is convergent by [Dirichlet's test](https://en.wikipedia.org/wiki/Dirichlet%27s_test) since $\left|\int\_I\cos(x)\,dx\right|\leq 2$ and $\frac{1}{x}$ decreases to zero on $x\geq \pi$. + +Accurate upper bounds can be deduced [from the Laplace transform](https://en.wikipedia.org/wiki/Laplace_transform#Evaluating_integrals_over_the_positive_real_axis) and Holder's inequality. Indeed +$$ \int\_{\pi}^{+\infty}\frac{\cos(x)}{x}\,dx = \int\_{0}^{+\infty}\frac{-\cos x}{x+\pi}\,dx = -\int\_{0}^{+\infty}\frac{s e^{-\pi s}}{1+s^2}\,ds<0 $$ +but +$$ \int\_{0}^{+\infty}\frac{s e^{-\pi s}}{1+s^2}\,ds = \int\_{0}^{+\infty}\left(\frac{s^{1/4}}{1+s^2}\right)^1\cdot\left(s^{1/4} e^{-\pi s/3}\right)^3\,ds $$ +is bounded by +$$ \left[\int\_{0}^{+\infty}\frac{s\,ds}{(1+s^2)^4}\right]^{1/4}\cdot\left[\int\_{0}^{+\infty}s e^{-4\pi s/3}\,ds\right]^{3/4}=\sqrt[4]{\frac{3^5}{2^{13}\,\pi^6}}\leq\frac{3}{40}. $$" +2626838,"Let $a\_{n} = 2^{-\frac {n}{2}}(1+i)^{n} \frac {1+n}{n}$ for n$ \in \mathbb N.$ + +In order to prove the $i$ is a point of accumulation of the sequence ${a\_{n}}$, I realize that I need to construct/find a subsequence $a\_{l}$ where $l \in \mathbb N$. I am perplexed with regards to $(1+i)^n$ as it does not seem to maintain an $i$ for any such $a\_{l}$. + +Am I on the right track? Any help would be greatly appreciated.",2018/01/29,"['https://math.stackexchange.com/questions/2626838', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/512018/']","You can first integrate by parts for $X > \pi$ + +> +> $$ +> \int\_{\pi}^{X}\frac{\cos\left(x\right)}{x}\text{d}x=\left[\frac{\sin\left(x\right)}{x}\right]^{X}\_{\pi}+\int\_{\pi}^{X}\frac{\sin\left(x\right)}{x^2}\text{d}x +> $$ +> +> +> + +Then you can apply your inequality +$$ +\left|\frac{\sin\left(X\right)}{X}\right| \leq \frac{1}{X} \underset{X \rightarrow +\infty}{\rightarrow}0 +$$ +and then +$$ +\left|\frac{\sin\left(x\right)}{x^2}\right| \leq \frac{1}{x^2} +$$ +which is integrable on $\left[\pi, +\infty\right[$. Letting $X \rightarrow +\infty$ gives you the convergence of the first integral because the three terms you find that one is constant, one tends to a constant and the last tends to $0$.","**Hint:** +$$ +\begin{align} +\int\_\pi^\infty\frac{\cos(x)}{x}\,\mathrm{d}x +&=\sum\_{k=1}^\infty\int\_{(2k-1)\pi}^{(2k+1)\pi}\frac{\cos(x)}{x}\,\mathrm{d}x\\ +&=\sum\_{k=1}^\infty\int\_{-\pi}^\pi\frac{\cos(x)}{x+2k\pi}\,\mathrm{d}x\\ +&=\sum\_{k=1}^\infty\int\_0^\pi\left[\frac{\cos(x)}{x+2k\pi}-\frac{\cos(x)}{x+(2k-1)\pi}\right]\mathrm{d}x\\ +&=-\pi\sum\_{k=1}^\infty\int\_0^\pi\frac{\cos(x)}{(x+2k\pi)(x+(2k-1)\pi)}\,\mathrm{d}x\\ +\end{align} +$$ +and +$$ +\left|\,\frac{\cos(x)}{(x+2k\pi)(x+(2k-1)\pi)}\,\right|\le\frac1{2k(2k-1)\pi^2} +$$" +2626838,"Let $a\_{n} = 2^{-\frac {n}{2}}(1+i)^{n} \frac {1+n}{n}$ for n$ \in \mathbb N.$ + +In order to prove the $i$ is a point of accumulation of the sequence ${a\_{n}}$, I realize that I need to construct/find a subsequence $a\_{l}$ where $l \in \mathbb N$. I am perplexed with regards to $(1+i)^n$ as it does not seem to maintain an $i$ for any such $a\_{l}$. + +Am I on the right track? Any help would be greatly appreciated.",2018/01/29,"['https://math.stackexchange.com/questions/2626838', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/512018/']","**Hint:** +$$ +\begin{align} +\int\_\pi^\infty\frac{\cos(x)}{x}\,\mathrm{d}x +&=\sum\_{k=1}^\infty\int\_{(2k-1)\pi}^{(2k+1)\pi}\frac{\cos(x)}{x}\,\mathrm{d}x\\ +&=\sum\_{k=1}^\infty\int\_{-\pi}^\pi\frac{\cos(x)}{x+2k\pi}\,\mathrm{d}x\\ +&=\sum\_{k=1}^\infty\int\_0^\pi\left[\frac{\cos(x)}{x+2k\pi}-\frac{\cos(x)}{x+(2k-1)\pi}\right]\mathrm{d}x\\ +&=-\pi\sum\_{k=1}^\infty\int\_0^\pi\frac{\cos(x)}{(x+2k\pi)(x+(2k-1)\pi)}\,\mathrm{d}x\\ +\end{align} +$$ +and +$$ +\left|\,\frac{\cos(x)}{(x+2k\pi)(x+(2k-1)\pi)}\,\right|\le\frac1{2k(2k-1)\pi^2} +$$","$$\int\_{\pi}^{+\infty}\frac{\cos x}{x}\,dx $$ +is convergent by [Dirichlet's test](https://en.wikipedia.org/wiki/Dirichlet%27s_test) since $\left|\int\_I\cos(x)\,dx\right|\leq 2$ and $\frac{1}{x}$ decreases to zero on $x\geq \pi$. + +Accurate upper bounds can be deduced [from the Laplace transform](https://en.wikipedia.org/wiki/Laplace_transform#Evaluating_integrals_over_the_positive_real_axis) and Holder's inequality. Indeed +$$ \int\_{\pi}^{+\infty}\frac{\cos(x)}{x}\,dx = \int\_{0}^{+\infty}\frac{-\cos x}{x+\pi}\,dx = -\int\_{0}^{+\infty}\frac{s e^{-\pi s}}{1+s^2}\,ds<0 $$ +but +$$ \int\_{0}^{+\infty}\frac{s e^{-\pi s}}{1+s^2}\,ds = \int\_{0}^{+\infty}\left(\frac{s^{1/4}}{1+s^2}\right)^1\cdot\left(s^{1/4} e^{-\pi s/3}\right)^3\,ds $$ +is bounded by +$$ \left[\int\_{0}^{+\infty}\frac{s\,ds}{(1+s^2)^4}\right]^{1/4}\cdot\left[\int\_{0}^{+\infty}s e^{-4\pi s/3}\,ds\right]^{3/4}=\sqrt[4]{\frac{3^5}{2^{13}\,\pi^6}}\leq\frac{3}{40}. $$" +482562,"I am facing an issue that some packets sent out to internet from inside network were missing. The pattern we are using is like: + +``` + Client A ←→ Switch A ← Router A:NAT ← .. Network .. + → Router B:NAT → Switch B ←→ Server B + +``` + +I want to do below two steps to track the issue: + +1. Capture the packets which are from Client A on Router B. +2. Check the translation table of Router B. + +Are both actions possible? + +More information: + +1. Client A is running on Windows XP +2. Server B is running on Linux (Fedora exactly). +3. The Router B use static port and address translation table which means incoming packets + +to specific port will be forwarded to Server B. +4. Both Router A and Router B are TPLink WR340+ products. +5. Both Router A and Router B have Full-cone NAT. +6. Switch A is DLink DES-1024R and Switch B is DLink DES-1016D. + +The reason why I want to perform the two actions is that we found packets were sent out of the network interface of ClientA, but due to unknown reason the TCP kernel of ClientA machine never receives any ACK packet from the other endpoint, thus it enters data transmission until timeout. And from the server side, also using Tool WireShark we found the network interface of Server B machine never receives the packet sent from client A. I guess the packets were dropped by Router B, so I wonder if it is possible to capture packets at Router B. + +Actually the issue only happened when we have two clients, say they are Client A and Client C. The Client A and Client C don't communicate with each other directly, but communicate with Server B instead. + +Problem happened when we unplug the network cable of Client A machine and on another machine log in Client A in about 30 seconds, client A on the new machine will start TCP communication with server B, the first many commands are OK, but after that server can't receive any command from Client A anymore.",2013/02/24,"['https://serverfault.com/questions/482562', 'https://serverfault.com', 'https://serverfault.com/users/161970/']","> +> Server B never received the packet +> +> +> + +If you run Wireshark from Server B is ok; if not please consider you would need a managed switch configuring a ""mirror/span/monitor"" port where you connect to Wireshark's PC. + +I would stick with Wireshark moving it to see packets between the Router B and the Switch B (can you add a hub in between to insert wireshark's PC?) + +if the packet does not make it to the segment RouterB-SwitchB then your port forwarding at Router B (in order to bypass its NAT services) could be not working right or the router is just not routing your traffic.","I think it is important to get more information, switches don't do NAT (but routers do), and different routers have widely varying abilities. I've never heard the term ""checking the translation table"" when referring to switches or routers, but I do understand what you mean with respect of routers. + +You will most likely find knowledge of NAT and checking translation tables etc a lot less valuable then using simple network tools. The first tool I would use is ""WinMTR"" from the Client A. Leave that running for a little (minutes ?) while and see if and where packet loss occurs. This will give you a very good idea where to look further. [ Looking at latencies and spikes in latencies will also give you some hints if you know what to look at ]. + +For someone to provide more help, you might want to provide more detail as to why you believe packets are going missing, and the characteristics of the problem." +482562,"I am facing an issue that some packets sent out to internet from inside network were missing. The pattern we are using is like: + +``` + Client A ←→ Switch A ← Router A:NAT ← .. Network .. + → Router B:NAT → Switch B ←→ Server B + +``` + +I want to do below two steps to track the issue: + +1. Capture the packets which are from Client A on Router B. +2. Check the translation table of Router B. + +Are both actions possible? + +More information: + +1. Client A is running on Windows XP +2. Server B is running on Linux (Fedora exactly). +3. The Router B use static port and address translation table which means incoming packets + +to specific port will be forwarded to Server B. +4. Both Router A and Router B are TPLink WR340+ products. +5. Both Router A and Router B have Full-cone NAT. +6. Switch A is DLink DES-1024R and Switch B is DLink DES-1016D. + +The reason why I want to perform the two actions is that we found packets were sent out of the network interface of ClientA, but due to unknown reason the TCP kernel of ClientA machine never receives any ACK packet from the other endpoint, thus it enters data transmission until timeout. And from the server side, also using Tool WireShark we found the network interface of Server B machine never receives the packet sent from client A. I guess the packets were dropped by Router B, so I wonder if it is possible to capture packets at Router B. + +Actually the issue only happened when we have two clients, say they are Client A and Client C. The Client A and Client C don't communicate with each other directly, but communicate with Server B instead. + +Problem happened when we unplug the network cable of Client A machine and on another machine log in Client A in about 30 seconds, client A on the new machine will start TCP communication with server B, the first many commands are OK, but after that server can't receive any command from Client A anymore.",2013/02/24,"['https://serverfault.com/questions/482562', 'https://serverfault.com', 'https://serverfault.com/users/161970/']","> +> Server B never received the packet +> +> +> + +If you run Wireshark from Server B is ok; if not please consider you would need a managed switch configuring a ""mirror/span/monitor"" port where you connect to Wireshark's PC. + +I would stick with Wireshark moving it to see packets between the Router B and the Switch B (can you add a hub in between to insert wireshark's PC?) + +if the packet does not make it to the segment RouterB-SwitchB then your port forwarding at Router B (in order to bypass its NAT services) could be not working right or the router is just not routing your traffic.","Here is an outline of a few ideas, and perhaps others know of how to do it in detail. + +Use a linux machine router. + +Perhaps Tomato or DDWRT can. So if your router supports that firmware / if you bought one that supports it, you could try that. + +You commented `""The reason why I want to perform the two actions is that we found packets were sent out of the network interface of ClientA, but due to unknown reason the TCP kernel of ClientA machine never receives any ACK packet from the other endpoint, thus it enters data transmission until timeout. And from the server side, also using Tool WireShark we found the network interface of Server B machine never receives the packet sent from client A, of course it was not able to send any ACK packet back to ClientA.""` + +Maybe a router is damaged, or you have a faulty cable. + +I love the fun ideas of how to see what is happening at your router, it may be possible with a fancier router, or better firmware. But if you can/want to do that, then you'd probably have or need a better router, or a replacement one to try. Don't overlook basic troubleshooting techniques, monkey type logic, like swapping parts! + +Is it just one way that has an issue? like A->B. Or B->A too? You could troubleshoot a bit there like swapping the cables around. swapping the ports they're connected to." +37704027,"I was trying to bootstrap my application using code below in a `boot.ts` file: + +``` +import {bootstrap} from 'angular2/platform/browser' +import {ROUTER_PROVIDERS} from 'angular2/router' + +import {AppComponent} from './app.component' + +bootstrap(AppComponent,[ROUTER_PROVIDERS]); + +``` + +It worked fine. + +Now I wanted to try and add Google Maps so imported `angular2-google-maps` package , created a `map.component.ts` file and added this to the router mapping (defined in the `app.component.ts` file). + +For the above package, `import {bootstrap} from '@angular/platform-browser-dynamic';` +is used in the [plunker code](http://plnkr.co/edit/YX7W20?p=preview) (provided as a starter code). + +Now the map is displaying if I add a `<map>` selector in my `index.html` page. + +I want it to follow the routing which was defined earlier. + +Bootstrapping is also happening twice (once for the `AppComponent` and once for the `Map`) + +How to bootstrap the map component properly so that bootstrapping happens only for the Main app? + +Also what is the difference between `@angular` and `angular2` packages and when to use them?",2016/06/08,"['https://Stackoverflow.com/questions/37704027', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1572356/']","`@angular` is for RC (release candidate) versions and `angular2` for beta versions. + +In RC versions, for example, `angular2/core` becomes `@angular/core`. You can also notice that the SystemJS configuration is different since you don't have bundled JS files. + +Now you need to configure Angular2 modules into map and packages blocks of your SystemJS configuration. See this link for more details: + +* <https://angular.io/guide/quickstart>","This is new for Angular2 versions after beta.x, and therefore `=> Angular2 RC.0` + +Versions `<= Angular2 beta.x` use `angular2`" +31412283,"I have a CMS that I intend to use for a number of websites on Azure. + +I want to be able to create clones of the website easily and have them deployed to Azure. + +Azure Automation was suggested as one possible solution, does this service fit my need? + +Which Azure service should I use to do this?",2015/07/14,"['https://Stackoverflow.com/questions/31412283', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4429847/']","Use `lapply`, not `sapply`, along with creating a custom environment: + +``` +O_envir<-new.env() +O_envir$Orig<-.45 +func<-function(n){ + O_envir$Orig<-pmin(O_envir$Orig*(1+Adjusted[n,]),100) + return(O_envir$Orig) +} +rbind(O_envir$Orig, + do.call(rbind,lapply(1:12,func))) + +```","Here's an [Rcpp](http://cran.r-project.org/web/packages/Rcpp/index.html) implementation: + +``` +library('Rcpp'); +cppFunction(' + NumericMatrix makeOriginal(double orig, int NR, int NC ) { + NumericMatrix m(NR,NC); + for (size_t c = 0; c < NC; ++c) + m[c*NR] = orig; + for (size_t r = 1; r < NR; ++r) for (size_t c = 0; c < NC; ++c) { + size_t i = r+c*NR; + m[i] = std::min<double>(m[i-1]*(i+1),100); + } + return m; + } +'); +makeOriginal(0.45,13L,10L); +## [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] +## [1,] 0.45 0.45 0.45 0.45 0.45 0.45 0.45 0.45 0.45 0.45 +## [2,] 0.90 6.75 12.60 18.45 24.30 30.15 36.00 41.85 47.70 53.55 +## [3,] 2.70 100.00 100.00 100.00 100.00 100.00 100.00 100.00 100.00 100.00 +## [4,] 10.80 100.00 100.00 100.00 100.00 100.00 100.00 100.00 100.00 100.00 +## [5,] 54.00 100.00 100.00 100.00 100.00 100.00 100.00 100.00 100.00 100.00 +## [6,] 100.00 100.00 100.00 100.00 100.00 100.00 100.00 100.00 100.00 100.00 +## [7,] 100.00 100.00 100.00 100.00 100.00 100.00 100.00 100.00 100.00 100.00 +## [8,] 100.00 100.00 100.00 100.00 100.00 100.00 100.00 100.00 100.00 100.00 +## [9,] 100.00 100.00 100.00 100.00 100.00 100.00 100.00 100.00 100.00 100.00 +## [10,] 100.00 100.00 100.00 100.00 100.00 100.00 100.00 100.00 100.00 100.00 +## [11,] 100.00 100.00 100.00 100.00 100.00 100.00 100.00 100.00 100.00 100.00 +## [12,] 100.00 100.00 100.00 100.00 100.00 100.00 100.00 100.00 100.00 100.00 +## [13,] 100.00 100.00 100.00 100.00 100.00 100.00 100.00 100.00 100.00 100.00 + +``` + +**Edit:** Another approach, but similar: + +``` +cppFunction(' + NumericMatrix makeOriginal(double orig, int NR, int NC ) { + NumericMatrix m(NR,NC); + size_t len = NR*NC; + for (size_t i = 0; i < len; ++i) + m[i] = i%NR == 0 ? orig : std::min<double>(m[i-1]*(1+i),100); + return m; + } +'); + +```" +31412283,"I have a CMS that I intend to use for a number of websites on Azure. + +I want to be able to create clones of the website easily and have them deployed to Azure. + +Azure Automation was suggested as one possible solution, does this service fit my need? + +Which Azure service should I use to do this?",2015/07/14,"['https://Stackoverflow.com/questions/31412283', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4429847/']","No need for sapply, as far as I can see. Try something like this. + +``` +adj1 <- 1 + rbind(0, Adjusted) +adjprod <- apply(adj1, 2, cumprod) + +result <- Orig * adjprod +result[result > 100] <- 100 +result + +```","Here's an [Rcpp](http://cran.r-project.org/web/packages/Rcpp/index.html) implementation: + +``` +library('Rcpp'); +cppFunction(' + NumericMatrix makeOriginal(double orig, int NR, int NC ) { + NumericMatrix m(NR,NC); + for (size_t c = 0; c < NC; ++c) + m[c*NR] = orig; + for (size_t r = 1; r < NR; ++r) for (size_t c = 0; c < NC; ++c) { + size_t i = r+c*NR; + m[i] = std::min<double>(m[i-1]*(i+1),100); + } + return m; + } +'); +makeOriginal(0.45,13L,10L); +## [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] +## [1,] 0.45 0.45 0.45 0.45 0.45 0.45 0.45 0.45 0.45 0.45 +## [2,] 0.90 6.75 12.60 18.45 24.30 30.15 36.00 41.85 47.70 53.55 +## [3,] 2.70 100.00 100.00 100.00 100.00 100.00 100.00 100.00 100.00 100.00 +## [4,] 10.80 100.00 100.00 100.00 100.00 100.00 100.00 100.00 100.00 100.00 +## [5,] 54.00 100.00 100.00 100.00 100.00 100.00 100.00 100.00 100.00 100.00 +## [6,] 100.00 100.00 100.00 100.00 100.00 100.00 100.00 100.00 100.00 100.00 +## [7,] 100.00 100.00 100.00 100.00 100.00 100.00 100.00 100.00 100.00 100.00 +## [8,] 100.00 100.00 100.00 100.00 100.00 100.00 100.00 100.00 100.00 100.00 +## [9,] 100.00 100.00 100.00 100.00 100.00 100.00 100.00 100.00 100.00 100.00 +## [10,] 100.00 100.00 100.00 100.00 100.00 100.00 100.00 100.00 100.00 100.00 +## [11,] 100.00 100.00 100.00 100.00 100.00 100.00 100.00 100.00 100.00 100.00 +## [12,] 100.00 100.00 100.00 100.00 100.00 100.00 100.00 100.00 100.00 100.00 +## [13,] 100.00 100.00 100.00 100.00 100.00 100.00 100.00 100.00 100.00 100.00 + +``` + +**Edit:** Another approach, but similar: + +``` +cppFunction(' + NumericMatrix makeOriginal(double orig, int NR, int NC ) { + NumericMatrix m(NR,NC); + size_t len = NR*NC; + for (size_t i = 0; i < len; ++i) + m[i] = i%NR == 0 ? orig : std::min<double>(m[i-1]*(1+i),100); + return m; + } +'); + +```" +2235118,"> +> Suppose that polynomial $x^4+x+1$ has multiple roots over a field of +> characteristic $p$ . What are the possible values of $p$? +> +> +> + +My solution : +Set $f=x^4+x+1$. Suppose the multiple root is $m$ . So $f,f'$ (the formal derivative of $f$) have root $m$ in the field of characteristic $p$. + +Hence $m^4+m+1=0 \pmod{p} $ and $4m^3+1=0 \pmod{p}$ + +So $3m+4=4(m^4+m+1)-m(4m^3+1)=0 \pmod{p}$ . + +From here it is easy to to see that $p\neq 3$. I have no idea if it is possible to proceed any further. Please provide a solution.",2017/04/15,"['https://math.stackexchange.com/questions/2235118', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/71612/']","Hint: + +Find the quotient and remainder when $(27)(4m^3 + 1)$ is divided by $3m+4$.","Using the [extended Euclidean algorithm](http://www.wolframalpha.com/input/?i=PolynomialExtendedGCD%5Bx%5E4+%2B+x+%2B+1,+4+x%5E3+%2B+1%5D) we get +$$ +229 = (x^4 + x + 1)(144 x^2 - 192 x + 256)+(4 x^3 + 1)(-36 x^3 + 48 x^2 - 64 x - 27) +$$ +This can also be found by computing the [resultant](http://www.wolframalpha.com/input/?i=resutant%5Bx%5E4+%2B+x+%2B+1,+4+x%5E3+%2B+1%5D) of $x^4 + x + 1$ and $4 x^3 + 1$, that is, the discriminant of $x^4 + x + 1$." +2235118,"> +> Suppose that polynomial $x^4+x+1$ has multiple roots over a field of +> characteristic $p$ . What are the possible values of $p$? +> +> +> + +My solution : +Set $f=x^4+x+1$. Suppose the multiple root is $m$ . So $f,f'$ (the formal derivative of $f$) have root $m$ in the field of characteristic $p$. + +Hence $m^4+m+1=0 \pmod{p} $ and $4m^3+1=0 \pmod{p}$ + +So $3m+4=4(m^4+m+1)-m(4m^3+1)=0 \pmod{p}$ . + +From here it is easy to to see that $p\neq 3$. I have no idea if it is possible to proceed any further. Please provide a solution.",2017/04/15,"['https://math.stackexchange.com/questions/2235118', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/71612/']","Hint: + +Find the quotient and remainder when $(27)(4m^3 + 1)$ is divided by $3m+4$.","$$3m+4 \equiv 0 \pmod{p} \\ +3m \equiv -4 \pmod{p} \\ +27m^3 \equiv -64 \pmod{p}$$ + +You also have +$$4m^3\equiv -1 \pmod{p}$$ + +Denote $m^3=:x$ then +$$27x \equiv -64 \pmod{p} \\ +4x \equiv -1 \pmod{p}$$ + +Multiply first equation by 4, second by 27 and subtract." +63792397,"It's well documented that Chrome and Firefox ignore the standard autocomplete=""off"" attribute in html as they (Google) feel it wasn't being used correctly. They have even come up with workarounds and their own set of values for autofilling fields. + +However, We need to prevent users passwords from being auto-filled for a website we're working on, and none of the suggestions put forward by Google appear to work. + +The current situation on our website is that login names and passwords are stored by the browser, and so when a user visits the site and they're forced to login, their username and passwords are pre-populated in the relevant fields and they simply click the login button to login. + +This has been deemed insecure, and while the infosec team are happy for the username to be pre-populated, they insist the password field is not. + +To start with I tried adding the autocomplete=""off"" attribute to the password fields, but the password was still pre-populated. After some googling I found this link that shows Google decided to ignore this value and come up with a list of their own values for the autocomplete attribute... + +[Google ignores autocomplete=""off""](https://bugs.chromium.org/p/chromium/issues/detail?id=468153#c164) + +They state that if we add our own, non-recognised value (such as autocomplete=""please-dont-auto-fill-me"") if shouldnt auto fill as it wouldnt know what that value is for. + +However, I added something more meaningful - autocomplete=""non-filled-value"" - and it still populated the field. I've since tried a number of other things, such as renaming the password input control (removing the word ""password"" from the control name) etc and nothing seems to work. every time I load the login page, the password is pre-populated. + +The issue I have is that my login form will be loaded on multiple browsers as different users from around the world login, and I need a solution that works for all browsers, not just Chrome. + +Does anyone have any experience of this, and has a working solution for preventing fields being pre-populated/auto-filled that works cross browser? Everything I've tried (renaming fields, adding hidden fields, setting obscure autocomplete attribute values) fails to work, and whatever I try, the password is pre-populated. + +Obviously, I have no control over the users actual browser settings and cant force them all to change their own personal settings.",2020/09/08,"['https://Stackoverflow.com/questions/63792397', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/564297/']","### New approach + +I know how frustrating it is to try all solutions and seeing user and password fields ignore them. + +Unforturnately, I haven't found a straightforward way of doing this, but I have a workaround for avoiding user password fields getting autofilled. + +### The problem + +The main problem is that if you set input type=""password"", browsers automatically try fo autofill the field with saved passwords and users for the webapp, and nothing seems to work in order to stop it. + +### The solution + +My approach is to avoid setting input type=""passoword"", but making the field look like a password field. + +The way I found to achieve this was to build a font composed only by discs, so when you type anything in the input field, it looks like a password field, but you will never be prompted with saved user and password credentials. + +I've tested this solution on Chrome, Firefox and Microsoft Edge, please let me know if is something worong with other browsers. + +I know the solution is awful, but seems to work. + +Link to the font, made by me using Font Forge: <https://drive.google.com/file/d/1xWGciDI-cQVxDP_H8s7OfdJt44ukBWQl/view?usp=sharing> + +**Example** + +Browsers will not fill in the input elements because none of them is type=""password"" + +Place the .ttf file in the same directory where you create the following html file: + +``` +<!DOCTYPE html> +<html> + <head> + <title>Font Test + + + Name: + Password: + + + + +``` + +Hope this is helpful, feel free to comment any issue.","Actually, i've recently faced this issue, and a workaround which worked form me is just setting the value as an empty string on a method (can be onload, for example if the input is in your main screen). Would be something like: + +``` +let login = document.querySelector('#inputLogin'); +let password = document.querySelector('#inputPassword'); + +function someFun () { + login.value = ''; + password.value = ''; +} + +``` + +Also I've already tried to put `autocomplete=""false""` but didn't work." +11289956,"I wanted to know in what language has the desktop application of Dropbox been coded? +Is it Python or Ruby?",2012/07/02,"['https://Stackoverflow.com/questions/11289956', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1495471/']","Replace this lines + +``` +File myFile = new File(""sdcard/mysdfile.txt""); +if(!myFile.exists()){ + myFile.mkdirs(); + } +myFile = new File(""sdcard/mysdfile.txt""); + +``` + +with + +//Saving the parsed data......... + +``` +File myFile = new File(Environment.getExternalStorageDirectory()+""/mysdfile.txt""); +myFile.createNewFile(); + +```","``` +File myFile = new File(""sdcard/mysdfile.txt""); + +``` + +Should be changed to + +``` +File myFile = new File(""/mnt/sdcard/mysdfile.txt""); + +```" +11289956,"I wanted to know in what language has the desktop application of Dropbox been coded? +Is it Python or Ruby?",2012/07/02,"['https://Stackoverflow.com/questions/11289956', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1495471/']","First thing, your `AndroidManifest.xml` file is correct. So no need to correct that. Though I would recommend organizing your permissions in one place. + +### Writing File to Internal Storage + +``` +FileOutputStream fOut = openFileOutput(""myinternalfile.txt"",MODE_WORLD_READABLE); +OutputStreamWriter osw = new OutputStreamWriter(fOut); + +//---write the contents to the file--- +osw.write(strFileData); +osw.flush(); +osw.close(); + +``` + +### Writing File to External SD Card + +``` +//This will get the SD Card directory and create a folder named MyFiles in it. +File sdCard = Environment.getExternalStorageDirectory(); +File directory = new File (sdCard.getAbsolutePath() + ""/MyFiles""); +directory.mkdirs(); + +//Now create the file in the above directory and write the contents into it +File file = new File(directory, ""mysdfile.txt""); +FileOutputStream fOut = new FileOutputStream(file); +OutputStreamWriter osw = new OutputStreamWriter(fOut); +osw.write(strFileData); +osw.flush(); +osw.close(); + +``` + +**Note: If running on an emulator, ensure that you have enabled SD Card support in the AVD properties and allocated it appropriate space.**","Replace this lines + +``` +File myFile = new File(""sdcard/mysdfile.txt""); +if(!myFile.exists()){ + myFile.mkdirs(); + } +myFile = new File(""sdcard/mysdfile.txt""); + +``` + +with + +//Saving the parsed data......... + +``` +File myFile = new File(Environment.getExternalStorageDirectory()+""/mysdfile.txt""); +myFile.createNewFile(); + +```" +11289956,"I wanted to know in what language has the desktop application of Dropbox been coded? +Is it Python or Ruby?",2012/07/02,"['https://Stackoverflow.com/questions/11289956', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1495471/']","First thing, your `AndroidManifest.xml` file is correct. So no need to correct that. Though I would recommend organizing your permissions in one place. + +### Writing File to Internal Storage + +``` +FileOutputStream fOut = openFileOutput(""myinternalfile.txt"",MODE_WORLD_READABLE); +OutputStreamWriter osw = new OutputStreamWriter(fOut); + +//---write the contents to the file--- +osw.write(strFileData); +osw.flush(); +osw.close(); + +``` + +### Writing File to External SD Card + +``` +//This will get the SD Card directory and create a folder named MyFiles in it. +File sdCard = Environment.getExternalStorageDirectory(); +File directory = new File (sdCard.getAbsolutePath() + ""/MyFiles""); +directory.mkdirs(); + +//Now create the file in the above directory and write the contents into it +File file = new File(directory, ""mysdfile.txt""); +FileOutputStream fOut = new FileOutputStream(file); +OutputStreamWriter osw = new OutputStreamWriter(fOut); +osw.write(strFileData); +osw.flush(); +osw.close(); + +``` + +**Note: If running on an emulator, ensure that you have enabled SD Card support in the AVD properties and allocated it appropriate space.**","``` +File myFile = new File(""sdcard/mysdfile.txt""); + +``` + +Should be changed to + +``` +File myFile = new File(""/mnt/sdcard/mysdfile.txt""); + +```" +682211,"I'm having a bit of difficulty with Cisco AnyConnect v3.1 in regards to automatic login. I have to stay connected to a single server all day every day, and it would be super if I didn't have to dig up my 16 char password each and every day. I'd love for the client to log on automatically, but I'm not even sure at this point that it's a possibility. + +I should note that the AnyConnect software is provided to me by our hosting company, and I nor anyone at my organization has access to the management side of things. I did see that there is such a piece of software on the interwebs called the ""AnyConnect Profile Editor,"" but Cisco wouldn't let me download without a valid login. + +I've been into `%appdata%\local\cisco\cisco anyconnect secure mobility client\preferences.xml` to review my preferences as well as `%programdata%\Cisco\Cisco AnyConnect Secure Mobility Client\Profile\ANYCONNECT.XML` to review my profile settings. Neither of these showed anywhere that I would be able to store my credentials. I even broke my profile a few times by trying to shoe-horn my password in places. That didn't work, go figure. + +Lastly, I found [this forum post](https://supportforums.cisco.com/thread/2148440#discussion-action-div-3994840) which seemed to specify client and server certificate ""thumbprints"" as well as something called an SDI token. + +*Disclaimer: I'm a front-end web developer by day and it's been quite a long time since I've had to do any network management for myself, sorry for the noob question!*",2013/11/29,"['https://superuser.com/questions/682211', 'https://superuser.com', 'https://superuser.com/users/278026/']","Here is my script to launch Cisco AnyConnect Mobility Client v3.1 and log in automatically. Save this script as *FILENAME.vbs*, replace *PASSWORD* with your password, replace the path to the VPN Client exe if needed (probably not), and you may also need to adjust the 2nd sleep time as well depending on your connection speed (mine works reliably at 5000 but yours may need less/more time to dial home). I have mine pinned to my task bar but you can hotkey it as well. + +``` +Set WshShell = WScript.CreateObject(""WScript.Shell"") + +WshShell.Run """"""%PROGRAMFILES(x86)%\Cisco\Cisco AnyConnect Secure Mobility Client\vpnui.exe"""""" + +WScript.Sleep 3000 + +WshShell.AppActivate ""Cisco AnyConnect Secure Mobility Client"" + +WshShell.SendKeys ""{TAB}"" +WshShell.SendKeys ""{TAB}"" +WshShell.SendKeys ""{ENTER}"" + +WScript.Sleep 5000 + +WshShell.SendKeys ""PASSWORD"" +WshShell.SendKeys ""{ENTER}"" + +```","I'm answering my own question with this ""meh"" answer - it's not what I was after, and I'll gladly accept another answer that can better answer my original question. + +Since I didn't have any luck with automatic logins, the next best thing I could think of was to have my ridiculously long password automatically copied to my clipboard. In Windows, I created a `.bat` file with this in the body: + +``` +echo|set /p=MyPassword|clip + +``` + +Where ""MyPassword"" is your actual password. + +When double-clicked, this file will copy your password into your clipboard for a quick login. Better than nothing!" +682211,"I'm having a bit of difficulty with Cisco AnyConnect v3.1 in regards to automatic login. I have to stay connected to a single server all day every day, and it would be super if I didn't have to dig up my 16 char password each and every day. I'd love for the client to log on automatically, but I'm not even sure at this point that it's a possibility. + +I should note that the AnyConnect software is provided to me by our hosting company, and I nor anyone at my organization has access to the management side of things. I did see that there is such a piece of software on the interwebs called the ""AnyConnect Profile Editor,"" but Cisco wouldn't let me download without a valid login. + +I've been into `%appdata%\local\cisco\cisco anyconnect secure mobility client\preferences.xml` to review my preferences as well as `%programdata%\Cisco\Cisco AnyConnect Secure Mobility Client\Profile\ANYCONNECT.XML` to review my profile settings. Neither of these showed anywhere that I would be able to store my credentials. I even broke my profile a few times by trying to shoe-horn my password in places. That didn't work, go figure. + +Lastly, I found [this forum post](https://supportforums.cisco.com/thread/2148440#discussion-action-div-3994840) which seemed to specify client and server certificate ""thumbprints"" as well as something called an SDI token. + +*Disclaimer: I'm a front-end web developer by day and it's been quite a long time since I've had to do any network management for myself, sorry for the noob question!*",2013/11/29,"['https://superuser.com/questions/682211', 'https://superuser.com', 'https://superuser.com/users/278026/']","I use something along these lines: + +``` +set FILE=%TEMP%\tmp +echo connect your.host.name> %FILE% +(echo 0)>> %FILE% +echo yourUserName>> %FILE% +echo yourPassWord>> %FILE% +""C:\Program Files\Cisco\Cisco AnyConnect Secure Mobility Client\vpncli.exe"" -s < %FILE% + +``` + +(**Update:** Why the parentheses around `echo 0`? This should remind you, when making a different choice than `0`, that `1>` or `2>` have a special meaning, redirecting `stdout` or `stderr`, respectively - but not echoing `1` or `2`. So we stay on the safe side with (`echo 0)`.) + +This is a little more concise: + +``` +(echo connect your.host.name& echo 0& echo yourUserName& echo yourPassWord& echo.) > %FILE% +more %FILE% | ""C:\Program Files\Cisco\Cisco AnyConnect Secure Mobility Client\vpncli.exe"" -s + +``` + +However, if you want to achieve the same thing without a temporary file, this does not work for me - I would be interested, why: + +``` +(echo connect your.host.name& echo 0& echo yourUserName& echo yourPassWord) | ""%ProgramFiles(x86)%\Cisco\Cisco AnyConnect Secure Mobility Client\vpncli.exe"" -s + +``` + +**Update:** This works, found via : + +``` +(echo connect your.host.name^& echo 0^& echo yourUserName^&echo yourPassWord^&rem.) | ""%ProgramFiles(x86)%\Cisco\Cisco AnyConnect Secure Mobility Client\vpncli.exe"" -s + +``` + +All these variants depend of course on your server's configuration (especially the VPN group you have to chose). To find out what you need to input, call `vpncli.exe` without any parameters once, start with `connect your.host.name`, and then note what you are prompted for. + +**Update:** This has the added advantage of offering complete freedom with regard to server, username and password, and does not rely on any sleep values (which is always difficult if your system tends to be busy with something else).","I'm answering my own question with this ""meh"" answer - it's not what I was after, and I'll gladly accept another answer that can better answer my original question. + +Since I didn't have any luck with automatic logins, the next best thing I could think of was to have my ridiculously long password automatically copied to my clipboard. In Windows, I created a `.bat` file with this in the body: + +``` +echo|set /p=MyPassword|clip + +``` + +Where ""MyPassword"" is your actual password. + +When double-clicked, this file will copy your password into your clipboard for a quick login. Better than nothing!" +240450,"I am trying to mount a disk image (consisting of MBR, fat, ext4 partitions) so I can modify the layout using `gparted`. (I am trying to move the partition to a 4M boundary.) + +I have tried `sudo mount img mountpoint -o loop` without success. + +How can I achieve this?",2015/11/03,"['https://unix.stackexchange.com/questions/240450', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/47111/']","Normally partitioning tools require that partitions are not mounted. You should use `parted` or `gparted` directly on the image file using: + +``` +parted /path/to/disk.img + +``` + +Sample output: + +``` +$ parted VirtualBox\ VMs/centos/VMDK-test-flat.vmdk +WARNING: You are not superuser. Watch out for permissions. +GNU Parted 2.3 +Using /home/testuser/VirtualBox VMs/centos/VMDK-test-flat.vmdk +Welcome to GNU Parted! Type 'help' to view a list of commands. +(parted) p +Model: (file) +Disk /home/testuser/VirtualBox VMs/centos/VMDK-test-flat.vmdk: 2147MB +Sector size (logical/physical): 512B/512B +Partition Table: msdos + +Number Start End Size Type File system Flags + 1 32,3kB 535MB 535MB primary ext4 + 2 535MB 1069MB 535MB primary ext4 + +(parted) + +```","I don't know if you may resize or move your partition on an image, but there is a tool for mounting partitions within an image file, **kpartx**. I never used it, but you can take a look here: " +240450,"I am trying to mount a disk image (consisting of MBR, fat, ext4 partitions) so I can modify the layout using `gparted`. (I am trying to move the partition to a 4M boundary.) + +I have tried `sudo mount img mountpoint -o loop` without success. + +How can I achieve this?",2015/11/03,"['https://unix.stackexchange.com/questions/240450', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/47111/']","You don't have to mount image to edit its partition table. Make `gparted` work directly with your image: + +``` +sudo gparted /path/to/img + +``` + +EDIT: `mount` is a term related to file systems. You can mount an image of file system. Image of disk containing partition table is an image of block device, which is generally not a valid file system.","I don't know if you may resize or move your partition on an image, but there is a tool for mounting partitions within an image file, **kpartx**. I never used it, but you can take a look here: " +27188074,"I have table structre like this: + +Table `MainTable` + +Columns: + +``` +Id INT, +TableName Varchar(50), +StartValue VARCHAR(50) + +``` + +Here TableName column have names of all the tables present in the database + +Now I need to update ""StartValue"" column in `MainTable` from corresponding tables. Any idea how to achieve this? + +Example + +`MainTable` + +``` +Id TableName StartValue +---------------------- +1 table1 NULL +2 Table2 Null + +``` + +I need to update `StartValue` column of `MainTable` by getting top 1 value from table name present in the tables + +Means record 1 will get first value from table1 and record 2 will get first value from table2 + +Any idea how to achieve this?",2014/11/28,"['https://Stackoverflow.com/questions/27188074', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1654393/']","Adding a check for `EXISTS` on the `INSERT` statement should not have a significant effect on performance. + +``` +INSERT INTO Employee ([Name] ,[Lname] ,[Code]) +SELECT [Name] ,[Lname] ,@Code +FROM @tblEmp AS t +WHERE NOT EXISTS + ( SELECT 1 + FROM Employee AS e + WHERE e.Name = t.Name + AND e.Lname = t.Lname + ); + +``` + +This is *fairly* safe, but still vulnerable to a [race condition](http://en.wikipedia.org/wiki/Race_condition). I think the safest way to do the insert, with is to use `MERGE` with the locking hint `HOLDLOCK`: + +``` +MERGE Employee WITH(HOLDLOCK) AS t +USING @tbl AS s + ON s.Name = t.Name + AND s.LName = t.LName +WHEN NOT MATCHED THEN + INSERT ([Name] ,[Lname] ,[Code]) + VALUES (s.Name, s.Lname, @Code); + +```",If the table has a primary key that is not set to auto generate then it will error when you try to insert a record without the key. You will need to either set the primary key field as an identity seed or you can include the primary key with the insert. +2704534,"Does the following converge or diverge? +$$ +\sum\_{n=2}^{\infty} a\_n^{-n}, +$$ +where$$ +a\_n = \int\_1^n \sin{\left(\frac{1}{\sqrt{x}}\right)} \,\mathrm{d}x. +$$ +My friends thought this sum would converge. I think we should do the square root test, checking the value of $t=\lim\limits\_{n \to \infty} \dfrac{1}{a\_n}$. And we knew that this goes to $0$. So, that would make the sum to converge… + +Is there any problem in my ideas? Some said that this sum diverges, which I can never understand why… + +It will be great if someone can explain me on this… Better with some proofs I can understand. (We are students learning calculus.)",2018/03/23,"['https://math.stackexchange.com/questions/2704534', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/544878/']","Your approach is correct: $a\_n$ is positive and by applying the root test the convergence of the series $\sum\_n (1/a\_n)^{n}$ follows as soon as you show that $1/a\_n\to L<1$. Here we have that $1/a\_n\to 0$ so $\sum\_n (1/a\_n)^{n}$ converges. + +In fact, $\sin(t)\geq 2t/\pi$ for $t\in [0,\pi/2]$ ($\sin(x)$ is concave in that interval). Hence for $n>1$, +$$a\_n = \int\_1^n \sin{\left(\frac{1}{\sqrt{x}}\right)} \,dx\geq \frac{2}{\pi}\int\_1^n \frac{1}{\sqrt{x}}\, dx =\frac{4(\sqrt{n}-1)}{\pi}\implies 0<\frac{1}{a\_n}\leq \frac{\pi}{4(\sqrt{n}-1)}$$ +which implies that $1/a\_n\to 0$ as $n$ goes to infinity. + +P.S. By the way $\sin(t)\leq t$ for $t\geq 0$ implies that +$$a\_n = \int\_1^n \sin{\left(\frac{1}{\sqrt{x}}\right)} \,dx\leq \int\_1^n \frac{1}{\sqrt{x}}\, dx ={2(\sqrt{n}-1)}\implies \frac{1}{a\_n}\geq \frac{1}{2(\sqrt{n}-1)}$$ +which implies that $\sum\_n (1/a\_n)=+\infty$.","As $n\to +\infty$ you have that asymptotically + +$$\int\_1^n\sin\frac{1}{\sqrt{x}} \sim 2\sqrt{n}$$ + +Thence the related series goes like $\frac{1}{n^{n+1/2}}$ which converges." +2704534,"Does the following converge or diverge? +$$ +\sum\_{n=2}^{\infty} a\_n^{-n}, +$$ +where$$ +a\_n = \int\_1^n \sin{\left(\frac{1}{\sqrt{x}}\right)} \,\mathrm{d}x. +$$ +My friends thought this sum would converge. I think we should do the square root test, checking the value of $t=\lim\limits\_{n \to \infty} \dfrac{1}{a\_n}$. And we knew that this goes to $0$. So, that would make the sum to converge… + +Is there any problem in my ideas? Some said that this sum diverges, which I can never understand why… + +It will be great if someone can explain me on this… Better with some proofs I can understand. (We are students learning calculus.)",2018/03/23,"['https://math.stackexchange.com/questions/2704534', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/544878/']","From $\sin x4$, + +$$\left(\int\_1^n\sin\frac1{\sqrt x}dx\right)^{-n}<\left(2\sqrt n\right)^{-n}<\frac1{n^2}$$ + +and the series converges.","As $n\to +\infty$ you have that asymptotically + +$$\int\_1^n\sin\frac{1}{\sqrt{x}} \sim 2\sqrt{n}$$ + +Thence the related series goes like $\frac{1}{n^{n+1/2}}$ which converges." +15855762,"I need to include and/or statement to an if condition in google script. I am new to script and am not able to find a way to do so. Please help + +``` +if (dateval<>"""") and (repval<>"""") {condition if true} + +``` + +Thank you for the help.",2013/04/06,"['https://Stackoverflow.com/questions/15855762', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2252756/']","you can find all the infos on [that subject](http://www.w3schools.com/js/js_comparisons.asp) (and others ) [on this site.](http://www.w3schools.com/js/) + +in your example the answer is + +``` +if (dateval!="""" && repval!="""") {do something} + +```","Logic Symbol + +Or || + +And && +Equal == +Not != + +" +15855762,"I need to include and/or statement to an if condition in google script. I am new to script and am not able to find a way to do so. Please help + +``` +if (dateval<>"""") and (repval<>"""") {condition if true} + +``` + +Thank you for the help.",2013/04/06,"['https://Stackoverflow.com/questions/15855762', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2252756/']","you can find all the infos on [that subject](http://www.w3schools.com/js/js_comparisons.asp) (and others ) [on this site.](http://www.w3schools.com/js/) + +in your example the answer is + +``` +if (dateval!="""" && repval!="""") {do something} + +```","I tried [Serge insas's answer](https://stackoverflow.com/a/15855859) and found out that it did not compile. + +I messed around, modifying the line as follows: + +``` +if ((dateval<>"""") and (repval<>"""")) {condition if true} + +``` + +I finally got this to work. Apparently, it needs the extra parentheses." +15855762,"I need to include and/or statement to an if condition in google script. I am new to script and am not able to find a way to do so. Please help + +``` +if (dateval<>"""") and (repval<>"""") {condition if true} + +``` + +Thank you for the help.",2013/04/06,"['https://Stackoverflow.com/questions/15855762', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2252756/']","Logic Symbol + +Or || + +And && +Equal == +Not != + +","I tried [Serge insas's answer](https://stackoverflow.com/a/15855859) and found out that it did not compile. + +I messed around, modifying the line as follows: + +``` +if ((dateval<>"""") and (repval<>"""")) {condition if true} + +``` + +I finally got this to work. Apparently, it needs the extra parentheses." +4900,"In the lyrics of *Friends Will Be Friends* by *Queen*: + +> +> Another red letter day +> +> So the pound has dropped and **the children are creating**. +> +> +> + +What does the phrase highlighted in bold mean?",2010/11/10,"['https://english.stackexchange.com/questions/4900', 'https://english.stackexchange.com', 'https://english.stackexchange.com/users/2038/']","Queen is a British band, and this usage of the intransitive *create* is British colloquial for ""create a fuss"", ""make noise"", or nearly, as ukayer says, ""create havoc"". The [*Compact Oxford Dictionary* has this](http://www.oxforddictionaries.com/definition/create?view=uk): + +> +> 2 [*no object*] *British informal* make a fuss; complain: +> +>    *little kids create because they hate being ignored* +> +> +> + +The [*Cambridge Advanced Learner's Dictionary* has this](http://dictionary.cambridge.org/dictionary/british/create_2): + +> +> **create** *verb* (BE ANGRY) /kriˈeɪt/ +> +> [I] UK *old-fashioned* to show that you are angry +> +>    *If she sees you with an ice cream she'll only start creating.* +> +> +> + +The [*Collins Pocket English Dictionary* has this](http://www.collinslanguage.com/results.aspx?context=3&reversed=False&action=define&homonym=-1&text=create): + +> +> 4. (Brit slang) to make an angry fuss, +> +> +> + +[*Dictionary.com*](http://dictionary.reference.com/browse/Create?r=66) (based on [*Random House*](http://dictionary.infoplease.com/create) dictionary) has this: + +> +> –*verb (used without object)* +> +> 8. *British*. to make a fuss. +> +> +> + +The [*Collins English Dictionary — Complete and Unabridged*](http://www.thefreedictionary.com/create) also has this: + +> +> 6. *(intr) Brit slang* to make a fuss or uproar +> +> +> + +See also [this post by lynneguist](http://separatedbyacommonlanguage.blogspot.com/2009/04/to-create-intransitive.html) on *Separated By a Common Language*, where I first encountred the term. It's used mostly for little children (or those considered little children), rather than adults.","Creating as in ""creating havoc"", i.e. helping to make the day even worse." +29598991,"Here's a code + +``` + About + Contact us + +``` + +I want the link1's color to be changed when link2 is hovered. +Is it possible with css?.",2015/04/13,"['https://Stackoverflow.com/questions/29598991', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4466855/']","Since CSS does not seem to be able to handle this, try JavaScript + +```js +window.onload=function() { + document.getElementById(""link2"").onmouseover=function() { + document.getElementById(""link1"").style.color=""red""; + } + document.getElementById(""link2"").onmouseout=function() { + document.getElementById(""link1"").style.color=""blue""; + } +} +``` + +```html + About + Contact us +``` + +Or using siblings + +```js +function prevSib(elem) {do { elem = elem.previousSibling;} while ( elem && elem.nodeType !== 1 ); return elem; } + +window.onload=function() { + document.getElementById(""link2"").onmouseover=function() { + prevSib(this).style.color=""red""; + } + document.getElementById(""link2"").onmouseout=function() { + prevSib(this).style.color=""blue""; + } +} +``` + +```html +About +Contact us +```","Using pure css it is not possible go backward. You can go in cascading ways. + +But, you can do it with JQuery. like: + +```js +$(document).ready(function(){ + $("".link2"").mouseover(function(){ + $("".link1"").css(""color"", ""red""); + }); + $("".link2"").mouseout(function(){ + $("".link1"").css(""color"", ""black""); + }); +}); +``` + +```html + +About + Contact us +``` + +Hope it helps." +29598991,"Here's a code + +``` + About + Contact us + +``` + +I want the link1's color to be changed when link2 is hovered. +Is it possible with css?.",2015/04/13,"['https://Stackoverflow.com/questions/29598991', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4466855/']","Since CSS does not seem to be able to handle this, try JavaScript + +```js +window.onload=function() { + document.getElementById(""link2"").onmouseover=function() { + document.getElementById(""link1"").style.color=""red""; + } + document.getElementById(""link2"").onmouseout=function() { + document.getElementById(""link1"").style.color=""blue""; + } +} +``` + +```html + About + Contact us +``` + +Or using siblings + +```js +function prevSib(elem) {do { elem = elem.previousSibling;} while ( elem && elem.nodeType !== 1 ); return elem; } + +window.onload=function() { + document.getElementById(""link2"").onmouseover=function() { + prevSib(this).style.color=""red""; + } + document.getElementById(""link2"").onmouseout=function() { + prevSib(this).style.color=""blue""; + } +} +``` + +```html +About +Contact us +```","CSS can't select the previous siblings. You can use JavaScript: + +``` +var links = [].slice.call(document.querySelectorAll('.menu_item')); + +function hover(event) { + var pre = this.previousElementSibling, + method = event.type === 'mouseenter' ? 'add' : 'remove'; + + if (pre) { + pre.classList[method]('active'); + } +} + +links.forEach(function(el) { + el.addEventListener('mouseenter', hover); + el.addEventListener('mouseleave', hover); +}); + +``` + +The above code assumes that the `a` elements have class of `menu_item` and class of `active` should be added to the previous sibling of the hovered element. + +[Here is a demo](http://jsfiddle.net/dxxbkLzt/)." +29598991,"Here's a code + +``` + About + Contact us + +``` + +I want the link1's color to be changed when link2 is hovered. +Is it possible with css?.",2015/04/13,"['https://Stackoverflow.com/questions/29598991', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4466855/']","Since CSS does not seem to be able to handle this, try JavaScript + +```js +window.onload=function() { + document.getElementById(""link2"").onmouseover=function() { + document.getElementById(""link1"").style.color=""red""; + } + document.getElementById(""link2"").onmouseout=function() { + document.getElementById(""link1"").style.color=""blue""; + } +} +``` + +```html + About + Contact us +``` + +Or using siblings + +```js +function prevSib(elem) {do { elem = elem.previousSibling;} while ( elem && elem.nodeType !== 1 ); return elem; } + +window.onload=function() { + document.getElementById(""link2"").onmouseover=function() { + prevSib(this).style.color=""red""; + } + document.getElementById(""link2"").onmouseout=function() { + prevSib(this).style.color=""blue""; + } +} +``` + +```html +About +Contact us +```","Use JavaScript to do that( `link1`'s color to be changed when `link2` is hovered ). You need to use html tag attributes like `onmouseover` and `onmouseout`. + +Try this code. For changing color of `link1` when `link2` is hovered. + +``` + + + + + + + +About + Contact us + + + + +```" +29598991,"Here's a code + +``` + About + Contact us + +``` + +I want the link1's color to be changed when link2 is hovered. +Is it possible with css?.",2015/04/13,"['https://Stackoverflow.com/questions/29598991', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4466855/']","Since CSS does not seem to be able to handle this, try JavaScript + +```js +window.onload=function() { + document.getElementById(""link2"").onmouseover=function() { + document.getElementById(""link1"").style.color=""red""; + } + document.getElementById(""link2"").onmouseout=function() { + document.getElementById(""link1"").style.color=""blue""; + } +} +``` + +```html + About + Contact us +``` + +Or using siblings + +```js +function prevSib(elem) {do { elem = elem.previousSibling;} while ( elem && elem.nodeType !== 1 ); return elem; } + +window.onload=function() { + document.getElementById(""link2"").onmouseover=function() { + prevSib(this).style.color=""red""; + } + document.getElementById(""link2"").onmouseout=function() { + prevSib(this).style.color=""blue""; + } +} +``` + +```html +About +Contact us +```","I suppose this is what are you looking for. + +First you need to wrap your links inside a container like this + +``` + + +``` + +and then apply this styles + +``` +.container:hover a:not(:hover){ + color:red; +} + +``` + +[css only demo here](https://jsfiddle.net/g39yyk9n/) + +**UPDATE** + +As I said in may comment bellow I supposed you wanted to change the style of all unhovered links, however if you want to change only link1 when link2 is hovered , but not change style of link2 when link1 is hovered you could write you css like this + +[second demo](https://jsfiddle.net/g39yyk9n/1/) + +``` +.container:hover a:first-child:not(:hover){ + color:red; +} + +```" +68178782,"I am trying to plot two columns from my dataset (the columns are 'cases' and 'vaccinations') on the same line graph. The x-axis only has one column (that is, 'country') that I want them to share. Is it possible to do this in Dash/Plotly? I can't find any solutions using Dash. Here's a snippet of my code: + +``` + html.Div( + children=dcc.Graph( + id=""cases-chart"", + config={""displayModeBar"": False}, + figure={ + ""data"": [ + { + ""x"": data[""country""], + ""y"": data[""cases""], + ""type"": ""lines"", + }, + ], + ""layout"": { + ""title"": { + ""text"": ""Cases by Country"", + ""x"": 0.05, + ""xanchor"": ""left"", + }, + ""xaxis"": {""fixedrange"": True}, + ""yaxis"": {""fixedrange"": True}, + ""colorway"": [""#17B897""], + }, + }, + ), + className=""card"", + ), + +``` + +Thanks.",2021/06/29,"['https://Stackoverflow.com/questions/68178782', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11845398/']","I hope this solves your problem. + +This is implemented in Python. + +First, we use imageio to import the image as an array. We need to use a modified version of your image (I filled the interior region in white). + +[![enter image description here](https://i.stack.imgur.com/rVHKd.png)](https://i.stack.imgur.com/rVHKd.png) + +Then, we transform the RGBA matrix into a binary matrix with a 0 contour defining your interface (phi in the code snippet) + +Here's phi from the snippet below (interior region value = +0.5, exterior region value = -0.5): +[![enter image description here](https://i.stack.imgur.com/lNR1m.png)](https://i.stack.imgur.com/lNR1m.png) + +```py +import imageio +import numpy as np +import matplotlib.pyplot as plt +import skfmm + +# Load image +im = imageio.imread(""0WmVI_filled.png"") +ima = np.array(im) + +# Differentiate the inside / outside region +phi = np.int64(np.any(ima[:, :, :3], axis = 2)) +# The array will go from - 1 to 0. Add 0.5(arbitrary) so there 's a 0 contour. +phi = np.where(phi, 0, -1) + 0.5 + +# Show phi +plt.imshow(phi) +plt.xticks([]) +plt.yticks([]) +plt.colorbar() +plt.show() + +# Compute signed distance +# dx = cell(pixel) size +sd = skfmm.distance(phi, dx = 1) + +# Plot results +plt.imshow(sd) +plt.colorbar() +plt.show() + +``` + +Finally, we use the scikit-fmm module to compute the signed distance. + +Here's the resulting signed distance field: + +[![enter image description here](https://i.stack.imgur.com/w1iJQ.png)](https://i.stack.imgur.com/w1iJQ.png)","For closed, non-intersecting and well oriented polygons, you can speed up the calculation of a signed distance field by limiting the work to feature extrusions based on [this paper](https://www.researchgate.net/publication/2393786_A_Fast_Algorithm_for_Computing_the_Closest_Point_and_Distance_Transform). + +The closest point to a line lies within the edge extrusion as you have shown in your image (regions A and E). The closest feature for the points in B, C and D are not the edges but the vertex. + +The algorithm is: + +* for each edge and vertex construct negative and positive extrusions +* for each point, determine which extrusions they are in and find the smallest magnitude distance of the correct sign. + +The work is reduced to a point-in-polygon test and distance calculations to lines and points. For reduced work, you can consider limited extrusions of the same size to define a thin shell where distance values are calculated. This seems the desired functionality for your halo shading example. + +While you still have to iterate over all features, both extrusion types are always convex so you can have early exits from quad trees, half-plane tests and other optimisations, especially with limited extrusion distances. + +The extrusions of edges are rectangles in the surface normal direction (negative normal for interior distances). + +From [1](https://www.researchgate.net/publication/2393786_A_Fast_Algorithm_for_Computing_the_Closest_Point_and_Distance_Transform): + +[![edge extrusions](https://i.stack.imgur.com/GtE3e.png)](https://i.stack.imgur.com/GtE3e.png) + +The extrusions for vertices are wedges whose sides are the normals of the edges that meet at that vertex. Vertices have either positive or negative extrusions depending on the angle between the edges. Flat vertices will have no extrusions as the space is covered by the edge extrusions. + +From [1](https://www.researchgate.net/publication/2393786_A_Fast_Algorithm_for_Computing_the_Closest_Point_and_Distance_Transform): + +[![enter image description here](https://i.stack.imgur.com/s9xS1.png)](https://i.stack.imgur.com/s9xS1.png)" +69151019,"I'm working on Google Colab and when I type + +`model.compile(optimizer=tf.keras.optimizers.Adam(lr=1e-6), loss=tf.keras.losses.BinaryCrossentropy())` + +it doesn't work and I get the following error message + +`Could not interpret optimizer identifier: `",2021/09/12,"['https://Stackoverflow.com/questions/69151019', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/16871891/']","Generally, Maybe you used a different version for the layers import and the optimizer import. +tensorflow.python.keras API for model and layers and keras.optimizers for SGD. They are two different Keras versions of TensorFlow and pure Keras. They could not work together. You have to change everything to one version. Then it should work. + +Maybe try import: + +``` +from tensorflow.keras.optimizers import Adam +model.compile(optimizer=Adam(lr=1e-6),loss=tf.keras.losses.BinaryCrossentropy()) + +```","Actually I am using + +``` +keras===2.7.0 +tensorflow==2.8.0 + +``` + +and it worked for me when I used : + +``` +from keras.optimizers import adam_v2 + +``` + +Then + +``` +optimizer = adam_v2.Adam(lr=learning_rate) +model.compile(loss=""binary_crossentropy"", optimizer=optimizer) + +``` + +Instead of using `tf.keras.optimizers.Adam`" +59499652,"I'm currently struggling with a display issue only in Firefox Android. +I have no problem on desktop neither in Android Chrome. + +I'm using Angular 8 and mat-toolbar. +I wanted to use a bottom navigation bar but this flickering issue is making it look bad. +It is only when I scroll up/down fast. + +The code I'm using is pretty simple: + +``` +
+
+

+Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed ut neque ipsum. Proin dolor ipsum, mattis non suscipit eget, condimentum id mauris. Vestibulum orci lectus, pretium et dictum ut, efficitur eget augue. Fusce dolor enim, maximus et justo eu, condimentum ornare ex. Nulla facilisi. Fusce ut enim est. Curabitur scelerisque, odio eu pretium blandit, nunc justo elementum nulla, vitae dignissim nisl tortor at augue. +

+

+Vestibulum nunc enim, porttitor vel nunc ultrices, facilisis dapibus lectus. Aliquam at gravida dui. Cras tincidunt malesuada mattis. Donec vitae magna convallis, suscipit lacus non, tincidunt lacus. Praesent faucibus et nulla non hendrerit. Nam tempus tincidunt viverra. Donec a justo ut sem porta malesuada. Nulla vestibulum, odio ac ornare ultrices, quam lectus vestibulum lectus, quis dignissim erat urna eget erat. Ut sed dui elementum, pellentesque libero sit amet, faucibus diam. Donec euismod purus nisi, ut fringilla erat pellentesque ut. +

+

+Cras gravida augue vel arcu scelerisque malesuada. Pellentesque sagittis quam a dolor gravida auctor. Curabitur elit elit, auctor eget ex quis, placerat aliquam ipsum. Ut efficitur dui id metus commodo congue. Nulla id lacus fringilla, semper augue vel, tincidunt eros. Ut non felis elit. Morbi nulla dui, tincidunt et dapibus sodales, condimentum et augue. Sed condimentum diam magna, non sollicitudin lorem pharetra id. Integer posuere pellentesque dolor, dapibus dignissim purus bibendum at. Donec vel diam a velit mattis fermentum. Sed semper aliquam ante, iaculis fermentum neque tincidunt vitae. +

+

+Fusce auctor iaculis elit nec elementum. Suspendisse non ante faucibus, convallis enim sed, cursus orci. Vestibulum a dolor pellentesque dui bibendum dictum. Phasellus venenatis arcu ut metus aliquam bibendum. Suspendisse sagittis leo felis, in sollicitudin nisl efficitur vel. Nulla feugiat varius elementum. Pellentesque at sem sit amet lacus suscipit dapibus. Mauris porta risus finibus volutpat ullamcorper. Nulla consequat augue quis efficitur rutrum. Cras fermentum dui elementum nisl porttitor, non sollicitudin mauris scelerisque. Donec a sollicitudin quam, eleifend gravida nisl. +

+

+Aenean eu sapien eleifend, posuere magna vel, ultricies ante. Aliquam nec urna magna. In in eros tellus. Donec a enim eget lorem venenatis feugiat vestibulum pulvinar leo. Morbi et odio lacinia, maximus lacus quis, bibendum ante. Mauris ut ligula quam. Ut tempor nisi in semper iaculis. Etiam ultrices magna quis auctor porttitor. Aliquam mattis, libero ornare tincidunt fermentum, ex leo fringilla neque, consectetur aliquet dolor lorem quis purus. Nam ligula felis, dictum sit amet maximus eu, tristique eu velit. +

+

+Duis lacinia eu felis et elementum. Suspendisse sed sem augue. Nullam tortor turpis, condimentum sed arcu eu, euismod lobortis odio. Quisque eu interdum purus, non tincidunt neque. Quisque tincidunt dolor vitae ipsum scelerisque, ac facilisis magna viverra. Phasellus malesuada velit nunc, vel ultrices urna sodales vitae. Praesent maximus aliquam tempor. Mauris accumsan imperdiet sodales. Suspendisse potenti. Nulla facilisi. Vestibulum vitae vehicula ipsum. Vivamus sed diam finibus, blandit enim in, commodo massa. Aliquam porttitor lectus sed tellus hendrerit, vitae blandit nisl placerat. Morbi laoreet neque quam, eu blandit dolor venenatis sit amet. Duis quam purus, viverra nec quam id, imperdiet suscipit felis. Nulla rhoncus purus a diam vestibulum dictum. +

+

+Suspendisse id libero ut ipsum ullamcorper suscipit. Duis sed vehicula leo. Aenean ullamcorper elementum est eu commodo. Curabitur consectetur nibh purus, at elementum magna iaculis eu. Vestibulum sit amet purus nec enim mattis pulvinar. Sed lobortis odio id quam sodales elementum. Nam facilisis aliquam pellentesque. Etiam non mauris eu magna scelerisque varius. Suspendisse non aliquam tellus, sed ullamcorper elit. Nullam id mattis est, quis euismod massa. Pellentesque vestibulum molestie felis nec condimentum. Pellentesque non lacus cursus, pulvinar purus a, ultricies dui. Pellentesque at erat leo. Nullam placerat pharetra est vitae pharetra. +

+

+Mauris rutrum nunc non sem feugiat vulputate. Vestibulum pulvinar consectetur turpis vitae placerat. Praesent sit amet felis varius, euismod enim nec, finibus diam. Aliquam sed nisi in lorem faucibus ultrices. Aenean aliquam tempor tortor. Sed dapibus blandit arcu, quis dapibus dui egestas vel. Nullam mattis, nulla a ultrices efficitur, turpis ligula rhoncus ligula, vel tristique orci risus sit amet urna. +

+

+Praesent porttitor facilisis dapibus. Quisque feugiat nec enim ut iaculis. Mauris feugiat, libero non porta suscipit, diam sapien aliquet est, et semper nunc ex nec quam. Etiam ut nulla id mauris placerat commodo. Vestibulum id iaculis libero, sit amet tempus leo. Morbi ullamcorper efficitur enim in mattis. Suspendisse imperdiet dui vitae lorem porta iaculis. Aenean lobortis quam lacus, sit amet rhoncus libero auctor ut. Nullam facilisis felis in fermentum luctus. Fusce odio mi, vehicula vitae suscipit ac, venenatis eget elit. Phasellus laoreet nec elit quis consectetur. +

+

+Integer justo enim, ornare eget lacus vel, ultricies tincidunt massa. Donec varius odio sed viverra fringilla. Sed lobortis nisi sed commodo posuere. Cras consectetur congue ipsum non pellentesque. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Pellentesque ullamcorper tortor et urna vestibulum, finibus finibus ex laoreet. Integer aliquam ex at mi tristique, in viverra diam pharetra. Etiam id venenatis arcu. Vivamus et diam eget est mollis volutpat. +

+

+Pellentesque vulputate porttitor magna sed semper. Cras vehicula sem eget mattis accumsan. Proin maximus ultrices finibus. Proin et elit magna. Curabitur eget fermentum sem. Aliquam laoreet felis id justo tincidunt blandit. Donec finibus erat vitae nisi pellentesque facilisis. Pellentesque porttitor eget purus mollis consectetur. Interdum et malesuada fames ac ante ipsum primis in faucibus. Praesent eu blandit justo. Vivamus nec libero ornare, tempus ex quis, varius dolor. Fusce eu imperdiet arcu. Nam egestas lectus nec mauris volutpat accumsan. Donec risus est, aliquet in eros ac, condimentum porta erat. Ut sagittis, ante sed rutrum vulputate, turpis augue fringilla eros, id dignissim nisi ex id dui. Nulla blandit ut leo at malesuada. +

+

+Nam quis euismod metus, sed consectetur odio. Ut id lacinia ante. Nulla molestie massa ligula, sed ornare purus euismod nec. Aliquam id quam auctor, aliquet leo vel, imperdiet quam. Nam eros nisi, ultrices nec facilisis sit amet, viverra sed dolor. Integer laoreet nunc quam, sit amet iaculis libero pharetra vitae. Quisque vel posuere diam, eget fermentum est. +

+

+Etiam nec volutpat urna. Pellentesque tempor sodales libero, non viverra nibh varius quis. Aenean hendrerit egestas molestie. Praesent tincidunt at lectus in sodales. Etiam rhoncus turpis vitae suscipit porttitor. Nulla est erat, pharetra ut tellus fringilla, pharetra consequat leo. Praesent sed finibus tellus, nec tincidunt velit. In pulvinar consequat neque id vulputate. Cras luctus finibus purus, a ultricies augue varius pellentesque. Aenean vehicula, nulla eget gravida euismod, ipsum nibh sollicitudin odio, convallis malesuada turpis elit non quam. Donec ac hendrerit felis. +

+

+Phasellus eget auctor lorem. Donec ut congue lectus. Fusce est nunc, fringilla at metus ac, volutpat pellentesque turpis. Curabitur elit leo, tincidunt nec velit non, vestibulum condimentum nibh. Maecenas varius justo ligula, quis hendrerit risus elementum quis. Integer felis eros, cursus non euismod vel, tempor sit amet metus. Nulla congue neque lobortis, sagittis purus finibus, pharetra augue. Sed dignissim rhoncus maximus. Fusce eros augue, iaculis sit amet pretium quis, dignissim sed lacus. Proin non tortor eros. Nulla sagittis ligula nec egestas egestas. +

+

+Vestibulum non nulla ultricies, convallis ante quis, interdum dui. Praesent maximus pulvinar nibh. Aliquam venenatis ante felis, eget ultrices neque posuere quis. Nam auctor in nisl quis vulputate. Donec venenatis ligula at nisi eleifend tincidunt. Fusce augue nibh, pharetra ullamcorper tellus rhoncus, tristique imperdiet massa. Phasellus at elit at risus sodales porta a ut metus. Quisque sodales nisi ac egestas auctor. Quisque hendrerit et risus sed consequat. Nullam ultrices metus elit, at egestas lectus pellentesque vitae. Donec eu vehicula ligula. Nam mattis pharetra arcu et imperdiet. Cras eget dignissim elit, quis porta elit. Vestibulum mollis nec leo in dignissim. Aliquam lacinia gravida dolor a sollicitudin. +

+ + + + +
+ +``` + +And my .scss file looks like this: + +``` +#lipsum { + background-color: #f5f5f6; +} + +.mat-toolbar { + position: fixed; + bottom: 0; + left: 0; + z-index: 2; + width: 100%; +} + +.container { + height: 100%; + width: 100%; + display: flex; flex-direction: column; +} + +``` + +I tooked a screenshot: [here](https://i.stack.imgur.com/Gd246.png) + +It seemed that the issue is that the mat-toolbar is not following instantly the bottom of the page. +There is a micro-lag causing the flickering. + +Do you have any idea how to fix this ?",2019/12/27,"['https://Stackoverflow.com/questions/59499652', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12606878/']","I changed a little bit my way of thinking. +Instead of trying to overlay the navigation menu in the bottom of the screen, I used [this method](https://moduscreate.com/blog/how-to-fix-overflow-issues-in-css-flex-layouts/). + +It uses a container and allow to overflow the content by displaying a scroll bar and the bottom is used by the menu navigation. No more problem of flickering now.","Your mat-toolbar is not a class in the html but an element, and if you have flex on it's parent you are best to use margin-top: auto on it instead of position fixed + +html + +``` +
+ +
+ +``` + +css + +``` +.mat-toolbar { +margin-top:auto; /* this pushes this div to the bottom of it's parent div that is display flex */ +z-index: 2; +width: 100%; +} + +```" +560893,I want to ask a question about thin provisioning. `get-vm` commandlet can easly give us real space used by a vm totally. Assume that you have a virtual machine which has more than one thin disk. If we want to get more detail so as to calculate each disk real used space which powercli command does this? I do not prefer getting it by datastore browser for performance issues.,2013/12/12,"['https://serverfault.com/questions/560893', 'https://serverfault.com', 'https://serverfault.com/users/202314/']","The actual used disk space is retrievable without accessing the datastore separately, but you won't find the information in the disk object, but rather in the VM object. It is hidden in `$vm.ExtensionData.LayoutEx.File`, which contains information about all files related to the VM, not only the disk files. So the trick is to get the file information that relates to the queried disk. + +If you only want the actual size, and nothing else, you can do it really quick like this: + +```powershell +(get-vm vmname).ExtensionData.LayoutEx.File | + Where-Object { $_.name -like '*-flat.vmdk' } |select Name,Size + +Name Size +---- ---- +[Datastore1] vmname/vmname-flat.vmdk 53895368934 +[Datastore1] vmname/vmname_1-flat.vmdk 73348843320 +[Datastore1] vmname/vmname_2-flat.vmdk 268902888606 +[Datastore1] vmname/vmname_3-flat.vmdk 37724234832 + +``` + +If you want some more information about the disks: + +```powershell +get-vm $vmname |Get-HardDisk | + Select name,capacitygb,StorageFormat,@{name=""UsedSpaceGB"";e={ + $disk=$_; + [math]::Round(($disk.Parent.ExtensionData.LayoutEx.File | + Where-Object { + $_.name -eq $disk.Filename.Replace(""."",""-flat."") + }).Size/1GB,2) + }} + +Name CapacityGB StorageFormat UsedSpaceGB +---- ---------- ------------- ----------- +Hard disk 1 50 EagerZeroedThick 50,19 +Hard disk 2 100 Thin 68,31 +Hard disk 3 300 Thin 250,44 +Hard disk 4 60 Thin 35,13 + +```","I found the following solution: + +``` +(Get-VM -Name $YourVmName).Extensiondata.Guest.Disk + +``` + +This command will give you all the disks of this vm with the provisioned size and the free space - with that you can calculate the real used size. + +Source (with a complete script to list all disks): " +300008,"Is there a practical reason that the roles of the primary and secondary of a simple single-phase transformer cannot be swapped? + +Say you have a transformer (from the old vacuum tube days) that has rated for primary 120 VAC 1 A and secondary 12.6 VAC 10 A (so there is about 0.120 kVA for this transformer). + +Is there any reason that one cannot take that transformer and drive the secondary with 12.6 VAC and up to 10 A and get from the primary power at 120 VAC up to 1 A? + +I cannot imagine a reason that, as long as the specs on the windings are kept that the roles of the primary and secondary windings of a simple power transformer cannot be swapped. But I would be happy to learn differently.",2017/04/17,"['https://electronics.stackexchange.com/questions/300008', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/89489/']","You can do exactly that. + +Respect the maximum voltage on each winding. Transformers cannot be over-volted and still behave themselves. + +Due to the various small non-idealities, winding resistance and leakage inductance being the major ones, you will notice that the voltage ratio one way when under load is slightly less than the reciprocal of the ratio the other way.","A simple answer is not always right. +The first problem you have is your quoted ratings. 120 V @ 1 A - 120 VA. If the load is entirely resistive, ie, there is no reactive load, then the maximum you can get out of the secondary will be about 12.6 V @ 9 A, if the efficiency is 95% - not 10 A. +Brian Drummond's answer is correct. I have designed transformers and been a production manager in a transformer manufacturing plant. I know what he and I are talking about - and he's correct. There will always be losses that the primary is designed to handle. So, if you reverse feed your transformer, the previously dedicated secondary will have to cover the magnetising, copper and eddy losses. So, you will get less power out of the 120 Vac winding. +However, there is one more point: the primary winding will generally have a higher insulation from the core of the transformer, than the secondary. So, you need to consider carefully the source of the power you feed into the previous secondary." +300008,"Is there a practical reason that the roles of the primary and secondary of a simple single-phase transformer cannot be swapped? + +Say you have a transformer (from the old vacuum tube days) that has rated for primary 120 VAC 1 A and secondary 12.6 VAC 10 A (so there is about 0.120 kVA for this transformer). + +Is there any reason that one cannot take that transformer and drive the secondary with 12.6 VAC and up to 10 A and get from the primary power at 120 VAC up to 1 A? + +I cannot imagine a reason that, as long as the specs on the windings are kept that the roles of the primary and secondary windings of a simple power transformer cannot be swapped. But I would be happy to learn differently.",2017/04/17,"['https://electronics.stackexchange.com/questions/300008', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/89489/']","Yes, that'll work - with one caveat. + +A carefully designed transformer will take into account the internal losses, to minimise them while reducing cost. So the primary may be wound with slightly thicker wire for lower resistance than in an ""ideal"" transformer, or the secondary with slightly thinner wire because it only has to handle the output power, minus the losses. + +Driving a transformer backwards, these changes work against you, so I would de-rate it to 90% - or maybe 80% - of its rated power to be on the safe side - that is, 120V at 0.8 or 0.9A rather than 1A - and as Neil says you may also observe a minor discrepancy in the voltage ratios.","A simple answer is not always right. +The first problem you have is your quoted ratings. 120 V @ 1 A - 120 VA. If the load is entirely resistive, ie, there is no reactive load, then the maximum you can get out of the secondary will be about 12.6 V @ 9 A, if the efficiency is 95% - not 10 A. +Brian Drummond's answer is correct. I have designed transformers and been a production manager in a transformer manufacturing plant. I know what he and I are talking about - and he's correct. There will always be losses that the primary is designed to handle. So, if you reverse feed your transformer, the previously dedicated secondary will have to cover the magnetising, copper and eddy losses. So, you will get less power out of the 120 Vac winding. +However, there is one more point: the primary winding will generally have a higher insulation from the core of the transformer, than the secondary. So, you need to consider carefully the source of the power you feed into the previous secondary." +27641563,"I am using MyBatis 3.2.8 in a Play Framework 2.3.6 Java project. I've been struggling for several days with iterating over a list of integers that is passed to a MyBatis mapper within a complex object parameter. Here is my setup: + +I have a class called EventFilter in EventFilter.java: + +``` +public class EventFilter { +private String beginDate; +private String endDate; +private List closestCountry; +private List territorialWaterStatus; +private List vesselCountry; +private String closestCountryInClause; +private String territorialWaterStatusInClause; +private String vesselCountryInClause; + +public EventFilter() { } + +public EventFilter(JsonNode jsonNode){ + this.beginDate = jsonNode.get(""beginDate"").asText(); + this.endDate = jsonNode.get(""endDate"").asText(); + this.closestCountry = JsonHelper.arrayNodeToIntegerList((ArrayNode) jsonNode.get(""closestCountry"")); + this.territorialWaterStatus = JsonHelper.arrayNodeToIntegerList((ArrayNode) jsonNode.get(""territorialWaterStatus"")); + this.vesselCountry = JsonHelper.arrayNodeToIntegerList((ArrayNode) jsonNode.get(""vesselCountry"")); +} + +public String getBeginDate() { + return beginDate; +} + +public void setBeginDate(String beginDate) { + this.beginDate = beginDate; +} + +public String getEndDate() { + return endDate; +} + +public void setEndDate(String endDate) { + this.endDate = endDate; +} + +public List getTerritorialWaterStatus() { + if(this.territorialWaterStatus.size() > 0) { + return territorialWaterStatus; + } else { + return null; + } +} + +public void setTerritorialWaterStatus(List territorialWaterStatus) { + this.territorialWaterStatus = territorialWaterStatus; +} + +public List getClosestCountry() { + if(this.closestCountry.size() > 0) { + return closestCountry; + } else { + return null; + } +} + +public void setClosestCountry(List closestCountry) { + this.closestCountry = closestCountry; +} + +public List getVesselCountry() { + if(this.vesselCountry.size() > 0) { + return vesselCountry; + } else { + return null; + } +} + +public void setVesselCountry(List vesselCountry) { + this.vesselCountry = vesselCountry; +} + +``` + +} + +This is referenced as a type alias in my mybatis config file: + +``` + + + + + + + + + + + + + + + + + + + + + + + + + +``` + +I have a mapper that takes an EventFilter object as its parameter. It should then check if the beginDate, endDate, closestCountry, vesselCountry, and territorialWaterStatus are set. If they are it uses them for the WHERE clause: + +``` + + +``` + +I have the mapper linked into an interface as follows: + +``` + public List getEventsWithFilter(@Param(""eventFilter"") EventFilter eventFilter); + +``` + +And I am calling it with a MybatisMapper helper class that generates my session as follows: + +``` +public static List getEvents(EventFilter eventFilter) { + MybatisMapper mapper = new MybatisMapper(); + SqlSession session = mapper.getSession(); + EventMapper eventMapper = session.getMapper(EventMapper.class); + + List events; + + List li = eventFilter.getClosestCountry(); + + try { + events = eventMapper.getEventsWithFilter(eventFilter); + } finally { + session.close(); + } + + return events; +} + +``` + +**The Problem(s):** + +The beginDate and endDate work completely fine by themselves. But I'm having the following problems with the integer lists: + +1. The if statement checking if the list is null seems to be getting +ignored, or evaluating to true when it should be false. +2. The integer lists are appearing to be passed as null into the IN clauses. +3. If I comment out the integer list IN clauses, and just to beginDate and +endDate, it works completely fine. However, if I leave the integer +list IN clauses, the query doesn't fail, but it returns an empty +set, as if to say ""WHERE column IN ()"". + +Here is the console logging printed by Play and Mybatis when the mapper/query are executed, along with the EventFilter printing its contents. They're a little lengthy so I put them in pastebin: + +* When I pass three countries for each of the three integer lists: +* When I pass only the beginDate and endDate: + +This became a little longer than I wanted it to, but thanks in advance for any help or suggestions.",2014/12/24,"['https://Stackoverflow.com/questions/27641563', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1695454/']","I finally got it working. The only thing I ended up having to change was addressing the parameter lists in my XML mapper without the surrounding curly braces. + +So instead of: + +``` + + AND ev.location_closest_country_id IN + + #{id} + + + +``` + +It should be: + +``` + + AND ev.location_closest_country_id IN + + #{id} + + + +``` + +Which is odd, because addressing strings in the passed object works with either method - i.e. #{eventFilter.beginDate} is the same as eventFilter.beginDate. + +A very subtle difference, but I hope it helps someone save some time in the future.","try this + +``` + + AND ev.location_closest_country_id IN + + ${id} + + + +```" +27641563,"I am using MyBatis 3.2.8 in a Play Framework 2.3.6 Java project. I've been struggling for several days with iterating over a list of integers that is passed to a MyBatis mapper within a complex object parameter. Here is my setup: + +I have a class called EventFilter in EventFilter.java: + +``` +public class EventFilter { +private String beginDate; +private String endDate; +private List closestCountry; +private List territorialWaterStatus; +private List vesselCountry; +private String closestCountryInClause; +private String territorialWaterStatusInClause; +private String vesselCountryInClause; + +public EventFilter() { } + +public EventFilter(JsonNode jsonNode){ + this.beginDate = jsonNode.get(""beginDate"").asText(); + this.endDate = jsonNode.get(""endDate"").asText(); + this.closestCountry = JsonHelper.arrayNodeToIntegerList((ArrayNode) jsonNode.get(""closestCountry"")); + this.territorialWaterStatus = JsonHelper.arrayNodeToIntegerList((ArrayNode) jsonNode.get(""territorialWaterStatus"")); + this.vesselCountry = JsonHelper.arrayNodeToIntegerList((ArrayNode) jsonNode.get(""vesselCountry"")); +} + +public String getBeginDate() { + return beginDate; +} + +public void setBeginDate(String beginDate) { + this.beginDate = beginDate; +} + +public String getEndDate() { + return endDate; +} + +public void setEndDate(String endDate) { + this.endDate = endDate; +} + +public List getTerritorialWaterStatus() { + if(this.territorialWaterStatus.size() > 0) { + return territorialWaterStatus; + } else { + return null; + } +} + +public void setTerritorialWaterStatus(List territorialWaterStatus) { + this.territorialWaterStatus = territorialWaterStatus; +} + +public List getClosestCountry() { + if(this.closestCountry.size() > 0) { + return closestCountry; + } else { + return null; + } +} + +public void setClosestCountry(List closestCountry) { + this.closestCountry = closestCountry; +} + +public List getVesselCountry() { + if(this.vesselCountry.size() > 0) { + return vesselCountry; + } else { + return null; + } +} + +public void setVesselCountry(List vesselCountry) { + this.vesselCountry = vesselCountry; +} + +``` + +} + +This is referenced as a type alias in my mybatis config file: + +``` + + + + + + + + + + + + + + + + + + + + + + + + + +``` + +I have a mapper that takes an EventFilter object as its parameter. It should then check if the beginDate, endDate, closestCountry, vesselCountry, and territorialWaterStatus are set. If they are it uses them for the WHERE clause: + +``` + + +``` + +I have the mapper linked into an interface as follows: + +``` + public List getEventsWithFilter(@Param(""eventFilter"") EventFilter eventFilter); + +``` + +And I am calling it with a MybatisMapper helper class that generates my session as follows: + +``` +public static List getEvents(EventFilter eventFilter) { + MybatisMapper mapper = new MybatisMapper(); + SqlSession session = mapper.getSession(); + EventMapper eventMapper = session.getMapper(EventMapper.class); + + List events; + + List li = eventFilter.getClosestCountry(); + + try { + events = eventMapper.getEventsWithFilter(eventFilter); + } finally { + session.close(); + } + + return events; +} + +``` + +**The Problem(s):** + +The beginDate and endDate work completely fine by themselves. But I'm having the following problems with the integer lists: + +1. The if statement checking if the list is null seems to be getting +ignored, or evaluating to true when it should be false. +2. The integer lists are appearing to be passed as null into the IN clauses. +3. If I comment out the integer list IN clauses, and just to beginDate and +endDate, it works completely fine. However, if I leave the integer +list IN clauses, the query doesn't fail, but it returns an empty +set, as if to say ""WHERE column IN ()"". + +Here is the console logging printed by Play and Mybatis when the mapper/query are executed, along with the EventFilter printing its contents. They're a little lengthy so I put them in pastebin: + +* When I pass three countries for each of the three integer lists: +* When I pass only the beginDate and endDate: + +This became a little longer than I wanted it to, but thanks in advance for any help or suggestions.",2014/12/24,"['https://Stackoverflow.com/questions/27641563', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1695454/']","I finally got it working. The only thing I ended up having to change was addressing the parameter lists in my XML mapper without the surrounding curly braces. + +So instead of: + +``` + + AND ev.location_closest_country_id IN + + #{id} + + + +``` + +It should be: + +``` + + AND ev.location_closest_country_id IN + + #{id} + + + +``` + +Which is odd, because addressing strings in the passed object works with either method - i.e. #{eventFilter.beginDate} is the same as eventFilter.beginDate. + +A very subtle difference, but I hope it helps someone save some time in the future.","I'm using MyBatis v. 3.4.6. + +My case: + +``` +@Mapper +public interface CorsoMapper { + List elenco(Filtro filtro); +} + +public class Filtro implements Serializable { + private static final long serialVersionUID = -8357822764110641974L; + + private String codice; + private List codici; + + public String getCodice() { + return codice; + } + + public void setCodice(String codice) { + this.codice = codice; + } + + public List getCodici() { + return codici; + } + + public void setCodici(List codici) { + this.codici = codici; + } +} + +``` + +SQL: + +``` + + +``` + +It works without using ""index"" attribute." +27641563,"I am using MyBatis 3.2.8 in a Play Framework 2.3.6 Java project. I've been struggling for several days with iterating over a list of integers that is passed to a MyBatis mapper within a complex object parameter. Here is my setup: + +I have a class called EventFilter in EventFilter.java: + +``` +public class EventFilter { +private String beginDate; +private String endDate; +private List closestCountry; +private List territorialWaterStatus; +private List vesselCountry; +private String closestCountryInClause; +private String territorialWaterStatusInClause; +private String vesselCountryInClause; + +public EventFilter() { } + +public EventFilter(JsonNode jsonNode){ + this.beginDate = jsonNode.get(""beginDate"").asText(); + this.endDate = jsonNode.get(""endDate"").asText(); + this.closestCountry = JsonHelper.arrayNodeToIntegerList((ArrayNode) jsonNode.get(""closestCountry"")); + this.territorialWaterStatus = JsonHelper.arrayNodeToIntegerList((ArrayNode) jsonNode.get(""territorialWaterStatus"")); + this.vesselCountry = JsonHelper.arrayNodeToIntegerList((ArrayNode) jsonNode.get(""vesselCountry"")); +} + +public String getBeginDate() { + return beginDate; +} + +public void setBeginDate(String beginDate) { + this.beginDate = beginDate; +} + +public String getEndDate() { + return endDate; +} + +public void setEndDate(String endDate) { + this.endDate = endDate; +} + +public List getTerritorialWaterStatus() { + if(this.territorialWaterStatus.size() > 0) { + return territorialWaterStatus; + } else { + return null; + } +} + +public void setTerritorialWaterStatus(List territorialWaterStatus) { + this.territorialWaterStatus = territorialWaterStatus; +} + +public List getClosestCountry() { + if(this.closestCountry.size() > 0) { + return closestCountry; + } else { + return null; + } +} + +public void setClosestCountry(List closestCountry) { + this.closestCountry = closestCountry; +} + +public List getVesselCountry() { + if(this.vesselCountry.size() > 0) { + return vesselCountry; + } else { + return null; + } +} + +public void setVesselCountry(List vesselCountry) { + this.vesselCountry = vesselCountry; +} + +``` + +} + +This is referenced as a type alias in my mybatis config file: + +``` + + + + + + + + + + + + + + + + + + + + + + + + + +``` + +I have a mapper that takes an EventFilter object as its parameter. It should then check if the beginDate, endDate, closestCountry, vesselCountry, and territorialWaterStatus are set. If they are it uses them for the WHERE clause: + +``` + + +``` + +I have the mapper linked into an interface as follows: + +``` + public List getEventsWithFilter(@Param(""eventFilter"") EventFilter eventFilter); + +``` + +And I am calling it with a MybatisMapper helper class that generates my session as follows: + +``` +public static List getEvents(EventFilter eventFilter) { + MybatisMapper mapper = new MybatisMapper(); + SqlSession session = mapper.getSession(); + EventMapper eventMapper = session.getMapper(EventMapper.class); + + List events; + + List li = eventFilter.getClosestCountry(); + + try { + events = eventMapper.getEventsWithFilter(eventFilter); + } finally { + session.close(); + } + + return events; +} + +``` + +**The Problem(s):** + +The beginDate and endDate work completely fine by themselves. But I'm having the following problems with the integer lists: + +1. The if statement checking if the list is null seems to be getting +ignored, or evaluating to true when it should be false. +2. The integer lists are appearing to be passed as null into the IN clauses. +3. If I comment out the integer list IN clauses, and just to beginDate and +endDate, it works completely fine. However, if I leave the integer +list IN clauses, the query doesn't fail, but it returns an empty +set, as if to say ""WHERE column IN ()"". + +Here is the console logging printed by Play and Mybatis when the mapper/query are executed, along with the EventFilter printing its contents. They're a little lengthy so I put them in pastebin: + +* When I pass three countries for each of the three integer lists: +* When I pass only the beginDate and endDate: + +This became a little longer than I wanted it to, but thanks in advance for any help or suggestions.",2014/12/24,"['https://Stackoverflow.com/questions/27641563', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1695454/']","try this + +``` + + AND ev.location_closest_country_id IN + + ${id} + + + +```","I'm using MyBatis v. 3.4.6. + +My case: + +``` +@Mapper +public interface CorsoMapper { + List elenco(Filtro filtro); +} + +public class Filtro implements Serializable { + private static final long serialVersionUID = -8357822764110641974L; + + private String codice; + private List codici; + + public String getCodice() { + return codice; + } + + public void setCodice(String codice) { + this.codice = codice; + } + + public List getCodici() { + return codici; + } + + public void setCodici(List codici) { + this.codici = codici; + } +} + +``` + +SQL: + +``` + + +``` + +It works without using ""index"" attribute." +53867961,"There is a GlobalSign CA. In most cases its root certificate is already exists in the Windows Certificates storage. +But sometimes (especially on old Windows versions) the storage doesn't contain the certificate. + +I need to check if the certificate exists and import it if does not. I exported the certificate to a file and imported it using the code below: + +``` +public void ImportCertificate(StoreName storeName, + StoreLocation location, + byte[] certificateData) +{ + X509Store x509Store = new X509Store(storeName, location); + X509Certificate2 certificate = new X509Certificate2(certificateData); + x509Store.Open(OpenFlags.ReadWrite); + x509Store.Add(certificate); + x509Store.Close(); +} + +``` + +The code adds the certificate but all certificate purposes are checked: + +[![Result](https://i.stack.imgur.com/NfPuo.png)](https://i.stack.imgur.com/NfPuo.png) + +I don't want to add extra purposes to the certificate just want to set those ones which have other root CAs like below: + +[![Expect](https://i.stack.imgur.com/tAXRR.png)](https://i.stack.imgur.com/tAXRR.png) + +How to do it programatically?",2018/12/20,"['https://Stackoverflow.com/questions/53867961', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4675884/']","DEPRECATED: As mentioned on this answer ([How can I run commands in a running container in AWS ECS using Fargate](https://stackoverflow.com/questions/51570928/how-can-i-run-commands-in-a-running-container-in-aws-ecs-using-fargate)) you cannot do it due to the fact AWS doesn't give you access to the underlying infrastructure. + +UPDATE: Pierre below mentions an announcement from AWS allowing to do just that.","As i know and having experience on ECS you are not allowed to do it. aws does not give you access to the underlying resources. + +if you are using fargate + EC2 Configuration then also it is not to access EC2." +53867961,"There is a GlobalSign CA. In most cases its root certificate is already exists in the Windows Certificates storage. +But sometimes (especially on old Windows versions) the storage doesn't contain the certificate. + +I need to check if the certificate exists and import it if does not. I exported the certificate to a file and imported it using the code below: + +``` +public void ImportCertificate(StoreName storeName, + StoreLocation location, + byte[] certificateData) +{ + X509Store x509Store = new X509Store(storeName, location); + X509Certificate2 certificate = new X509Certificate2(certificateData); + x509Store.Open(OpenFlags.ReadWrite); + x509Store.Add(certificate); + x509Store.Close(); +} + +``` + +The code adds the certificate but all certificate purposes are checked: + +[![Result](https://i.stack.imgur.com/NfPuo.png)](https://i.stack.imgur.com/NfPuo.png) + +I don't want to add extra purposes to the certificate just want to set those ones which have other root CAs like below: + +[![Expect](https://i.stack.imgur.com/tAXRR.png)](https://i.stack.imgur.com/tAXRR.png) + +How to do it programatically?",2018/12/20,"['https://Stackoverflow.com/questions/53867961', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4675884/']","DEPRECATED: As mentioned on this answer ([How can I run commands in a running container in AWS ECS using Fargate](https://stackoverflow.com/questions/51570928/how-can-i-run-commands-in-a-running-container-in-aws-ecs-using-fargate)) you cannot do it due to the fact AWS doesn't give you access to the underlying infrastructure. + +UPDATE: Pierre below mentions an announcement from AWS allowing to do just that.","I don't know if this is what you are trying to achieve, but if you want you can run a command on a new container that you instantiate for the occasion through a CloudWatch Rule + +It will be enough to create a new task definition and indicate the command to execute (in the example executing a Laravel command) + +``` +ECSReputationSchedulerTask: + Type: AWS::ECS::TaskDefinition + Properties: + Cpu: 256 + ExecutionRoleArn: !ImportValue ECSTaskExecutionRole + Family: TaskDefinitionFamily + Memory: 512 + NetworkMode: awsvpc + RequiresCompatibilities: + - FARGATE + ContainerDefinitions: + - + Command: + - ""php"" + - ""/home/application/artisan"" + - ""execute:operation"" + Name: 'MySchedulerContainer' + ... + +``` + +and then reference it into a CloudWatch rule (unfortunately this can't be done via CloudFormation yet)" +53867961,"There is a GlobalSign CA. In most cases its root certificate is already exists in the Windows Certificates storage. +But sometimes (especially on old Windows versions) the storage doesn't contain the certificate. + +I need to check if the certificate exists and import it if does not. I exported the certificate to a file and imported it using the code below: + +``` +public void ImportCertificate(StoreName storeName, + StoreLocation location, + byte[] certificateData) +{ + X509Store x509Store = new X509Store(storeName, location); + X509Certificate2 certificate = new X509Certificate2(certificateData); + x509Store.Open(OpenFlags.ReadWrite); + x509Store.Add(certificate); + x509Store.Close(); +} + +``` + +The code adds the certificate but all certificate purposes are checked: + +[![Result](https://i.stack.imgur.com/NfPuo.png)](https://i.stack.imgur.com/NfPuo.png) + +I don't want to add extra purposes to the certificate just want to set those ones which have other root CAs like below: + +[![Expect](https://i.stack.imgur.com/tAXRR.png)](https://i.stack.imgur.com/tAXRR.png) + +How to do it programatically?",2018/12/20,"['https://Stackoverflow.com/questions/53867961', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4675884/']","DEPRECATED: As mentioned on this answer ([How can I run commands in a running container in AWS ECS using Fargate](https://stackoverflow.com/questions/51570928/how-can-i-run-commands-in-a-running-container-in-aws-ecs-using-fargate)) you cannot do it due to the fact AWS doesn't give you access to the underlying infrastructure. + +UPDATE: Pierre below mentions an announcement from AWS allowing to do just that.","You may be able to script your container to execute a cli command, but you cannot ssh into the container though. +If you can invoke a `.sh` file from the `CMD` command in the Dockerfile, the cli command will get executed as long as you have aws-cli installed on the docker image. + +In the Dockerfile make sure to run `pip3 install awscli --upgrade --user` before you invoke your script that contains cli commands. + +As an alternative, you can use [boto3](https://boto3.amazonaws.com/v1/documentation/api/latest/index.html) for Python or the [AWS SDK for JavaScript](https://docs.amazonaws.cn/AWSJavaScriptSDK/latest/), which both have comprehensive documentation and enable you to run all the commands you could have run via cli" +53867961,"There is a GlobalSign CA. In most cases its root certificate is already exists in the Windows Certificates storage. +But sometimes (especially on old Windows versions) the storage doesn't contain the certificate. + +I need to check if the certificate exists and import it if does not. I exported the certificate to a file and imported it using the code below: + +``` +public void ImportCertificate(StoreName storeName, + StoreLocation location, + byte[] certificateData) +{ + X509Store x509Store = new X509Store(storeName, location); + X509Certificate2 certificate = new X509Certificate2(certificateData); + x509Store.Open(OpenFlags.ReadWrite); + x509Store.Add(certificate); + x509Store.Close(); +} + +``` + +The code adds the certificate but all certificate purposes are checked: + +[![Result](https://i.stack.imgur.com/NfPuo.png)](https://i.stack.imgur.com/NfPuo.png) + +I don't want to add extra purposes to the certificate just want to set those ones which have other root CAs like below: + +[![Expect](https://i.stack.imgur.com/tAXRR.png)](https://i.stack.imgur.com/tAXRR.png) + +How to do it programatically?",2018/12/20,"['https://Stackoverflow.com/questions/53867961', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4675884/']","As i know and having experience on ECS you are not allowed to do it. aws does not give you access to the underlying resources. + +if you are using fargate + EC2 Configuration then also it is not to access EC2.","I don't know if this is what you are trying to achieve, but if you want you can run a command on a new container that you instantiate for the occasion through a CloudWatch Rule + +It will be enough to create a new task definition and indicate the command to execute (in the example executing a Laravel command) + +``` +ECSReputationSchedulerTask: + Type: AWS::ECS::TaskDefinition + Properties: + Cpu: 256 + ExecutionRoleArn: !ImportValue ECSTaskExecutionRole + Family: TaskDefinitionFamily + Memory: 512 + NetworkMode: awsvpc + RequiresCompatibilities: + - FARGATE + ContainerDefinitions: + - + Command: + - ""php"" + - ""/home/application/artisan"" + - ""execute:operation"" + Name: 'MySchedulerContainer' + ... + +``` + +and then reference it into a CloudWatch rule (unfortunately this can't be done via CloudFormation yet)" +53867961,"There is a GlobalSign CA. In most cases its root certificate is already exists in the Windows Certificates storage. +But sometimes (especially on old Windows versions) the storage doesn't contain the certificate. + +I need to check if the certificate exists and import it if does not. I exported the certificate to a file and imported it using the code below: + +``` +public void ImportCertificate(StoreName storeName, + StoreLocation location, + byte[] certificateData) +{ + X509Store x509Store = new X509Store(storeName, location); + X509Certificate2 certificate = new X509Certificate2(certificateData); + x509Store.Open(OpenFlags.ReadWrite); + x509Store.Add(certificate); + x509Store.Close(); +} + +``` + +The code adds the certificate but all certificate purposes are checked: + +[![Result](https://i.stack.imgur.com/NfPuo.png)](https://i.stack.imgur.com/NfPuo.png) + +I don't want to add extra purposes to the certificate just want to set those ones which have other root CAs like below: + +[![Expect](https://i.stack.imgur.com/tAXRR.png)](https://i.stack.imgur.com/tAXRR.png) + +How to do it programatically?",2018/12/20,"['https://Stackoverflow.com/questions/53867961', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4675884/']","As i know and having experience on ECS you are not allowed to do it. aws does not give you access to the underlying resources. + +if you are using fargate + EC2 Configuration then also it is not to access EC2.","You may be able to script your container to execute a cli command, but you cannot ssh into the container though. +If you can invoke a `.sh` file from the `CMD` command in the Dockerfile, the cli command will get executed as long as you have aws-cli installed on the docker image. + +In the Dockerfile make sure to run `pip3 install awscli --upgrade --user` before you invoke your script that contains cli commands. + +As an alternative, you can use [boto3](https://boto3.amazonaws.com/v1/documentation/api/latest/index.html) for Python or the [AWS SDK for JavaScript](https://docs.amazonaws.cn/AWSJavaScriptSDK/latest/), which both have comprehensive documentation and enable you to run all the commands you could have run via cli" +53867961,"There is a GlobalSign CA. In most cases its root certificate is already exists in the Windows Certificates storage. +But sometimes (especially on old Windows versions) the storage doesn't contain the certificate. + +I need to check if the certificate exists and import it if does not. I exported the certificate to a file and imported it using the code below: + +``` +public void ImportCertificate(StoreName storeName, + StoreLocation location, + byte[] certificateData) +{ + X509Store x509Store = new X509Store(storeName, location); + X509Certificate2 certificate = new X509Certificate2(certificateData); + x509Store.Open(OpenFlags.ReadWrite); + x509Store.Add(certificate); + x509Store.Close(); +} + +``` + +The code adds the certificate but all certificate purposes are checked: + +[![Result](https://i.stack.imgur.com/NfPuo.png)](https://i.stack.imgur.com/NfPuo.png) + +I don't want to add extra purposes to the certificate just want to set those ones which have other root CAs like below: + +[![Expect](https://i.stack.imgur.com/tAXRR.png)](https://i.stack.imgur.com/tAXRR.png) + +How to do it programatically?",2018/12/20,"['https://Stackoverflow.com/questions/53867961', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4675884/']","AWS have now launched Amazon ECS Exec, which allows you to directly interact with containers: .","As i know and having experience on ECS you are not allowed to do it. aws does not give you access to the underlying resources. + +if you are using fargate + EC2 Configuration then also it is not to access EC2." +53867961,"There is a GlobalSign CA. In most cases its root certificate is already exists in the Windows Certificates storage. +But sometimes (especially on old Windows versions) the storage doesn't contain the certificate. + +I need to check if the certificate exists and import it if does not. I exported the certificate to a file and imported it using the code below: + +``` +public void ImportCertificate(StoreName storeName, + StoreLocation location, + byte[] certificateData) +{ + X509Store x509Store = new X509Store(storeName, location); + X509Certificate2 certificate = new X509Certificate2(certificateData); + x509Store.Open(OpenFlags.ReadWrite); + x509Store.Add(certificate); + x509Store.Close(); +} + +``` + +The code adds the certificate but all certificate purposes are checked: + +[![Result](https://i.stack.imgur.com/NfPuo.png)](https://i.stack.imgur.com/NfPuo.png) + +I don't want to add extra purposes to the certificate just want to set those ones which have other root CAs like below: + +[![Expect](https://i.stack.imgur.com/tAXRR.png)](https://i.stack.imgur.com/tAXRR.png) + +How to do it programatically?",2018/12/20,"['https://Stackoverflow.com/questions/53867961', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4675884/']","AWS have now launched Amazon ECS Exec, which allows you to directly interact with containers: .","I don't know if this is what you are trying to achieve, but if you want you can run a command on a new container that you instantiate for the occasion through a CloudWatch Rule + +It will be enough to create a new task definition and indicate the command to execute (in the example executing a Laravel command) + +``` +ECSReputationSchedulerTask: + Type: AWS::ECS::TaskDefinition + Properties: + Cpu: 256 + ExecutionRoleArn: !ImportValue ECSTaskExecutionRole + Family: TaskDefinitionFamily + Memory: 512 + NetworkMode: awsvpc + RequiresCompatibilities: + - FARGATE + ContainerDefinitions: + - + Command: + - ""php"" + - ""/home/application/artisan"" + - ""execute:operation"" + Name: 'MySchedulerContainer' + ... + +``` + +and then reference it into a CloudWatch rule (unfortunately this can't be done via CloudFormation yet)" +53867961,"There is a GlobalSign CA. In most cases its root certificate is already exists in the Windows Certificates storage. +But sometimes (especially on old Windows versions) the storage doesn't contain the certificate. + +I need to check if the certificate exists and import it if does not. I exported the certificate to a file and imported it using the code below: + +``` +public void ImportCertificate(StoreName storeName, + StoreLocation location, + byte[] certificateData) +{ + X509Store x509Store = new X509Store(storeName, location); + X509Certificate2 certificate = new X509Certificate2(certificateData); + x509Store.Open(OpenFlags.ReadWrite); + x509Store.Add(certificate); + x509Store.Close(); +} + +``` + +The code adds the certificate but all certificate purposes are checked: + +[![Result](https://i.stack.imgur.com/NfPuo.png)](https://i.stack.imgur.com/NfPuo.png) + +I don't want to add extra purposes to the certificate just want to set those ones which have other root CAs like below: + +[![Expect](https://i.stack.imgur.com/tAXRR.png)](https://i.stack.imgur.com/tAXRR.png) + +How to do it programatically?",2018/12/20,"['https://Stackoverflow.com/questions/53867961', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4675884/']","AWS have now launched Amazon ECS Exec, which allows you to directly interact with containers: .","You may be able to script your container to execute a cli command, but you cannot ssh into the container though. +If you can invoke a `.sh` file from the `CMD` command in the Dockerfile, the cli command will get executed as long as you have aws-cli installed on the docker image. + +In the Dockerfile make sure to run `pip3 install awscli --upgrade --user` before you invoke your script that contains cli commands. + +As an alternative, you can use [boto3](https://boto3.amazonaws.com/v1/documentation/api/latest/index.html) for Python or the [AWS SDK for JavaScript](https://docs.amazonaws.cn/AWSJavaScriptSDK/latest/), which both have comprehensive documentation and enable you to run all the commands you could have run via cli" +31441040,"I'm trying to retain the selected value of a dropdownlist once the user change the dropdownlist item but its not working as expected what I wanted is to retain the selected item in the dropdownlist but its it defaulted to the `Select Company` everytime i select the item from dropdownlist, once the user change it postback the page (i know there is no postback in the MVC) + +What I'm doing wrong here? + +``` +
+ @using (Html.BeginForm(""Index"", ""Home"", FormMethod.Post, new { @id = ""form_dropdown"" })) + { + @Html.DropDownListFor(m => m.ListOfCompanies, + new SelectList((System.Collections.IEnumerable)Model.ListOfCompanies, ""Value"", ""Text""), + ""Select Company"", new { @class = ""form-control"", Name = ""sel"" }) + } + +``` + +``` +[HttpPost] +public ActionResult Index(string sel) +{ + var vModel = new EmployeeViewModel(); + vModel = _db.GetEmployee.ToList(); + + //load list of companies: + + var company = _db.LoadComapny.ToList(); + IEnumerable result = model.Select(b => new SelectListItem + { + Value = b.Value, + Text = b.Text, + Selected = b.Text == sel + }).ToList(); + + vModel.ListOfCompanies = company; + vModel.SELECTED_COMPANY = sel; + + return View(vModel); +} + +``` + +Model: + +``` +public class EmployeeViewModel +{ + public IEnumerable ListOfCompanies { get; set; } + public string SELECTED_COMPANY { get; set; } + //other props +} + +```",2015/07/15,"['https://Stackoverflow.com/questions/31441040', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/275390/']","As I wrote in the comment section, it's really unclear to me what you're asking. +However, looking at your code examples, it seems to me that `trait A` isn't really required. +You can use the types that already come with the Scala SDK: + +``` +object B extends (()=>Unit) { + def apply() { /* implementation */ } +} + +``` + +Or, as a variant: + +``` +object B { + val aType:()=>Unit = {() => /* implementation */ } +} + +``` + +In the first case, you can access the singleton instance with `B`, in the second case with `B.aType`. +In the second case, no explicit declaration of the `apply` method is needed. + +Pick what you like. +The essential message is: You don't need a trait if you just define one simple method. +That's what Scala functions are for. + +The list type might look like this: + +``` +private val aList:ListBuffer[()=>Unit] = ??? + +``` + +(By the way: Why not declare it as `Seq[()=>Unit]`? Is it important to the caller that it is a `ListBuffer` and not some other kind of sequence?) + +Your worker might then look like this: + +``` +abstract class Worker { + def aType:()=>Unit // no need for the `get` prefix here, or the empty parameter list + def do() {aType()} +} + +``` + +Note that now the `Worker` type has become a class that offers a method that invokes a function. +So, there is really no need to have a `Worker` class. +You can just take the function (`aType`) directly and invoke it, just so. + +If you always want to call the implementation in `object B`, well - just do that then. +There is no need to wrap the call in instances of other types. +Your example class `B` just forwards the call to the `B` object, which is really unnecessary. +There is no need to even create an instance of `B`. +It does have the private member variable `creator`, but since it's never used, it will never be accessed in any way. + +So, I would recommend to completely remove the `class B`. +All you need is the type `()=>Unit`, which is exactly what you need: A function that takes no parameters and returns nothing. + +If you get tired of writing `()=>Unit` all the time, you can define a type alias, for example inside the package object. +Here is my recommentation: + +``` +type SideEffect = ()=>Unit + +``` + +Then you can use `SideEffect` as an alias for `()=>Unit`. + +That's all I can make of it. +It looks to me that this is probably not what you were looking for. +But maybe this will help you a little bit along the way. +If you want to have a more concrete answer, it would be nice if you would clarify the question.","`object B` doesn't really have much to do with `class B` aside from some special rules. + +If you wish to reuse that `doSomething` method you should just reuse the implementation from the object: + +``` +class B { + def doSomething() = B.doSomething() +} + +``` + +If you want to specify `object B` as a specific instance of `class B` then you should do the following: + +``` +object B extends B(""some particular creator"") { +... +} + +``` + +You also do not need `override` modifiers although they can be handy for compiler checks." +31441040,"I'm trying to retain the selected value of a dropdownlist once the user change the dropdownlist item but its not working as expected what I wanted is to retain the selected item in the dropdownlist but its it defaulted to the `Select Company` everytime i select the item from dropdownlist, once the user change it postback the page (i know there is no postback in the MVC) + +What I'm doing wrong here? + +``` +
+ @using (Html.BeginForm(""Index"", ""Home"", FormMethod.Post, new { @id = ""form_dropdown"" })) + { + @Html.DropDownListFor(m => m.ListOfCompanies, + new SelectList((System.Collections.IEnumerable)Model.ListOfCompanies, ""Value"", ""Text""), + ""Select Company"", new { @class = ""form-control"", Name = ""sel"" }) + } + +``` + +``` +[HttpPost] +public ActionResult Index(string sel) +{ + var vModel = new EmployeeViewModel(); + vModel = _db.GetEmployee.ToList(); + + //load list of companies: + + var company = _db.LoadComapny.ToList(); + IEnumerable result = model.Select(b => new SelectListItem + { + Value = b.Value, + Text = b.Text, + Selected = b.Text == sel + }).ToList(); + + vModel.ListOfCompanies = company; + vModel.SELECTED_COMPANY = sel; + + return View(vModel); +} + +``` + +Model: + +``` +public class EmployeeViewModel +{ + public IEnumerable ListOfCompanies { get; set; } + public string SELECTED_COMPANY { get; set; } + //other props +} + +```",2015/07/15,"['https://Stackoverflow.com/questions/31441040', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/275390/']","As I wrote in the comment section, it's really unclear to me what you're asking. +However, looking at your code examples, it seems to me that `trait A` isn't really required. +You can use the types that already come with the Scala SDK: + +``` +object B extends (()=>Unit) { + def apply() { /* implementation */ } +} + +``` + +Or, as a variant: + +``` +object B { + val aType:()=>Unit = {() => /* implementation */ } +} + +``` + +In the first case, you can access the singleton instance with `B`, in the second case with `B.aType`. +In the second case, no explicit declaration of the `apply` method is needed. + +Pick what you like. +The essential message is: You don't need a trait if you just define one simple method. +That's what Scala functions are for. + +The list type might look like this: + +``` +private val aList:ListBuffer[()=>Unit] = ??? + +``` + +(By the way: Why not declare it as `Seq[()=>Unit]`? Is it important to the caller that it is a `ListBuffer` and not some other kind of sequence?) + +Your worker might then look like this: + +``` +abstract class Worker { + def aType:()=>Unit // no need for the `get` prefix here, or the empty parameter list + def do() {aType()} +} + +``` + +Note that now the `Worker` type has become a class that offers a method that invokes a function. +So, there is really no need to have a `Worker` class. +You can just take the function (`aType`) directly and invoke it, just so. + +If you always want to call the implementation in `object B`, well - just do that then. +There is no need to wrap the call in instances of other types. +Your example class `B` just forwards the call to the `B` object, which is really unnecessary. +There is no need to even create an instance of `B`. +It does have the private member variable `creator`, but since it's never used, it will never be accessed in any way. + +So, I would recommend to completely remove the `class B`. +All you need is the type `()=>Unit`, which is exactly what you need: A function that takes no parameters and returns nothing. + +If you get tired of writing `()=>Unit` all the time, you can define a type alias, for example inside the package object. +Here is my recommentation: + +``` +type SideEffect = ()=>Unit + +``` + +Then you can use `SideEffect` as an alias for `()=>Unit`. + +That's all I can make of it. +It looks to me that this is probably not what you were looking for. +But maybe this will help you a little bit along the way. +If you want to have a more concrete answer, it would be nice if you would clarify the question.","The notion of a *companion object* extending a trait is useful for defining behavior associated with the class itself (e.g. static methods) as opposed to instances of the class. In other words, it allows your static methods to implement interfaces. Here's an example: + +``` +import java.nio.ByteBuffer + +// a trait to be implemented by the companion object of a class +// to convey the fixed size of any instance of that class +trait Sized { def size: Int } + +// create a buffer based on the size information provided by the +// companion object +def createBuffer(sized: Sized): ByteBuffer = ByteBuffer.allocate(sized.size) + +class MyClass(x: Long) { + def writeTo(buffer: ByteBuffer) { buffer.putLong(x) } +} +object MyClass extends Sized { + def size = java.lang.Long.SIZE / java.lang.Byte.SIZE +} + +// create a buffer with correct sizing for MyClass whose companion +// object implements Sized. Note that we don't need an instance +// of MyClass to obtain sizing information. +val buf = createBuffer(MyClass) + +// write an instance of MyClass to the buffer. +val c = new MyClass(42) +c.writeTo(buf) + +```" +31441040,"I'm trying to retain the selected value of a dropdownlist once the user change the dropdownlist item but its not working as expected what I wanted is to retain the selected item in the dropdownlist but its it defaulted to the `Select Company` everytime i select the item from dropdownlist, once the user change it postback the page (i know there is no postback in the MVC) + +What I'm doing wrong here? + +``` +
+ @using (Html.BeginForm(""Index"", ""Home"", FormMethod.Post, new { @id = ""form_dropdown"" })) + { + @Html.DropDownListFor(m => m.ListOfCompanies, + new SelectList((System.Collections.IEnumerable)Model.ListOfCompanies, ""Value"", ""Text""), + ""Select Company"", new { @class = ""form-control"", Name = ""sel"" }) + } + +``` + +``` +[HttpPost] +public ActionResult Index(string sel) +{ + var vModel = new EmployeeViewModel(); + vModel = _db.GetEmployee.ToList(); + + //load list of companies: + + var company = _db.LoadComapny.ToList(); + IEnumerable result = model.Select(b => new SelectListItem + { + Value = b.Value, + Text = b.Text, + Selected = b.Text == sel + }).ToList(); + + vModel.ListOfCompanies = company; + vModel.SELECTED_COMPANY = sel; + + return View(vModel); +} + +``` + +Model: + +``` +public class EmployeeViewModel +{ + public IEnumerable ListOfCompanies { get; set; } + public string SELECTED_COMPANY { get; set; } + //other props +} + +```",2015/07/15,"['https://Stackoverflow.com/questions/31441040', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/275390/']","`object B` doesn't really have much to do with `class B` aside from some special rules. + +If you wish to reuse that `doSomething` method you should just reuse the implementation from the object: + +``` +class B { + def doSomething() = B.doSomething() +} + +``` + +If you want to specify `object B` as a specific instance of `class B` then you should do the following: + +``` +object B extends B(""some particular creator"") { +... +} + +``` + +You also do not need `override` modifiers although they can be handy for compiler checks.","The notion of a *companion object* extending a trait is useful for defining behavior associated with the class itself (e.g. static methods) as opposed to instances of the class. In other words, it allows your static methods to implement interfaces. Here's an example: + +``` +import java.nio.ByteBuffer + +// a trait to be implemented by the companion object of a class +// to convey the fixed size of any instance of that class +trait Sized { def size: Int } + +// create a buffer based on the size information provided by the +// companion object +def createBuffer(sized: Sized): ByteBuffer = ByteBuffer.allocate(sized.size) + +class MyClass(x: Long) { + def writeTo(buffer: ByteBuffer) { buffer.putLong(x) } +} +object MyClass extends Sized { + def size = java.lang.Long.SIZE / java.lang.Byte.SIZE +} + +// create a buffer with correct sizing for MyClass whose companion +// object implements Sized. Note that we don't need an instance +// of MyClass to obtain sizing information. +val buf = createBuffer(MyClass) + +// write an instance of MyClass to the buffer. +val c = new MyClass(42) +c.writeTo(buf) + +```" +2815373,"I'm looking for the following features: + +1. Scheduler uses SQL Server as the backing store +2. Tasks can be scheduled by one application and executed by another +3. I can have multiple applications, each of which handles a specific subset of tasks +4. Tasks can be triggered at specific times, now, or based on the success or failure of other tasks +5. Data can be attached to tasks + +There are a number of nice-to-have's, like a web management console, clustering/failover support, customizable logging, but they're not requirements. + +On the surface Quartz.NET has a nice interface and seems to fit the bill as it satisfies (1), (4 with some custom work) and (5), but I've been beating my head against (2) and (3) seems like I'd have to invest more effort than it's worth, especially given how convoluted the innards of it are. + +Any other libraries out there? Open source is preferred, with free as a close runner up. It's really hard to get management to pay for things like this when it's not their idea.",2010/05/12,"['https://Stackoverflow.com/questions/2815373', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/156767/']","I hate to say it, but it sounds like you want [BizTalk](http://www.microsoft.com/biztalk/en/us/default.aspx) which is neither open source, nor free, but is ideally suited towards what you are trying to accomplish.","You could use Windows Workflow (WF), maybe along with Quartz.NET" +332362,"Suppose $M$ is a $\sigma$-finite measure space, and $\Gamma$ a set of positive-measure subsets of $M$ such that every point in $M$ belongs to only finitely many members of $\Gamma$. Must $\Gamma$ be countable? (And if the answer to this question is *no* for general σ-finite measures, is it also no for, say, Lebesgue measure?) + +• I can see that if the conjecture that Γ has to be countable is true when $M$ has *finite* measure, it must be also be true when $M$ is σ-finite. (Just decompose $M$ into $M\_0 ∪ M\_1 ∪ \ldots$ where each $M\_i$ is finite-measure. For each $i$, only countably many of Γ will have positive measure intersection with $M\_i$; but every member of Γ must have positive-measure overlap with some $M\_i$, so Γ must be countable.) So we can focus on the case where $M$ is finite measure. + +• I can prove the following weaker result: suppose $M$ is finite-measure and Γ a set of positive-measure subsets of $M$ such that every point in $M$ belongs to at most $n$ members of Γ, then Γ must be countable. (For each ε>0, at most $nμ(M)/ε$ members of Γ have measure ≥ε. So we can enumerate all the members of Γ by first enumerating those with measure≥1, then those with measure ≥1/2, then those with measure ≥1/4, etc.) + +• Returning to the original conjecture, I can see how to prove it if only I could take it for granted that for each $i$, the set $E\_i$ of points in $M$ that belong to exactly $i$ members of Γ is measurable. In that case, I could first use the weaker result to show that for each $i$, at most countably many members of Γ have positive-measure overlap with $E\_i$, and then argue that since $M = E\_0 ∪ E\_1 ∪ \ldots$ and the $E\_i$ are measurable, every member of Γ must have positive-measure overlap with at least one of the $E\_i$, establishing that Γ is itself countable. Unfortunately this doesn't work if the $E\_i$ aren't measurable, and I don't see any way to show that they are. + +(This question is a follow-up to [Can an uncountable family of positive-measure sets be such that no point belongs to uncountably many of them?](https://math.stackexchange.com/questions/319358/).)",2013/03/16,"['https://math.stackexchange.com/questions/332362', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/4909/']","Assume a finite measure. There is an $\epsilon > 0$ and countable collection $E\_i$ with $\mu(E\_i) > \epsilon$, because the alternative is that $\lbrace E: \mu(E) > \frac 1 n \rbrace$ is finite for all $n$, which would make $\lbrace E: \mu(E) > 0 \rbrace$ countable. Let $F\_n = E\_n \cup E\_{n+1} \cup .... $. The sequence of indicators $1\_{F\_n} $ is monotone decreasing and converges to $0$ on the set where $x \in E\_i$ finitely often, and $1$ if $x \in E\_i$ infinitely often. It is also bounded by 1. By bounded convergence it converges in $ \mathbb L \_1$. But since $\int 1\_{F\_n} d\mu > \epsilon $ the same must be true of the limit.","Here is a more detailed and more elementary version of mike's proof, using continuity rather than the bounded convergence theorem, which I'm writing up mostly for my own edification. + +Suppose that for some finite-measure $S$ and $ε>0$, there are infinitely many $E⊂Γ$ with $μ(S∩E)≥ε$. Let $E\_0, E\_1, E\_2\ldots$ be a countable sequence of such $E$. And let $F\_n = S ∩ (E\_n ∪ E\_{n+1} ∪ E\_{n+2} ∪ \cdots)$. Clearly $μ(S) ≥ μ(F\_i) ≥ μ(S∩E\_i) ≥ ε$ for each $i$, and $F\_i ⊂ F\_j$ whenever $j), $μ(\bigcap\_{i=1}^\infty F\_i) = \lim\_{i→∞}μ(F\_i) ≥ ε$. But for any point $p$ in $S$, $p∈\bigcap\_{i=1}^\infty F\_i$ if and only if p belongs to infinitely many of the $E\_i$. Therefore there are some points in $M$ (in fact, a positive-measure set of them) that belong to infinitely many of the $E\_i$, contradicting the stipulation that each point only belongs to finitely many members of Γ. + +So we can conclude that for every finite-measure subset $S$ of $M$ and every $ε>0$, there are only finitely many $E∈Γ$ with $μ(S∩E)≥ε$. Then the set of $E∈Γ$ with $μ(S∩E)≥0$ is countable for every finite-measure $S$, since we can enumerate these $E$ by first listing those for which $μ(S∩E)≥1$, then those for which $μ(S∩E)≥1/2$, then those for which $μ(S∩E)≥1/3$, etc. But $M$ is σ-finite, so there is a countable collection of finite-measure sets $S\_0, S\_1, S\_2\ldots$ such that every positive-measure subset of $M$ has positive-measure overlap with at least one of $S\_0, S\_1, S\_2\ldots$. So Γ itself is countable, being the union of countably many countable sets." +201346,"We were fighting Vecna himself, and at one point had a *[prismatic wall](https://www.dndbeyond.com/spells/prismatic-wall)* up between us and Vecna. The *prismatic wall* says it creates ""a vertical, opaque wall."" + +Vecna's powers include truesight, and presumably x-ray vision as well (since the artifact *Eye of Vecna* allows its bearer to use x-ray vision), and the DM thought Vecna would be able to see through the prismatic wall and target us. A *[ring of x-ray vision](https://www.dndbeyond.com/magic-items/4738-ring-of-x-ray-vision)* states: + +> +> While wearing this ring, you can use an action to speak its command word. When you do so, you can see into and through solid matter for 1 minute. This vision has a radius of 30 feet. To you, solid objects within that radius appear transparent and don't prevent light from passing through them. The vision can penetrate 1 foot of stone, 1 inch of common metal, or up to 3 feet of wood or dirt. Thicker substances block the vision, as does a thin sheet of lead. +> +> +> + +So can someone see through a prismatic wall using truesight/x-ray vision?",2022/09/10,"['https://rpg.stackexchange.com/questions/201346', 'https://rpg.stackexchange.com', 'https://rpg.stackexchange.com/users/30992/']","**Truesight does not help** - a Prismatic Wall is an Abjuration, not an Illusion, and neither involves the Ethereal plane nor shapeshifting. + +**X-ray vision is less clear** - Prismatic Wall is defined as one inch thick, which definitely fits within the realm of X-ray vision. However, X-ray vision states ""solid objects"", which I'd argue a Prismatic Wall isn't, being defined as ""a shimmering, multicolored plane of light "". As Prismatic Wall is a 9th level spell, so I'd tend to argue in favor of it doing more rather than less. + +However, I'd say the rules are unclear enough that **a DM ruling is required**. And **Rule 0** is always a thing - if the DM wants Vecna, one of the top BBEGs in D&D, to be able to see through something, then Vecna definitely can.","*Prismatic wall*: + +> +> A shimmering, multicolored plane of light forms a vertical opaque wall +> +> +> + +Truesight: maybe indirectly +--------------------------- + +Monster Manual (p. 9): + +> +> A monster with truesight can, out to a specific range, see in normal and magical darkness, see invisible creatures and objects, automatically detect visual illusions and succeed on saving throws against them, and perceive the original form of a shapechanger or a creature that is transformed by magic. +> +> +> + +Nothing in this implies that truesight allows one to see through an opaque wall. However, truesight also grants: + +> +> Furthermore, the monster can see into the Ethereal Plane within the same range. +> +> +> + +And here is where it gets complicated. Nothing in the description of *prismatic wall* says or implies that any layer of the wall is made of force, and thus the wall does not exist on the Ethereal plane. However, the characters are (presumably) living, and the DMG says that ""[living beings] on the [Material] hamper the movement of a creature in the Border Ethereal."" The [*Etherealness*](https://www.dndbeyond.com/spells/etherealness) spell states that ""You can see and hear the plane you originated from, but everything there looks gray, and you can't see anything more than 60 feet away."" That is, someone on the Border Ethereal can see a version of the overlapping Material plane (although the objects appear as muted gray forms) and living creatures on the Material create impassible physical barriers on the Ethereal. + +Thus it seems reasonable for a DM to rule that Vecna could use his truesight to see into the Border Ethereal, where projections of the characters appear in gray tones and where the wall does not block his sight. Since Border Ethereal locations 'map one to one' with the Material, it is then possible to rule that he can use this [indirect sight to target characters](https://rpg.stackexchange.com/questions/195034/can-i-target-someone-who-i-can-see-in-a-mirror?rq=1) on the material plane, since he can, in effect, 'see their location' by noting the location of their forms that are visible on the Ethereal. It is certainly not RAW, but it is also not an unreasonable interpretation. If anyone could do this, Vecna could. + +X-ray vision - no +----------------- + +The [*ring of X-ray vision*](https://www.dndbeyond.com/magic-items/4738-ring-of-x-ray-vision) says: + +> +> When you do so, you can see into and through solid matter for 1 minute. This vision has a radius of 30 feet. To you, solid objects within that radius appear transparent and don't prevent light from passing through them. +> +> +> + +The ring specifically says that it can be used to see through ""solid matter [and] solid objects""; it does not impart any ability to see through opaque substances that are *not* solid. It could not be used, for example, to see through an inch thick of liquid mercury, or a dense gaseous [fog or smoke](https://rpg.stackexchange.com/q/72780/23547). + +While the wall is opaque, the ""shimmering plane of light"" is not solid in any natural English usage of the word. Creatures passing through it may trigger damage or other effects, but it does not physically block their passage. And it is certainly not an *object*; it is a magical effect. Thus the ring's ability to make ""solid objects...appear transparent"" simply does not apply." +201346,"We were fighting Vecna himself, and at one point had a *[prismatic wall](https://www.dndbeyond.com/spells/prismatic-wall)* up between us and Vecna. The *prismatic wall* says it creates ""a vertical, opaque wall."" + +Vecna's powers include truesight, and presumably x-ray vision as well (since the artifact *Eye of Vecna* allows its bearer to use x-ray vision), and the DM thought Vecna would be able to see through the prismatic wall and target us. A *[ring of x-ray vision](https://www.dndbeyond.com/magic-items/4738-ring-of-x-ray-vision)* states: + +> +> While wearing this ring, you can use an action to speak its command word. When you do so, you can see into and through solid matter for 1 minute. This vision has a radius of 30 feet. To you, solid objects within that radius appear transparent and don't prevent light from passing through them. The vision can penetrate 1 foot of stone, 1 inch of common metal, or up to 3 feet of wood or dirt. Thicker substances block the vision, as does a thin sheet of lead. +> +> +> + +So can someone see through a prismatic wall using truesight/x-ray vision?",2022/09/10,"['https://rpg.stackexchange.com/questions/201346', 'https://rpg.stackexchange.com', 'https://rpg.stackexchange.com/users/30992/']","**Truesight does not help** - a Prismatic Wall is an Abjuration, not an Illusion, and neither involves the Ethereal plane nor shapeshifting. + +**X-ray vision is less clear** - Prismatic Wall is defined as one inch thick, which definitely fits within the realm of X-ray vision. However, X-ray vision states ""solid objects"", which I'd argue a Prismatic Wall isn't, being defined as ""a shimmering, multicolored plane of light "". As Prismatic Wall is a 9th level spell, so I'd tend to argue in favor of it doing more rather than less. + +However, I'd say the rules are unclear enough that **a DM ruling is required**. And **Rule 0** is always a thing - if the DM wants Vecna, one of the top BBEGs in D&D, to be able to see through something, then Vecna definitely can.","RAW, vague. +----------- + +True sight and x-ray vision could either be *argued* to see through *Prismatic Wall* depending on various definitions of light, matter, ethereal, etc. However, D&D 5e is not a physics simulator. Neither *explicitly* states they see through 'planes of shimmering light' or w/e, yet they both talk about seeing through all kinds of stuff, so it's basically an argument either way. + +Whenever there's an argument about anything in D&D, it comes down to the DM's decision. That's in large part *why* you have a DM (as well as to apply structure and motivation to the story). What a DM decides is reasonable in that situation is up to the DM and their table's expectations, but, + +*Should* Vecna be able to see through his Prismatic Wall? +--------------------------------------------------------- + +Yes. + +He is Vecna." +201346,"We were fighting Vecna himself, and at one point had a *[prismatic wall](https://www.dndbeyond.com/spells/prismatic-wall)* up between us and Vecna. The *prismatic wall* says it creates ""a vertical, opaque wall."" + +Vecna's powers include truesight, and presumably x-ray vision as well (since the artifact *Eye of Vecna* allows its bearer to use x-ray vision), and the DM thought Vecna would be able to see through the prismatic wall and target us. A *[ring of x-ray vision](https://www.dndbeyond.com/magic-items/4738-ring-of-x-ray-vision)* states: + +> +> While wearing this ring, you can use an action to speak its command word. When you do so, you can see into and through solid matter for 1 minute. This vision has a radius of 30 feet. To you, solid objects within that radius appear transparent and don't prevent light from passing through them. The vision can penetrate 1 foot of stone, 1 inch of common metal, or up to 3 feet of wood or dirt. Thicker substances block the vision, as does a thin sheet of lead. +> +> +> + +So can someone see through a prismatic wall using truesight/x-ray vision?",2022/09/10,"['https://rpg.stackexchange.com/questions/201346', 'https://rpg.stackexchange.com', 'https://rpg.stackexchange.com/users/30992/']","Neither effect allows you to see through a Prismatic Wall +--------------------------------------------------------- + +Prismatic Wall has this effect: + +> +> A shimmering, multicolored plane of light forms a vertical opaque wall +> +> +> + +### Truesight + +[Truesight](https://www.dndbeyond.com/sources/basic-rules/monsters#Truesight) allows you to + +> +> see in normal and magical darkness, see invisible creatures and objects, automatically detect visual illusions and succeed on saving throws against them, and perceive the original form of a shapechanger or a creature that is transformed by magic [...] see into the Ethereal Plane +> +> +> + +It does not allow you to see through an opaque barrier. While you can see into the Ethereal Plane, what you are looking at is not not *on* the Ethereal Plane, and if you could see them *from* there does not matter, as neither are you. + +### X-Ray Vision + +X-Ray Vision (as in the [ring](https://www.dndbeyond.com/magic-items/4738-ring-of-x-ray-vision)) allows you to + +> +> see into and through solid matter (...) To you, solid objects within that radius appear transparent and don't prevent light from passing through them +> +> +> + +The wall is not a solid object or solid matter, as it is made of insubstantial light that you can walk through, which you could not if it were solid. So X-Ray Vision does not allow you to see through it, either. + +### Vecna + +Could you use either as a player character if you tried to look through a Prismatic Wall? No. + +Could Vecna? Not by the official stat block that has been printed in the [Vecna Dossier](https://www.dndbeyond.com/claim/source/vecna) (where he does not even have X-Ray Vision, as he does not have the Hand or Eye of Vecna, he is said to be questing for them). However, the lore section there states that + +> +> More recently, Vecna decamped to the Outer Planes, where he grew so powerful that he became a god. +> +> +> + +And there are no printed rules for gods. Even without invoking their right to overrule anything, the DM can rule that he could see through the wall. And even for pre-apotheosis Vecna, they of course can rule so, because it's Vecna and because of their right to overrule. Your DM in any case did rule so, so your Vecna could.","*Prismatic wall*: + +> +> A shimmering, multicolored plane of light forms a vertical opaque wall +> +> +> + +Truesight: maybe indirectly +--------------------------- + +Monster Manual (p. 9): + +> +> A monster with truesight can, out to a specific range, see in normal and magical darkness, see invisible creatures and objects, automatically detect visual illusions and succeed on saving throws against them, and perceive the original form of a shapechanger or a creature that is transformed by magic. +> +> +> + +Nothing in this implies that truesight allows one to see through an opaque wall. However, truesight also grants: + +> +> Furthermore, the monster can see into the Ethereal Plane within the same range. +> +> +> + +And here is where it gets complicated. Nothing in the description of *prismatic wall* says or implies that any layer of the wall is made of force, and thus the wall does not exist on the Ethereal plane. However, the characters are (presumably) living, and the DMG says that ""[living beings] on the [Material] hamper the movement of a creature in the Border Ethereal."" The [*Etherealness*](https://www.dndbeyond.com/spells/etherealness) spell states that ""You can see and hear the plane you originated from, but everything there looks gray, and you can't see anything more than 60 feet away."" That is, someone on the Border Ethereal can see a version of the overlapping Material plane (although the objects appear as muted gray forms) and living creatures on the Material create impassible physical barriers on the Ethereal. + +Thus it seems reasonable for a DM to rule that Vecna could use his truesight to see into the Border Ethereal, where projections of the characters appear in gray tones and where the wall does not block his sight. Since Border Ethereal locations 'map one to one' with the Material, it is then possible to rule that he can use this [indirect sight to target characters](https://rpg.stackexchange.com/questions/195034/can-i-target-someone-who-i-can-see-in-a-mirror?rq=1) on the material plane, since he can, in effect, 'see their location' by noting the location of their forms that are visible on the Ethereal. It is certainly not RAW, but it is also not an unreasonable interpretation. If anyone could do this, Vecna could. + +X-ray vision - no +----------------- + +The [*ring of X-ray vision*](https://www.dndbeyond.com/magic-items/4738-ring-of-x-ray-vision) says: + +> +> When you do so, you can see into and through solid matter for 1 minute. This vision has a radius of 30 feet. To you, solid objects within that radius appear transparent and don't prevent light from passing through them. +> +> +> + +The ring specifically says that it can be used to see through ""solid matter [and] solid objects""; it does not impart any ability to see through opaque substances that are *not* solid. It could not be used, for example, to see through an inch thick of liquid mercury, or a dense gaseous [fog or smoke](https://rpg.stackexchange.com/q/72780/23547). + +While the wall is opaque, the ""shimmering plane of light"" is not solid in any natural English usage of the word. Creatures passing through it may trigger damage or other effects, but it does not physically block their passage. And it is certainly not an *object*; it is a magical effect. Thus the ring's ability to make ""solid objects...appear transparent"" simply does not apply." +201346,"We were fighting Vecna himself, and at one point had a *[prismatic wall](https://www.dndbeyond.com/spells/prismatic-wall)* up between us and Vecna. The *prismatic wall* says it creates ""a vertical, opaque wall."" + +Vecna's powers include truesight, and presumably x-ray vision as well (since the artifact *Eye of Vecna* allows its bearer to use x-ray vision), and the DM thought Vecna would be able to see through the prismatic wall and target us. A *[ring of x-ray vision](https://www.dndbeyond.com/magic-items/4738-ring-of-x-ray-vision)* states: + +> +> While wearing this ring, you can use an action to speak its command word. When you do so, you can see into and through solid matter for 1 minute. This vision has a radius of 30 feet. To you, solid objects within that radius appear transparent and don't prevent light from passing through them. The vision can penetrate 1 foot of stone, 1 inch of common metal, or up to 3 feet of wood or dirt. Thicker substances block the vision, as does a thin sheet of lead. +> +> +> + +So can someone see through a prismatic wall using truesight/x-ray vision?",2022/09/10,"['https://rpg.stackexchange.com/questions/201346', 'https://rpg.stackexchange.com', 'https://rpg.stackexchange.com/users/30992/']","Neither effect allows you to see through a Prismatic Wall +--------------------------------------------------------- + +Prismatic Wall has this effect: + +> +> A shimmering, multicolored plane of light forms a vertical opaque wall +> +> +> + +### Truesight + +[Truesight](https://www.dndbeyond.com/sources/basic-rules/monsters#Truesight) allows you to + +> +> see in normal and magical darkness, see invisible creatures and objects, automatically detect visual illusions and succeed on saving throws against them, and perceive the original form of a shapechanger or a creature that is transformed by magic [...] see into the Ethereal Plane +> +> +> + +It does not allow you to see through an opaque barrier. While you can see into the Ethereal Plane, what you are looking at is not not *on* the Ethereal Plane, and if you could see them *from* there does not matter, as neither are you. + +### X-Ray Vision + +X-Ray Vision (as in the [ring](https://www.dndbeyond.com/magic-items/4738-ring-of-x-ray-vision)) allows you to + +> +> see into and through solid matter (...) To you, solid objects within that radius appear transparent and don't prevent light from passing through them +> +> +> + +The wall is not a solid object or solid matter, as it is made of insubstantial light that you can walk through, which you could not if it were solid. So X-Ray Vision does not allow you to see through it, either. + +### Vecna + +Could you use either as a player character if you tried to look through a Prismatic Wall? No. + +Could Vecna? Not by the official stat block that has been printed in the [Vecna Dossier](https://www.dndbeyond.com/claim/source/vecna) (where he does not even have X-Ray Vision, as he does not have the Hand or Eye of Vecna, he is said to be questing for them). However, the lore section there states that + +> +> More recently, Vecna decamped to the Outer Planes, where he grew so powerful that he became a god. +> +> +> + +And there are no printed rules for gods. Even without invoking their right to overrule anything, the DM can rule that he could see through the wall. And even for pre-apotheosis Vecna, they of course can rule so, because it's Vecna and because of their right to overrule. Your DM in any case did rule so, so your Vecna could.","RAW, vague. +----------- + +True sight and x-ray vision could either be *argued* to see through *Prismatic Wall* depending on various definitions of light, matter, ethereal, etc. However, D&D 5e is not a physics simulator. Neither *explicitly* states they see through 'planes of shimmering light' or w/e, yet they both talk about seeing through all kinds of stuff, so it's basically an argument either way. + +Whenever there's an argument about anything in D&D, it comes down to the DM's decision. That's in large part *why* you have a DM (as well as to apply structure and motivation to the story). What a DM decides is reasonable in that situation is up to the DM and their table's expectations, but, + +*Should* Vecna be able to see through his Prismatic Wall? +--------------------------------------------------------- + +Yes. + +He is Vecna." +17724172,"How to convert the string ""Thu Jul 18 13:20:12 GMT+05:30 2013"" in date in android? Using DateFormatter and SimpleDateFormatter throw an exception saying cannot parse the date format while using it to convert into date.",2013/07/18,"['https://Stackoverflow.com/questions/17724172', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1954375/']","``` +try { + String dateString = ""Thu Jul 18 13:20:12 GMT+05:30 2013""; + SimpleDateFormat sdf = new SimpleDateFormat(""EEE MMM dd HH:mm:ss zzzz yyyy""); + Date date = sdf.parse(dateString); +} catch (ParseException e) { + e.printStackTrace(); +} + +```","You can also do this: + +``` +SimpleDateFormat dateFormat = new SimpleDateFormat(""DD-MM-YYYY""); +Date dd = dateFormat.parse(""string"") + +```" +17724172,"How to convert the string ""Thu Jul 18 13:20:12 GMT+05:30 2013"" in date in android? Using DateFormatter and SimpleDateFormatter throw an exception saying cannot parse the date format while using it to convert into date.",2013/07/18,"['https://Stackoverflow.com/questions/17724172', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1954375/']","``` +try { + String dateString = ""Thu Jul 18 13:20:12 GMT+05:30 2013""; + SimpleDateFormat sdf = new SimpleDateFormat(""EEE MMM dd HH:mm:ss zzzz yyyy""); + Date date = sdf.parse(dateString); +} catch (ParseException e) { + e.printStackTrace(); +} + +```","This is how you can do: + +``` +try { + String dateString = ""Thu Jul 18 13:20:12 GMT+05:30 2013""; + + Date date = new SimpleDateFormat(""EEE MMM dd HH:mm:ss z yyyy"").parse(dateString ); + } + catch (ParseException e) + { + e.printStackTrace(); + } + +```" +17724172,"How to convert the string ""Thu Jul 18 13:20:12 GMT+05:30 2013"" in date in android? Using DateFormatter and SimpleDateFormatter throw an exception saying cannot parse the date format while using it to convert into date.",2013/07/18,"['https://Stackoverflow.com/questions/17724172', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1954375/']","``` +SimpleDateFormat formatter = new SimpleDateFormat(""EEE MMM dd HH:mm:ss zzzz yyyy""); + try { + String dateString = ""Thu Jul 18 13:20:12 GMT+05:30 2013""; + Date date = formatter.parse(dateString); + } catch (Exception e) { + e.printStackTrace(); + } + +``` + +this is how we doing in android..but if you can post your code then can help you precisely","You can also do this: + +``` +SimpleDateFormat dateFormat = new SimpleDateFormat(""DD-MM-YYYY""); +Date dd = dateFormat.parse(""string"") + +```" +17724172,"How to convert the string ""Thu Jul 18 13:20:12 GMT+05:30 2013"" in date in android? Using DateFormatter and SimpleDateFormatter throw an exception saying cannot parse the date format while using it to convert into date.",2013/07/18,"['https://Stackoverflow.com/questions/17724172', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1954375/']","``` +SimpleDateFormat formatter = new SimpleDateFormat(""EEE MMM dd HH:mm:ss zzzz yyyy""); + try { + String dateString = ""Thu Jul 18 13:20:12 GMT+05:30 2013""; + Date date = formatter.parse(dateString); + } catch (Exception e) { + e.printStackTrace(); + } + +``` + +this is how we doing in android..but if you can post your code then can help you precisely","This is how you can do: + +``` +try { + String dateString = ""Thu Jul 18 13:20:12 GMT+05:30 2013""; + + Date date = new SimpleDateFormat(""EEE MMM dd HH:mm:ss z yyyy"").parse(dateString ); + } + catch (ParseException e) + { + e.printStackTrace(); + } + +```" +73306,"Tables allow us to easily see how **2** variables (for example ""Employee"" and ""Time"") correlate. For me the main benefit of this view is that you can easily find answers to two kinds of questions. Like: + +* What is employee X been doing since he started working for us? +* What is everybody doing today? + +My question: is there a way to create an equally easy to use view that does the same for **3** variables (for example ""Employee"", ""Time"" and ""Project"")?",2015/02/09,"['https://ux.stackexchange.com/questions/73306', 'https://ux.stackexchange.com', 'https://ux.stackexchange.com/users/28176/']","While it can be computationaly and mathematically complex, the concept of heat maps can help you out here. + +The point of a heat map is you add a third dimension to a 2 dimensional plot not by actually having an additional axis, but by using color. For example, your X axis could be ""employees"", your Y axis could be ""project"", and time could be represented by color along the XY plane. One color could can mean ""more time"" while another color can mean ""little time"". + +In the fictious example below, a certain epmloyee has spent a high amount of time on a certain project, less time on closely related projects and no time on unrelated projects. + +![enter image description here](https://i.stack.imgur.com/qsJwf.jpg) + +By using additional colors, a 4th or 5th dimension can be added. For example, all hues of blue can mean ""time"", whereas all hues of red could mean ""resource spent"". by combining these colors, you get purple. hues of purple can mean time & resources spent. In my opinion, the complexity (both for a developer as for a user) tend to increase dramatically by each additional dimension added. I don't have an official study to back up that claim, it's just my own experience.","There was a similar question posted a little bit back about visualization combinations (see [Best visualization for combinations](https://ux.stackexchange.com/questions/72605/best-visualization-for-combinations/72683#72683)). In addition to the heat map posted above you also have a couple other choices which are similar but distinct. + +Contour Plot +============ + +A contour plot is very similar to a heat map except that it displays the boundary of the regions. There is a bit of variance in whether or not folks plot the regions with color simply display the boundary. The option gets its name from topographical maps where it truly is showing the contour of the land. It works equally well for displaying 3 pieces of data that are related. + +* This is the stock example for d3. +* Here is a decent example of this showing how to do it in d3 and R (picture below is R). +![enter image description here](https://i.stack.imgur.com/9S5mX.png) + +Standard scatter plot with variable markers +=========================================== + +This option is just an extension of the standard 2d scatter plot. Instead of just placing a dot in the region for the data point, you encode additional information in the marker. Things that can be used include: + +* Color to display a continuous variable +* Size to display a continuous variable (be careful with this; people can have difficulty perceiving quantitative relationships between sizes of certain objects) +* Marker shape can be used to encode a discrete or categorical variable + +Multiple scatter plots +====================== + +If you are looking to show relationships between pairs of multiple variables, you can also use the matrix or multiple scatter plot approach. This works well for finding relationships between pairs of large groups of variables. + +* Here is an example of that done with d3. +![multiple scatter plots](https://i.stack.imgur.com/qRph6.png) + +Parallel Coordinates Plot +========================= + +The parallel coordinates plot works well when you have more than 3 variables to show, but it can work well for 3 also. Its specialty is that it allows for filtering and interaction which can be used to select data for other visualizations. It is also well geared toward encoding color and other data across the lines. It is very compact in space as well considering the number of variables that can be displayed. It is less useful for relationships unless they come in groups. + +* This is one of the best combo visualizations which shows the parallel coordinates and underlying data below. . The source for this is coming from . +![par coords example](https://i.stack.imgur.com/ajC5P.png)" +4442828,"I'm playing with the latest Entity Framework CTP 5 release and building a simple asp.net MVC blog where I just have two tables: Post and Comments. This is done entirely in POCO, I just need help on the DbContext part, where I need it to be unit testable (using IDbSet?) and I need a simple/generic repository pattern for add, update, delete, retrieval. Any help is appreciated. + +Thanks.",2010/12/14,"['https://Stackoverflow.com/questions/4442828', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/248480/']","Start with you DbContext, create a new file called Database.cs: + +**Database.cs** + +``` +public class Database : DbContext + { + + private IDbSet _posts; + + public IDbSet Posts { + get { return _posts ?? (_posts = DbSet()); } + } + + public virtual IDbSet DbSet() where T : class { + return Set(); + } + public virtual void Commit() { + base.SaveChanges(); + } +} + +``` + +Define a IDatabaseFactory and implement it with DatabaseFactory: + +**IDatabaseFactory.cs** + +``` +public interface IDatabaseFactory : IDisposable + { + Database Get(); + } + +``` + +**DatabaseFactory.cs** + +``` +public class DatabaseFactory : Disposable, IDatabaseFactory { + private Database _database; + public Database Get() { + return _database ?? (_database = new Database()); + } + protected override void DisposeCore() { + if (_database != null) + _database.Dispose(); + } + } + +``` + +Disposable extension method: + +**Disposable.cs** + +``` +public class Disposable : IDisposable + { + private bool isDisposed; + + ~Disposable() + { + Dispose(false); + } + + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } + private void Dispose(bool disposing) + { + if(!isDisposed && disposing) + { + DisposeCore(); + } + + isDisposed = true; + } + + protected virtual void DisposeCore() + { + } + } + +``` + +Now we can define our IRepository and our RepositoryBase + +**IRepository.cs** + +``` +public interface IRepository where T : class +{ + void Add(T entity); + void Delete(T entity); + void Update(T entity); + T GetById(long Id); + IEnumerable All(); + IEnumerable AllReadOnly(); +} + +``` + +**RepositoryBase.cs** + +``` +public abstract class RepositoryBase where T : class + { + private Database _database; + private readonly IDbSet _dbset; + protected RepositoryBase(IDatabaseFactory databaseFactory) + { + DatabaseFactory = databaseFactory; + _dbset = Database.Set(); + } + + protected IDatabaseFactory DatabaseFactory + { + get; private set; + } + + protected Database Database + { + get { return _database ?? (_database = DatabaseFactory.Get()); } + } + public virtual void Add(T entity) + { + _dbset.Add(entity); + } + + public virtual void Delete(T entity) + { + _dbset.Remove(entity); + } + + public virtual void Update(T entity) + { + _database.Entry(entity).State = EntityState.Modified; + } + public virtual T GetById(long id) + { + return _dbset.Find(id); + } + + public virtual IEnumerable All() + { + return _dbset.ToList(); + } + public virtual IEnumerable AllReadOnly() + { + return _dbset.AsNoTracking().ToList(); + } + } + +``` + +Now you can create your IPostRepository and PostRepository: + +**IPostRepository.cs** + +``` + public interface IPostRepository : IRepository + { + //Add custom methods here if needed + Post ByTitle(string title); + } + +``` + +**PostRepository.cs** + +``` + public class PostRepository : RepositoryBase, IPostRepository + { + public PostRepository(IDatabaseFactory databaseFactory) : base(databaseFactory) + { + } + public Post ByTitle(string title) { + return base.Database.Posts.Single(x => x.Title == title); + } + } + +``` + +Lastly, the UoW: + +**IUnitOfWork.cs** + +``` +public interface IUnitOfWork +{ + void Commit(); +} + +``` + +**UnitOfWork.cs** + +``` +private readonly IDatabaseFactory _databaseFactory; +private Database _database; + +public UnitOfWork(IDatabaseFactory databaseFactory) +{ + _databaseFactory = databaseFactory; +} + +protected Database Database +{ + get { return _database ?? (_database = _databaseFactory.Get()); } +} + +public void Commit() +{ + Database.Commit(); +} + +``` + +**Using in your controller:** + +``` +private readonly IPostRepository _postRepository; +private readonly IUnitOfWork_unitOfWork; + + public PostController(IPostRepository postRepository, IUnitOfWork unitOfWork) + { + _postRepository = postRepository; + _unitOfWork = unitOfWork; + } + + public ActionResult Add(Post post) { + _postRepository.Add(post); + _unitOfWork.Commit(); + } + +``` + +You will need to use an IoC container like StructureMap to make this work. You can install structure map via NuGet, or if you are using MVC 3, you can install the StructureMap-MVC NuGet package. (Links Below) + +[Install-Package StructureMap.MVC4](http://nuget.org/List/Packages/StructureMap.MVC4) + +[Install-Package StructureMap.MVC3](http://nuget.org/List/Packages/StructureMap.MVC3) + +[Install-Package Structuremap](http://nuget.org/List/Packages/structuremap) + +If you have questions just let me know. Hope it helps.","The only thing I'd do differently is in the implementation, i.e. expose the IPostRepository in the service layer and have an interface field of type IPostService in the controller just as another layer of abstraction but otherwise this is a good example - nice one, Paul." +4442828,"I'm playing with the latest Entity Framework CTP 5 release and building a simple asp.net MVC blog where I just have two tables: Post and Comments. This is done entirely in POCO, I just need help on the DbContext part, where I need it to be unit testable (using IDbSet?) and I need a simple/generic repository pattern for add, update, delete, retrieval. Any help is appreciated. + +Thanks.",2010/12/14,"['https://Stackoverflow.com/questions/4442828', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/248480/']","Start with you DbContext, create a new file called Database.cs: + +**Database.cs** + +``` +public class Database : DbContext + { + + private IDbSet _posts; + + public IDbSet Posts { + get { return _posts ?? (_posts = DbSet()); } + } + + public virtual IDbSet DbSet() where T : class { + return Set(); + } + public virtual void Commit() { + base.SaveChanges(); + } +} + +``` + +Define a IDatabaseFactory and implement it with DatabaseFactory: + +**IDatabaseFactory.cs** + +``` +public interface IDatabaseFactory : IDisposable + { + Database Get(); + } + +``` + +**DatabaseFactory.cs** + +``` +public class DatabaseFactory : Disposable, IDatabaseFactory { + private Database _database; + public Database Get() { + return _database ?? (_database = new Database()); + } + protected override void DisposeCore() { + if (_database != null) + _database.Dispose(); + } + } + +``` + +Disposable extension method: + +**Disposable.cs** + +``` +public class Disposable : IDisposable + { + private bool isDisposed; + + ~Disposable() + { + Dispose(false); + } + + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } + private void Dispose(bool disposing) + { + if(!isDisposed && disposing) + { + DisposeCore(); + } + + isDisposed = true; + } + + protected virtual void DisposeCore() + { + } + } + +``` + +Now we can define our IRepository and our RepositoryBase + +**IRepository.cs** + +``` +public interface IRepository where T : class +{ + void Add(T entity); + void Delete(T entity); + void Update(T entity); + T GetById(long Id); + IEnumerable All(); + IEnumerable AllReadOnly(); +} + +``` + +**RepositoryBase.cs** + +``` +public abstract class RepositoryBase where T : class + { + private Database _database; + private readonly IDbSet _dbset; + protected RepositoryBase(IDatabaseFactory databaseFactory) + { + DatabaseFactory = databaseFactory; + _dbset = Database.Set(); + } + + protected IDatabaseFactory DatabaseFactory + { + get; private set; + } + + protected Database Database + { + get { return _database ?? (_database = DatabaseFactory.Get()); } + } + public virtual void Add(T entity) + { + _dbset.Add(entity); + } + + public virtual void Delete(T entity) + { + _dbset.Remove(entity); + } + + public virtual void Update(T entity) + { + _database.Entry(entity).State = EntityState.Modified; + } + public virtual T GetById(long id) + { + return _dbset.Find(id); + } + + public virtual IEnumerable All() + { + return _dbset.ToList(); + } + public virtual IEnumerable AllReadOnly() + { + return _dbset.AsNoTracking().ToList(); + } + } + +``` + +Now you can create your IPostRepository and PostRepository: + +**IPostRepository.cs** + +``` + public interface IPostRepository : IRepository + { + //Add custom methods here if needed + Post ByTitle(string title); + } + +``` + +**PostRepository.cs** + +``` + public class PostRepository : RepositoryBase, IPostRepository + { + public PostRepository(IDatabaseFactory databaseFactory) : base(databaseFactory) + { + } + public Post ByTitle(string title) { + return base.Database.Posts.Single(x => x.Title == title); + } + } + +``` + +Lastly, the UoW: + +**IUnitOfWork.cs** + +``` +public interface IUnitOfWork +{ + void Commit(); +} + +``` + +**UnitOfWork.cs** + +``` +private readonly IDatabaseFactory _databaseFactory; +private Database _database; + +public UnitOfWork(IDatabaseFactory databaseFactory) +{ + _databaseFactory = databaseFactory; +} + +protected Database Database +{ + get { return _database ?? (_database = _databaseFactory.Get()); } +} + +public void Commit() +{ + Database.Commit(); +} + +``` + +**Using in your controller:** + +``` +private readonly IPostRepository _postRepository; +private readonly IUnitOfWork_unitOfWork; + + public PostController(IPostRepository postRepository, IUnitOfWork unitOfWork) + { + _postRepository = postRepository; + _unitOfWork = unitOfWork; + } + + public ActionResult Add(Post post) { + _postRepository.Add(post); + _unitOfWork.Commit(); + } + +``` + +You will need to use an IoC container like StructureMap to make this work. You can install structure map via NuGet, or if you are using MVC 3, you can install the StructureMap-MVC NuGet package. (Links Below) + +[Install-Package StructureMap.MVC4](http://nuget.org/List/Packages/StructureMap.MVC4) + +[Install-Package StructureMap.MVC3](http://nuget.org/List/Packages/StructureMap.MVC3) + +[Install-Package Structuremap](http://nuget.org/List/Packages/structuremap) + +If you have questions just let me know. Hope it helps.","I just love this in-depth article about Entity Framework 4 POCO, Repository and Specification Pattern + +" +4442828,"I'm playing with the latest Entity Framework CTP 5 release and building a simple asp.net MVC blog where I just have two tables: Post and Comments. This is done entirely in POCO, I just need help on the DbContext part, where I need it to be unit testable (using IDbSet?) and I need a simple/generic repository pattern for add, update, delete, retrieval. Any help is appreciated. + +Thanks.",2010/12/14,"['https://Stackoverflow.com/questions/4442828', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/248480/']","I just love this in-depth article about Entity Framework 4 POCO, Repository and Specification Pattern + +","The only thing I'd do differently is in the implementation, i.e. expose the IPostRepository in the service layer and have an interface field of type IPostService in the controller just as another layer of abstraction but otherwise this is a good example - nice one, Paul." +2441903,"factorize $$x^4+4abx^2-(a^2-b^2)^2$$ +I am getting problem in factoring this. Anyone help me. I tried synthetic division but that doesn't work. Can anyone suggest me any other ways",2017/09/23,"['https://math.stackexchange.com/questions/2441903', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/483811/']","$\color{red}{x^4-4abx^2}-(a^2-b^2)^2$ + +The red part is *almost* a square. What we need is adding $4a^2b^2$ + +But if we add then we modify the polynomial and this is not legal, so we must subtract the same quantity to be fair. Therefore we get + +$\color{red}{x^4-4abx^2+4a^2b^2}\color{blue}{-4a^2b^2-(a^2-b^2)^2}=\color{red}{x^4-4abx^2+4a^2b^2}\color{blue}{-a^4-2 a^2 b^2-b^4}=$ + +$=\color{red}{x^4-4abx^2+4a^2b^2}-\color{blue}{(a^4+2 a^2 b^2+b^4)}=$ + +The red is perfect square and the blue is a perfect square either so we can write + +$=\color{red}{(x^2-2ab)^2}-\color{blue}{(a^2+b^2)^2}=$ + +Now remember the basic $P^2-Q^2=(P+Q)(P-Q)$ + +here $P\to x^2-2ab$ and $Q\to a^2+b^2$ so we have + +$(\color{red}{(x^2-2ab)}+\color{blue}{(a^2+b^2)})(\color{red}{(x^2-2ab)}-\color{blue}{(a^2+b^2)})=\\=(x^2-2ab+a^2+b^2)(x^2-2ab-a^2-b^2)$ + +We are almost done + +The second parenthesis can be written in this way + +$x^2-(2ab+a^2+b^2)=x^2-(a+b)^2=(x+a+b)(x-a-b)$ + +Now the factoring is complete + +$$x^4-4abx^2-(a^2-b^2)^2=(x^2-2ab+a^2+b^2)(x+a+b)(x-a-b)$$ + +I tried to explain best than I could + +Hope it is useful","HINT: $$x=a+b$$ and $$x=-(a+b)$$ are two Solutions +and now you can divide your equation $$x^4-4abx^2-(a^2-b^2)^2$$ by $$x^2+(a+b)^2$$ +note that your equation can factorized into $$- \left( {a}^{2}-2\,ab+{b}^{2}+{x}^{2} \right) \left( b+a+x \right) + \left( b+a-x \right) +$$" +20254346,"I'm trying to save my list of images to a folder determined by the user, in this case I have this list. + +``` +List ListOfSystemDrawingImage = new List(); + + ListOfSystemDrawingImage.Add(MatrizWPF.Properties.Resources.Earth); + ListOfSystemDrawingImage.Add(MatrizWPF.Properties.Resources.Grass); + ListOfSystemDrawingImage.Add(MatrizWPF.Properties.Resources.Rabbit); + ListOfSystemDrawingImage.Add(MatrizWPF.Properties.Resources.Wolf); + +``` + +Where Earth, Grass, Rabbit and Wolf are PNG images called the same way. + +My question is, How can I store my + +``` +List listOfSystemDrawingImage = new List(); + +``` + +To a folder determined by the user?",2013/11/27,"['https://Stackoverflow.com/questions/20254346', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3023107/']","You can use `System.Windows.Forms.FolderBrowserDialog` for the user to pick the destination folder and use the `Image.Save` to save the image in the format of your chioce + +Example: + +``` +List listOfSystemDrawingImage = new List(); + +System.Windows.Forms.FolderBrowserDialog dialog = new System.Windows.Forms.FolderBrowserDialog(); +if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) +{ + int index = 0; + foreach (var image in listOfSystemDrawingImage) + { + image.Save(string.Format(""{0}\\Image{1}.png"", dialog.SelectedPath, index), System.Drawing.Imaging.ImageFormat.Png); + index++; + } +} + +``` + +**However, I do not recommend mixing Window.Forms and System.Drawing with WPF,**",If you have the names you can just convert the image to a byte array and then use `File.WriteAllBytes`. Make sure the file name you pass toe `WriteAllBytes` has a .png extension. There's probably a simpler way but I don't really deal with media like that as much as raw data so this is what comes to mind for me. +20254346,"I'm trying to save my list of images to a folder determined by the user, in this case I have this list. + +``` +List ListOfSystemDrawingImage = new List(); + + ListOfSystemDrawingImage.Add(MatrizWPF.Properties.Resources.Earth); + ListOfSystemDrawingImage.Add(MatrizWPF.Properties.Resources.Grass); + ListOfSystemDrawingImage.Add(MatrizWPF.Properties.Resources.Rabbit); + ListOfSystemDrawingImage.Add(MatrizWPF.Properties.Resources.Wolf); + +``` + +Where Earth, Grass, Rabbit and Wolf are PNG images called the same way. + +My question is, How can I store my + +``` +List listOfSystemDrawingImage = new List(); + +``` + +To a folder determined by the user?",2013/11/27,"['https://Stackoverflow.com/questions/20254346', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3023107/']","You can use `System.Windows.Forms.FolderBrowserDialog` for the user to pick the destination folder and use the `Image.Save` to save the image in the format of your chioce + +Example: + +``` +List listOfSystemDrawingImage = new List(); + +System.Windows.Forms.FolderBrowserDialog dialog = new System.Windows.Forms.FolderBrowserDialog(); +if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) +{ + int index = 0; + foreach (var image in listOfSystemDrawingImage) + { + image.Save(string.Format(""{0}\\Image{1}.png"", dialog.SelectedPath, index), System.Drawing.Imaging.ImageFormat.Png); + index++; + } +} + +``` + +**However, I do not recommend mixing Window.Forms and System.Drawing with WPF,**","You can save the list of `System.Drawing.Image` this way: + +``` +string folder = @""C:\temp""; +int count = 1; +foreach(Image image in listOfSystemDrawingImage) +{ + string path = Path.Combine(folder, String.Format(""image{0}.png"", count)); + image.Save(path); + count++; +} + +``` + +I don't know where you store the image names, so I just called them image1.png, image2.png, and so on." +81063,"I submitted an article around 11 months ago to a SCI journal and another article around 5 months ago in another SCI journal. The second article cited the first article which was under review for 6 months at the time of submission of second article. Recently, we got acceptance letter for 2nd article while 1st article is still under review. +What action should we take? remove the citation in 2nd article and cite the 2nd article in 1st article or we stay with the current situation. but what if our 1st article got rejection?",2016/12/05,"['https://academia.stackexchange.com/questions/81063', 'https://academia.stackexchange.com', 'https://academia.stackexchange.com/users/9709/']","If I understand correctly, this is your situation: + +* Paper 1 was submitted for review 11 months ago +* Paper 2 was submitted for review six months later. +* Paper 2 was accepted for publication. Paper 1 is still under review. + +Presumably, Paper 2 cites Paper 1 as being ""submitted"". The present version of Paper 1 does not cite Paper 2 because Paper 2 was not in existence when Paper 1 was submitted. + +Are these correct? If so, here are some thoughts about your questions: + +**Should you continue to cite Paper 1 in Paper 2?** + +I would. The fact that Paper 1 is still under review is out of your control. In fact, its final disposition is also up in the air. Nevertheless, Paper 2 uses information derived from Paper 1, hence the need to cite it. That Paper 2 was accepted with the citation to Paper 1 is important evidence that the reviewers and the editors thought that it was appropriate, despite the ""submitted"" tag. + +**Should you remove the citation of Paper 1 in Paper 2?** + +I wouldn't do this, unless there was a material change in your manuscript. If the parts of Paper 2 that depend on Paper 1 were lost in revision, then fine. However, it is not a good idea to eliminate references simply because of publication status. + +**Should you cite Paper 2 in Paper 1?** + +You should only cite papers that support your statements. Frivolously citing one paper of yours just because it was published is a rather trivial reason. However, if you genuinely feel that Paper 2 has substantial contributions to Paper 1, then this should be fine. You would do this in the revision stage. Be aware, though, that alert editorial staff may review this change with skepticism. + +**If you retain the citation of Paper 1 in Paper 2 and Paper 1 gets rejected, then what happens?** + +Generally, there's nothing you can do about this. Journals still operate as if the manuscripts were static entities. That is to say, once a final version has been approved at the galley stage, no changes can be made. Paper 1 will always be cited in Paper 2 as being ""submitted"" in perpetuity. There are some publishing models now that account for this fluidity in publication status, although there are not widespread, and rather experimental. Say, for example, that you cited the work of Doorman (2014) and your work was published in 2015. In 2016, Doorman was found to have committed research misconduct and his 2014 publication was retracted because all the data were fabricated. Well, your 2015 publication would still cite Doorman 2014. There are no easy solutions to this issue as yet. + +Good luck.","If the second article depends in some substantive way in the material from the first, the second should cite the first, according to the journal's policy for material under review. (Different journals tend to handle such matters in different ways.) If there is no real dependence, I would suggest omitting the citation, and having the first paper, when it gets published, cite the second. + +Having each paper cite the others might be deemed less than optimal, but that does happen. If you don't have a problem with the circular citation arrangement, I would include a citation to the second, published article in the first, even if the second already cites the first." +81063,"I submitted an article around 11 months ago to a SCI journal and another article around 5 months ago in another SCI journal. The second article cited the first article which was under review for 6 months at the time of submission of second article. Recently, we got acceptance letter for 2nd article while 1st article is still under review. +What action should we take? remove the citation in 2nd article and cite the 2nd article in 1st article or we stay with the current situation. but what if our 1st article got rejection?",2016/12/05,"['https://academia.stackexchange.com/questions/81063', 'https://academia.stackexchange.com', 'https://academia.stackexchange.com/users/9709/']","If the second article depends in some substantive way in the material from the first, the second should cite the first, according to the journal's policy for material under review. (Different journals tend to handle such matters in different ways.) If there is no real dependence, I would suggest omitting the citation, and having the first paper, when it gets published, cite the second. + +Having each paper cite the others might be deemed less than optimal, but that does happen. If you don't have a problem with the circular citation arrangement, I would include a citation to the second, published article in the first, even if the second already cites the first.","The traditional method to avoid these messes was to refer to any work as ***forthcoming*** until such a time as the work having definitely and definitively entered the literature. So yes, it did happen that certain papers were eternally immortalised as ""forthcoming"" - and as a reader you could be in for a bit of detective work (this was back when you had to physically schlepp to an actual brick and mortar library). A fun and not infrequent intermediate case arose when a promise was made or a claim was staked for the forthcoming paper, which, once it did come forth, was never made good on! Preprints were always a patchwork solution (as physical copies could be hard to track down), but luckily now we have archiv, BioArchiv and the like. Authors' personal webpages may help, but beware, as different authors may link to different versions of the work." +81063,"I submitted an article around 11 months ago to a SCI journal and another article around 5 months ago in another SCI journal. The second article cited the first article which was under review for 6 months at the time of submission of second article. Recently, we got acceptance letter for 2nd article while 1st article is still under review. +What action should we take? remove the citation in 2nd article and cite the 2nd article in 1st article or we stay with the current situation. but what if our 1st article got rejection?",2016/12/05,"['https://academia.stackexchange.com/questions/81063', 'https://academia.stackexchange.com', 'https://academia.stackexchange.com/users/9709/']","If I understand correctly, this is your situation: + +* Paper 1 was submitted for review 11 months ago +* Paper 2 was submitted for review six months later. +* Paper 2 was accepted for publication. Paper 1 is still under review. + +Presumably, Paper 2 cites Paper 1 as being ""submitted"". The present version of Paper 1 does not cite Paper 2 because Paper 2 was not in existence when Paper 1 was submitted. + +Are these correct? If so, here are some thoughts about your questions: + +**Should you continue to cite Paper 1 in Paper 2?** + +I would. The fact that Paper 1 is still under review is out of your control. In fact, its final disposition is also up in the air. Nevertheless, Paper 2 uses information derived from Paper 1, hence the need to cite it. That Paper 2 was accepted with the citation to Paper 1 is important evidence that the reviewers and the editors thought that it was appropriate, despite the ""submitted"" tag. + +**Should you remove the citation of Paper 1 in Paper 2?** + +I wouldn't do this, unless there was a material change in your manuscript. If the parts of Paper 2 that depend on Paper 1 were lost in revision, then fine. However, it is not a good idea to eliminate references simply because of publication status. + +**Should you cite Paper 2 in Paper 1?** + +You should only cite papers that support your statements. Frivolously citing one paper of yours just because it was published is a rather trivial reason. However, if you genuinely feel that Paper 2 has substantial contributions to Paper 1, then this should be fine. You would do this in the revision stage. Be aware, though, that alert editorial staff may review this change with skepticism. + +**If you retain the citation of Paper 1 in Paper 2 and Paper 1 gets rejected, then what happens?** + +Generally, there's nothing you can do about this. Journals still operate as if the manuscripts were static entities. That is to say, once a final version has been approved at the galley stage, no changes can be made. Paper 1 will always be cited in Paper 2 as being ""submitted"" in perpetuity. There are some publishing models now that account for this fluidity in publication status, although there are not widespread, and rather experimental. Say, for example, that you cited the work of Doorman (2014) and your work was published in 2015. In 2016, Doorman was found to have committed research misconduct and his 2014 publication was retracted because all the data were fabricated. Well, your 2015 publication would still cite Doorman 2014. There are no easy solutions to this issue as yet. + +Good luck.","The traditional method to avoid these messes was to refer to any work as ***forthcoming*** until such a time as the work having definitely and definitively entered the literature. So yes, it did happen that certain papers were eternally immortalised as ""forthcoming"" - and as a reader you could be in for a bit of detective work (this was back when you had to physically schlepp to an actual brick and mortar library). A fun and not infrequent intermediate case arose when a promise was made or a claim was staked for the forthcoming paper, which, once it did come forth, was never made good on! Preprints were always a patchwork solution (as physical copies could be hard to track down), but luckily now we have archiv, BioArchiv and the like. Authors' personal webpages may help, but beware, as different authors may link to different versions of the work." +114561,"I am a GIS beginner, and I have a question about how to get the distance between two points in meters instead of decimal degree. + +In QGIS 2.4 I have a project with two point layers (in WGS84). From both layers I used I wanted to have the distance in meters between the two closest point between the layers. So what I did: Vector -> analyse tools -> distance Matrix, ticked the box ""only nearest (k) target points: 1"". This created a CSV file with all the distances, but in the wrong units. + +So I looked it up on the internet and I found out two things: + +* I have to set my CRV in a projected coordinate system (like a UTM zone). +* And I have to tick or untick the box with ""on the fly"" --> which I cannot find in QGIS2.4 Project --> project setting --> CRS. + +I tried the first option. I tried to set the layers in UTM 29 ZONE IRENET95, EPSG: 2158 by ""save as"" --> add new vector layer. It still gives the distance in the wrong units. My project only contains point in southwest Ireland, so that is why I picked this projection. Or should I project it in a different projection? + +I also tried to find a converter to convert the decimal degree outcome to meters, but I did not find any. I guess there is none. Am I right? + +For me it seems like there must me an easy solution, but I did not manage to find one. I think I am doing something wrong with setting the layers in a different projection.",2014/09/21,"['https://gis.stackexchange.com/questions/114561', 'https://gis.stackexchange.com', 'https://gis.stackexchange.com/users/37252/']","gdal\_Calc.py can do that, a reclass + +Something like.. + +gdal\_calc.py -A filename.tiff --outfile=filename.tiff +--calc=""A\*(A>3)"" --NoDataValue=0 --calc=""1\*(A<3) + +See this one + +[gdal\_calc.py raster reclass equivalent of ArcGIS reclass or r.reclass in grass](https://gis.stackexchange.com/questions/100348/gdal-calc-py-raster-reclass-equivalent-of-arcgis-reclass-or-r-reclass-in-grass)","If the min value is consistent - like a no data value, you might be able to use the snodata option and specify the value you want ignore. As listed in the doc for [gdal\_contour](http://www.gdal.org/gdal_contour.html)" +2127460,"Prove +$$I=\int\_0^\infty {\frac{x}{{\left( {x + 1} \right)\sqrt {4{x^4} + 8{x^3} + 12{x^2} + 8x + 1} }}dx} = \frac{{\ln 3}}{2} - \frac{{\ln 2}}{3}.$$ + +First note that +$$4{x^4} + 8{x^3} + 12{x^2} + 8x + 1 = 4{\left( {{x^2} + x + 1} \right)^2} - 3,$$ +we let +$${x^2} + x + 1 = \frac{{\sqrt 3 }}{{2\cos \theta }} \Rightarrow x = \sqrt { - \frac{3}{4} + \frac{{\sqrt 3 }}{{2\cos \theta }}} - \frac{1}{2},$$ +then +$$I=\frac{1}{2}\int\_{\frac{\pi }{6}}^{\frac{\pi }{2}} {\frac{{\left( {\sqrt {2\sqrt 3 \sec \theta - 3} - 1} \right)\sec \theta }}{{\left( {\sqrt {2\sqrt 3 \sec \theta - 3} + 1} \right)\sqrt {2\sqrt 3 \sec \theta - 3} }}d\theta } .$$ +we have +\begin{align\*} +&\frac{{\left( {\sqrt {2\sqrt 3 \sec \theta - 3} - 1} \right)\sec \theta }}{{\left( {\sqrt {2\sqrt 3 \sec \theta - 3} + 1} \right)\sqrt {2\sqrt 3 \sec \theta - 3} }} = \frac{{{{\left( {\sqrt {2\sqrt 3 \sec \theta - 3} - 1} \right)}^2}\sec \theta }}{{\left( {2\sqrt 3 \sec \theta - 4} \right)\sqrt {2\sqrt 3 \sec \theta - 3} }}\\ + =& \frac{{\left( {2\sqrt 3 \sec \theta - 2 - 2\sqrt {2\sqrt 3 \sec \theta - 3} } \right)\sec \theta }}{{\left( {2\sqrt 3 \sec \theta - 4} \right)\sqrt {2\sqrt 3 \sec \theta - 3} }} = \frac{{\left( {\sqrt 3 \sec \theta - 1 - \sqrt {2\sqrt 3 \sec \theta - 3} } \right)\sec \theta }}{{\left( {\sqrt 3 \sec \theta - 2} \right)\sqrt {2\sqrt 3 \sec \theta - 3} }}\\ + = &\frac{{\left( {\sqrt 3 \sec \theta - 1} \right)\sec \theta }}{{\left( {\sqrt 3 \sec \theta - 2} \right)\sqrt {2\sqrt 3 \sec \theta - 3} }} - \frac{{\sec \theta }}{{\sqrt 3 \sec \theta - 2}}. +\end{align\*} +and +$$\int {\frac{{\sec \theta }}{{\sqrt 3 \sec \theta - 2}}d\theta } = \ln \frac{{\left( {2 + \sqrt 3 } \right)\tan \frac{\theta }{2} - 1}}{{\left( {2 + \sqrt 3 } \right)\tan \frac{\theta }{2} + 1}}+ C.$$ +while +\begin{align\*}&\int {\frac{{\left( {\sqrt 3 \sec \theta - 1} \right)\sec \theta }}{{\left( {\sqrt 3 \sec \theta - 2} \right)\sqrt {2\sqrt 3 \sec \theta - 3} }}d\theta } = \int {\frac{{\sqrt 3 - \cos \theta }}{{\left( {\sqrt 3 - 2\cos \theta } \right)\sqrt {2\sqrt 3 \cos \theta - 3{{\left( {\cos \theta } \right)}^2}} }}d\theta } \\ + = &\frac{1}{2}\int {\frac{1}{{\sqrt {2\sqrt 3 \cos \theta - 3{{\left( {\cos \theta } \right)}^2}} }}d\theta } + \frac{{\sqrt 3 }}{2}\int {\frac{1}{{\left( {\sqrt 3 - 2\cos \theta } \right)\sqrt {2\sqrt 3 \cos \theta - 3{{\left( {\cos \theta } \right)}^2}} }}d\theta } . +\end{align\*} +But how can we continue? It is related to elliptic integral.",2017/02/03,"['https://math.stackexchange.com/questions/2127460', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/165013/']","This is a pseudo-elliptic integral, it has an elementary anti-derivative: + +$$\int \frac{x}{(x+1)\sqrt{4x^4+8x^3+12x^2+8x+1}} dx = \frac{\ln\left[P(x)+Q(x)\sqrt{4x^4+8x^3+12x^2+8x+1}\right]}{6} - \ln(x+1) + C$$ + +where $$P(x) = 112x^6+360x^5+624x^4+772x^3+612x^2+258x+43$$ +and +$$Q(x) = 52x^4+92x^3+30x^2-22x-11$$ + +To obtain this answer, just follow the systematic method of symbolic integration over simple algebraic extension. Alternatively, you can throw it to a CAS with Risch algorithm implemented (**not Mathematica**), a convenient software is the online **Axiom sandbox**.","**HINT 1** + +$$x=2x+1-(x+1),$$ +so +$$I=\frac12\int\_0^\infty\frac{(2x+1)dx}{(x+1)\sqrt{(x^2+x+1)^2-\frac34}} - \frac12\int\_0^\infty\frac{(2x+1)dx}{(2x+1)\sqrt{(x^2+x+1)^2-\frac34}}.$$ + +**HINT 2** + +$$(2x+1)dx = d(x^2+x+1) = \frac{\sqrt3}2d\sec\theta$$" +2514,"I am trying to start `carthagenet.sh` in RPC mode on Ubuntu 18.04 + +``` +$ ./carthagenet.sh start --rpc-port 8732 + +``` + +It appears to start fine: + +``` +v7.0: Pulling from tezos/tezos +Digest: sha256:da126e8d6bf137a9b326c3992c0e464622b94e2ee42b7d311df158212b8ae153 +Status: Image is up to date for tezos/tezos:v7.0 +docker.io/tezos/tezos:v7.0 +Creating network ""carthagenet_default"" with the default driver +Creating carthagenet_node_1 ... done +Creating carthagenet_upgrader_1 ... done +Creating carthagenet_baker-006-PsCARTHA-test_1 ... done +Creating carthagenet_endorser-alpha-test_1 ... done +Creating carthagenet_endorser-006-PsCARTHA_1 ... done +Creating carthagenet_baker-006-PsCARTHA_1 ... done +Creating carthagenet_accuser-alpha_1 ... done +Creating carthagenet_accuser-006-PsCARTHA-test_1 ... done +Creating carthagenet_accuser-alpha-test_1 ... done +Creating carthagenet_endorser-006-PsCARTHA-test_1 ... done +Creating carthagenet_baker-alpha-test_1 ... done +Creating carthagenet_endorser-alpha_1 ... done +Creating carthagenet_baker-alpha_1 ... done +Creating carthagenet_accuser-006-PsCARTHA_1 ... done + +``` + +However, as soon as I run any command I get an error: + +``` +$ ./carthagenet.sh client list known addresses +Error response from daemon: Container 9920d6b346868d3d5491c0cd88eee100189c470d2107fa49cde6086568ec1383 is restarting, wait until the container is running + +``` + +I used the following command to debug issues with the docker container: + +``` +docker logs --tail 50 --follow --timestamps 9920d6b346868d3d5491c0cd88eee100189c470d21 + +``` + +It appears the docker container keeps trying to restart with this error message: + +``` +2020-05-14T07:02:29.592446544Z Current public chain: 2018-06-30T16:07:32Z. +2020-05-14T07:02:29.593149945Z Local chain data: 2018-06-30T16:07:32Z. +2020-05-14T07:02:29.593724545Z Updating the node configuration... +2020-05-14T07:02:29.666034593Z tezos-node: unknown option `--rpc-port'. +2020-05-14T07:02:29.666059993Z Usage: tezos-node config [OPTION]... [OPERATION] +2020-05-14T07:02:29.666064593Z Try `tezos-node config --help' or `tezos-node --help' for more information. + +``` + +All documentation I find seems to suggest --rpc-port is the correct option. Where could I be having issues?",2020/05/14,"['https://tezos.stackexchange.com/questions/2514', 'https://tezos.stackexchange.com', 'https://tezos.stackexchange.com/users/4999/']","First off, never risk more than you can afford. Secondly, your funds are not stuck. If you look at your address, , everything is still there. As the operation shows, the operation backtracked so, no, nothing transfered. + +Restart your trezor and try the transfer again. Remember, your tokens are stored on the chain, not in the device.","I have the exact same problem except a small amount. I transferred a small amount of XTZ from my coinbase account to simplestaking via my Trezor T. That went fine. Then a couple of days later, I tried to send the XTZ back to coinbase. The same thing happened that you described. I opened a chat with simplestaking to ask what the problem is. According to them, it is a known issue that is related to the latest Trezor connect update. They said they are working on a fix. They didn't tell me what will happen when they fix the bug. So I don't know if the transaction will eventually go through or it will just be canceled and the fee returned. My guess it will just be canceled and I will have to transfer later. The reason I was doing this small transfer of XTZ to/from coinbase was to test simplestaking to decide if I wanted to move all my XTZ there....LOL + +However, whenever I plan on transferring a large amount of anything, I always first transfer a small amount to ensure it transfers as expected. This bug reinforces in me why I do this. I would rather pay a small extra fee then have an unnerving situation occur with a large amount. + +Update: I went back on simplestaking a week later and the transaction was voided and the XTZ back in the wallet. However, I see they still charged the transfer 0.010 fee. I don't think they should be charging the fee with something like that. Does anyone know if this bug has been fixed yet? I don't want to try again until I hear it's fixed." +37563013,"I have some variable like this; + +``` + + +``` + +This variable prints; + +``` +Some text 1 +Some text 2 +Some text 3 +Some text 4 + +``` + +source code is here: + +[![](https://i.stack.imgur.com/9vm5Q.jpg)](https://i.stack.imgur.com/9vm5Q.jpg) + +and look like this + +[![](https://i.stack.imgur.com/vj98f.jpg)](https://i.stack.imgur.com/vj98f.jpg) + +Now, i want to convert **br** tag to **hr** like this + +[![enter image description here](https://i.stack.imgur.com/OLgCz.jpg)](https://i.stack.imgur.com/OLgCz.jpg) + +I tried the following ***[nospor](https://stackoverflow.com/users/6356056/nospor)***'s codes but not worked. + +``` +$change = the_field('reviews'); +$change = str_replace(array('
', '
'), array('', '
'), $change); +echo $change; + +``` + +How can i change that **br** tags to **hr** tag with PHP?",2016/06/01,"['https://Stackoverflow.com/questions/37563013', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2745938/']","`
Some text 1
` - wow.... who wrote that? + +Anyway... do it as simple as possible ;) + +``` +$change = the_field('reviews'); +$change = str_replace(array('
', '
'), array('', '
'), $change); +echo $change; + +``` + +edit: + +Probably instead of `the_field` you should use `get_field` because first one displays it and second returns.","``` +$string= the_field('reviews'); +$change = str_replace( + array('
', '
'), + array('
', ''), + $string +); +echo $change; + +``` + +Use simple php str\_replace function" +37563013,"I have some variable like this; + +``` + + +``` + +This variable prints; + +``` +Some text 1 +Some text 2 +Some text 3 +Some text 4 + +``` + +source code is here: + +[![](https://i.stack.imgur.com/9vm5Q.jpg)](https://i.stack.imgur.com/9vm5Q.jpg) + +and look like this + +[![](https://i.stack.imgur.com/vj98f.jpg)](https://i.stack.imgur.com/vj98f.jpg) + +Now, i want to convert **br** tag to **hr** like this + +[![enter image description here](https://i.stack.imgur.com/OLgCz.jpg)](https://i.stack.imgur.com/OLgCz.jpg) + +I tried the following ***[nospor](https://stackoverflow.com/users/6356056/nospor)***'s codes but not worked. + +``` +$change = the_field('reviews'); +$change = str_replace(array('
', '
'), array('', '
'), $change); +echo $change; + +``` + +How can i change that **br** tags to **hr** tag with PHP?",2016/06/01,"['https://Stackoverflow.com/questions/37563013', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2745938/']","`
Some text 1
` - wow.... who wrote that? + +Anyway... do it as simple as possible ;) + +``` +$change = the_field('reviews'); +$change = str_replace(array('
', '
'), array('', '
'), $change); +echo $change; + +``` + +edit: + +Probably instead of `the_field` you should use `get_field` because first one displays it and second returns.","[Above answer](https://stackoverflow.com/a/37563100/3536236) is exactly correct. + +You should use `str_replace` + +the different between `str_replace` and `preg_replace` + +``` +$string = ""foo fighters""; +$str_replace = str_replace('foo','bar',$string); +$preg_replace = preg_replace('/f.{2}/','bar',$string); +echo 'str_replace: ' . $str_replace . ', preg_replace: ' . $preg_replace; + +``` + +the output will be: + +``` +str_replace: bar fighters, preg_replace: bar barhters + +```" +37563013,"I have some variable like this; + +``` + + +``` + +This variable prints; + +``` +Some text 1 +Some text 2 +Some text 3 +Some text 4 + +``` + +source code is here: + +[![](https://i.stack.imgur.com/9vm5Q.jpg)](https://i.stack.imgur.com/9vm5Q.jpg) + +and look like this + +[![](https://i.stack.imgur.com/vj98f.jpg)](https://i.stack.imgur.com/vj98f.jpg) + +Now, i want to convert **br** tag to **hr** like this + +[![enter image description here](https://i.stack.imgur.com/OLgCz.jpg)](https://i.stack.imgur.com/OLgCz.jpg) + +I tried the following ***[nospor](https://stackoverflow.com/users/6356056/nospor)***'s codes but not worked. + +``` +$change = the_field('reviews'); +$change = str_replace(array('
', '
'), array('', '
'), $change); +echo $change; + +``` + +How can i change that **br** tags to **hr** tag with PHP?",2016/06/01,"['https://Stackoverflow.com/questions/37563013', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2745938/']","`
Some text 1
` - wow.... who wrote that? + +Anyway... do it as simple as possible ;) + +``` +$change = the_field('reviews'); +$change = str_replace(array('
', '
'), array('', '
'), $change); +echo $change; + +``` + +edit: + +Probably instead of `the_field` you should use `get_field` because first one displays it and second returns.","`

` is incorrect. + +**HTML** `
` is an empty tag,so there is no end tag. + +**XHTML** `
` + +then you can use function `str_replace` to relace ""br"" by ""hr"" + +``` +$tag_br = array( + ""
"", + ""
"" +); +$tag_hr = array( + ""
"", + """" +); +$change = str_replace($tag_br,$tag_hr ,$change); + +```" +37563013,"I have some variable like this; + +``` + + +``` + +This variable prints; + +``` +Some text 1 +Some text 2 +Some text 3 +Some text 4 + +``` + +source code is here: + +[![](https://i.stack.imgur.com/9vm5Q.jpg)](https://i.stack.imgur.com/9vm5Q.jpg) + +and look like this + +[![](https://i.stack.imgur.com/vj98f.jpg)](https://i.stack.imgur.com/vj98f.jpg) + +Now, i want to convert **br** tag to **hr** like this + +[![enter image description here](https://i.stack.imgur.com/OLgCz.jpg)](https://i.stack.imgur.com/OLgCz.jpg) + +I tried the following ***[nospor](https://stackoverflow.com/users/6356056/nospor)***'s codes but not worked. + +``` +$change = the_field('reviews'); +$change = str_replace(array('
', '
'), array('', '
'), $change); +echo $change; + +``` + +How can i change that **br** tags to **hr** tag with PHP?",2016/06/01,"['https://Stackoverflow.com/questions/37563013', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2745938/']","[Above answer](https://stackoverflow.com/a/37563100/3536236) is exactly correct. + +You should use `str_replace` + +the different between `str_replace` and `preg_replace` + +``` +$string = ""foo fighters""; +$str_replace = str_replace('foo','bar',$string); +$preg_replace = preg_replace('/f.{2}/','bar',$string); +echo 'str_replace: ' . $str_replace . ', preg_replace: ' . $preg_replace; + +``` + +the output will be: + +``` +str_replace: bar fighters, preg_replace: bar barhters + +```","``` +$string= the_field('reviews'); +$change = str_replace( + array('
', '
'), + array('
', ''), + $string +); +echo $change; + +``` + +Use simple php str\_replace function" +37563013,"I have some variable like this; + +``` + + +``` + +This variable prints; + +``` +Some text 1 +Some text 2 +Some text 3 +Some text 4 + +``` + +source code is here: + +[![](https://i.stack.imgur.com/9vm5Q.jpg)](https://i.stack.imgur.com/9vm5Q.jpg) + +and look like this + +[![](https://i.stack.imgur.com/vj98f.jpg)](https://i.stack.imgur.com/vj98f.jpg) + +Now, i want to convert **br** tag to **hr** like this + +[![enter image description here](https://i.stack.imgur.com/OLgCz.jpg)](https://i.stack.imgur.com/OLgCz.jpg) + +I tried the following ***[nospor](https://stackoverflow.com/users/6356056/nospor)***'s codes but not worked. + +``` +$change = the_field('reviews'); +$change = str_replace(array('
', '
'), array('', '
'), $change); +echo $change; + +``` + +How can i change that **br** tags to **hr** tag with PHP?",2016/06/01,"['https://Stackoverflow.com/questions/37563013', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2745938/']","`

` is incorrect. + +**HTML** `
` is an empty tag,so there is no end tag. + +**XHTML** `
` + +then you can use function `str_replace` to relace ""br"" by ""hr"" + +``` +$tag_br = array( + ""
"", + ""
"" +); +$tag_hr = array( + ""
"", + """" +); +$change = str_replace($tag_br,$tag_hr ,$change); + +```","``` +$string= the_field('reviews'); +$change = str_replace( + array('
', '
'), + array('
', ''), + $string +); +echo $change; + +``` + +Use simple php str\_replace function" +37563013,"I have some variable like this; + +``` + + +``` + +This variable prints; + +``` +Some text 1 +Some text 2 +Some text 3 +Some text 4 + +``` + +source code is here: + +[![](https://i.stack.imgur.com/9vm5Q.jpg)](https://i.stack.imgur.com/9vm5Q.jpg) + +and look like this + +[![](https://i.stack.imgur.com/vj98f.jpg)](https://i.stack.imgur.com/vj98f.jpg) + +Now, i want to convert **br** tag to **hr** like this + +[![enter image description here](https://i.stack.imgur.com/OLgCz.jpg)](https://i.stack.imgur.com/OLgCz.jpg) + +I tried the following ***[nospor](https://stackoverflow.com/users/6356056/nospor)***'s codes but not worked. + +``` +$change = the_field('reviews'); +$change = str_replace(array('
', '
'), array('', '
'), $change); +echo $change; + +``` + +How can i change that **br** tags to **hr** tag with PHP?",2016/06/01,"['https://Stackoverflow.com/questions/37563013', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2745938/']","`

` is incorrect. + +**HTML** `
` is an empty tag,so there is no end tag. + +**XHTML** `
` + +then you can use function `str_replace` to relace ""br"" by ""hr"" + +``` +$tag_br = array( + ""
"", + ""
"" +); +$tag_hr = array( + ""
"", + """" +); +$change = str_replace($tag_br,$tag_hr ,$change); + +```","[Above answer](https://stackoverflow.com/a/37563100/3536236) is exactly correct. + +You should use `str_replace` + +the different between `str_replace` and `preg_replace` + +``` +$string = ""foo fighters""; +$str_replace = str_replace('foo','bar',$string); +$preg_replace = preg_replace('/f.{2}/','bar',$string); +echo 'str_replace: ' . $str_replace . ', preg_replace: ' . $preg_replace; + +``` + +the output will be: + +``` +str_replace: bar fighters, preg_replace: bar barhters + +```" +58054390,"I have a program written in C that traverses a tree in reverse pre-order, reverse in-order, and reverse post-order whose individual functions rely heavily on recursion. How would I go about modifying these functions so that they perform the exact same task but without using any sort of recursion? I've spent many hours trying to figure that out by using variables that temporarily store values but I keep drawing a blank unfortunately. I'm using the GCC compiler on Ubuntu Linux BTW. + +Here is my code: + +``` +#include +#include + +struct node +{ + int data; + struct node* left; + struct node* right; +}; + +struct node* newNode(int data) +{ + struct node* node = (struct node*) + malloc(sizeof(struct node)); + node->data = data; + node->left = NULL; + node->right = NULL; + + return(node); +} + +void reversePostOrder(struct node* node) +{ + if (node == NULL) + return; + + reversePostOrder(node->right); + + reversePostOrder(node->left); + + printf(""%d "", node->data); +} + +void reverseInOrder(struct node* node) +{ + if (node == NULL) + return; + + reverseInOrder(node->right); + + printf(""%d "", node->data); + + reverseInOrder(node->left); + +} + +void reversePreOrder(struct node* node) +{ + if (node == NULL) + return; + + printf(""%d "", node->data); + + reversePreOrder(node->right); + + reversePreOrder(node->left); + +} + +int main() +{ + + struct node *root = newNode(1); + root->left = newNode(-2); + root->right = newNode(-3); + root->left->left = newNode(4); + root->left->right = newNode(5); + root->right->left =newNode(6); + root->right->right=newNode(7); + root->left->right->left=newNode(-8); + root->left->right->right=newNode(-9); + root->right->right->left=newNode(10); + root->right->right->right=newNode(11); + root->right->right->right->left=newNode(-12); + root->right->right->right->right=newNode(-13); + root->right->right->right->right->left=newNode(14); + printf(""\nReverse Preorder traversal of binary tree is \n""); + reversePreOrder(root); + + printf(""\nReverse Inorder traversal of binary tree is \n""); + reverseInOrder(root); + + printf(""\nReverse Postorder traversal of binary tree is \n""); + reversePostOrder(root); + + getchar(); + return 0; +} + +```",2019/09/23,"['https://Stackoverflow.com/questions/58054390', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12076645/']","The problem is made difficult because your list nodes do not have pointers to their parents. When an iterative/imperative procedure marches down the left or right link of the current node to navigate to another node, it has no reverse path. + +There are two general approaches to the problem: + +1. Maintain an explicit stack which enables the procedure to navigate to the parent. +2. Mutate the tree itself temporarily to provide a return path. That is to say, overwrite the `left` and `right` links with reverse pointers to the parent temporarily; then restore the values when returning up the tree. + +If the tree is a balanced tree with a guaranteed maximum depth, then (1) can be implemented with a reasonably small, fixed-size array.","you can use a stack to store the parent and an array if a node was previously processed or not before. example for inorder + +``` +push(root) +while stack is not empty() + parent=stack.top() + if parent->left and done[parent->left]==false + left=parent->left + push(parent) + done[left]=true + continue + if done[parent]==false + process(parent) + done[parent]=true + if parent->right and done[parent->right]==false + right=parent->right + push(right) + done[right]=true + continue + stack.pop() + +```" +37918148,"I'm building a simple shopping cart for a site and have been working on the `add to cart`action. While I have ti working I feel there is probably a simple more elegant way of doing it. + +This is the starting state: + +``` +start_state = { + inventory: [ + {sku: ""product_1"", price: 600, name: ""Product 1""}, + {sku: ""product_2"", price: 800, name: ""Product 2""} + ], + cart: [] +} + +``` + +And this is the desired end state: + +``` +start_state = { + inventory: [ + {sku: ""product_1"", price: 600, name: ""Product 1""}, + {sku: ""product_2"", price: 800, name: ""Product 2""} + ], + cart: [ + {sku: ""product_1"", quantity: 2}, + {sku: ""product_2"", quantity: 1} + ] +} + +``` + +And this is the function Im triggering to take it from the initial state to new final\_state, the `sku` argument is the item from the state that is passed in when the action is called: + +``` +addToCart: function (sku) { + let currentCart = this.state.cart + let itemInCart = _.findIndex(currentCart, ['sku', sku]) + + let newItem = { sku: sku } + if (itemInCart !== -1) { + let newQuantity = currentCart[itemInCart].quantity + newItem.quantity = newQuantity + 1 + } else { + newItem.quantity = 1 + } + + let filteredCart = _.filter(currentCart, (item) => { return item.sku !== sku }) + let newCart = _.concat(filteredCart, newItem) + + this.setState({cart: newCart}) +}, + +```",2016/06/20,"['https://Stackoverflow.com/questions/37918148', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1945168/']","Since you are using ES6, you can use some of its new features like `findIndex` and `Object.assign` to achieve what you want. + +``` +addToCart: function(product) { + let index = this.state.cart.findIndex((x) => x.sku === product.sku); + if(index === -1) { + let newProduct = {sku: product.sku, quantity:1} + this.setState({cart : this.state.cart.concat([newProduct])}) + } + else { + let newCart = Object.assign([], this.state.cart); + newCart[index].quantity = newCart[index].quantity+1; + this.setState({cart: newCart}); + } +} + +``` + +[full working example](http://jsfiddle.net/jwm6k66c/638/)","I think this way is better: + +``` +function getCardWithIncItem(currentCart, itemInCart) { + return [ + ...currentCart.slice(0, itemInCart), + Object.assign({}, currentCart[itemInCart], { + quantity: currentCart[itemInCart].quantity + 1, + }), + ...currentCart.slice(itemInCart + 1), + ]; +} + +function getCardWithNewItem(currentCart, sku) { + return [ + ...currentCart, { + sku: sku, + quantity: 1, + } + ]; +} + +const currentCart = this.state.cart; +const itemInCart = _.findIndex(currentCart, ['sku', sku]); +const newCart = (itemInCart !== -1) + ? getCardWithIncItem(currentCart, itemInCart) + : getCardWithIncItem(currentCart, sku); +this.setState({ + cart: newCart, +}) + +```" +35624113,"I am trying to transfer data between controllers. + +So this is my first controller that fetches data first when page loads using http- + +``` +function GetController($scope, $http) { + $http.defaults.useXDomain = true; + $http({ + method: 'POST', url: serviceUrl + '/GetProductsByCategoryOrName', headers: { + 'Authorization': apiKey + }, + data: { ""query"": ""grocery"", ""categoryId"": ""976759"", ""pageIndex"": 0, ""sortDirection"": ""asc"" } + }).then(function successCallback(response) { + $scope.products = response.data; + }).then(function errorCallback(error) { + }) +} + +``` + +the view looks like- + +``` +
+
+ +
+
{{product.name}}
+
+
+
+
+ +``` + +Where now my need is to rebind this HTML with the same request but different parameters. So I created another controller for this job- + +``` +function searchProductsController($scope, $http) { + $http.defaults.useXDomain = true; + $scope.searchText = """"; + $scope.submit = function () { + $http({ + method: 'POST', url: serviceUrl + '/GetProductsByCategoryOrName', headers: { + 'Authorization': apiKey + }, + data: { ""query"": $scope.searchText, ""categoryId"": ""976759"", ""pageIndex"": 0, ""sortDirection"": ""asc"" } + }).then(function successCallback(response) { + $scope.products = response.data; //how to bind this with GetController's $scope.products?? + }).then(function errorCallback(error) { + }); + } +}; + +``` + +**What is needed-** + +I want to bind `$scope.products` of `searchProductsController` to `GetController's` `$scope.products` so that it renders in view. + +I don't have any idea how to do this at the moment as I am very new to angular. +However, I've given a try to create service for transferring purpose but don't really have idea how to integrate it with it. + +**Edit-** + +I've edited controller methods as @Varkal suggested using service, Still couldn't get the problem resolved. + +``` +var app = angular.module(""productsApp"", []) + .service(""serviceProvider"", function ($http) { + this.getDatas = function getDatas(data) { + return $http({ + method: 'POST', url: serviceUrl + '/GetProductsByCategoryOrName', headers: { + 'Authorization': apiKey + }, + data: data + }) + } + return this + }); + +function GetController($scope, serviceProvider) { + var data = { ""query"": ""grocery"", ""categoryId"": ""976759"", ""pageIndex"": 0, ""sortDirection"": ""asc"" }; + serviceProvider.getDatas(data).then(function (response) { + $scope.products = response.data.data; + }); +} + +function searchProductsController($scope, serviceProvider) { + var data = { ""query"": $scope.searchText, ""categoryId"": ""976759"", ""pageIndex"": 0, ""sortDirection"": ""asc"" }; + + $scope.submit = function () { + serviceProvider.getDatas(data).then(function (response) { + console.log(response.data.data); + $scope.products = response.data.data; + }); + } +}; + +```",2016/02/25,"['https://Stackoverflow.com/questions/35624113', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1982631/']","When you need to share things betweens controller, those things should be in a [service](https://docs.angularjs.org/guide/services) + +For example : + +``` +angular.service(""datasService"", function ($http) { + this.getDatas = function getDatas() { + return $http({ + method: 'POST', url: serviceUrl + '/GetProductsByCategoryOrName', headers: { + 'Authorization': apiKey + }, + data: { ""query"": ""grocery"", ""categoryId"": ""976759"", ""pageIndex"": 0, ""sortDirection"": ""asc"" } + }) + } + return this +}); + +``` + +And in your controller : + +``` +function GetController($scope, datasService) { + datasService.getDatas().then(function(){ + $scope.products = response.data + } +} + +``` + +This is a very simple example : you can also store your datas in the service, so call $http only once, and add a method to refresh the product list + +This is the most ""Angular-ly"" way of share datas between controllers, but you can also use localStorage ([ngStorage](https://github.com/gsklee/ngStorage) can help you here)","If you have 2 `views` with 2 `controllers`, it is possible to share the `$scope` variables(data) between controllers through services and factory.But, the `$scope` variables are local to the controller itself so set the data to the service or factory to know about that particular variable.I prefer using factory, easy and smooth as butter. If you are using the `service` or `factory` in a separate file you need to include the file in `index.html`. + +``` + app.controller('Ctrl1', function($scope, myService, $state) { + $scope.variable1 = ""One""; + myService.set($scope.variable1); + $state.go('app.thepagewhereyouwanttoshare'); //go to the page where you want to share that variable. +}); + +app.controller('Ctrl2', function($scope, myService) { + console.log(""shared variable "" + myService.get()); +}); +.factory('myService', function() { + function set(data) { + products = data; + } + + function get() { + return products; + } + + return { + set: set, + get: get + } + +}) + +``` + +Also, you can use `localstorage` for the purpose of sharing data.`localStorage` comes with `angularjs` so no need to inject any additional dependency in the controller or app. +In the controller which has to pass data: + +``` +localStorage.setItem(""products"",$scope.products); + +``` + +In the controller where you to access data: + +``` +localStorage.getItem(""products""); + +``` + +**In your case:** + +``` +function GetController($scope, $http) { + $http.defaults.useXDomain = true; + $http({ + method: 'POST', url: serviceUrl + '/GetProductsByCategoryOrName', headers: { + 'Authorization': apiKey + }, + data: { ""query"": ""grocery"", ""categoryId"": ""976759"", ""pageIndex"": 0, ""sortDirection"": ""asc"" } + }).then(function successCallback(response) { + $scope.products = response.data; + localStorage.setItem(""products"",$scope.products); + }).then(function errorCallback(error) { + }) +} + +function searchProductsController($scope, $http) { + $http.defaults.useXDomain = true; + $scope.searchText = """"; + $scope.submit = function () { + $http({ + method: 'POST', url: serviceUrl + '/GetProductsByCategoryOrName', headers: { + 'Authorization': apiKey + }, + data: { ""query"": $scope.searchText, ""categoryId"": ""976759"", ""pageIndex"": 0, ""sortDirection"": ""asc"" } + }).then(function successCallback(response) { + $scope.products = response.data; //how to bind this with GetController's $scope.products?? + $scope.productsFromGetController = localStorage.getItem(""products""); + }).then(function errorCallback(error) { + }); + } +}; + +``` + +Using the `factory`, you need to navigate to the page where you want to get the data after you set it since the data set can be overwritten by another set in another views. + +**FINAL UPDATE: Using service and factory** + +``` + + + + Angular JS Controller + + + + +

AngularJS Sample Application

+ +
+ +
+ + +
+
+
+

{{product.name}}

+
+
+
+ + + + + + +``` + +**Update regarding your unworking plunker:** + +It is closest i can get with the mock of your `controller`: +" +15982291,"I have read all the previous replies or solutions for the same linker problem. I understand that the Linker is unable to access the library file that has the functions defined but still I have no luck in solving it! + +The errors: + +``` +1>trial_12th.obj : error LNK2019: unresolved external symbol _viStatusDesc@12 referenced in function _main +1>trial_12th.obj : error LNK2019: unresolved external symbol _viClose@4 referenced in function _main +1>trial_12th.obj : error LNK2019: unresolved external symbol _viRead@16 referenced in function _main +1>trial_12th.obj : error LNK2019: unresolved external symbol _viWrite@16 referenced in function _main +1>trial_12th.obj : error LNK2019: unresolved external symbol _viOpen@20 referenced in function _main +1>trial_12th.obj : error LNK2019: unresolved external symbol _viOpenDefaultRM@4 referenced in function _main +1>C:\Users\41kchoudhary\Documents\Visual Studio 2010\Projects\trial_12th\Debug\trial_12th.exe : fatal error LNK1120: 6 unresolved externals + +``` + +I am trying to send and receive data from a mixed-signal oscilloscope. In doing so I am required to write a .cpp file using the pre-defined commands/functions defined using Microsoft Visual Studio C++. I have read the user manual for using these commands, and I also have the header files and libraries required to implement it. + +I am using the following code: + +``` +#include +#include ""stdafx.h"" +#include +#include + +int main(int argc, char* argv[]) +{ + ViSession rm = VI_NULL, vi = VI_NULL; + ViStatus status; + ViChar buffer[256]; + ViUInt32 retCnt; + + // Open a default session + status = viOpenDefaultRM(&rm); + if (status < VI_SUCCESS) goto error; + + // Open the GPIB device at primary address 1, GPIB board 8 + status = viOpen(rm, ""USB::0x0699::0x0377::C011104::INSTR"", VI_NULL, VI_NULL, + &vi); + if (status < VI_SUCCESS) goto error; + + // Send an ID query. + status = viWrite(vi, (ViBuf) ""*idn?"", 5, &retCnt); + if (status < VI_SUCCESS) goto error; + + // Clear the buffer and read the response + memset(buffer, 0, sizeof(buffer)); + status = viRead(vi, (ViBuf) buffer, sizeof(buffer), &retCnt); + if (status < VI_SUCCESS) goto error; + + // Print the response + printf(""id: %s\n"", buffer); + + // Clean up + viClose(vi); // Not needed, but makes things a bit more + + // understandable + viClose(rm); // Closes resource manager and any sessions + + // opened with it + return 0; + + error: + // Report error and clean up + viStatusDesc(vi, status, buffer); + fprintf(stderr, ""failure: %s\n"", buffer); + if (rm != VI_NULL) { + viClose(rm); + } + return 1; +} + +```",2013/04/12,"['https://Stackoverflow.com/questions/15982291', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2276161/']","You could use the [`zero?`](http://ruby-doc.org/core-2.0/File.html#method-c-zero-3F) method: + +``` +File.zero?(""test.rb"") + +```",One different approach is to iterate over each line and do stuff for each iteration. 0 lines = 0 iterations = no extra code needed. +15982291,"I have read all the previous replies or solutions for the same linker problem. I understand that the Linker is unable to access the library file that has the functions defined but still I have no luck in solving it! + +The errors: + +``` +1>trial_12th.obj : error LNK2019: unresolved external symbol _viStatusDesc@12 referenced in function _main +1>trial_12th.obj : error LNK2019: unresolved external symbol _viClose@4 referenced in function _main +1>trial_12th.obj : error LNK2019: unresolved external symbol _viRead@16 referenced in function _main +1>trial_12th.obj : error LNK2019: unresolved external symbol _viWrite@16 referenced in function _main +1>trial_12th.obj : error LNK2019: unresolved external symbol _viOpen@20 referenced in function _main +1>trial_12th.obj : error LNK2019: unresolved external symbol _viOpenDefaultRM@4 referenced in function _main +1>C:\Users\41kchoudhary\Documents\Visual Studio 2010\Projects\trial_12th\Debug\trial_12th.exe : fatal error LNK1120: 6 unresolved externals + +``` + +I am trying to send and receive data from a mixed-signal oscilloscope. In doing so I am required to write a .cpp file using the pre-defined commands/functions defined using Microsoft Visual Studio C++. I have read the user manual for using these commands, and I also have the header files and libraries required to implement it. + +I am using the following code: + +``` +#include +#include ""stdafx.h"" +#include +#include + +int main(int argc, char* argv[]) +{ + ViSession rm = VI_NULL, vi = VI_NULL; + ViStatus status; + ViChar buffer[256]; + ViUInt32 retCnt; + + // Open a default session + status = viOpenDefaultRM(&rm); + if (status < VI_SUCCESS) goto error; + + // Open the GPIB device at primary address 1, GPIB board 8 + status = viOpen(rm, ""USB::0x0699::0x0377::C011104::INSTR"", VI_NULL, VI_NULL, + &vi); + if (status < VI_SUCCESS) goto error; + + // Send an ID query. + status = viWrite(vi, (ViBuf) ""*idn?"", 5, &retCnt); + if (status < VI_SUCCESS) goto error; + + // Clear the buffer and read the response + memset(buffer, 0, sizeof(buffer)); + status = viRead(vi, (ViBuf) buffer, sizeof(buffer), &retCnt); + if (status < VI_SUCCESS) goto error; + + // Print the response + printf(""id: %s\n"", buffer); + + // Clean up + viClose(vi); // Not needed, but makes things a bit more + + // understandable + viClose(rm); // Closes resource manager and any sessions + + // opened with it + return 0; + + error: + // Report error and clean up + viStatusDesc(vi, status, buffer); + fprintf(stderr, ""failure: %s\n"", buffer); + if (rm != VI_NULL) { + viClose(rm); + } + return 1; +} + +```",2013/04/12,"['https://Stackoverflow.com/questions/15982291', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2276161/']","You could use the [`zero?`](http://ruby-doc.org/core-2.0/File.html#method-c-zero-3F) method: + +``` +File.zero?(""test.rb"") + +```","`File.size?('test.rb')` evaluates to `nil` if the file is empty `or` it does not exist. `File.zero?('test.rb')` will return true is the file is empty, but it will return false if the file is not found. Depending on your particular needs you should be careful to use the correct method. + +As an example in the topic creator's question they specifically asked, ""What is the best way to check in Ruby that a file is empty?"" The accepted answer does this correctly and will raise a `No such file or directory` error message if the file does not exist. + +In some situations we may consider the lack of a file to be ""equivalent"" to an empty file." +15982291,"I have read all the previous replies or solutions for the same linker problem. I understand that the Linker is unable to access the library file that has the functions defined but still I have no luck in solving it! + +The errors: + +``` +1>trial_12th.obj : error LNK2019: unresolved external symbol _viStatusDesc@12 referenced in function _main +1>trial_12th.obj : error LNK2019: unresolved external symbol _viClose@4 referenced in function _main +1>trial_12th.obj : error LNK2019: unresolved external symbol _viRead@16 referenced in function _main +1>trial_12th.obj : error LNK2019: unresolved external symbol _viWrite@16 referenced in function _main +1>trial_12th.obj : error LNK2019: unresolved external symbol _viOpen@20 referenced in function _main +1>trial_12th.obj : error LNK2019: unresolved external symbol _viOpenDefaultRM@4 referenced in function _main +1>C:\Users\41kchoudhary\Documents\Visual Studio 2010\Projects\trial_12th\Debug\trial_12th.exe : fatal error LNK1120: 6 unresolved externals + +``` + +I am trying to send and receive data from a mixed-signal oscilloscope. In doing so I am required to write a .cpp file using the pre-defined commands/functions defined using Microsoft Visual Studio C++. I have read the user manual for using these commands, and I also have the header files and libraries required to implement it. + +I am using the following code: + +``` +#include +#include ""stdafx.h"" +#include +#include + +int main(int argc, char* argv[]) +{ + ViSession rm = VI_NULL, vi = VI_NULL; + ViStatus status; + ViChar buffer[256]; + ViUInt32 retCnt; + + // Open a default session + status = viOpenDefaultRM(&rm); + if (status < VI_SUCCESS) goto error; + + // Open the GPIB device at primary address 1, GPIB board 8 + status = viOpen(rm, ""USB::0x0699::0x0377::C011104::INSTR"", VI_NULL, VI_NULL, + &vi); + if (status < VI_SUCCESS) goto error; + + // Send an ID query. + status = viWrite(vi, (ViBuf) ""*idn?"", 5, &retCnt); + if (status < VI_SUCCESS) goto error; + + // Clear the buffer and read the response + memset(buffer, 0, sizeof(buffer)); + status = viRead(vi, (ViBuf) buffer, sizeof(buffer), &retCnt); + if (status < VI_SUCCESS) goto error; + + // Print the response + printf(""id: %s\n"", buffer); + + // Clean up + viClose(vi); // Not needed, but makes things a bit more + + // understandable + viClose(rm); // Closes resource manager and any sessions + + // opened with it + return 0; + + error: + // Report error and clean up + viStatusDesc(vi, status, buffer); + fprintf(stderr, ""failure: %s\n"", buffer); + if (rm != VI_NULL) { + viClose(rm); + } + return 1; +} + +```",2013/04/12,"['https://Stackoverflow.com/questions/15982291', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2276161/']","You could use the [`zero?`](http://ruby-doc.org/core-2.0/File.html#method-c-zero-3F) method: + +``` +File.zero?(""test.rb"") + +```","As of Ruby 2.4.0, there is [File.empty?](https://ruby-doc.org/core-2.4.0/File.html#method-c-empty-3F). + +(Note that it always returns `false` if you pass it a directory, whether that directory is empty or not: `File.empty?('/') # => false`. So use [Dir.empty?](https://ruby-doc.org/core-2.4.0/Dir.html#method-c-empty-3F) for that instead, or [Pathname#empty?](https://ruby-doc.org/stdlib-2.4.0/libdoc/pathname/rdoc/Pathname.html#method-i-empty-3F) which works for both files and directories.)" +15982291,"I have read all the previous replies or solutions for the same linker problem. I understand that the Linker is unable to access the library file that has the functions defined but still I have no luck in solving it! + +The errors: + +``` +1>trial_12th.obj : error LNK2019: unresolved external symbol _viStatusDesc@12 referenced in function _main +1>trial_12th.obj : error LNK2019: unresolved external symbol _viClose@4 referenced in function _main +1>trial_12th.obj : error LNK2019: unresolved external symbol _viRead@16 referenced in function _main +1>trial_12th.obj : error LNK2019: unresolved external symbol _viWrite@16 referenced in function _main +1>trial_12th.obj : error LNK2019: unresolved external symbol _viOpen@20 referenced in function _main +1>trial_12th.obj : error LNK2019: unresolved external symbol _viOpenDefaultRM@4 referenced in function _main +1>C:\Users\41kchoudhary\Documents\Visual Studio 2010\Projects\trial_12th\Debug\trial_12th.exe : fatal error LNK1120: 6 unresolved externals + +``` + +I am trying to send and receive data from a mixed-signal oscilloscope. In doing so I am required to write a .cpp file using the pre-defined commands/functions defined using Microsoft Visual Studio C++. I have read the user manual for using these commands, and I also have the header files and libraries required to implement it. + +I am using the following code: + +``` +#include +#include ""stdafx.h"" +#include +#include + +int main(int argc, char* argv[]) +{ + ViSession rm = VI_NULL, vi = VI_NULL; + ViStatus status; + ViChar buffer[256]; + ViUInt32 retCnt; + + // Open a default session + status = viOpenDefaultRM(&rm); + if (status < VI_SUCCESS) goto error; + + // Open the GPIB device at primary address 1, GPIB board 8 + status = viOpen(rm, ""USB::0x0699::0x0377::C011104::INSTR"", VI_NULL, VI_NULL, + &vi); + if (status < VI_SUCCESS) goto error; + + // Send an ID query. + status = viWrite(vi, (ViBuf) ""*idn?"", 5, &retCnt); + if (status < VI_SUCCESS) goto error; + + // Clear the buffer and read the response + memset(buffer, 0, sizeof(buffer)); + status = viRead(vi, (ViBuf) buffer, sizeof(buffer), &retCnt); + if (status < VI_SUCCESS) goto error; + + // Print the response + printf(""id: %s\n"", buffer); + + // Clean up + viClose(vi); // Not needed, but makes things a bit more + + // understandable + viClose(rm); // Closes resource manager and any sessions + + // opened with it + return 0; + + error: + // Report error and clean up + viStatusDesc(vi, status, buffer); + fprintf(stderr, ""failure: %s\n"", buffer); + if (rm != VI_NULL) { + viClose(rm); + } + return 1; +} + +```",2013/04/12,"['https://Stackoverflow.com/questions/15982291', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2276161/']","You could use the [`zero?`](http://ruby-doc.org/core-2.0/File.html#method-c-zero-3F) method: + +``` +File.zero?(""test.rb"") + +```","I think should check like this: + +``` +def file_empty?(file_path) + !(File.file?(file_path) && !File.zero?(file_path)) +end + +``` + +so we do not need to worry about file exist or not. + +File.zero?('test.rb') return false if file not exist" +15982291,"I have read all the previous replies or solutions for the same linker problem. I understand that the Linker is unable to access the library file that has the functions defined but still I have no luck in solving it! + +The errors: + +``` +1>trial_12th.obj : error LNK2019: unresolved external symbol _viStatusDesc@12 referenced in function _main +1>trial_12th.obj : error LNK2019: unresolved external symbol _viClose@4 referenced in function _main +1>trial_12th.obj : error LNK2019: unresolved external symbol _viRead@16 referenced in function _main +1>trial_12th.obj : error LNK2019: unresolved external symbol _viWrite@16 referenced in function _main +1>trial_12th.obj : error LNK2019: unresolved external symbol _viOpen@20 referenced in function _main +1>trial_12th.obj : error LNK2019: unresolved external symbol _viOpenDefaultRM@4 referenced in function _main +1>C:\Users\41kchoudhary\Documents\Visual Studio 2010\Projects\trial_12th\Debug\trial_12th.exe : fatal error LNK1120: 6 unresolved externals + +``` + +I am trying to send and receive data from a mixed-signal oscilloscope. In doing so I am required to write a .cpp file using the pre-defined commands/functions defined using Microsoft Visual Studio C++. I have read the user manual for using these commands, and I also have the header files and libraries required to implement it. + +I am using the following code: + +``` +#include +#include ""stdafx.h"" +#include +#include + +int main(int argc, char* argv[]) +{ + ViSession rm = VI_NULL, vi = VI_NULL; + ViStatus status; + ViChar buffer[256]; + ViUInt32 retCnt; + + // Open a default session + status = viOpenDefaultRM(&rm); + if (status < VI_SUCCESS) goto error; + + // Open the GPIB device at primary address 1, GPIB board 8 + status = viOpen(rm, ""USB::0x0699::0x0377::C011104::INSTR"", VI_NULL, VI_NULL, + &vi); + if (status < VI_SUCCESS) goto error; + + // Send an ID query. + status = viWrite(vi, (ViBuf) ""*idn?"", 5, &retCnt); + if (status < VI_SUCCESS) goto error; + + // Clear the buffer and read the response + memset(buffer, 0, sizeof(buffer)); + status = viRead(vi, (ViBuf) buffer, sizeof(buffer), &retCnt); + if (status < VI_SUCCESS) goto error; + + // Print the response + printf(""id: %s\n"", buffer); + + // Clean up + viClose(vi); // Not needed, but makes things a bit more + + // understandable + viClose(rm); // Closes resource manager and any sessions + + // opened with it + return 0; + + error: + // Report error and clean up + viStatusDesc(vi, status, buffer); + fprintf(stderr, ""failure: %s\n"", buffer); + if (rm != VI_NULL) { + viClose(rm); + } + return 1; +} + +```",2013/04/12,"['https://Stackoverflow.com/questions/15982291', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2276161/']","`File.size?('test.rb')` evaluates to `nil` if the file is empty `or` it does not exist. `File.zero?('test.rb')` will return true is the file is empty, but it will return false if the file is not found. Depending on your particular needs you should be careful to use the correct method. + +As an example in the topic creator's question they specifically asked, ""What is the best way to check in Ruby that a file is empty?"" The accepted answer does this correctly and will raise a `No such file or directory` error message if the file does not exist. + +In some situations we may consider the lack of a file to be ""equivalent"" to an empty file.",One different approach is to iterate over each line and do stuff for each iteration. 0 lines = 0 iterations = no extra code needed. +15982291,"I have read all the previous replies or solutions for the same linker problem. I understand that the Linker is unable to access the library file that has the functions defined but still I have no luck in solving it! + +The errors: + +``` +1>trial_12th.obj : error LNK2019: unresolved external symbol _viStatusDesc@12 referenced in function _main +1>trial_12th.obj : error LNK2019: unresolved external symbol _viClose@4 referenced in function _main +1>trial_12th.obj : error LNK2019: unresolved external symbol _viRead@16 referenced in function _main +1>trial_12th.obj : error LNK2019: unresolved external symbol _viWrite@16 referenced in function _main +1>trial_12th.obj : error LNK2019: unresolved external symbol _viOpen@20 referenced in function _main +1>trial_12th.obj : error LNK2019: unresolved external symbol _viOpenDefaultRM@4 referenced in function _main +1>C:\Users\41kchoudhary\Documents\Visual Studio 2010\Projects\trial_12th\Debug\trial_12th.exe : fatal error LNK1120: 6 unresolved externals + +``` + +I am trying to send and receive data from a mixed-signal oscilloscope. In doing so I am required to write a .cpp file using the pre-defined commands/functions defined using Microsoft Visual Studio C++. I have read the user manual for using these commands, and I also have the header files and libraries required to implement it. + +I am using the following code: + +``` +#include +#include ""stdafx.h"" +#include +#include + +int main(int argc, char* argv[]) +{ + ViSession rm = VI_NULL, vi = VI_NULL; + ViStatus status; + ViChar buffer[256]; + ViUInt32 retCnt; + + // Open a default session + status = viOpenDefaultRM(&rm); + if (status < VI_SUCCESS) goto error; + + // Open the GPIB device at primary address 1, GPIB board 8 + status = viOpen(rm, ""USB::0x0699::0x0377::C011104::INSTR"", VI_NULL, VI_NULL, + &vi); + if (status < VI_SUCCESS) goto error; + + // Send an ID query. + status = viWrite(vi, (ViBuf) ""*idn?"", 5, &retCnt); + if (status < VI_SUCCESS) goto error; + + // Clear the buffer and read the response + memset(buffer, 0, sizeof(buffer)); + status = viRead(vi, (ViBuf) buffer, sizeof(buffer), &retCnt); + if (status < VI_SUCCESS) goto error; + + // Print the response + printf(""id: %s\n"", buffer); + + // Clean up + viClose(vi); // Not needed, but makes things a bit more + + // understandable + viClose(rm); // Closes resource manager and any sessions + + // opened with it + return 0; + + error: + // Report error and clean up + viStatusDesc(vi, status, buffer); + fprintf(stderr, ""failure: %s\n"", buffer); + if (rm != VI_NULL) { + viClose(rm); + } + return 1; +} + +```",2013/04/12,"['https://Stackoverflow.com/questions/15982291', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2276161/']",One different approach is to iterate over each line and do stuff for each iteration. 0 lines = 0 iterations = no extra code needed.,"I think should check like this: + +``` +def file_empty?(file_path) + !(File.file?(file_path) && !File.zero?(file_path)) +end + +``` + +so we do not need to worry about file exist or not. + +File.zero?('test.rb') return false if file not exist" +15982291,"I have read all the previous replies or solutions for the same linker problem. I understand that the Linker is unable to access the library file that has the functions defined but still I have no luck in solving it! + +The errors: + +``` +1>trial_12th.obj : error LNK2019: unresolved external symbol _viStatusDesc@12 referenced in function _main +1>trial_12th.obj : error LNK2019: unresolved external symbol _viClose@4 referenced in function _main +1>trial_12th.obj : error LNK2019: unresolved external symbol _viRead@16 referenced in function _main +1>trial_12th.obj : error LNK2019: unresolved external symbol _viWrite@16 referenced in function _main +1>trial_12th.obj : error LNK2019: unresolved external symbol _viOpen@20 referenced in function _main +1>trial_12th.obj : error LNK2019: unresolved external symbol _viOpenDefaultRM@4 referenced in function _main +1>C:\Users\41kchoudhary\Documents\Visual Studio 2010\Projects\trial_12th\Debug\trial_12th.exe : fatal error LNK1120: 6 unresolved externals + +``` + +I am trying to send and receive data from a mixed-signal oscilloscope. In doing so I am required to write a .cpp file using the pre-defined commands/functions defined using Microsoft Visual Studio C++. I have read the user manual for using these commands, and I also have the header files and libraries required to implement it. + +I am using the following code: + +``` +#include +#include ""stdafx.h"" +#include +#include + +int main(int argc, char* argv[]) +{ + ViSession rm = VI_NULL, vi = VI_NULL; + ViStatus status; + ViChar buffer[256]; + ViUInt32 retCnt; + + // Open a default session + status = viOpenDefaultRM(&rm); + if (status < VI_SUCCESS) goto error; + + // Open the GPIB device at primary address 1, GPIB board 8 + status = viOpen(rm, ""USB::0x0699::0x0377::C011104::INSTR"", VI_NULL, VI_NULL, + &vi); + if (status < VI_SUCCESS) goto error; + + // Send an ID query. + status = viWrite(vi, (ViBuf) ""*idn?"", 5, &retCnt); + if (status < VI_SUCCESS) goto error; + + // Clear the buffer and read the response + memset(buffer, 0, sizeof(buffer)); + status = viRead(vi, (ViBuf) buffer, sizeof(buffer), &retCnt); + if (status < VI_SUCCESS) goto error; + + // Print the response + printf(""id: %s\n"", buffer); + + // Clean up + viClose(vi); // Not needed, but makes things a bit more + + // understandable + viClose(rm); // Closes resource manager and any sessions + + // opened with it + return 0; + + error: + // Report error and clean up + viStatusDesc(vi, status, buffer); + fprintf(stderr, ""failure: %s\n"", buffer); + if (rm != VI_NULL) { + viClose(rm); + } + return 1; +} + +```",2013/04/12,"['https://Stackoverflow.com/questions/15982291', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2276161/']","`File.size?('test.rb')` evaluates to `nil` if the file is empty `or` it does not exist. `File.zero?('test.rb')` will return true is the file is empty, but it will return false if the file is not found. Depending on your particular needs you should be careful to use the correct method. + +As an example in the topic creator's question they specifically asked, ""What is the best way to check in Ruby that a file is empty?"" The accepted answer does this correctly and will raise a `No such file or directory` error message if the file does not exist. + +In some situations we may consider the lack of a file to be ""equivalent"" to an empty file.","As of Ruby 2.4.0, there is [File.empty?](https://ruby-doc.org/core-2.4.0/File.html#method-c-empty-3F). + +(Note that it always returns `false` if you pass it a directory, whether that directory is empty or not: `File.empty?('/') # => false`. So use [Dir.empty?](https://ruby-doc.org/core-2.4.0/Dir.html#method-c-empty-3F) for that instead, or [Pathname#empty?](https://ruby-doc.org/stdlib-2.4.0/libdoc/pathname/rdoc/Pathname.html#method-i-empty-3F) which works for both files and directories.)" +15982291,"I have read all the previous replies or solutions for the same linker problem. I understand that the Linker is unable to access the library file that has the functions defined but still I have no luck in solving it! + +The errors: + +``` +1>trial_12th.obj : error LNK2019: unresolved external symbol _viStatusDesc@12 referenced in function _main +1>trial_12th.obj : error LNK2019: unresolved external symbol _viClose@4 referenced in function _main +1>trial_12th.obj : error LNK2019: unresolved external symbol _viRead@16 referenced in function _main +1>trial_12th.obj : error LNK2019: unresolved external symbol _viWrite@16 referenced in function _main +1>trial_12th.obj : error LNK2019: unresolved external symbol _viOpen@20 referenced in function _main +1>trial_12th.obj : error LNK2019: unresolved external symbol _viOpenDefaultRM@4 referenced in function _main +1>C:\Users\41kchoudhary\Documents\Visual Studio 2010\Projects\trial_12th\Debug\trial_12th.exe : fatal error LNK1120: 6 unresolved externals + +``` + +I am trying to send and receive data from a mixed-signal oscilloscope. In doing so I am required to write a .cpp file using the pre-defined commands/functions defined using Microsoft Visual Studio C++. I have read the user manual for using these commands, and I also have the header files and libraries required to implement it. + +I am using the following code: + +``` +#include +#include ""stdafx.h"" +#include +#include + +int main(int argc, char* argv[]) +{ + ViSession rm = VI_NULL, vi = VI_NULL; + ViStatus status; + ViChar buffer[256]; + ViUInt32 retCnt; + + // Open a default session + status = viOpenDefaultRM(&rm); + if (status < VI_SUCCESS) goto error; + + // Open the GPIB device at primary address 1, GPIB board 8 + status = viOpen(rm, ""USB::0x0699::0x0377::C011104::INSTR"", VI_NULL, VI_NULL, + &vi); + if (status < VI_SUCCESS) goto error; + + // Send an ID query. + status = viWrite(vi, (ViBuf) ""*idn?"", 5, &retCnt); + if (status < VI_SUCCESS) goto error; + + // Clear the buffer and read the response + memset(buffer, 0, sizeof(buffer)); + status = viRead(vi, (ViBuf) buffer, sizeof(buffer), &retCnt); + if (status < VI_SUCCESS) goto error; + + // Print the response + printf(""id: %s\n"", buffer); + + // Clean up + viClose(vi); // Not needed, but makes things a bit more + + // understandable + viClose(rm); // Closes resource manager and any sessions + + // opened with it + return 0; + + error: + // Report error and clean up + viStatusDesc(vi, status, buffer); + fprintf(stderr, ""failure: %s\n"", buffer); + if (rm != VI_NULL) { + viClose(rm); + } + return 1; +} + +```",2013/04/12,"['https://Stackoverflow.com/questions/15982291', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2276161/']","`File.size?('test.rb')` evaluates to `nil` if the file is empty `or` it does not exist. `File.zero?('test.rb')` will return true is the file is empty, but it will return false if the file is not found. Depending on your particular needs you should be careful to use the correct method. + +As an example in the topic creator's question they specifically asked, ""What is the best way to check in Ruby that a file is empty?"" The accepted answer does this correctly and will raise a `No such file or directory` error message if the file does not exist. + +In some situations we may consider the lack of a file to be ""equivalent"" to an empty file.","I think should check like this: + +``` +def file_empty?(file_path) + !(File.file?(file_path) && !File.zero?(file_path)) +end + +``` + +so we do not need to worry about file exist or not. + +File.zero?('test.rb') return false if file not exist" +15982291,"I have read all the previous replies or solutions for the same linker problem. I understand that the Linker is unable to access the library file that has the functions defined but still I have no luck in solving it! + +The errors: + +``` +1>trial_12th.obj : error LNK2019: unresolved external symbol _viStatusDesc@12 referenced in function _main +1>trial_12th.obj : error LNK2019: unresolved external symbol _viClose@4 referenced in function _main +1>trial_12th.obj : error LNK2019: unresolved external symbol _viRead@16 referenced in function _main +1>trial_12th.obj : error LNK2019: unresolved external symbol _viWrite@16 referenced in function _main +1>trial_12th.obj : error LNK2019: unresolved external symbol _viOpen@20 referenced in function _main +1>trial_12th.obj : error LNK2019: unresolved external symbol _viOpenDefaultRM@4 referenced in function _main +1>C:\Users\41kchoudhary\Documents\Visual Studio 2010\Projects\trial_12th\Debug\trial_12th.exe : fatal error LNK1120: 6 unresolved externals + +``` + +I am trying to send and receive data from a mixed-signal oscilloscope. In doing so I am required to write a .cpp file using the pre-defined commands/functions defined using Microsoft Visual Studio C++. I have read the user manual for using these commands, and I also have the header files and libraries required to implement it. + +I am using the following code: + +``` +#include +#include ""stdafx.h"" +#include +#include + +int main(int argc, char* argv[]) +{ + ViSession rm = VI_NULL, vi = VI_NULL; + ViStatus status; + ViChar buffer[256]; + ViUInt32 retCnt; + + // Open a default session + status = viOpenDefaultRM(&rm); + if (status < VI_SUCCESS) goto error; + + // Open the GPIB device at primary address 1, GPIB board 8 + status = viOpen(rm, ""USB::0x0699::0x0377::C011104::INSTR"", VI_NULL, VI_NULL, + &vi); + if (status < VI_SUCCESS) goto error; + + // Send an ID query. + status = viWrite(vi, (ViBuf) ""*idn?"", 5, &retCnt); + if (status < VI_SUCCESS) goto error; + + // Clear the buffer and read the response + memset(buffer, 0, sizeof(buffer)); + status = viRead(vi, (ViBuf) buffer, sizeof(buffer), &retCnt); + if (status < VI_SUCCESS) goto error; + + // Print the response + printf(""id: %s\n"", buffer); + + // Clean up + viClose(vi); // Not needed, but makes things a bit more + + // understandable + viClose(rm); // Closes resource manager and any sessions + + // opened with it + return 0; + + error: + // Report error and clean up + viStatusDesc(vi, status, buffer); + fprintf(stderr, ""failure: %s\n"", buffer); + if (rm != VI_NULL) { + viClose(rm); + } + return 1; +} + +```",2013/04/12,"['https://Stackoverflow.com/questions/15982291', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2276161/']","As of Ruby 2.4.0, there is [File.empty?](https://ruby-doc.org/core-2.4.0/File.html#method-c-empty-3F). + +(Note that it always returns `false` if you pass it a directory, whether that directory is empty or not: `File.empty?('/') # => false`. So use [Dir.empty?](https://ruby-doc.org/core-2.4.0/Dir.html#method-c-empty-3F) for that instead, or [Pathname#empty?](https://ruby-doc.org/stdlib-2.4.0/libdoc/pathname/rdoc/Pathname.html#method-i-empty-3F) which works for both files and directories.)","I think should check like this: + +``` +def file_empty?(file_path) + !(File.file?(file_path) && !File.zero?(file_path)) +end + +``` + +so we do not need to worry about file exist or not. + +File.zero?('test.rb') return false if file not exist" +54004943,"I am using for adding Facebook ads to my app. I am following the documentation properly, but Facebook ads are not visible on my app home screen. + +BottomBannerAd.js + +``` +import React from 'react'; +import { FacebookAds } from 'expo'; +const { AdIconView, AdMediaView } = FacebookAds; + +class AdComponent extends React.Component { + render() { + return ( + + + + {this.props.nativeAd.bodyText} + + + ); + } +} + +export default FacebookAds.withNativeAd(AdComponent); + +``` + +HomeScreen.js + +``` +import React from 'react'; +import { Image, TextInput, FlatList, StyleSheet, Text, View, +TouchableOpacity, ActivityIndicator, Platform } from 'react-native'; +import { NavigationEvents } from 'react-navigation'; + +import { FacebookAds } from 'expo'; +import AdComponent from '../components/BottomBannerAd'; +const adsManager = new FacebookAds.NativeAdsManager('xxxxxxxxxxx', 10); + +import { + AdMobBanner, + AdMobInterstitial, + + AdMobRewarded +} from ""expo""; + +export default class HomeScreen extends React.Component { +render(){ +return ( + +... + + + + +) +} +} + +``` + +I have a view component that holds the ad component. That view component works well when I add Google ads, but not working for Facebook ads.",2019/01/02,"['https://Stackoverflow.com/questions/54004943', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10825278/']","One solution is to enter an actual device ID for testing, I wasn't able to get it working otherwise. + +[![setting up ID](https://i.stack.imgur.com/ojpl0.png)](https://i.stack.imgur.com/ojpl0.png) + +Your code above should generate something like this (attachment below), but only on the active device. + +[![enter image description here](https://i.stack.imgur.com/h1jn3.png)](https://i.stack.imgur.com/h1jn3.png) + +The normal way of testing should be by adding a +`FacebookAds.AdSettings.addTestDevice(FacebookAds.AdSettings.currentDeviceHash);` to your code, but it didn't work (for me at least). + +To get an IDFA id on an iPhone, download DeviceId (by AppsFlyer) from the AppStore and also disable Limit Ad Tracking in your Privacy > Advertising settings. + +Hope it helps.","Check this out - [react-native with expo problem with facebook ads](https://stackoverflow.com/questions/53836535/react-native-with-expo-problem-with-facebook-ads) + +I'm having the same issue. It appears FB ads are broken in the current expo builds." +346122,"Let $M$, $N$ be $n$-dimensional real manifolds. Does $M\times N$ admits a complex structure? If not, are there known condidtions ensuring that $M\times N$ admits a complex structure?",2019/11/15,"['https://mathoverflow.net/questions/346122', 'https://mathoverflow.net', 'https://mathoverflow.net/users/147073/']","I assume you are asking if $M \times N$ admits a complex structure. +I believe that there is no result known on this question, although we might have something to say about the existence of an almost complex structure for which both factors are totally real. +Once again we can quote [Gromov](https://www.ihes.fr/~gromov/wp-content/uploads/2018/08/SpacesandQuestions.pdf): Page 30. ""How much do we gain in global understanding of a compact $(V, J)$ by assuming that the structure $J$ is integrable (i.e. complex)? It seems nothing at all: there is no single result concerning all compact complex manifolds"".","[EDIT: I started to write this answer, and then realized it doesn't really answers the question - I leave it here anyway, just in case] + +Let $X=M\times N$, and let $E=\pi\_M^\*TM$ and $F=\pi\_N^\*TN$. Note that $TX=E\oplus F$. +As suggested in Ben McKay's answer, you could first look for the existence of an almost complex structure $J\in End(TX)$, $J^2=-Id$, for which both projections $\pi\_M$ and $\pi\_N$ have totally real fibers. + +This may exist or not. It does for instance under the assumption that there exists an isomorphism of vector bundles $\phi:E\to F$. In that case, define +$$ +J:=\left(\matrix{0 &\phi^{-1} \\ -\phi & 0}\right) +$$ +In this situation the eigenbundle $T^{1,0}X$ corresponding to $+i$ is isomorphic to $E^{\mathbb{C}}$ in the following way: +$$ +E^{\mathbb{C}}\to T^{1,0}X\quad;\quad v\mapsto v+i\phi(v) +$$ +You may want to look for conditions on $\phi$ for $J$ to be integrable." +346122,"Let $M$, $N$ be $n$-dimensional real manifolds. Does $M\times N$ admits a complex structure? If not, are there known condidtions ensuring that $M\times N$ admits a complex structure?",2019/11/15,"['https://mathoverflow.net/questions/346122', 'https://mathoverflow.net', 'https://mathoverflow.net/users/147073/']","I'm going to take $M$ and $N$ to be connected. Note that they cannot have boundary. Furthermore, as complex manifolds are orientable, $M$ and $N$ must also be orientable. + +If $n = 1$, then $M, N \in \{\mathbb{R}, S^1\}$. Note that $\mathbb{R}\times\mathbb{R}$ has a complex structure, in fact, precisely two: $\mathbb{D}$ and $\mathbb{C}$. In addition, $\mathbb{R}\times S^1 = S^1\times \mathbb{R}$ and $S^1\times S^1$ have uncountably many complex structures (annuli and tori respectively). + +If $n = 2$, then $M$ and $N$ are orientable surfaces. These always admit complex structures, and therefore, so do their products. + +Already for $n = 3$, we do not have a complete answer. In this case, the manifold $M\times N$ always admits an almost complex structure, but it is not clear when it admits an integrable one (i.e. a complex structure). This is a major open problem in complex geometry: + +> +> If a manifold admits an almost complex structure, does it admit a complex structure? +> +> +> + +The answer is known to be false in real dimension four, but completely open in higher dimensions. + +For $n = 4$, the manifold $M\times N$ may not even admit an almost complex structure. For example, $M = N = S^4$. Theorem 1 of [this paper](https://www.sciencedirect.com/science/article/pii/0040938370900315) of Heaps completely characterises which closed eight-manifolds admit an almost complex structure. In principle, this could be used to determine what $M$ and $N$ could be, at least in the compact case.","I assume you are asking if $M \times N$ admits a complex structure. +I believe that there is no result known on this question, although we might have something to say about the existence of an almost complex structure for which both factors are totally real. +Once again we can quote [Gromov](https://www.ihes.fr/~gromov/wp-content/uploads/2018/08/SpacesandQuestions.pdf): Page 30. ""How much do we gain in global understanding of a compact $(V, J)$ by assuming that the structure $J$ is integrable (i.e. complex)? It seems nothing at all: there is no single result concerning all compact complex manifolds""." +346122,"Let $M$, $N$ be $n$-dimensional real manifolds. Does $M\times N$ admits a complex structure? If not, are there known condidtions ensuring that $M\times N$ admits a complex structure?",2019/11/15,"['https://mathoverflow.net/questions/346122', 'https://mathoverflow.net', 'https://mathoverflow.net/users/147073/']","I'm going to take $M$ and $N$ to be connected. Note that they cannot have boundary. Furthermore, as complex manifolds are orientable, $M$ and $N$ must also be orientable. + +If $n = 1$, then $M, N \in \{\mathbb{R}, S^1\}$. Note that $\mathbb{R}\times\mathbb{R}$ has a complex structure, in fact, precisely two: $\mathbb{D}$ and $\mathbb{C}$. In addition, $\mathbb{R}\times S^1 = S^1\times \mathbb{R}$ and $S^1\times S^1$ have uncountably many complex structures (annuli and tori respectively). + +If $n = 2$, then $M$ and $N$ are orientable surfaces. These always admit complex structures, and therefore, so do their products. + +Already for $n = 3$, we do not have a complete answer. In this case, the manifold $M\times N$ always admits an almost complex structure, but it is not clear when it admits an integrable one (i.e. a complex structure). This is a major open problem in complex geometry: + +> +> If a manifold admits an almost complex structure, does it admit a complex structure? +> +> +> + +The answer is known to be false in real dimension four, but completely open in higher dimensions. + +For $n = 4$, the manifold $M\times N$ may not even admit an almost complex structure. For example, $M = N = S^4$. Theorem 1 of [this paper](https://www.sciencedirect.com/science/article/pii/0040938370900315) of Heaps completely characterises which closed eight-manifolds admit an almost complex structure. In principle, this could be used to determine what $M$ and $N$ could be, at least in the compact case.","[EDIT: I started to write this answer, and then realized it doesn't really answers the question - I leave it here anyway, just in case] + +Let $X=M\times N$, and let $E=\pi\_M^\*TM$ and $F=\pi\_N^\*TN$. Note that $TX=E\oplus F$. +As suggested in Ben McKay's answer, you could first look for the existence of an almost complex structure $J\in End(TX)$, $J^2=-Id$, for which both projections $\pi\_M$ and $\pi\_N$ have totally real fibers. + +This may exist or not. It does for instance under the assumption that there exists an isomorphism of vector bundles $\phi:E\to F$. In that case, define +$$ +J:=\left(\matrix{0 &\phi^{-1} \\ -\phi & 0}\right) +$$ +In this situation the eigenbundle $T^{1,0}X$ corresponding to $+i$ is isomorphic to $E^{\mathbb{C}}$ in the following way: +$$ +E^{\mathbb{C}}\to T^{1,0}X\quad;\quad v\mapsto v+i\phi(v) +$$ +You may want to look for conditions on $\phi$ for $J$ to be integrable." +35950535,"I have a function I've written to handle calculations of percent reductions with significant digits, and I'm having a problem with keeping trailing zeroes. +The function: + +``` +Function RegexReduction(IValue As Double, EValue As Double) As String + Dim TempPercent As Double + Dim TempString As String + Dim NumFormat As String + Dim DecPlaces As Long + Dim regex As Object + Dim rxMatches As Object + + TempPercent = (1 - EValue / IValue) + NumFormat = ""0"" + Set regex = CreateObject(""VBScript.RegExp"") + With regex + .Pattern = ""([^1-8])*[0-8]{1}[0-9]?"" + .Global = False + End With + Set rxMatches = regex.Execute(CStr(TempPercent)) + If rxMatches.Count <> 0 Then + TempString = rxMatches.Item(0) + DecPlaces = Len(Split(TempString, ""."")(1)) - 2 + If DecPlaces > 0 Then NumFormat = NumFormat & ""."" & String(DecPlaces, ""0"") + End If + RegexReduction = Format(TempPercent, NumFormat & ""%"") +End Function + +``` + +This trims percentages to two digits after any leading zeroes or nines: + +``` +99.999954165% -> 99.99954% +34.564968% -> 35% +0.000516% -> 0.00052% + +``` + +The one problem I've found isn't related to the regex, but to Excel's rounding: + +``` +99.50% -> 99.5% + +``` + +Is there a solution that will save trailing zeroes that could be implemented here?",2016/03/11,"['https://Stackoverflow.com/questions/35950535', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4747836/']","You had several bugs. + +The first root loop was wrong, so with `-np 2` you would send to rank 2. + +The second root loop was wrong -- it should match the corrected first loop. + +A third bug, that only shows up with `-np` greater than 2 is that the root `MPI_Recv` is wrong. The program will hang. + +I've corrected the program and annotated the source. I moved the essential code to a function. Each time I made a fix I added a new function with the fix so you can see the history of the debug process. + +Since you also wanted help with debugging, I've added debugging code that I used to find the problems. I've used this sort of code many times before. + +I've also added the output trace files at the bottom. + +**Update:** There is a fourth bug. If the `-np` value minus 1 does *not* divide `SIZE` evenly, some of the last elements will not be summed (e.g. `-np 7`). I've added more annotation and added an additional function that fixes this. + +Anyway, here's the code [please pardon the gratuitous style cleanup]: + +``` +//array parallel + +#include +#include +#include +#include +#include +#include +#include + +typedef long long s64; + +double tvzero; // initial start time + +int opt_debug; // 1=trace +int opt_run; // version to run + +int size; // MPI size +int rank; // MPI rank of current process +int proc; // number of child processes +int chunksize; // size of chunk +MPI_Status status; + +#define TVSEC 1000000000 + +// tvget -- get time in nanoseconds +s64 +tvget(void) +{ + struct timespec ts; + s64 nsec; + + clock_gettime(CLOCK_REALTIME,&ts); + nsec = ts.tv_sec; + nsec *= TVSEC; + nsec += ts.tv_nsec; + + return nsec; +} + +// tvgetf -- get time in fractional seconds +double +tvgetf(void) +{ + struct timespec ts; + double sec; + + clock_gettime(CLOCK_REALTIME,&ts); + sec = ts.tv_nsec; + sec /= TVSEC; + sec += ts.tv_sec; + + return sec; +} + +void +_dbgprt(int lno,const char *fmt,...) +__attribute__((__format__(__printf__,2,3))); + +#define dbgprt(_lvl,_fmt...) \ + do { \ + if (opt_debug >= _lvl) \ + _dbgprt(__LINE__,_fmt); \ + } while (0) + +void +_dbgprt(int lno,const char *fmt,...) +{ + va_list ap; + double tvnow; + char *bp; + char bf[1000]; + + bp = bf; + + tvnow = tvgetf(); + tvnow -= tvzero; + + bp += sprintf(bp,""[%.9f/R:%d/L:%d] "",tvnow,rank,lno); + + va_start(ap,fmt); + bp += vsprintf(bp,fmt,ap); + va_end(ap); + + fputs(bf,stdout); +} + +// _dbgptr -- interpret pointer +char * +_dbgptr(const void *ptr,const char *sym,MPI_Datatype typ) +{ + char *bp; + static char bf[100]; + + bp = bf; + *bp = 0; + + do { + bp += sprintf(bp,""%s="",sym); + + if (typ == MPI_INT) { + bp += sprintf(bp,""%d"",*(int *) ptr); + break; + } + + bp += sprintf(bp,""%p"",ptr); + } while (0); + + return bf; +} + +#define xMPI_Send(_ptr,_cnt,_typ,_torank,_tag,_comm) \ + do { \ + dbgprt(2,""MPI_Send ptr=[%s] cnt=%d typ=%s torank=%d tag=%d comm=%s\n"", \ + _dbgptr(_ptr,#_ptr,_typ),_cnt,#_typ,_torank,_tag,#_comm); \ + MPI_Send(_ptr,_cnt,_typ,_torank,_tag,_comm); \ + } while (0) + +#define xMPI_Recv(_ptr,_cnt,_typ,_fmrank,_tag,_comm,_status) \ + do { \ + dbgprt(2,""MPI_Recv ptr=%p cnt=%d typ=%s fmrank=%d tag=%d comm=%s\n"", \ + _ptr,_cnt,#_typ,_fmrank,_tag,#_comm); \ + MPI_Recv(_ptr,_cnt,_typ,_fmrank,_tag,_comm,_status); \ + } while (0) + +#define xMPI_Finalize() \ + do { \ + dbgprt(1,""MPI_Finalize\n""); \ + MPI_Finalize(); \ + } while (0) + +#define SIZE 50000 +int data1[SIZE]; +int data2[SIZE]; + +// init -- initialize array and return sum +int +init(void) +{ + int i; + int Tsum; + + for (i = 0; i < SIZE; ++i) + data1[i] = i + 1; + + Tsum = 0; + for (i = 0; i < SIZE; ++i) + Tsum += data1[i]; + + printf(""Total Sum: %d \n"",Tsum); + + return Tsum; +} + +// run_orig -- original code with all bugs noted +void +run_orig(void) +{ + int i; + int dest; + int source; + int Tsum; + int Rsum; + int sum; + int index; + + // BUG(1a): this should be one less (e.g. for -np 2, root=0, child=1) + proc = size; + + // BUG(4): if SIZE is not a multiple of proc, the last few elements will + // _not_ be processed -- the last child must get a larger chunk size, so in + // addition to sending the index to each child, we must send it a custom + // chunk size + chunksize = SIZE / proc; + + if (rank == 0) { + Tsum = init(); + + // send split of array to children + // BUG(1b): this loop goes one beyond the last child and caused the send + // to blow up + index = 0; + for (dest = 1; dest <= proc; ++dest) { + xMPI_Send(&index,1,MPI_INT,dest,0,MPI_COMM_WORLD); + xMPI_Send(&data1[index],chunksize,MPI_INT,dest,0,MPI_COMM_WORLD); + index = index + chunksize; + } + + // collect sum of children + // BUG(2): this for loop is wrong -- it should match the one above + Rsum = 0; + for (i = 0; i < proc; ++i) { + // BUG(3): source should be ""i"" + source = 1; + xMPI_Recv(&sum,1,MPI_INT,source,0,MPI_COMM_WORLD,&status); + Rsum = Rsum + sum; + printf(""- - - - - - - - - - - - - -\n""); + printf(""Received from process %d, Sum: %d \n"",source,sum); + } + + printf(""Total Sum received: %d -- %s\n"", + Rsum,(Rsum == Tsum) ? ""PASS"" : ""FAIL""); + } + + else { + xMPI_Recv(&index,1,MPI_INT,0,0,MPI_COMM_WORLD,&status); + xMPI_Recv(&data2[index],chunksize,MPI_INT,0,0,MPI_COMM_WORLD,&status); + + sum = 0; + for (i = index; i < index + chunksize; ++i) + sum += data2[i]; + + xMPI_Send(&sum,1,MPI_INT,0,0,MPI_COMM_WORLD); + } +} + +// run_edit1 -- no changes to original +void +run_edit1(void) +{ + int i; + int cldno; + int Tsum; + int Rsum; + int sum; + int index; + int source; + + proc = size; + + chunksize = SIZE / proc; + + if (rank == 0) { + Tsum = init(); + + // send split of array to children + index = 0; + for (cldno = 1; cldno <= proc; ++cldno) { + xMPI_Send(&index,1,MPI_INT,cldno,0,MPI_COMM_WORLD); + xMPI_Send(&data1[index],chunksize,MPI_INT,cldno,0,MPI_COMM_WORLD); + index = index + chunksize; + } + + // collect sum of children + Rsum = 0; + for (cldno = 0; cldno < proc; ++cldno) { + source = 1; + xMPI_Recv(&sum,1,MPI_INT,source,0,MPI_COMM_WORLD,&status); + Rsum += sum; + printf(""- - - - - - - - - - - - - -\n""); + printf(""Received from process %d, Sum: %d \n"",cldno,sum); + } + + printf(""Total Sum received: %d -- %s\n"", + Rsum,(Rsum == Tsum) ? ""PASS"" : ""FAIL""); + } + + else { + xMPI_Recv(&index,1,MPI_INT,0,0,MPI_COMM_WORLD,&status); + xMPI_Recv(&data2[index],chunksize,MPI_INT,0,0,MPI_COMM_WORLD,&status); + + sum = 0; + for (i = index; i < index + chunksize; ++i) + sum += data2[i]; + + xMPI_Send(&sum,1,MPI_INT,0,0,MPI_COMM_WORLD); + } +} + +// run_edit2 -- fixed child count +void +run_edit2(void) +{ + int i; + int cldno; + int Tsum; + int Rsum; + int sum; + int index; + int source; + + // BUGFIX #1 -- child count must be one less than size + proc = size - 1; + + chunksize = SIZE / proc; + + if (rank == 0) { + Tsum = init(); + + // send split of array to children + index = 0; + for (cldno = 1; cldno <= proc; ++cldno) { + xMPI_Send(&index,1,MPI_INT,cldno,0,MPI_COMM_WORLD); + xMPI_Send(&data1[index],chunksize,MPI_INT,cldno,0,MPI_COMM_WORLD); + index = index + chunksize; + } + + // collect sum of children + Rsum = 0; + for (cldno = 0; cldno < proc; ++cldno) { + source = 1; + xMPI_Recv(&sum,1,MPI_INT,source,0,MPI_COMM_WORLD,&status); + Rsum += sum; + printf(""- - - - - - - - - - - - - -\n""); + printf(""Received from process %d, Sum: %d \n"",cldno,sum); + } + + printf(""Total Sum received: %d -- %s\n"", + Rsum,(Rsum == Tsum) ? ""PASS"" : ""FAIL""); + } + + else { + xMPI_Recv(&index,1,MPI_INT,0,0,MPI_COMM_WORLD,&status); + xMPI_Recv(&data2[index],chunksize,MPI_INT,0,0,MPI_COMM_WORLD,&status); + + sum = 0; + for (i = index; i < index + chunksize; ++i) + sum += data2[i]; + + xMPI_Send(&sum,1,MPI_INT,0,0,MPI_COMM_WORLD); + } +} + +// run_edit3 -- fixed second root loop and MPI_Recv +void +run_edit3(void) +{ + int i; + int cldno; + int Tsum; + int Rsum; + int sum; + int index; + + // BUGFIX #1 -- child count must be one less than size + proc = size - 1; + + chunksize = SIZE / proc; + + if (rank == 0) { + Tsum = init(); + + // send split of array to children + index = 0; + for (cldno = 1; cldno <= proc; ++cldno) { + xMPI_Send(&index,1,MPI_INT,cldno,0,MPI_COMM_WORLD); + xMPI_Send(&data1[index],chunksize,MPI_INT,cldno,0,MPI_COMM_WORLD); + index = index + chunksize; + } + + // collect sum of children + // BUGFIX #2 -- loop was wrong and the source arg must be the child rank + Rsum = 0; + for (cldno = 1; cldno <= proc; ++cldno) { + xMPI_Recv(&sum,1,MPI_INT,cldno,0,MPI_COMM_WORLD,&status); + Rsum += sum; + printf(""- - - - - - - - - - - - - -\n""); + printf(""Received from process %d, Sum: %d \n"",cldno,sum); + } + + printf(""Total Sum received: %d -- %s\n"", + Rsum,(Rsum == Tsum) ? ""PASS"" : ""FAIL""); + } + + else { + xMPI_Recv(&index,1,MPI_INT,0,0,MPI_COMM_WORLD,&status); + xMPI_Recv(&data2[index],chunksize,MPI_INT,0,0,MPI_COMM_WORLD,&status); + + sum = 0; + for (i = index; i < index + chunksize; ++i) + sum += data2[i]; + + xMPI_Send(&sum,1,MPI_INT,0,0,MPI_COMM_WORLD); + } +} + +// run_edit4 -- fixed chunk size allocation +void +run_edit4(void) +{ + int i; + int cldno; + int Tsum; + int Rsum; + int sum; + int sendsize; + int totsize; + int index; + + // BUGFIX #1 -- child count must be one less than size + proc = size - 1; + + totsize = SIZE; + chunksize = totsize / proc; + + if (rank == 0) { + Tsum = init(); + + // send split of array to children + index = 0; + for (cldno = 1; cldno <= proc; ++cldno, totsize -= sendsize) { + // BUGFIX #3a -- not every child node gets the same amount + if (cldno < proc) + sendsize = chunksize; + else + sendsize = totsize; + xMPI_Send(&index,1,MPI_INT,cldno,0,MPI_COMM_WORLD); + xMPI_Send(&sendsize,1,MPI_INT,cldno,0,MPI_COMM_WORLD); + xMPI_Send(&data1[index],sendsize,MPI_INT,cldno,0,MPI_COMM_WORLD); + index = index + sendsize; + } + + // collect sum of children + // BUGFIX #2 -- loop was wrong and the source arg must be the child rank + Rsum = 0; + for (cldno = 1; cldno <= proc; ++cldno) { + xMPI_Recv(&sum,1,MPI_INT,cldno,0,MPI_COMM_WORLD,&status); + Rsum += sum; + printf(""- - - - - - - - - - - - - -\n""); + printf(""Received from process %d, Sum: %d \n"",cldno,sum); + } + + printf(""Total Sum received: %d -- %s\n"", + Rsum,(Rsum == Tsum) ? ""PASS"" : ""FAIL""); + } + + else { + // BUGFIX #3b -- not every child node gets the same amount + xMPI_Recv(&index,1,MPI_INT,0,0,MPI_COMM_WORLD,&status); + xMPI_Recv(&chunksize,1,MPI_INT,0,0,MPI_COMM_WORLD,&status); + xMPI_Recv(&data2[index],chunksize,MPI_INT,0,0,MPI_COMM_WORLD,&status); + + sum = 0; + for (i = index; i < index + chunksize; ++i) + sum += data2[i]; + + xMPI_Send(&sum,1,MPI_INT,0,0,MPI_COMM_WORLD); + } +} + +int +main(int argc,char **argv) +{ + char *cp; + + // NOTE: this will vary a bit with rank + // to do the job properly we'd need the root to bcast this -- see below + tvzero = tvgetf(); + + MPI_Init(&argc,&argv); + MPI_Comm_rank(MPI_COMM_WORLD,&rank); + MPI_Comm_size(MPI_COMM_WORLD,&size); + + --argc; + ++argv; + + for (; argc > 0; --argc, ++argv) { + cp = *argv; + if (*cp != '-') + break; + + switch (cp[1]) { + case 'R': + cp += 2; + opt_run = (*cp != 0) ? atoi(cp) : 1; + break; + + case 'T': + cp += 2; + opt_debug = (*cp != 0) ? atoi(cp) : 1; + break; + } + } + + // root send to all children + if (opt_debug) + MPI_Bcast(&tvzero,1,MPI_DOUBLE,0,MPI_COMM_WORLD); + + // show our pid so we can map it to rank [which is more meaningful] + dbgprt(1,""PID pid=%d\n"",getpid()); + + switch (opt_run) { + case 1: + run_edit1(); + break; + case 2: + run_edit2(); + break; + case 3: + run_edit3(); + break; + case 4: + run_edit4(); + break; + default: + break; + } + + xMPI_Finalize(); + + return 0; +} + +``` + +--- + +Here are the logs [combined into one to save space]: + +``` +# test #1 edit #1 with -np=2 -T9 +[manderly:6620] *** An error occurred in MPI_Send +[manderly:6620] *** reported by process [3255828481,0] +[manderly:6620] *** on communicator MPI_COMM_WORLD +[manderly:6620] *** MPI_ERR_RANK: invalid rank +[manderly:6620] *** MPI_ERRORS_ARE_FATAL (processes in this communicator will now abort, +[manderly:6620] *** and potentially your MPI job) +[0.014549255/R:0/L:480] PID pid=6620 +[0.014554262/R:1/L:480] PID pid=6621 +[0.014572620/R:1/L:259] MPI_Recv ptr=0x7ffc98d18a6c cnt=1 typ=MPI_INT fmrank=0 tag=0 comm=MPI_COMM_WORLD +Total Sum: 1250025000 +[0.014715672/R:0/L:239] MPI_Send ptr=[&index=0] cnt=1 typ=MPI_INT torank=1 tag=0 comm=MPI_COMM_WORLD +[0.014730692/R:0/L:240] MPI_Send ptr=[&data1[index]=1] cnt=25000 typ=MPI_INT torank=1 tag=0 comm=MPI_COMM_WORLD +[0.014730930/R:1/L:260] MPI_Recv ptr=0x603960 cnt=25000 typ=MPI_INT fmrank=0 tag=0 comm=MPI_COMM_WORLD +[0.014817476/R:0/L:239] MPI_Send ptr=[&index=25000] cnt=1 typ=MPI_INT torank=2 tag=0 comm=MPI_COMM_WORLD +[0.014842749/R:1/L:266] MPI_Send ptr=[&sum=312512500] cnt=1 typ=MPI_INT torank=0 tag=0 comm=MPI_COMM_WORLD +[0.014861822/R:1/L:499] MPI_Finalize + +# test #2 edit #2 with -np=2 -T0 +Total Sum: 1250025000 +- - - - - - - - - - - - - - +Received from process 0, Sum: 1250025000 +Total Sum received: 1250025000 -- PASS + +# test #3 edit #2 with -np=5 -T9 +[0.028285980/R:0/L:480] PID pid=6632 +[0.028294086/R:1/L:480] PID pid=6633 +[0.028315544/R:1/L:313] MPI_Recv ptr=0x7ffe22a554ec cnt=1 typ=MPI_INT fmrank=0 tag=0 comm=MPI_COMM_WORLD +[0.028294325/R:4/L:480] PID pid=6637 +[0.028332472/R:4/L:313] MPI_Recv ptr=0x7ffd5ed6a77c cnt=1 typ=MPI_INT fmrank=0 tag=0 comm=MPI_COMM_WORLD +[0.028387308/R:2/L:480] PID pid=6634 +[0.028410435/R:2/L:313] MPI_Recv ptr=0x7fff6f23896c cnt=1 typ=MPI_INT fmrank=0 tag=0 comm=MPI_COMM_WORLD +[0.028449297/R:3/L:480] PID pid=6635 +[0.028471947/R:3/L:313] MPI_Recv ptr=0x7ffd23af2ecc cnt=1 typ=MPI_INT fmrank=0 tag=0 comm=MPI_COMM_WORLD +Total Sum: 1250025000 +[0.028527975/R:0/L:293] MPI_Send ptr=[&index=0] cnt=1 typ=MPI_INT torank=1 tag=0 comm=MPI_COMM_WORLD +[0.028543711/R:0/L:294] MPI_Send ptr=[&data1[index]=1] cnt=12500 typ=MPI_INT torank=1 tag=0 comm=MPI_COMM_WORLD +[0.028544903/R:1/L:314] MPI_Recv ptr=0x603960 cnt=12500 typ=MPI_INT fmrank=0 tag=0 comm=MPI_COMM_WORLD +[0.028627157/R:0/L:293] MPI_Send ptr=[&index=12500] cnt=1 typ=MPI_INT torank=2 tag=0 comm=MPI_COMM_WORLD +[0.028636694/R:0/L:294] MPI_Send ptr=[&data1[index]=12501] cnt=12500 typ=MPI_INT torank=2 tag=0 comm=MPI_COMM_WORLD +[0.028637648/R:2/L:314] MPI_Recv ptr=0x60fcb0 cnt=12500 typ=MPI_INT fmrank=0 tag=0 comm=MPI_COMM_WORLD +[0.028641224/R:1/L:320] MPI_Send ptr=[&sum=78131250] cnt=1 typ=MPI_INT torank=0 tag=0 comm=MPI_COMM_WORLD +[0.028657198/R:1/L:499] MPI_Finalize +[0.028701305/R:0/L:293] MPI_Send ptr=[&index=25000] cnt=1 typ=MPI_INT torank=3 tag=0 comm=MPI_COMM_WORLD +[0.028716326/R:0/L:294] MPI_Send ptr=[&data1[index]=25001] cnt=12500 typ=MPI_INT torank=3 tag=0 comm=MPI_COMM_WORLD +[0.028719425/R:2/L:320] MPI_Send ptr=[&sum=234381250] cnt=1 typ=MPI_INT torank=0 tag=0 comm=MPI_COMM_WORLD +[0.028721094/R:3/L:314] MPI_Recv ptr=0x61c000 cnt=12500 typ=MPI_INT fmrank=0 tag=0 comm=MPI_COMM_WORLD +[0.028738737/R:2/L:499] MPI_Finalize +[0.028776169/R:0/L:293] MPI_Send ptr=[&index=37500] cnt=1 typ=MPI_INT torank=4 tag=0 comm=MPI_COMM_WORLD +[0.028784752/R:0/L:294] MPI_Send ptr=[&data1[index]=37501] cnt=12500 typ=MPI_INT torank=4 tag=0 comm=MPI_COMM_WORLD +[0.028797865/R:3/L:320] MPI_Send ptr=[&sum=390631250] cnt=1 typ=MPI_INT torank=0 tag=0 comm=MPI_COMM_WORLD +[0.028819084/R:3/L:499] MPI_Finalize +[0.028877974/R:4/L:314] MPI_Recv ptr=0x628350 cnt=12500 typ=MPI_INT fmrank=0 tag=0 comm=MPI_COMM_WORLD +[0.028944492/R:0/L:302] MPI_Recv ptr=0x7ffe7db6e4b8 cnt=1 typ=MPI_INT fmrank=1 tag=0 comm=MPI_COMM_WORLD +- - - - - - - - - - - - - - +Received from process 0, Sum: 78131250 +[0.028969765/R:0/L:302] MPI_Recv ptr=0x7ffe7db6e4b8 cnt=1 typ=MPI_INT fmrank=1 tag=0 comm=MPI_COMM_WORLD +[0.028957367/R:4/L:320] MPI_Send ptr=[&sum=546881250] cnt=1 typ=MPI_INT torank=0 tag=0 comm=MPI_COMM_WORLD +[0.028982162/R:4/L:499] MPI_Finalize +TIMEOUT!!! + +# test #4 edit #3 with -np=5 -T0 +Total Sum: 1250025000 +- - - - - - - - - - - - - - +Received from process 1, Sum: 78131250 +- - - - - - - - - - - - - - +Received from process 2, Sum: 234381250 +- - - - - - - - - - - - - - +Received from process 3, Sum: 390631250 +- - - - - - - - - - - - - - +Received from process 4, Sum: 546881250 +Total Sum received: 1250025000 -- PASS + +# test #5 edit #3 with -np=7 -T9 +[0.043676138/R:0/L:480] PID pid=6662 +[0.043689251/R:1/L:480] PID pid=6663 +[0.043709040/R:1/L:366] MPI_Recv ptr=0x7ffc571a085c cnt=1 typ=MPI_INT fmrank=0 tag=0 comm=MPI_COMM_WORLD +[0.043683767/R:4/L:480] PID pid=6666 +[0.043709040/R:4/L:366] MPI_Recv ptr=0x7ffd9e8ea57c cnt=1 typ=MPI_INT fmrank=0 tag=0 comm=MPI_COMM_WORLD +[0.043860435/R:3/L:480] PID pid=6665 +[0.043884993/R:3/L:366] MPI_Recv ptr=0x7ffd1f26c0fc cnt=1 typ=MPI_INT fmrank=0 tag=0 comm=MPI_COMM_WORLD +[0.043950558/R:5/L:480] PID pid=6669 +[0.043974400/R:5/L:366] MPI_Recv ptr=0x7ffc171ddf2c cnt=1 typ=MPI_INT fmrank=0 tag=0 comm=MPI_COMM_WORLD +[0.043961048/R:2/L:480] PID pid=6664 +[0.043980122/R:2/L:366] MPI_Recv ptr=0x7ffde0a06dec cnt=1 typ=MPI_INT fmrank=0 tag=0 comm=MPI_COMM_WORLD +[0.043968439/R:6/L:480] PID pid=6670 +[0.043987513/R:6/L:366] MPI_Recv ptr=0x7ffe4afba88c cnt=1 typ=MPI_INT fmrank=0 tag=0 comm=MPI_COMM_WORLD +Total Sum: 1250025000 +[0.044004679/R:0/L:346] MPI_Send ptr=[&index=0] cnt=1 typ=MPI_INT torank=1 tag=0 comm=MPI_COMM_WORLD +[0.044021130/R:0/L:347] MPI_Send ptr=[&data1[index]=1] cnt=8333 typ=MPI_INT torank=1 tag=0 comm=MPI_COMM_WORLD +[0.044066429/R:1/L:367] MPI_Recv ptr=0x603960 cnt=8333 typ=MPI_INT fmrank=0 tag=0 comm=MPI_COMM_WORLD +[0.044160843/R:0/L:346] MPI_Send ptr=[&index=8333] cnt=1 typ=MPI_INT torank=2 tag=0 comm=MPI_COMM_WORLD +[0.044172764/R:0/L:347] MPI_Send ptr=[&data1[index]=8334] cnt=8333 typ=MPI_INT torank=2 tag=0 comm=MPI_COMM_WORLD +[0.044173002/R:2/L:367] MPI_Recv ptr=0x60bb94 cnt=8333 typ=MPI_INT fmrank=0 tag=0 comm=MPI_COMM_WORLD +[0.044213533/R:1/L:373] MPI_Send ptr=[&sum=34723611] cnt=1 typ=MPI_INT torank=0 tag=0 comm=MPI_COMM_WORLD +[0.044217110/R:0/L:346] MPI_Send ptr=[&index=16666] cnt=1 typ=MPI_INT torank=3 tag=0 comm=MPI_COMM_WORLD +[0.044228792/R:0/L:347] MPI_Send ptr=[&data1[index]=16667] cnt=8333 typ=MPI_INT torank=3 tag=0 comm=MPI_COMM_WORLD +[0.044233561/R:2/L:373] MPI_Send ptr=[&sum=104162500] cnt=1 typ=MPI_INT torank=0 tag=0 comm=MPI_COMM_WORLD +[0.044246435/R:2/L:499] MPI_Finalize +[0.044233799/R:3/L:367] MPI_Recv ptr=0x613dc8 cnt=8333 typ=MPI_INT fmrank=0 tag=0 comm=MPI_COMM_WORLD +[0.044275522/R:0/L:346] MPI_Send ptr=[&index=24999] cnt=1 typ=MPI_INT torank=4 tag=0 comm=MPI_COMM_WORLD +[0.044286489/R:4/L:367] MPI_Recv ptr=0x61bffc cnt=8333 typ=MPI_INT fmrank=0 tag=0 comm=MPI_COMM_WORLD +[0.044291496/R:3/L:373] MPI_Send ptr=[&sum=173601389] cnt=1 typ=MPI_INT torank=0 tag=0 comm=MPI_COMM_WORLD +[0.044314146/R:3/L:499] MPI_Finalize +[0.044286251/R:0/L:347] MPI_Send ptr=[&data1[index]=25000] cnt=8333 typ=MPI_INT torank=4 tag=0 comm=MPI_COMM_WORLD +[0.044338703/R:0/L:346] MPI_Send ptr=[&index=33332] cnt=1 typ=MPI_INT torank=5 tag=0 comm=MPI_COMM_WORLD +[0.044353485/R:0/L:347] MPI_Send ptr=[&data1[index]=33333] cnt=8333 typ=MPI_INT torank=5 tag=0 comm=MPI_COMM_WORLD +[0.044402599/R:0/L:346] MPI_Send ptr=[&index=41665] cnt=1 typ=MPI_INT torank=6 tag=0 comm=MPI_COMM_WORLD +[0.044354916/R:4/L:373] MPI_Send ptr=[&sum=243040278] cnt=1 typ=MPI_INT torank=0 tag=0 comm=MPI_COMM_WORLD +[0.044372797/R:4/L:499] MPI_Finalize +[0.044359684/R:5/L:367] MPI_Recv ptr=0x624230 cnt=8333 typ=MPI_INT fmrank=0 tag=0 comm=MPI_COMM_WORLD +[0.044411659/R:5/L:373] MPI_Send ptr=[&sum=312479167] cnt=1 typ=MPI_INT torank=0 tag=0 comm=MPI_COMM_WORLD +[0.044427156/R:5/L:499] MPI_Finalize +[0.044423819/R:6/L:367] MPI_Recv ptr=0x62c464 cnt=8333 typ=MPI_INT fmrank=0 tag=0 comm=MPI_COMM_WORLD +[0.044469357/R:6/L:373] MPI_Send ptr=[&sum=381918056] cnt=1 typ=MPI_INT torank=0 tag=0 comm=MPI_COMM_WORLD +[0.044484377/R:6/L:499] MPI_Finalize +[0.044419050/R:0/L:347] MPI_Send ptr=[&data1[index]=41666] cnt=8333 typ=MPI_INT torank=6 tag=0 comm=MPI_COMM_WORLD +[0.044459820/R:0/L:355] MPI_Recv ptr=0x7fffd9e14708 cnt=1 typ=MPI_INT fmrank=1 tag=0 comm=MPI_COMM_WORLD +- - - - - - - - - - - - - - +Received from process 1, Sum: 34723611 +[0.044672012/R:0/L:355] MPI_Recv ptr=0x7fffd9e14708 cnt=1 typ=MPI_INT fmrank=2 tag=0 comm=MPI_COMM_WORLD +- - - - - - - - - - - - - - +Received from process 2, Sum: 104162500 +[0.044713497/R:0/L:355] MPI_Recv ptr=0x7fffd9e14708 cnt=1 typ=MPI_INT fmrank=3 tag=0 comm=MPI_COMM_WORLD +- - - - - - - - - - - - - - +Received from process 3, Sum: 173601389 +[0.044723034/R:0/L:355] MPI_Recv ptr=0x7fffd9e14708 cnt=1 typ=MPI_INT fmrank=4 tag=0 comm=MPI_COMM_WORLD +- - - - - - - - - - - - - - +Received from process 4, Sum: 243040278 +[0.044659376/R:1/L:499] MPI_Finalize +[0.044735193/R:0/L:355] MPI_Recv ptr=0x7fffd9e14708 cnt=1 typ=MPI_INT fmrank=5 tag=0 comm=MPI_COMM_WORLD +- - - - - - - - - - - - - - +Received from process 5, Sum: 312479167 +[0.044743538/R:0/L:355] MPI_Recv ptr=0x7fffd9e14708 cnt=1 typ=MPI_INT fmrank=6 tag=0 comm=MPI_COMM_WORLD +- - - - - - - - - - - - - - +Received from process 6, Sum: 381918056 +Total Sum received: 1249925001 -- FAIL +[0.044760466/R:0/L:499] MPI_Finalize + +# test #6 edit #4 with -np=7 -T0 +Total Sum: 1250025000 +- - - - - - - - - - - - - - +Received from process 1, Sum: 34723611 +- - - - - - - - - - - - - - +Received from process 2, Sum: 104162500 +- - - - - - - - - - - - - - +Received from process 3, Sum: 173601389 +- - - - - - - - - - - - - - +Received from process 4, Sum: 243040278 +- - - - - - - - - - - - - - +Received from process 5, Sum: 312479167 +- - - - - - - - - - - - - - +Received from process 6, Sum: 382018055 +Total Sum received: 1250025000 -- PASS + +```","The line + +``` +for (dest = 1; dest <= proc; ++dest) + +``` + +should be + +``` +for (dest = 1; dest < proc; ++dest) + +``` + +You are trying to send to a rank with a label of 2, but with only 2 ranks, you only have ranks 0 and 1 + +Also, when you are receiving on rank 0, you have: + +``` +for (int i = 0; i < proc; ++i) + +``` + +Which implies you plan to receive from yourself, but you do not have a corresponding send." +7718418,"Let's have simplified class: + +``` +class A +{ + bool val_; + public: + A() : val_(true) {} + bool isNew() const { return val_; } + void setDirty() { val_ = false; } +}; + +``` + +and the vector of objects of such class: + +``` +vector coll; +coll.push_back(A()); +coll.push_back(A()); +coll.push_back(A()); +coll.push_back(A()); +coll[1].setDirty(); +coll[3].setDirty(); + +``` + +I need some elegant solution to rearrange(sort) elements in the vector, so that not modified objects will be grouped at the beginning of the sequence.",2011/10/10,"['https://Stackoverflow.com/questions/7718418', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/801620/']","You can use [Partition](http://www.cplusplus.com/reference/algorithm/partition/) algorithm from standard library for that: + +``` +bool MyPredicate(A& a) { return a.isNew();} +... +// bound is iterator pointing to the first element for which predicate returns false +vector::iterator bound = partition(coll.begin(), coll.end(), MyPredicate); + +``` + +Or, as Christian Rau suggested solution without separate function: + +``` +std::partition(coll.begin(), coll.end(), std::mem_fun_ref(&A::isNew)) + +```","How about `sort`: + +``` +#include + +std::sort(coll.begin(), coll.end(), + [](const A & a, const A & b) -> bool { return a.isNew() < b.isNew(); } ); + +``` + +You'll have to rewrite the class to declare `isNew()` as `const`. + +For older compilers, use a function instead of the lambda: + +``` +bool isNewCompare(const A & a, const A & b) { return a.isNew() < b.isNew(); } +std::sort(coll.begin(), coll.end(), isNewCompare); + +``` + +*Edit:* @Vladimir has the better answer, `std::partition()` is the more appropriate algorithm for this problem." +7718418,"Let's have simplified class: + +``` +class A +{ + bool val_; + public: + A() : val_(true) {} + bool isNew() const { return val_; } + void setDirty() { val_ = false; } +}; + +``` + +and the vector of objects of such class: + +``` +vector coll; +coll.push_back(A()); +coll.push_back(A()); +coll.push_back(A()); +coll.push_back(A()); +coll[1].setDirty(); +coll[3].setDirty(); + +``` + +I need some elegant solution to rearrange(sort) elements in the vector, so that not modified objects will be grouped at the beginning of the sequence.",2011/10/10,"['https://Stackoverflow.com/questions/7718418', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/801620/']","You can use [Partition](http://www.cplusplus.com/reference/algorithm/partition/) algorithm from standard library for that: + +``` +bool MyPredicate(A& a) { return a.isNew();} +... +// bound is iterator pointing to the first element for which predicate returns false +vector::iterator bound = partition(coll.begin(), coll.end(), MyPredicate); + +``` + +Or, as Christian Rau suggested solution without separate function: + +``` +std::partition(coll.begin(), coll.end(), std::mem_fun_ref(&A::isNew)) + +```","`std::sort` lets you provide a custom comparison function object. You define a class that overrides the paranthesis operator, and returns true if the first argument should come before the right argument: + +``` +class COrderByDirty +{ + bool operator(const A& lhs, const A& rhs) const + { + // Says lhs should come before rhs only if + // lhs is marked as dirty, and rhs is not + if (lhs.GetDirty() < rhs.Dirty()) + { + return true; + } + } + } + +``` + +Then simply instantiate it use it to sort: + +``` + std::sort(coll.begin(), coll.end(), COrderByDirty()); + +``` + +If you can use C++11, you can avoid the lengthy class creation and use a lambda, as Kernek does in his answer." +7718418,"Let's have simplified class: + +``` +class A +{ + bool val_; + public: + A() : val_(true) {} + bool isNew() const { return val_; } + void setDirty() { val_ = false; } +}; + +``` + +and the vector of objects of such class: + +``` +vector coll; +coll.push_back(A()); +coll.push_back(A()); +coll.push_back(A()); +coll.push_back(A()); +coll[1].setDirty(); +coll[3].setDirty(); + +``` + +I need some elegant solution to rearrange(sort) elements in the vector, so that not modified objects will be grouped at the beginning of the sequence.",2011/10/10,"['https://Stackoverflow.com/questions/7718418', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/801620/']","You can use [Partition](http://www.cplusplus.com/reference/algorithm/partition/) algorithm from standard library for that: + +``` +bool MyPredicate(A& a) { return a.isNew();} +... +// bound is iterator pointing to the first element for which predicate returns false +vector::iterator bound = partition(coll.begin(), coll.end(), MyPredicate); + +``` + +Or, as Christian Rau suggested solution without separate function: + +``` +std::partition(coll.begin(), coll.end(), std::mem_fun_ref(&A::isNew)) + +```","You could use `std::sort` from `` together with `boost::bind`. It could look something like this: + +``` +std::sort(coll.begin(), coll.end(), boost::bind(&A::isDirty, _1)); + +``` + +Assuming `A` has a function `bool A::isDirty() const`. + +This works because you use the following ordering predicate implicitly: + +``` +bool cmp(const A &a, const A &b) { + return a.isDirty(); +} + +``` + +We just don't care what happens when both are dirty or both are not dirty." +7718418,"Let's have simplified class: + +``` +class A +{ + bool val_; + public: + A() : val_(true) {} + bool isNew() const { return val_; } + void setDirty() { val_ = false; } +}; + +``` + +and the vector of objects of such class: + +``` +vector coll; +coll.push_back(A()); +coll.push_back(A()); +coll.push_back(A()); +coll.push_back(A()); +coll[1].setDirty(); +coll[3].setDirty(); + +``` + +I need some elegant solution to rearrange(sort) elements in the vector, so that not modified objects will be grouped at the beginning of the sequence.",2011/10/10,"['https://Stackoverflow.com/questions/7718418', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/801620/']","How about `sort`: + +``` +#include + +std::sort(coll.begin(), coll.end(), + [](const A & a, const A & b) -> bool { return a.isNew() < b.isNew(); } ); + +``` + +You'll have to rewrite the class to declare `isNew()` as `const`. + +For older compilers, use a function instead of the lambda: + +``` +bool isNewCompare(const A & a, const A & b) { return a.isNew() < b.isNew(); } +std::sort(coll.begin(), coll.end(), isNewCompare); + +``` + +*Edit:* @Vladimir has the better answer, `std::partition()` is the more appropriate algorithm for this problem.","`std::sort` lets you provide a custom comparison function object. You define a class that overrides the paranthesis operator, and returns true if the first argument should come before the right argument: + +``` +class COrderByDirty +{ + bool operator(const A& lhs, const A& rhs) const + { + // Says lhs should come before rhs only if + // lhs is marked as dirty, and rhs is not + if (lhs.GetDirty() < rhs.Dirty()) + { + return true; + } + } + } + +``` + +Then simply instantiate it use it to sort: + +``` + std::sort(coll.begin(), coll.end(), COrderByDirty()); + +``` + +If you can use C++11, you can avoid the lengthy class creation and use a lambda, as Kernek does in his answer." +7718418,"Let's have simplified class: + +``` +class A +{ + bool val_; + public: + A() : val_(true) {} + bool isNew() const { return val_; } + void setDirty() { val_ = false; } +}; + +``` + +and the vector of objects of such class: + +``` +vector coll; +coll.push_back(A()); +coll.push_back(A()); +coll.push_back(A()); +coll.push_back(A()); +coll[1].setDirty(); +coll[3].setDirty(); + +``` + +I need some elegant solution to rearrange(sort) elements in the vector, so that not modified objects will be grouped at the beginning of the sequence.",2011/10/10,"['https://Stackoverflow.com/questions/7718418', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/801620/']","How about `sort`: + +``` +#include + +std::sort(coll.begin(), coll.end(), + [](const A & a, const A & b) -> bool { return a.isNew() < b.isNew(); } ); + +``` + +You'll have to rewrite the class to declare `isNew()` as `const`. + +For older compilers, use a function instead of the lambda: + +``` +bool isNewCompare(const A & a, const A & b) { return a.isNew() < b.isNew(); } +std::sort(coll.begin(), coll.end(), isNewCompare); + +``` + +*Edit:* @Vladimir has the better answer, `std::partition()` is the more appropriate algorithm for this problem.","You could use `std::sort` from `` together with `boost::bind`. It could look something like this: + +``` +std::sort(coll.begin(), coll.end(), boost::bind(&A::isDirty, _1)); + +``` + +Assuming `A` has a function `bool A::isDirty() const`. + +This works because you use the following ordering predicate implicitly: + +``` +bool cmp(const A &a, const A &b) { + return a.isDirty(); +} + +``` + +We just don't care what happens when both are dirty or both are not dirty." +11277841,"If I try to build my .sln file in visual studio (using release configuration, but actually none of my configurations build), the build fails with zero errors in the output window and none the error list. In fact, in the build output window, I have 7 projects listed. And under normal verbosity, I have 7 ""Build succeeded."" lines after each project. Yet at the bottom: + +``` +========== Build: 6 succeeded or up-to-date, 1 failed, 0 skipped ========== + +``` + +By building the projects one by one, I have found the 'failing' project and I tried to build it all by itself. It depends on one other project and that builds just fine all by itself. I try building the 'failing' project by itself and I get zero errors and no warnings and a build failed. However in the 'bin' folder for that project, (if I delete the old bin file) I am getting a built dll. Doesn't do me much good though, since the build is 'failing', visual studio makes no effort to launch my project in debug mode. + +Here's something puzzling: In the command line, I have navigated to the directory with my .sln file in it, and I then run this command: + +``` +C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe /ToolsVersion:4.0 /p:Configuration=Release + +``` + +Then, in bin/Release, voila, I have my built project. The build passes in the command line but not the IDE. + +Does anyone have any suggestions? This problem has happened to me twice: Once on windows server 2008 and once on windows xp sp3.",2012/06/30,"['https://Stackoverflow.com/questions/11277841', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/300385/']","[Visual Studio 2010 says Build failed with no errors after I change a source file](https://stackoverflow.com/questions/5068011/visual-studio-2010-says-build-failed-with-no-errors-after-i-change-a-source-file) + +One answer there suggested that I change the place from where I'm building. Here's the path of the debug directory: + +C:\Users\Isaac\Documents\Visual Studio 2010\Projects\checkout\Library Projects\BaseSystemCore\BaseSystemCore\bin\Debug + +Just moving the checkout directory to c:\ did the trick. Something to do with the build path being too long.","I had the same error, it would not build but no errors. Restarting visual studio worked for me, this was in visual studio 2012." +11277841,"If I try to build my .sln file in visual studio (using release configuration, but actually none of my configurations build), the build fails with zero errors in the output window and none the error list. In fact, in the build output window, I have 7 projects listed. And under normal verbosity, I have 7 ""Build succeeded."" lines after each project. Yet at the bottom: + +``` +========== Build: 6 succeeded or up-to-date, 1 failed, 0 skipped ========== + +``` + +By building the projects one by one, I have found the 'failing' project and I tried to build it all by itself. It depends on one other project and that builds just fine all by itself. I try building the 'failing' project by itself and I get zero errors and no warnings and a build failed. However in the 'bin' folder for that project, (if I delete the old bin file) I am getting a built dll. Doesn't do me much good though, since the build is 'failing', visual studio makes no effort to launch my project in debug mode. + +Here's something puzzling: In the command line, I have navigated to the directory with my .sln file in it, and I then run this command: + +``` +C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe /ToolsVersion:4.0 /p:Configuration=Release + +``` + +Then, in bin/Release, voila, I have my built project. The build passes in the command line but not the IDE. + +Does anyone have any suggestions? This problem has happened to me twice: Once on windows server 2008 and once on windows xp sp3.",2012/06/30,"['https://Stackoverflow.com/questions/11277841', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/300385/']","[Visual Studio 2010 says Build failed with no errors after I change a source file](https://stackoverflow.com/questions/5068011/visual-studio-2010-says-build-failed-with-no-errors-after-i-change-a-source-file) + +One answer there suggested that I change the place from where I'm building. Here's the path of the debug directory: + +C:\Users\Isaac\Documents\Visual Studio 2010\Projects\checkout\Library Projects\BaseSystemCore\BaseSystemCore\bin\Debug + +Just moving the checkout directory to c:\ did the trick. Something to do with the build path being too long.","Close Visual Studio. Run cmd, and type: **C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe +/ToolsVersion:4.0 /p:Configuration=Release *yoursolution.sln*** +Then, enter again on VS and run your project. Worked for me!" +11277841,"If I try to build my .sln file in visual studio (using release configuration, but actually none of my configurations build), the build fails with zero errors in the output window and none the error list. In fact, in the build output window, I have 7 projects listed. And under normal verbosity, I have 7 ""Build succeeded."" lines after each project. Yet at the bottom: + +``` +========== Build: 6 succeeded or up-to-date, 1 failed, 0 skipped ========== + +``` + +By building the projects one by one, I have found the 'failing' project and I tried to build it all by itself. It depends on one other project and that builds just fine all by itself. I try building the 'failing' project by itself and I get zero errors and no warnings and a build failed. However in the 'bin' folder for that project, (if I delete the old bin file) I am getting a built dll. Doesn't do me much good though, since the build is 'failing', visual studio makes no effort to launch my project in debug mode. + +Here's something puzzling: In the command line, I have navigated to the directory with my .sln file in it, and I then run this command: + +``` +C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe /ToolsVersion:4.0 /p:Configuration=Release + +``` + +Then, in bin/Release, voila, I have my built project. The build passes in the command line but not the IDE. + +Does anyone have any suggestions? This problem has happened to me twice: Once on windows server 2008 and once on windows xp sp3.",2012/06/30,"['https://Stackoverflow.com/questions/11277841', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/300385/']","[Visual Studio 2010 says Build failed with no errors after I change a source file](https://stackoverflow.com/questions/5068011/visual-studio-2010-says-build-failed-with-no-errors-after-i-change-a-source-file) + +One answer there suggested that I change the place from where I'm building. Here's the path of the debug directory: + +C:\Users\Isaac\Documents\Visual Studio 2010\Projects\checkout\Library Projects\BaseSystemCore\BaseSystemCore\bin\Debug + +Just moving the checkout directory to c:\ did the trick. Something to do with the build path being too long.","if your solution contains too many projects , + +build projects individually, + +Check which project is failing + +for that project check the references of that project , if on any reference if their is yellow color mark, then delete that reference , and add that again , then build and check, + +this will work + +or + +check in output window , each line , in some line it may be showing , dependency is their, but file didnt exist + +that is the problem causing + +this may be due to file corruption" +11277841,"If I try to build my .sln file in visual studio (using release configuration, but actually none of my configurations build), the build fails with zero errors in the output window and none the error list. In fact, in the build output window, I have 7 projects listed. And under normal verbosity, I have 7 ""Build succeeded."" lines after each project. Yet at the bottom: + +``` +========== Build: 6 succeeded or up-to-date, 1 failed, 0 skipped ========== + +``` + +By building the projects one by one, I have found the 'failing' project and I tried to build it all by itself. It depends on one other project and that builds just fine all by itself. I try building the 'failing' project by itself and I get zero errors and no warnings and a build failed. However in the 'bin' folder for that project, (if I delete the old bin file) I am getting a built dll. Doesn't do me much good though, since the build is 'failing', visual studio makes no effort to launch my project in debug mode. + +Here's something puzzling: In the command line, I have navigated to the directory with my .sln file in it, and I then run this command: + +``` +C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe /ToolsVersion:4.0 /p:Configuration=Release + +``` + +Then, in bin/Release, voila, I have my built project. The build passes in the command line but not the IDE. + +Does anyone have any suggestions? This problem has happened to me twice: Once on windows server 2008 and once on windows xp sp3.",2012/06/30,"['https://Stackoverflow.com/questions/11277841', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/300385/']","I had the same error, it would not build but no errors. Restarting visual studio worked for me, this was in visual studio 2012.","Close Visual Studio. Run cmd, and type: **C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe +/ToolsVersion:4.0 /p:Configuration=Release *yoursolution.sln*** +Then, enter again on VS and run your project. Worked for me!" +11277841,"If I try to build my .sln file in visual studio (using release configuration, but actually none of my configurations build), the build fails with zero errors in the output window and none the error list. In fact, in the build output window, I have 7 projects listed. And under normal verbosity, I have 7 ""Build succeeded."" lines after each project. Yet at the bottom: + +``` +========== Build: 6 succeeded or up-to-date, 1 failed, 0 skipped ========== + +``` + +By building the projects one by one, I have found the 'failing' project and I tried to build it all by itself. It depends on one other project and that builds just fine all by itself. I try building the 'failing' project by itself and I get zero errors and no warnings and a build failed. However in the 'bin' folder for that project, (if I delete the old bin file) I am getting a built dll. Doesn't do me much good though, since the build is 'failing', visual studio makes no effort to launch my project in debug mode. + +Here's something puzzling: In the command line, I have navigated to the directory with my .sln file in it, and I then run this command: + +``` +C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe /ToolsVersion:4.0 /p:Configuration=Release + +``` + +Then, in bin/Release, voila, I have my built project. The build passes in the command line but not the IDE. + +Does anyone have any suggestions? This problem has happened to me twice: Once on windows server 2008 and once on windows xp sp3.",2012/06/30,"['https://Stackoverflow.com/questions/11277841', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/300385/']","I had the same error, it would not build but no errors. Restarting visual studio worked for me, this was in visual studio 2012.","if your solution contains too many projects , + +build projects individually, + +Check which project is failing + +for that project check the references of that project , if on any reference if their is yellow color mark, then delete that reference , and add that again , then build and check, + +this will work + +or + +check in output window , each line , in some line it may be showing , dependency is their, but file didnt exist + +that is the problem causing + +this may be due to file corruption" +12964364,"I am working on a physics engine related project. In the C++ code below: + +``` +#include +#include + +struct Vector3 +{ + float x; + float y; + float z; +}; + +struct object +{ + std::vector < std::vector < Vector3 > > set_vertices; + int ID; + int Type; +}; + +class World +{ + public: + std::vector< object > objects; + + private: + // other members +}; + +int main (void) +{ + World world; + + // How to fill in ""objects"" of ""world""? + // Is this safe to do? + world.objects.resize(5); + // What about the way of allocating ""set_vertices"" below? + for(size_t i=0; i(3)); + for(size_t j=0; j +
+ + + + + + + + + + + + + + + + + + + + +
IDFirst NameLast Name
1JohnDoe
2JaneDoe
+
+ ... +
+ +``` + +And I am currently styling it using the following stylesheet: + +``` +.shadow-z-1 { + -webkit-box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.12), 0 1px 2px 0 rgba(0, 0, 0, 0.24); + -moz-box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.12), 0 1px 2px 0 rgba(0, 0, 0, 0.24); + box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.12), 0 1px 2px 0 rgba(0, 0, 0, 0.24); +} + +.table { + width: 100%; + max-width: 100%; + margin-top: 1rem; + margin-bottom: 2rem; + background-color: #fff; + > { + thead > tr, tbody > tr, tfoot > tr { + -webkit-transition: all 0.3s ease; + -o-transition: all 0.3s ease; + transition: all 0.3s ease; + } + thead > tr > th, tbody > tr > th, tfoot > tr > th, thead > tr > td, tbody > tr > td, tfoot > tr > td { + text-align: left; + padding: 1.6rem; + vertical-align: top; + border-top: 0; + -webkit-transition: all 0.3s ease; + -o-transition: all 0.3s ease; + transition: all 0.3s ease; + } + thead > tr > th { + font-weight: 400; + color: #757575; + vertical-align: bottom; + border-bottom: 1px solid rgba(0, 0, 0, 0.12); + } + caption + thead > tr:first-child > th, colgroup + thead > tr:first-child > th, thead:first-child > tr:first-child > th, caption + thead > tr:first-child > td, colgroup + thead > tr:first-child > td, thead:first-child > tr:first-child > td { + border-top: 0; + } + tbody + tbody { + border-top: 1px solid rgba(0, 0, 0, 0.12); + } + } + .table { + background-color: #fff; + } + .no-border { + border: 0; + } +} + +.table-condensed > { + thead > tr > th, tbody > tr > th, tfoot > tr > th, thead > tr > td, tbody > tr > td, tfoot > tr > td { + padding: 0.8rem; + } +} + +.table-bordered { + border: 0; + > { + thead > tr > th, tbody > tr > th, tfoot > tr > th, thead > tr > td, tbody > tr > td, tfoot > tr > td { + border: 0; + border-bottom: 1px solid #e0e0e0; + } + thead > tr > { + th, td { + border-bottom-width: 2px; + } + } + } +} + +.table-striped > tbody > tr:nth-child(odd) > { + td, th { + background-color: #f5f5f5; + } +} + +.table-hover > tbody > tr:hover > { + td, th { + background-color: rgba(0, 0, 0, 0.12); + } +} + +``` + +This is working fine but what I am trying to do now is add in vertical and horizontal scrolling to the table. For the vertical scrolling, I would like to keep the header fixed so I know I need to give the table body a definitive height but I can't figure out where I should be doing it in my stylesheet. For the horizontal scrolling, I don't really know where to begin. I would like to be able to keep the width of all the columns the same so that if another one is added, rather than being squeezed into a defined area the horizontal scrollbar will show up. + +Ideally I am looking to achieve this using only css (or SaSS in my case). + +Any help with this would be much appreciated! + +Thanks for your time.",2017/02/02,"['https://Stackoverflow.com/questions/42006760', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5993072/']","Here is a css code: + +```css +.scroll-table-container { +border:2px solid green; +height: 300px; +overflow: scroll; +} +.scroll-table, td, th { +border-collapse:collapse; +border:1px solid #777; +min-width: 300px;} +```","Check this example: + +``` + + + + + + + + + + + +
IDFirst NameLast Name
+
+ + + + + + + + + + + + + + + + + + + + + +
1JohnDoe
2JaneDoe
3JoshDoe
4JoanaDoe
+
+ + + +```" +47488903,"I downloaded PayuMoney payment extension for Magento 1.9 from their website and copied the respective directories/code in the app folder. + +In the Admin, it is showing the configuration settings for this extension where I entered following details as instructed in the integration guide document: + +``` +Enabled: ​ ‘Yes’ +Environment: sandbox +PayUmoney Key: Test key as provided in the guide (for testing purpose) +PayUmoney Salt:​ Test salt as provided in the guide (for testing purpose) +Citrus Payment/Vanity Url: Blank +Citrus Access Key:​ Blank +Citrus Secret Key: Blank +Route (%): Blank + +``` + +[Refer the screenshot: PayuMoney extension setting in Magento Admin](https://i.stack.imgur.com/cHsFi.png) + +I want to test the functionality hence want to use sandbox environment with test credentials provided in the guide. But with above configuration setting, PayuMoney is not coming up for the customer in the checkout page as a payment option. + +I checked related threads but it has not helped much. Appreciate if anyone has any idea to solve this problem.",2017/11/25,"['https://Stackoverflow.com/questions/47488903', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4873820/']","First of all, it's important to realize that though ""model the animal kingdom in a class hierarchy"" is a common beginner exercise, and often used in examples -- I use Animal, Mammal, Giraffe, Tiger, and so on all the time in examples -- **it is not a realistic problem to solve using OO techniques**. It's simply intended to get you thinking about the concepts in OO programming by thinking about a domain that you already understand well. + +Real zoos which have software to manage their animal inventory do not build class hierarchies like this because their concerns do not actually include what mammals have in common over what birds have in common. Though animal kingdom analogies are useful to get going with OO, it's important to not come away with the belief that every feature that exists in a real-world hierarchy has to be modeled in the class hierarchy. + +So, that said, the rest of my critique will be assuming that you really do want to model the animal kingdom as an exercise. + +Second, the fundamental problem with your implementation is that the hierarchy is either not deep enough or too deep. The problem is that *mammal and bird should be abstract* because there is no thing in the world that is *just a mammal* or *just a bird*. What you want is an abstract class bird that extends animal, and then a concrete (and probably sealed!) class Crow that extends Bird. + +Then the question to ask is: do I really need the mammal and bird levels at all? Are they *useful* to my program? Am I ever going to have a method that can take any mammal but no lizard? If its not useful then eliminate it, and go straight from animal to crow. + +Third, the sound a crow makes is ""caw caw"", not ""crow sound"". :-) + +Fourth, to answer your best question: you typically use an interface when you have *several unrelated things that ""can do"" the same thing but with different implementations* and you use an abstract class *to share implementation details amongst classes that have an ""is a kind of"" relationship.* + +Making a sound is a something that a lot of things can do that are unrelated to each other. A bird and a piano are not the same kind of thing and they have different mechanisms, but they both make sounds. So making sound should be represented by an interface. A bird is a kind of animal, and there might be functions common to all animals that are specialized by birds. + +In short: a bird is a kind of animal, so it should be a subclass. A bird can make a sound, and lots of other things can also, so making a sound should be an interface.","one of the reasons you want to use Interface is that C# does not support multiple inheritance. + +In general, I would like to think of interface as ability or feature instead of being a model. + +Something like: + +``` + public interface ISwimable + { + int SwimmingSpeed { get; set; } + } + + public interface IWalkable + { + int RunningSpeed { get; set; } + } + +``` + +Now if I have an animal that lives in water I would like it to implement ISwimable, and if I have an animal that can walk, its class should implement IWalkable, and if it can do both, it will implement both." +59174310,"I am working on a C++ project using CodeBlocks on Windows but then decided to switch to NetBeans IDE 8.2. + +Within my project, I am calling another executable file with some passed parameters (I run the other .exe with suitable parameters then I take the output of it to use in my main project), and it used to work on CodeBlocks but not on NetBeans. + +The code is the following: + +``` +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include ""My_Constants.h"" +#include ""Data.h"" +#include ""Parameters.h"" +#include ""Pattern.h"" +#include ""Squish.h"" +#include ""Deserializer.h"" +#include ""Automatic_Run.h"" + +using namespace std; + +int main() +{ + + Parameters parameters; + parameters.mode = SQUISH; + Automatic_Run runner; + string inputname; + + //--------------------------------User Input------------------------------------- + cout << ""enter input file name \n""; + getline(cin, inputname); + parameters.inputFileName.assign(inputname); + cout<<""=============================================================================\n""; + + //--------------------------------Running SQUISH/first call-------------------------- + cout<<""Running SQUISH - first call\n""; + char command[1000]=""""; + string passedParameters = "" -i ""+parameters.inputFileName +"" -f ""+ ""t""; + strcat(command,""C:\\Users\\Administrator\\Documents\\CodeBlocksProjects\\TestSQUISH\\bin\\Debug\\TestSQUISH.exe ""); + strcat(command,passedParameters.c_str()); + int result = system(command); + + // the rest of the code(not relevant to the problem) + + return 0; +} + +``` + +On CodeBlocks, it used to work perfectly and give me the output as a file in the path of my main project (the one I am calling TestSQUISH from). However, now on NetBeans, I am getting the following error: + +> +> sh: C:UsersAdministratorDocumentsCodeBlocksProjectsTestSQUISHbinDebugTestSQUISH.exe: command not found +> +> +> + +I checked the terminal of NetBeans to get an idea of what is happening (assuming it might be related) and I noticed that I have to change the path first, then run the executable using: + +> +> ./ TestSQUISH.exe (+parameters) +> +> +> + +However, that also didn't work for my project. + +Can anyone please suggest a solution or tell me how I can make NetBeans run the command on a Windows terminal as CodeBlocks used to do?",2019/12/04,"['https://Stackoverflow.com/questions/59174310', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1383685/']","Your current remote will be using https protocol. That is why it is still asking for password. + +use `git remote show origin | grep URL` to see the current remote URL for origin + +if it starts with `https://` it will ask for username and password. + +Then remove it by `git remote rm origin` + +Then add ssh url by `git remote add origin ` +Make sure that you provide ssh url here, it should be something like `git@github.com..` + +Go to your github repo and click on green clone button and if it is in https format change it to ssh +[![enter image description here](https://i.stack.imgur.com/AAX5b.png)](https://i.stack.imgur.com/AAX5b.png) + +Use the `Use SSH` link to change it to SSH + +Then you should see the ssh url + +[![enter image description here](https://i.stack.imgur.com/GNuIo.png)](https://i.stack.imgur.com/GNuIo.png)","Github does not provide SSH access. Your command is trying to connecto to github by ssh as connection to a remote computer. This is not what you are allowed to do. + +What you can do with the SSH keys in github now, is clone repositories, commit, etc. + +``` +git clone git@github.com: + +``` + +And with SSH you are allowed to do actions on a project with the registered user. Now you can commit, perform pull requests, ..." +59174310,"I am working on a C++ project using CodeBlocks on Windows but then decided to switch to NetBeans IDE 8.2. + +Within my project, I am calling another executable file with some passed parameters (I run the other .exe with suitable parameters then I take the output of it to use in my main project), and it used to work on CodeBlocks but not on NetBeans. + +The code is the following: + +``` +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include ""My_Constants.h"" +#include ""Data.h"" +#include ""Parameters.h"" +#include ""Pattern.h"" +#include ""Squish.h"" +#include ""Deserializer.h"" +#include ""Automatic_Run.h"" + +using namespace std; + +int main() +{ + + Parameters parameters; + parameters.mode = SQUISH; + Automatic_Run runner; + string inputname; + + //--------------------------------User Input------------------------------------- + cout << ""enter input file name \n""; + getline(cin, inputname); + parameters.inputFileName.assign(inputname); + cout<<""=============================================================================\n""; + + //--------------------------------Running SQUISH/first call-------------------------- + cout<<""Running SQUISH - first call\n""; + char command[1000]=""""; + string passedParameters = "" -i ""+parameters.inputFileName +"" -f ""+ ""t""; + strcat(command,""C:\\Users\\Administrator\\Documents\\CodeBlocksProjects\\TestSQUISH\\bin\\Debug\\TestSQUISH.exe ""); + strcat(command,passedParameters.c_str()); + int result = system(command); + + // the rest of the code(not relevant to the problem) + + return 0; +} + +``` + +On CodeBlocks, it used to work perfectly and give me the output as a file in the path of my main project (the one I am calling TestSQUISH from). However, now on NetBeans, I am getting the following error: + +> +> sh: C:UsersAdministratorDocumentsCodeBlocksProjectsTestSQUISHbinDebugTestSQUISH.exe: command not found +> +> +> + +I checked the terminal of NetBeans to get an idea of what is happening (assuming it might be related) and I noticed that I have to change the path first, then run the executable using: + +> +> ./ TestSQUISH.exe (+parameters) +> +> +> + +However, that also didn't work for my project. + +Can anyone please suggest a solution or tell me how I can make NetBeans run the command on a Windows terminal as CodeBlocks used to do?",2019/12/04,"['https://Stackoverflow.com/questions/59174310', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1383685/']","Your current remote will be using https protocol. That is why it is still asking for password. + +use `git remote show origin | grep URL` to see the current remote URL for origin + +if it starts with `https://` it will ask for username and password. + +Then remove it by `git remote rm origin` + +Then add ssh url by `git remote add origin ` +Make sure that you provide ssh url here, it should be something like `git@github.com..` + +Go to your github repo and click on green clone button and if it is in https format change it to ssh +[![enter image description here](https://i.stack.imgur.com/AAX5b.png)](https://i.stack.imgur.com/AAX5b.png) + +Use the `Use SSH` link to change it to SSH + +Then you should see the ssh url + +[![enter image description here](https://i.stack.imgur.com/GNuIo.png)](https://i.stack.imgur.com/GNuIo.png)","All I want at this point is to no enter my username and password whenever I want to push my stuff on github. I made it work. But a day I had to create an other ssh key and id for my VPS but I overwrited it, I didn't know that I have to create one id/key per file. + +So I delete known\_host and erase the content of rsa.pub and rsa, and create a brand new one but it don't work.." +56323181,"How to delete duplicate from this result + +``` +select *, + row_number() over (order by (select null)) as seqnum +from [elo].[dbo].[objkeys] +where parentid in (select parentid + from [elo].[dbo].[objekte] + inner join [elo].[dbo].[objkeys] on objid = parentid + where objmask like 26 and okeydata like 'yes' + ) + +``` + +output is + +``` +parentid okeyname okeydata + 1 name a + 1 number 1 + 1 yes_no yes + 2 name a + 2 number 1 + 2 yes_no yes + 3 name a + 3 number 1 + 3 yes_no no + 4 name a + 4 number 2 + 4 yes_no no + 5 name b + 5 number 3 + 5 yes_no yes + 6 name b + 6 number 3 + 6 yes_no yes + 7 name b + 7 number 3 + 7 yes_no no + 8 name b + 8 number 3 + 8 yes_no no + +``` + +need to be like this + +``` +parentid okeyname okeydata + 1 name a + 1 number 1 + 1 yes_no yes + + 3 name a + 3 number 1 + 3 yes_no no + + 5 name b + 5 number 3 + 5 yes_no yes + + 7 name b + 7 number 3 + 7 yes_no no + +```",2019/05/27,"['https://Stackoverflow.com/questions/56323181', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10306114/']","Can you please try **ml-auto** instead of **mr-auto**? + +So the ul tag will be like this + +``` +