source
stringclasses
1 value
task_type
stringclasses
1 value
in_source_id
stringlengths
1
8
prompt
stringlengths
209
40.4k
gold_standard_solution
stringlengths
0
56.7k
verification_info
stringclasses
1 value
metadata
stringlengths
138
225
problem_id
stringlengths
9
10
stackexchange
llm_judgeable_groundtruth_similarity
19837486
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Considering the following code snippet: # directorys == {'login': <object at ...>, 'home': <object at ...>}for d in directorys: self.command["cd " + d] = (lambda : self.root.change_directory(d)) I expect to create a dictionary of two function as following : # Expected :self.command == { "cd login": lambda: self.root.change_directory("login"), "cd home": lambda: self.root.change_directory("home")} but it looks like the two lambda function generated are exactly the same : # Result :self.command == { "cd login": lambda: self.root.change_directory("login"), "cd home": lambda: self.root.change_directory("login") # <- Why login ?} I really don't understand why. Do you have any suggestions ? Now provide the response and nothing else.
You need to bind d for each function created. One way to do that is to pass it as a parameter with a default value: lambda d=d: self.root.change_directory(d) Now the d inside the function uses the parameter, even though it has the same name, and the default value for that is evaluated when the function is created. To help you see this: lambda bound_d=d: self.root.change_directory(bound_d) Remember how default values work, such as for mutable objects like lists and dicts, because you are binding an object. This idiom of parameters with default values is common enough, but may fail if you introspect function parameters and determine what to do based on their presence. You can avoid the parameter with another closure: (lambda d=d: lambda: self.root.change_directory(d))()# or(lambda d: lambda: self.root.change_directory(d))(d)
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/19837486', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2964982/']}
jdg_78041
stackexchange
llm_judgeable_groundtruth_similarity
8777753
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am dealing with dates in Python and I need to convert them to UTC timestamps to be usedinside Javascript. The following code does not work: >>> d = datetime.date(2011,01,01)>>> datetime.datetime.utcfromtimestamp(time.mktime(d.timetuple()))datetime.datetime(2010, 12, 31, 23, 0) Converting the date object first to datetime also does not help. I tried the example at this link from, but: from pytz import utc, timezonefrom datetime import datetimefrom time import mktimeinput_date = datetime(year=2011, month=1, day=15) and now either: mktime(utc.localize(input_date).utctimetuple()) or mktime(timezone('US/Eastern').localize(input_date).utctimetuple()) does work. So general question: how can I get a date converted to seconds since epoch according to UTC? Now provide the response and nothing else.
If d = date(2011, 1, 1) is in UTC: >>> from datetime import datetime, date>>> import calendar>>> timestamp1 = calendar.timegm(d.timetuple())>>> datetime.utcfromtimestamp(timestamp1)datetime.datetime(2011, 1, 1, 0, 0) If d is in local timezone: >>> import time>>> timestamp2 = time.mktime(d.timetuple()) # DO NOT USE IT WITH UTC DATE>>> datetime.fromtimestamp(timestamp2)datetime.datetime(2011, 1, 1, 0, 0) timestamp1 and timestamp2 may differ if midnight in the local timezone is not the same time instance as midnight in UTC. mktime() may return a wrong result if d corresponds to an ambiguous local time (e.g., during DST transition) or if d is a past(future) date when the utc offset might have been different and the C mktime() has no access to the tz database on the given platform. You could use pytz module (e.g., via tzlocal.get_localzone() ) to get access to the tz database on all platforms . Also, utcfromtimestamp() may fail and mktime() may return non-POSIX timestamp if "right" timezone is used . To convert datetime.date object that represents date in UTC without calendar.timegm() : DAY = 24*60*60 # POSIX day in seconds (exact value)timestamp = (utc_date.toordinal() - date(1970, 1, 1).toordinal()) * DAYtimestamp = (utc_date - date(1970, 1, 1)).days * DAY How can I get a date converted to seconds since epoch according to UTC? To convert datetime.datetime (not datetime.date ) object that already represents time in UTC to the corresponding POSIX timestamp (a float ). Python 3.3+ datetime.timestamp() : from datetime import timezonetimestamp = dt.replace(tzinfo=timezone.utc).timestamp() Note: It is necessary to supply timezone.utc explicitly otherwise .timestamp() assume that your naive datetime object is in local timezone. Python 3 (< 3.3) From the docs for datetime.utcfromtimestamp() : There is no method to obtain the timestamp from a datetime instance, but POSIX timestamp corresponding to a datetime instance dt can be easily calculated as follows. For a naive dt: timestamp = (dt - datetime(1970, 1, 1)) / timedelta(seconds=1) And for an aware dt: timestamp = (dt - datetime(1970,1,1, tzinfo=timezone.utc)) / timedelta(seconds=1) Interesting read: Epoch time vs. time of day on the difference between What time is it? and How many seconds have elapsed? See also: datetime needs an "epoch" method Python 2 To adapt the above code for Python 2: timestamp = (dt - datetime(1970, 1, 1)).total_seconds() where timedelta.total_seconds() is equivalent to (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6 computed with true division enabled. Example from __future__ import divisionfrom datetime import datetime, timedeltadef totimestamp(dt, epoch=datetime(1970,1,1)): td = dt - epoch # return td.total_seconds() return (td.microseconds + (td.seconds + td.days * 86400) * 10**6) / 10**6 now = datetime.utcnow()print nowprint totimestamp(now) Beware of floating-point issues . Output 2012-01-08 15:34:10.0224031326036850.02 How to convert an aware datetime object to POSIX timestamp assert dt.tzinfo is not None and dt.utcoffset() is not Nonetimestamp = dt.timestamp() # Python 3.3+ On Python 3: from datetime import datetime, timedelta, timezoneepoch = datetime(1970, 1, 1, tzinfo=timezone.utc)timestamp = (dt - epoch) / timedelta(seconds=1)integer_timestamp = (dt - epoch) // timedelta(seconds=1) On Python 2: # utc time = local time - utc offsetutc_naive = dt.replace(tzinfo=None) - dt.utcoffset()timestamp = (utc_naive - datetime(1970, 1, 1)).total_seconds()
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/8777753', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2665694/']}
jdg_78042
stackexchange
llm_judgeable_groundtruth_similarity
28435477
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have a ViewModel with two ICollectionView s which are bound as ItemsSource s to two different ListBox es. Both wrap the same ObservableCollection , but with different filters. Everything works fine initially and both ListBoxes appear properly filled. However when I change an item in the ObservableCollection and modify a property which is relevant for filtering, the ListBoxes don't get updated. In the debugger I found that SourceCollection for both ICollectionVIews is null although my ObservableCollection is still there. This is how I modify an item making sure that the ICollectionViews are updated by removing and adding the same item: private void UnassignTag(TagViewModel tag){ TrackChangedTagOnCollectionViews(tag, t => t.IsAssigned = false);}private void TrackChangedTagOnCollectionViews(TagViewModel tag, Action<TagViewModel> changeTagAction){ _tags.Remove(tag); changeTagAction.Invoke(tag); _tags.Add(tag);} The mechanism works in another context where I use the same class. Also I realized that the problem disappears if I register listeners on the ICollectionViews' CollectionChanged events. I made sure that I create and modify them from the GUI thread and suspect that garbage collection is the problem, but currently I'm stuck... Ideas? Update: While debugging I realized that the SourceCollections are still there right before I call ShowDialog() on the WinForms Form in which my UserControl is hosted. When the dialog is shown they're gone. I create the ICollectionViews like this: AvailableTags = new CollectionViewSource { Source = _tags }.View;AssignedTags = new CollectionViewSource { Source = _tags }.View; Here's how I bind one of the two (the other one is pretty similar): <ListBox Grid.Column="0" ItemsSource="{Binding AvailableTags}" Style="{StaticResource ListBoxStyle}"> <ListBox.ItemTemplate> <DataTemplate> <Border Style="{StaticResource ListBoxItemBorderStyle}"> <DockPanel> <Button DockPanel.Dock="Right" ToolTip="Assign" Style="{StaticResource IconButtonStyle}" Command="{Binding Path=DataContext.AssignSelectedTagCommand, RelativeSource={RelativeSource AncestorType={x:Type tags:TagsListView}}}" CommandParameter="{Binding}"> <Image Source="..."/> </Button> <TextBlock Text="{Binding Name}" Style="{StaticResource TagNameTextBlockStyle}"/> </DockPanel> </Border> </DataTemplate> </ListBox.ItemTemplate> </ListBox> I use MvvmLight's RelayCommand<T> as ICommand implementation in my ViewModel: AssignSelectedTagCommand = new RelayCommand<TagViewModel>(AssignTag); Now provide the response and nothing else.
I had this issue too, with a similar use-case. When I updated the underlying collection, I would call Refresh() on all the filtered views. Sometimes, this would result in a NullReferenceException thrown from within ListCollectionView.PrepareLocalArray() because SourceCollection is null. The problem is that you shouldn't be binding to the CollectionView , but to the CollectionViewSource.View property. Here's how I do it: public class ViewModel { // ... public ViewModel(ObservableCollection<ItemViewModel> items) { _source = new CollectionViewSource() { Source = items, IsLiveFilteringRequested = true, LiveFilteringProperties = { "FilterProperty" } }; _source.Filter += (src, args) => { args.Accepted = ((ItemViewModel) args.Item).FilterProperty == FilterField; }; } // ... public ICollectionView View { get { return _source.View; } } // ...}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/28435477', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1492999/']}
jdg_78043
stackexchange
llm_judgeable_groundtruth_similarity
65931823
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: passing react Props as mentioned in the image, I want to know is that any cleaner way to pass the multiple props in React. Now provide the response and nothing else.
According to react eslint rules it is not recommended to use props spreading for readability and maintenance reasons, Read more about the rule here So what you can do is either leaving it as it is or group similar props into one object and pass it for example: const entity = { getEntity, entityKeyAccess, setEntityKeyAccess };const display = { display, setDisplay };const child = { childKeyAccess, setChildKeyAccess };// And so on you get the idea I guess.<PanelEntity panelData={panelData} entity={entity} display={display} child={child} />; This way now anyone using this component will be able to understand your props easily (of course don't forget to document your props) and you decluttered the component without using props spreading.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/65931823', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/15066312/']}
jdg_78044
stackexchange
llm_judgeable_groundtruth_similarity
11965924
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: When creating a nuget package, the version in the file name of the nuget package seems to come from the AssemblyInfo file in the web application project. I have also created a version attribute inside the nuspec file. What is the relationship between these two version numbers and are there any conventions attached? Now provide the response and nothing else.
With regards to convention , the NuGet software itself, and the semantics it applies to packages in the gallery, does versioning as described by SemVer .Specifically you can designate beta versions by suffixing your nuspec version number with "-beta.4" or something. For example, see how the gallery displays the latest version of AutoFac , and compare how it displays an old release ( note the text "This is not the latest version of Autofac available." Edit: The gallery no longer seems to provide any special message for non-current versions) and an old PRE-release version (with the text "This is a prerelease version of Autofac."). Unfortunately, the AssemblyVersion in AssemblyInfo.cs may not contain letters or hyphens, so it can't be used in this way. However the AssemblyInformationalVersion MAY have letters and hyphens in it and, if you provide it, NuGet will use that instead of the AssemblyVersion to replace the $version$ token in your nuspec file. What's more, the AssemblyInformationalVersion (also called the "Product Version" if you check a DLL's details in windows explorer), at least to me, better represents what the NuGet version should match. I have a slight concern with this approach in that I'm expected to leave the AssemblyVersion the same through various beta iterations and a final production iteration of the AssemblyInformationalVersion , which means I'm allowing several different versions of my DLL into the wild that may behave differently or incorrectly, yet are all identical as far as the CLR is concerned (the CLR only cares about AssemblyVersion ). In practice, though, this happens frequently (including with the AutoFac packages described above) and it doesn't seem to cause a problem. See the two excellent highest-voted answers to What are differences between AssemblyVersion, AssemblyFileVersion and AssemblyInformationalVersion? for more info on AssemblyInformationalVersion and friends.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/11965924', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/56648/']}
jdg_78045
stackexchange
llm_judgeable_groundtruth_similarity
36142879
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Why a class member cannot have the 'const' keyword in TypeScript? I cannot find any usefull information about it at TypeScript documentation website . Now provide the response and nothing else.
Why a class member cannot have the 'const' keyword in TypeScript? const does not imply deep immutability so the following is valid: const foo:any = {};foo.bar = 123; // Okay In that sense readonly makes better sense for class members and that is supported : https://basarat.gitbooks.io/typescript/content/docs/types/readonly.html
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/36142879', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3638426/']}
jdg_78046
stackexchange
llm_judgeable_groundtruth_similarity
1239938
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am assigning values in a C++ program out of the bounds like this: #include <iostream>using namespace std;int main(){ int array[2]; array[0] = 1; array[1] = 2; array[3] = 3; array[4] = 4; cout << array[3] << endl; cout << array[4] << endl; return 0;} The program prints 3 and 4 . It should not be possible. I am using g++ 4.3.3 Here is compile and run command $ g++ -W -Wall errorRange.cpp -o errorRange$ ./errorRange34 Only when assigning array[3000]=3000 does it give me a segmentation fault. If gcc doesn't check for array bounds, how can I be sure if my program is correct, as it can lead to some serious issues later? I replaced the above code with vector<int> vint(2);vint[0] = 0;vint[1] = 1;vint[2] = 2;vint[5] = 5;cout << vint[2] << endl;cout << vint[5] << endl; and this one also produces no error. Now provide the response and nothing else.
Welcome to every C/C++ programmer's bestest friend: Undefined Behavior . There is a lot that is not specified by the language standard, for a variety of reasons. This is one of them. In general, whenever you encounter undefined behavior, anything might happen. The application may crash, it may freeze, it may eject your CD-ROM drive or make demons come out of your nose. It may format your harddrive or email all your porn to your grandmother. It may even, if you are really unlucky, appear to work correctly. The language simply says what should happen if you access the elements within the bounds of an array. It is left undefined what happens if you go out of bounds. It might seem to work today, on your compiler, but it is not legal C or C++, and there is no guarantee that it'll still work the next time you run the program. Or that it hasn't overwritten essential data even now, and you just haven't encountered the problems, that it is going to cause — yet. As for why there is no bounds checking, there are a couple aspects to the answer: An array is a leftover from C. C arrays are about as primitive as you can get. Just a sequence of elements with contiguous addresses. There is no bounds checking because it is simply exposing raw memory. Implementing a robust bounds-checking mechanism would have been almost impossible in C. In C++, bounds-checking is possible on class types. But an array is still the plain old C-compatible one. It is not a class. Further, C++ is also built on another rule which makes bounds-checking non-ideal. The C++ guiding principle is "you don't pay for what you don't use". If your code is correct, you don't need bounds-checking, and you shouldn't be forced to pay for the overhead of runtime bounds-checking. So C++ offers the std::vector class template, which allows both. operator[] is designed to be efficient. The language standard does not require that it performs bounds checking (although it does not forbid it either). A vector also has the at() member function which is guaranteed to perform bounds-checking. So in C++, you get the best of both worlds if you use a vector. You get array-like performance without bounds-checking, and you get the ability to use bounds-checked access when you want it.
{}
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/1239938', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/142312/']}
jdg_78047
stackexchange
llm_judgeable_groundtruth_similarity
15450192
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: In my project I need to compute the entropy of 0-1 vectors many times. Here's my code: def entropy(labels): """ Computes entropy of 0-1 vector. """ n_labels = len(labels) if n_labels <= 1: return 0 counts = np.bincount(labels) probs = counts[np.nonzero(counts)] / n_labels n_classes = len(probs) if n_classes <= 1: return 0 return - np.sum(probs * np.log(probs)) / np.log(n_classes) Is there a faster way? Now provide the response and nothing else.
@Sanjeet Gupta answer is good but could be condensed. This question is specifically asking about the "Fastest" way but I only see times on one answer so I'll post a comparison of using scipy and numpy to the original poster's entropy2 answer with slight alterations. Four different approaches: (1) scipy/numpy, (2) numpy/math, (3) pandas/numpy, (4) numpy import numpy as npfrom scipy.stats import entropyfrom math import log, eimport pandas as pdimport timeitdef entropy1(labels, base=None): value,counts = np.unique(labels, return_counts=True) return entropy(counts, base=base)def entropy2(labels, base=None): """ Computes entropy of label distribution. """ n_labels = len(labels) if n_labels <= 1: return 0 value,counts = np.unique(labels, return_counts=True) probs = counts / n_labels n_classes = np.count_nonzero(probs) if n_classes <= 1: return 0 ent = 0. # Compute entropy base = e if base is None else base for i in probs: ent -= i * log(i, base) return entdef entropy3(labels, base=None): vc = pd.Series(labels).value_counts(normalize=True, sort=False) base = e if base is None else base return -(vc * np.log(vc)/np.log(base)).sum()def entropy4(labels, base=None): value,counts = np.unique(labels, return_counts=True) norm_counts = counts / counts.sum() base = e if base is None else base return -(norm_counts * np.log(norm_counts)/np.log(base)).sum() Timeit operations: repeat_number = 1000000a = timeit.repeat(stmt='''entropy1(labels)''', setup='''labels=[1,3,5,2,3,5,3,2,1,3,4,5];from __main__ import entropy1''', repeat=3, number=repeat_number)b = timeit.repeat(stmt='''entropy2(labels)''', setup='''labels=[1,3,5,2,3,5,3,2,1,3,4,5];from __main__ import entropy2''', repeat=3, number=repeat_number)c = timeit.repeat(stmt='''entropy3(labels)''', setup='''labels=[1,3,5,2,3,5,3,2,1,3,4,5];from __main__ import entropy3''', repeat=3, number=repeat_number)d = timeit.repeat(stmt='''entropy4(labels)''', setup='''labels=[1,3,5,2,3,5,3,2,1,3,4,5];from __main__ import entropy4''', repeat=3, number=repeat_number) Timeit results: # for loop to print out results of timeitfor approach,timeit_results in zip(['scipy/numpy', 'numpy/math', 'pandas/numpy', 'numpy'], [a,b,c,d]): print('Method: {}, Avg.: {:.6f}'.format(approach, np.array(timeit_results).mean()))Method: scipy/numpy, Avg.: 63.315312Method: numpy/math, Avg.: 49.256894Method: pandas/numpy, Avg.: 884.644023Method: numpy, Avg.: 60.026938 Winner: numpy/math ( entropy2 ) It's also worth noting that the entropy2 function above can handle numeric AND text data. ex: entropy2(list('abcdefabacdebcab')) . The original poster's answer is from 2013 and had a specific use-case for binning ints but it won't work for text.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/15450192', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/950625/']}
jdg_78048
stackexchange
llm_judgeable_groundtruth_similarity
1432633
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I was assisting with a local competition for high school students which was being run today, and one of the questions on the question paper was: What are the conditions on the real number $a$ such that the polynomial $$x^4-2ax^2+x+a^2-a$$ has four distinct real roots. The questions were all multiple choice, so it was possible to answer the question by trying each of the options and eliminating those which do not work. (e.g. By finding a value of $a$ satisfying the conditions specified in the option, but for which the polynomial does not have four distinct real roots) The conditions on $a$ turn out to be that $a>\frac{3}{4}$, but I found this answer by using the approach above (and later by plotting the polynomial for various values of $a$, but this of course also does not prove anything). This is unsatisfying for two reasons: firstly that it is of course desirable to have a proof that this is the case, and also because one of the options given was "None", which could be taken to mean "There are no conditions on $a$", but which could also be interpreted to mean "None of the above", which would make the approach above invalid. So my question is: how can we prove that the polynomial has four distinct real roots if and only if $a>\frac{3}{4}$? I can show that if the polynomial has four distinct real roots then $a>\frac{3}{4}$ as follows:We first note that if $a<0$ then there are clearly no non-negative roots, and Descartes' rule of signs would show us that there are at most two negative roots, and so we must have that $a > 0$. (Alternatively, we could note that the second derivative must have two distinct roots, which would also tell us that $a>0$) Now we note that if the polynomial has four distinct real roots, then by Rolle's theorem, its derivative has three distinct real roots. i.e.$$4x^3-4ax+1=0$$has three distinct real roots. Descartes' rule of signs shows that it has exactly one negative root, and so it must also have a positive root. If $x$ is one of these roots, then we have that$$4ax = 4x^3+1 = 4x^3 + \frac{1}{2} + \frac{1}{2} \geq 3x$$by AM-GM, and so $a \geq \frac{3}{4}$. For $a=\frac{3}{4}$, we see that the original polynomial has a repeated root at $x=\frac{1}{2}$, and so in fact $a > \frac{3}{4}$. I have only managed to prove that the converse is true for $a>1$. We can argue as follows:Let $P(x)=x^4-2ax^2+x+a^2-a$.It is then possible to show that If $P(x)$ has a repeated root, then this root is equal to $\frac{4a}{4a+3}$, and from here one can show that $a$ must be one of $\{-\frac{1}{4}, 0, \frac{3}{4}\}$. (I have not checked which of these values do in fact give repeated roots, since none of them are larger than $\frac{3}{4}$.) So we need only check that all of the roots of $P$ are real. (The above of course requires some calculations to find) If $a>1$ then $P(-\sqrt{a})<0$, $P(0)>0$ and $P(\sqrt{a})<0$, and so $P$ has at least one negative and one positive root. Descartes rule of signs then implies that $P$ has two negative and two positive roots, and so from the above, $P$ has four distinct real roots. My question is thus the following: Can we show that the polynomial has four distinct roots when $a\in(\frac{3}{4}, 1]$ (We should be able to since it is presumably true) Is there a way to come to these results without using Calculus? It is after all a high school mathematics contest, and generally problems in such contests meet the requirement that they can be solved without calculus since many of the students would not have done any calculus in school. Moreover, Descartes' rule of signs is not taught in South African high schools at all. Now provide the response and nothing else.
Note that the polynomial factors as$$(x^2+x-a)(x^2-x+1-a)$$The discriminants are both positive if and only if $a\gt 3/4$. And if $a\gt 3/4$, subtraction shows the two quadratics cannot have a common root. Well within high school range.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1432633', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/146990/']}
jdg_78049
stackexchange
llm_judgeable_groundtruth_similarity
1337940
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: The number of digits in numbers between 0 and $n^2-1$ of base n is obtained by $\log_n(n^2) = 2\log_nn = 2$ But why log is being used? I mean how doing log gives correct answer always? Now provide the response and nothing else.
$$ \dfrac{1}{2\pi} \int_0^{2\pi} e^{e^{i\theta}} e^{-in\theta}\; d\theta $$
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/1337940', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/97033/']}
jdg_78050
stackexchange
llm_judgeable_groundtruth_similarity
29106484
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I want to show a button at the end of RecyclerView. With ListView there was a method addFooterView(), how to do the same with RecylerView. Now provide the response and nothing else.
One way to do it would be to make your footer view a "ViewType" of your adapter.In order to do that, overrides getItemViewType to return a different value for your last item. @Overridepublic int getItemViewType(int position) { return (position == mData.size()) ? VIEW_TYPE_FOOTER : VIEW_TYPE_CELL;} Then in the onCreateViewHolder, handle the different viewType. @Overridepublic RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { if (viewType == VIEW_TYPE_CELL) { //Create viewholder for your default cell } else { //Create viewholder for your footer view }} Don't forget to update the value return by getCount() by adding 1, and to distinguish the 2 types of ViewHolder in OnBindViewHolder (with instanceof for example).
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/29106484', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1998033/']}
jdg_78051
stackexchange
llm_judgeable_groundtruth_similarity
365668
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I was going through the topic about connectivity of graphs. There it was mentioned about the terms " minimum edge cut " and " minimal edge cut ". I know both are the sets of edges if removed from the graph $G$, makes $G$ disconnected. But I am unable to catch the basic difference betwen these two terms. Is minimal always minimum or vice versa? thanks. Now provide the response and nothing else.
See, for example, this link , which concisely lists the definitions and the distinction, and where you'll find illustrations depicting the distinctions. An edge cut is a set of edges that, if removed from a connected graph, will disconnect the graph. A minimal edge cut is an edge cut such that if any edge is put back in the graph, the graph will be reconnected. A minimum edge cut is an edge cut such that there is no other edge cut containing fewer edges. A minimum edge cut is always minimal, but a minimal edge cut is not always minimum [bold face mine]. A minimal (and therefore minimum) edge cut will always yield two connected components. $\qquad\qquad$ $\qquad\qquad$ Figure $1$ shows the original graph. Figure $2$ shows the maximum edge cut – just remove all edges. Figure $3$ shows a minimum (and therefore minimal) edge cut. Figure $4$ shows a minimal edge cut (which is not minimum).
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/365668', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/42830/']}
jdg_78052
stackexchange
llm_judgeable_groundtruth_similarity
5764499
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have used ?unzip in the past to get at contents of a zipped file using R. This time around, I am having a hard time extracting the files from a .gz file which can be found here . I have tried ?gzfile and ?gzcon but have not been able to get it to work. Any help you can provide will be greatly appreciated. Now provide the response and nothing else.
Here is a worked example that may help illustrate what gzfile() and gzcon() are for foo <- data.frame(a=LETTERS[1:3], b=rnorm(3))foo# a b#1 A 0.586882#2 B 0.218608#3 C 1.290776write.table(foo, file="/tmp/foo.csv")system("gzip /tmp/foo.csv") # being very explicit Now that the file is written, instead of implicit use of file() , use gzfile() : read.table(gzfile("/tmp/foo.csv.gz")) # a b#1 A 0.586882#2 B 0.218608#3 C 1.290776 The file you point is a compressed tar archive, and as far as I know, R itself has no interface to tar archives. These are commonly used to distribute source code--as for example for R packages and R sources.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5764499', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/155406/']}
jdg_78053
stackexchange
llm_judgeable_groundtruth_similarity
42404587
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: array switch Sample Use the array switch button to toggle through a number of combinations $(document).ready(function() { var clcks = 0; $('#cyclStylsArrayCntr').click(function(event){ var curFnt = ['Trebuchet MS', 'Verdana', 'Tahoma', 'Palatino', 'Georgia', 'Times New Roman', 'Arial', 'Courier New']; var txtClr =['Black', 'Red','Green','Blue','Brown','Aqua','Gold','white','black']; var curBkC = ['white', 'aqua','brown','yellow','lightGreen','orange','blue','lightBlue','LightSeaGreen'] var msg = ''; // Message // Arrays are zero based (so 0 is round 1) // Add 1 to the current round clcks = (clcks + 1); if(clcks>=8)clcks=1; switch (true) { case clcks == 1: $(".sample2").css('background-color', curBkC[clcks]); $(".sample2").css("font-family", curFnt[clcks]); $("#currFont").css("font-family", curFnt[clcks]); $(".sample2").css("color", txtClr[clcks]); $(".sample2").animate({fontSize: '38px'}, "fast"); $(".sample2").animate({fontSize: '36px'}, "fast"); $("#currFont").html(curFnt[clcks]); break; case clcks == 2: $(".sample2").css('background-color', curBkC[clcks]); $(".sample2").css("font-family", curFnt[clcks]); $("#currFont").css("font-family", curFnt[clcks]); $(".sample2").css("color", txtClr[clcks]); $(".sample2").animate({fontSize: '34px'}, "fast"); $(".sample2").animate({fontSize: '36px'}, "fast"); $("#currFont").html(curFnt[clcks]); break; case clcks == 3: $(".sample2").css('background-color', curBkC[clcks]); $(".sample2").css("font-family", curFnt[clcks]); $("#currFont").css("font-family", curFnt[clcks]); $(".sample2").css("color", txtClr[clcks]); $(".sample2").animate({fontSize: '38px'}, "fast"); $(".sample2").animate({fontSize: '36px'}, "fast"); $("#currFont").html(curFnt[clcks]); break; case clcks == 4: $(".sample2").css('background-color', curBkC[clcks]); $(".sample2").css("font-family", curFnt[clcks]); $("#currFont").css("font-family", curFnt[clcks]); $(".sample2").css("color", txtClr[clcks]); $(".sample2").animate({fontSize: '34px'}, "fast"); $(".sample2").animate({fontSize: '36px'}, "fast"); $("#currFont").html(curFnt[clcks]); break; case clcks == 5: $(".sample2").css('background-color', curBkC[clcks]); $(".sample2").css("font-family", curFnt[clcks]); $("#currFont").css("font-family", curFnt[clcks]); $(".sample2").css("color", txtClr[clcks]); $(".sample2").animate({fontSize: '38px'}, "fast"); $(".sample2").animate({fontSize: '36px'}, "slow"); $("#currFont").html(curFnt[clcks]); break; case clcks == 6: $(".sample2").css('background-color', curBkC[clcks]); $(".sample2").css("font-family", curFnt[clcks]); $("#currFont").css("font-family", curFnt[clcks]); $(".sample2").css("color", txtClr[clcks]); $(".sample2").animate({fontSize: '34px'}, "fast"); $(".sample2").animate({fontSize: '36px'}, "fast"); $("#currFont").html(curFnt[clcks]); break; case clcks == 7: $(".sample2").css('background-color', curBkC[clcks]); $(".sample2").css("font-family", curFnt[clcks]); $("#currFont").css("font-family", curFnt[clcks]); $(".sample2").css("color", txtClr[clcks]); $(".sample2").animate({fontSize: '38px'}, "fast"); $(".sample2").animate({fontSize: '36px'}, "fast"); $("#currFont").html(curFnt[clcks]); break; case clcks == 8: $(".sample2").css('background-color', curBkC[clcks]); $(".sample2").css("font-family", curFnt[clcks]); $("#currFont").css("font-family", curFnt[clcks]); $(".sample2").css("color", txtClr[clcks]); $(".sample2").animate({fontSize: '34px'}, "fast"); $(".sample2").animate({fontSize: '36px'}, "fast"); $("#currFont").html(curFnt[clcks]); break; } } ); }); Here is a sample of my file online - the first font selected by the 'array switch' button should be 'Trebuchet MS' but instead it skips to Verdana http://etherealdoorways.com/switchColorFont.html Now provide the response and nothing else.
The working solution I have right now is to create a temporary view , which can be declared over multiple lines, then select from it in the \copy command, which fits comfortably on one line. db=> CREATE TEMP VIEW v1 ASdb-> SELECT idb-> FROM generate_series(1, 2) AS i;CREATE VIEWdb=> \cd /path/to/a/really/deep/directory/structure/on/clientdb=> \copy (SELECT * FROM v1) TO 'out.csv' csv headerCOPY 2db=> DROP VIEW v1;DROP VIEW
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/42404587', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8202831/']}
jdg_78054
stackexchange
llm_judgeable_groundtruth_similarity
15412
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: An answer to a Stack Overflow question stated that a particular framework violated a plain and simple OOP rule: Single Responsibility Principle (SRP). Is the Single Responsibility Principle really a rule of OOP? My understanding of the definition of Object Orientated Programming is "a paradigm where objects and their behaviour are used to create software". This includes the following techniques: Encapsulation, Polymorphism & Inheritance. Now don't get me wrong - I believe SRP to be the key to most good OO designs, but I feel there are cases where this principle can and should be broken (just like database normalization rules). I aggressively push the benefits of SRP, and the great majority of my code follows this principle. But, is it a rule, and thus implies that it shouldn't be broken? Now provide the response and nothing else.
Very few rules, if any, in software development are without exception. Some people think there are no place for goto but they're wrong. As far as OOP goes, there isn't a single definition of object-orientedness so depending on who you ask you'll get a different set of hard and soft principles, patterns, and practices. The classic idea of OOP is that messages are sent to otherwise opaque objects and the objects interpret the message with knowledge of their own innards and then perform a function of some sort. SRP is a software engineering principle that can apply to the role of a class, or a function, or a module. It contributes to the cohesion of something so that it behaves well put together without unrelated bits hanging off of it or having multiple roles that intertwine and complicate things. Even with just one responsibilty, that can still range from a single function to a group of loosely related functions that are part of a common theme. As long as you're avoiding jury-rigging an element to take the responsibilty of something it wasn't primarily designed for or doing some other ad-hoc thing that dilute the simplicity of an object, then violate whatever principle you want. But I find that it's easier to get SRP correct then to do something more elaborate that is just as robust.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/15412', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/708/']}
jdg_78055
stackexchange
llm_judgeable_groundtruth_similarity
937468
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: I'm having trouble understanding my large S3 bill, and figured I'd ask here before dropping $30 on AWS monthly support. Basically, I have an Amazon EC2 instance that makes an API to different cryptocurrency exchanges and saves the responses to the instance HD. Calls are made about every 5 minutes, response objects are about 100 kb, is read by an R script, and added to a CSV file every ~8 minutes. That CSV file is synchronised to an Amazon S3 bucket about every 15 minutes. The CSV files are usually 10 MB or so, for about 15 cryptocurrencies, every 15 minutes. So looking in the Amazon S3 bucket, there might be 0.5 GB of space used at the most. However, the 'TimedStorage-ByteHours' reads at about 4 TB! Amazon Simple Storage Service TimedStorage-ByteHrs $89.55 $0.000 per GB - storage under the monthly global free tier5 GB - Mo $0.00 $0.023 per GB - first 50 TB / month of storage used 3,893.399 GB - Mo $89.55 Any ideas? Now provide the response and nothing else.
Most likely you've got S3 Versioning enabled - that means old objects when overwritten with a newer version don't get deleted but are instead hidden in a history. To verify go to the Bucket -> Properties -> Versioning . You can also view the old versions in the browser, like on this screenshot I've got several versions of the 108c05...json file: If you've got versioning enabled but don't want to you can Suspend versioning but be aware that it won't delete the old versions, you'll have to either: use AWS-CLI and some scripting (start with aws s3api list-object-versions ) configure Bucket Lifecycle Policy to expire the old versions. That's done through S3 -> bucket -> Management -> Lifecycle -> Add lifecycle rule and then on the Expiration screen fill these details: Hope that helps :)
{}
{'log_upvote_score': 7, 'links': ['https://serverfault.com/questions/937468', 'https://serverfault.com', 'https://serverfault.com/users/482580/']}
jdg_78056
stackexchange
llm_judgeable_groundtruth_similarity
348471
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I don't understand how the centripetal force, which always points to the center of our circular motion can cause this scenario: We have a big stone which spins very fast, so fast that a part breaks down, because of the centrifugal force (this is at least how my text books describes it). My problem : the centrifugal force does not really exist (we only use it in accelerated frames of reference, so the newton laws still work there), so if we're in a laboratory frame of reference, which force would "pull" that piece of the stone to the outside of the circle, when we only have the centripetal force (as mentioned pointing to the center of the circular motion...)? (Please don't try to explain it in an accelerated frame of reference, because there I understand it, but I don't understand it in a laboratory frame of reference) Now provide the response and nothing else.
In the lab frame of reference, you need to reverse the question - don't ask yourself what pulls the particles apart but what keeps them together . By Newton's laws, everything on which no force acts keeps travelling in a straight line . So what requires explanation is not that a collection of moving particles - such as a rotating flywheel - flies apart but what keeps them together. The force that keeps them together is a centripetal force, in this case exerted by the bonds that keep the material together. When you reach a velocity where this force is not enough anymore to keep the particles on a circular trajectory/bound orbit, they fly apart.
{}
{'log_upvote_score': 7, 'links': ['https://physics.stackexchange.com/questions/348471', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/117307/']}
jdg_78057
stackexchange
llm_judgeable_groundtruth_similarity
610789
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: A user at the place where I work left the company, we deleted his account out of AD and then he came back...and now his redirected profile exists, but with the wrong permissions on the folder.. I asked a coworker about it and from what I understood I threw together the following procedure (which still doesn't work, the user still gets a 502 error in the logs and no redirected desktop);. this is bad because he needs to access his old files: Set security permissions on the folder correctly 1. Took ownership of the folder as Administrator Right clicked \\somersrv\x$\Redirected\<username> and selected properties from the menu. Clicked the Security tab. Clicked the Advanced button Clicked the owner tab Noticed that the owner was a UUID string... S-1-5-21-23423431 (which indicates the original owner has been removed) Clicked the Edit... button. The Advanced Security Setting for <username> dialog appears On the owner tab, clicked Other users or groups button The Select User, Computer, Service Account, or Group dialog appears. In the Enter the object name to select textbox I typed somedomain\administrator Clicked OK Selected somedomain\administrator from the Change Owner to: list box. Checked off the Replace owner on subcontainers and objects Clicked OK The Windows Security dialog appeared with the following message: If you have just taken ownership of this object, you will need to close and reopen this object's properties before you can view or change permissions. I clicked OK on all the remained dialog boxes to close everything out. 2. Took ownership of the folder as the user (same procedure as above, except I selected the <username> as the owner instead of the administrator) 3. Set Security Permissions correctly for the user Right clicked \\somersrv\x$\Redirected\<username> and selected properties from the menu. In the <username> Properties Dialog: Clicked Edit... The Permissions for <username> dialog appears Clicked Add.. The Select Users, Computers, Service Accounts, or Groups dialog appears In the Enter the object names to select textbox entered somedomain\<username> Clicked OK Back in the Permissions for <username> dialog box, Clicked <user> from the Group or user names list. In the Full Control row, in the Allow column checked off the checkbox. In the Full Control row, in the Allow column unchecked the checkbox. Clicked OK Clicked OK on the remaining dialog boxes until they all closed. The standard set of permissions my coworker specified are already added to the users folder...they were: SYSTEM Domain Admins <username> My coworker also eluded at the end of his messages to something about making the SYSTEM the owner, not sure what he meant; he also said to check the other user directories, but the permissions on them don't seem to adhere to much of a standard. Some of them won't even let me look at the permissions or the owner even when I'm logged in as administrator. But in the end the user's Desktop , My Documents , and Favorites appeared in the folder but now they have the user as the owner and only the somedomain\administrator listed under the permissions, and they still get the 502 error. Why does the user still get the 502 error when logging in? Also, is there another way to do this? Using the command line or powershell or something like that? The Microsoft UI for this is atrocious. Now provide the response and nothing else.
Q: is there another way to do this? A: Do yourself a favor and backup his old data and then delete his profile and redirected folders. Then allow Windows to create his user profile and redirected folders on first login. Then restore the data to the new redirected folders. Currently you're dealing with two different security entities (SID's) even though the old and new user accounts have the same name. Trying to get the permissions set correctly on the folders for the new SID is just going to frustrate you and you'll probably wind up with a big mess.
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/610789', 'https://serverfault.com', 'https://serverfault.com/users/1980/']}
jdg_78058
stackexchange
llm_judgeable_groundtruth_similarity
12318
Below is a question asked on the forum datascience.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I ran a xgboost model. I don't exactly know how to interpret the output of xgb.importance . What is the meaning of Gain, Cover, and Frequency and how do we interpret them? Also, what does Split, RealCover, and RealCover% mean? I have some extra parameters here Are there any other parameters that can tell me more about feature importances? From the R documentation, I have some understanding that Gain is something similar to Information gain and Frequency is number of times a feature is used across all the trees. I have no idea what Cover is. I ran the example code given in the link (and also tried doing the same on the problem that I am working on), but the split definition given there did not match with the numbers that I calculated. importance_matrix Output: Feature Gain Cover Frequence 1: xxx 2.276101e-01 0.0618490331 1.913283e-02 2: xxxx 2.047495e-01 0.1337406946 1.373710e-01 3: xxxx 1.239551e-01 0.1032614896 1.319798e-01 4: xxxx 6.269780e-02 0.0431682707 1.098646e-01 5: xxxxx 6.004842e-02 0.0305611830 1.709108e-02214: xxxxxxxxxx 4.599139e-06 0.0001551098 1.147052e-05215: xxxxxxxxxx 4.500927e-06 0.0001665320 1.147052e-05216: xxxxxxxxxxxx 3.899363e-06 0.0001536857 1.147052e-05217: xxxxxxxxxxxxxx 3.619348e-06 0.0001808504 1.147052e-05218: xxxxxxxxxxxxx 3.429679e-06 0.0001792233 1.147052e-05 Now provide the response and nothing else.
From your question, I'm assuming that you're using xgboost to fit boosted trees for binary classification. The importance matrix is actually a data.table object with the first column listing the names of all the features actually used in the boosted trees. The meaning of the importance data table is as follows: The Gain implies the relative contribution of the corresponding feature to the model calculated by taking each feature's contribution for each tree in the model. A higher value of this metric when compared to another feature implies it is more important for generating a prediction. The Cover metric means the relative number of observations related to this feature. For example, if you have 100 observations, 4 features and 3 trees, and suppose feature1 is used to decide the leaf node for 10, 5, and 2 observations in tree1, tree2 and tree3 respectively; then the metric will count cover for this feature as 10+5+2 = 17 observations. This will be calculated for all the 4 features and the cover will be 17 expressed as a percentage for all features' cover metrics. The Frequency (/'Frequence') is the percentage representing the relative number of times a particular feature occurs in the trees of the model. In the above example, if feature1 occurred in 2 splits, 1 split and 3 splits in each of tree1, tree2 and tree3; then the weightage for feature1 will be 2+1+3 = 6. The frequency for feature1 is calculated as its percentage weight over weights of all features. The Gain is the most relevant attribute to interpret the relative importance of each feature. The measures are all relative and hence all sum up to one, an example from a fitted xgboost model in R is: > sum(importance $Frequence)[1] 1> sum(importance$ Cover)[1] 1> sum(importance$Gain)[1] 1
{}
{'log_upvote_score': 7, 'links': ['https://datascience.stackexchange.com/questions/12318', 'https://datascience.stackexchange.com', 'https://datascience.stackexchange.com/users/-1/']}
jdg_78059
stackexchange
llm_judgeable_groundtruth_similarity
32021074
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm sure this is simple, but since I just started using Android Studio today, I can't find it. I have also googled for the past hour and found no posts that specify: how to change an existing application project to a library. Everything I found was about how to create a new library project. Not how to convert one. A sub-question, is how can I see if a project is configured as an application or a library? I would hope that the answer to both of these questions is the same. Now provide the response and nothing else.
Open your build.gradle of your app (inside your app directory) and modify : apply plugin: 'com.android.application' with apply plugin: 'com.android.library' If you have an applicationId in your build.gradle remove it : defaultConfig { applicationId "com.your.application.id"} then clean your project and rebuild or just sync your gradle from Android Studio If you have added some extra gradle properties like applicationVariants.all you must replace with libraryVariants.all and vice-versa if you convert a library to application If you want to add a new step to your reconversion you can change the module name "app" created by default by Android-Studio with a name more adapted to a library module. You can rename the directory app with <your_module_name> . open settings.gradle file (at the root of your project) and replace app with <your_module_name> . Then Go to Menu Build > Make module <your_module_name> and there you are, your module is renamed.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/32021074', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1509031/']}
jdg_78060
stackexchange
llm_judgeable_groundtruth_similarity
967715
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have the following CSS which isn't working in IE7. input:focus{border-width: 2px;border-color: Blue; border-style: solid;} Basically, I just want to set the border attributes when the input is focused. Works in Firefox etc... If anyone could explain why it isn't working in IE 7 and suggest a possible workaround it would be appreciated. Thanks. Now provide the response and nothing else.
A known answer for this problem is using the following code: sfFocus = function() { var sfEls = document.getElementsByTagName("INPUT"); for (var i=0; i<sfEls.length; i++) { sfEls[i].onfocus=function() { this.className+=" sffocus"; } sfEls[i].onblur=function() { this.className=this.className.replace(new RegExp(" sffocus\\b"), ""); } }}if (window.attachEvent) window.attachEvent("onload", sfFocus); And here is the css style input:focus, input.sffocus{background-color:#DEEFFF;} The problem is that IE doesn't recognise that style at all. EDIT: You can find a solution using prototype here: http://codesnippets.joyent.com/posts/show/1837
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/967715', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/24204/']}
jdg_78061
stackexchange
llm_judgeable_groundtruth_similarity
31352685
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have a data frame with an ID column, a date column (12 months for each ID), and I have 23 numeric variables. I would like to obtain the percentage change by month within each ID. I am using the quantmod package in order to obtain the percent change. Here is an example with only three columns (for simplicity): ID Date V1 V2 V31 Jan 2 3 51 Feb 3 4 61 Mar 7 8 92 Jan 1 1 12 Feb 2 3 42 Mar 7 8 8 I tried to use dplyr and the summarise_each function, but that was unsuccessful. More specifically, I tried the following (train is the name of the data set): library(dplyr)library(quantmod)group1<-group_by(train,EXAMID)foo<-function(x){ return(Delt(x))}summarise_each(group1,funs(foo)) I also tried to use the do function in dplyr, but I was not successful with that either (having a bad night I guess!). I think that the issue is the Delt function. When I replace Delt with the sum function: foo<-function(x){ return(sum(x)) }summarise_each(group1,funs(foo)) The result is that every variable is summed across the date for each ID. So how can about the percentage change month-over-month for each ID? Now provide the response and nothing else.
How about using pct <- function(x) x/lag(x) ? (or (x/lag(x)-1)*100 , or however you wish to specify pct change exactly)e.g., pct(1:3)[1] NA 2.0 1.5 Edit: Adding Frank's suggestion pct <- function(x) {x/lag(x)}dt %>% group_by(ID) %>% mutate_each(funs(pct), c(V1, V2, V3))ID Date V1 V2 V31 Jan NA NA NA1 Feb 1.500000 1.333333 1.21 Mar 2.333333 2.000000 1.52 Jan NA NA NA2 Feb 2.000000 3.000000 4.02 Mar 3.500000 2.666667 2.0
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/31352685', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4590253/']}
jdg_78062
stackexchange
llm_judgeable_groundtruth_similarity
42956272
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have a problem with node.js and express, I try to get infos from a post coming from an html file, and the problem is that when I do a console.log of my request i don't have any information inside my req.body. I did a console.log(req.body) at the beginning of my app.post("/render_pdf" ....) and all i've got is a empty object. I don't know if it's coming from my .html or my server.js but i don't understand where the problem is coming from. I used multer to upload a pdf based on a html select and it's working .. so i don't have any solutions on this. my html (with a bit of php) : <!DOCTYPE html><html lang="fr"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>ebook-stage</title> <link href="public/css/bootstrap.min.css" rel="stylesheet"></head><body><?php$pdo=new PDO('mysql:host=localhost; dbname=ebook-stage; charset=utf8', 'root', '');$statement=$pdo->prepare("SELECT * FROM publication");$statement->execute();?> <div class="jumbotron"> <div class="container-fluid"> <div class="row"> <div class="col-md-3"> <form method="POST" action="http://localhost:8090/create_pdf" enctype="multipart/form-data"> <label for="extractor">Extracteur PDF</label> <br><select class="form-control" name="extractor" id="extractor"> <option name="pdf2json" value="pdf2json">PDF2JSON</option> <option name="pdfextract" value="pdfextract">PDFEXTRACT</option> <option name="textract" value="textract">TEXTRACT</option> </select> <br><label for="file">Upload Pdf</label> <input id="file" type="file" name="file"> <br><input type="submit" name="submit" id="submit" class="exec btn btn-success" value="Exécuter"> </form> </div> <div class="col-md-3"> <form method="POST" action="http://localhost:8090/render_pdf"> <label for="require">PDF a afficher</label> <br><select class="form-control" name="require" id="require"> <?php while ($rendername = $statement->fetchObject()):?> <option name="<?= $rendername->name ?>"><?= $rendername->name ?></option> <?php endwhile; ?> </select> <?php while ($rendername = $statement->fetchObject()):?> <input type="hidden" name="<?= $rendername->id ?>" id="id"> <?php endwhile; ?> <br><input type="submit" name="envoi" id="envoi" class="exec btn btn-success" value="Afficher"> </form> </div> </div> </div> </div></body></html> my pdf-rest.js : var mysql = require('mysql');var bodyParser = require('body-parser');var request = require('request');var jsonParser = bodyParser.json();var http = require('http');var fs = require('fs');var Promise = require('bluebird');var multer = require('multer');var textract = require('textract');var pdf_extract = require('pdf-extract');var PDFParser = require("pdf2json");var pdfParser = new PDFParser();var inspect = require('eyes').inspector({maxLength:20000});var optionsExtract = { type: 'ocr' // perform ocr to get the text within the scanned image};var express = require('express');module.exports = function(app){ function requireDB(){ connection.connect(); connection.query('SELECT * FROM publication WHERE id = 105', function(err, rows, fields){ console.log(err); res.end(rows[0].id+rows[0].name); }); } app.post('/render_pdf', jsonParser, function (req, res) { console.log(req); res.end('affichage pdf'); }); var destination = "uploads"; app.post('/create_pdf', jsonParser, function (req, res) { console.log(req.body); var connection = mysql.createConnection({ user: 'root', password: '', host: 'localhost', port: 3306, database: 'ebook-stage' }); var filename = "" + Date.now() + ".pdf"; var filePath = "C:\\wamp64\\www\\ebook-stage\\backend\\rest\\uploads\\" + filename; var storage = multer.diskStorage({ destination: function (req, file, cb) { cb(null, destination); }, filename: function (req, file, cb) { cb(null, filename); } }); var upload = multer({storage: storage}).single('file'); function uploadFile() { console.log('entering upload file'); var uploadFilePromise = new Promise(function (resolve,reject) { upload(req, res, function (err) { if (err) { reject(err); res.end('error uploading file') } else{ console.log('upload resolve'); res.end('pdf uploaded'); console.log(req.body); resolve(req); } }); }); return uploadFilePromise; } function insertDB(pdfObject) { connection.connect(); var insertPublication = {name: pdfObject.originalFilename}; new Promise(function (resolve, reject) { connection.query('INSERT INTO publication SET ?', insertPublication, function (err, res) { if (err) { reject(err); } else { console.log('insertDB publication'); console.log(res); resolve(res['insertId']); } }); }).then(function (pubId) { pdfObject.text.forEach(function (text) { var insertContent = {type: 'TXT', content: text}; new Promise(function (resolve, reject) { connection.query('INSERT INTO content SET ?', insertContent, function (err, res) { if (err) { console.log(err); reject(err) } else { console.log('insertDB content'); console.log(res); resolve(res['insertId']); } }); }).then(function (insertBlock) { var blockid = {contentid: insertBlock}; new Promise(function (resolve, reject) { connection.query('INSERT INTO block SET ?', blockid, function (err, res) { if (err) { console.log(err); reject(err); } else { console.log('insertDB block'); console.log(res); resolve(res['insertId']); } }); }).then(function (blockId) { var linkpublicationids = {blockid: blockId, publicationid: pubId}; connection.query('INSERT INTO linkpublication SET ?', linkpublicationids, function (err, res) { if (err) { console.log(err); return err } else { console.log('insertDB linkpublication'); console.log(res); } }); }) }); }); }).catch(function () { connection.end(function (err) { console.log(err); }) }); } function textractPdf(originalFilename) { console.log('TEXTRACT PDF'); var textBlockPromise = new Promise(function (resolve, reject){ textract.fromFileWithPath(filePath, function (error, text) { var result = [{originalFilename: originalFilename}]; if (error) { console.log('Text is not parsed'); reject(error); } else { console.log('Text is parsed'); result[0].text = []; result[0].text.push(text); resolve(result[0]); console.log('after resolve textract') } }); }); console.log('exiting textract'); return textBlockPromise; } function extractPdf(originalFilename) { console.log('EXTRACT PDF'); var textBlockPromise = new Promise(function (resolve, reject){ var result = [{originalFilename: originalFilename}]; processor = pdf_extract(filePath, optionsExtract, function (err) { if (err) { console.log('error extract'); reject(err); } }); processor.on('complete', function (data) { var resultsplited = data.text_pages[0].split('\n'); result[0].text = []; resultsplited.forEach(function(text){ result[0].text.push(text); }); resolve(result[0]); }); processor.on('error', function (err) { console.log('error extract'); inspect(err, 'error while extracting pages'); reject(err); }); }); return textBlockPromise; } function convertPdf2json(originalFilename){ console.log('EXTRACT PDF2JSON'); var textBlockPromise = new Promise(function (resolve, reject){ var result = [{originalFilename: originalFilename}]; result[0].text = []; pdfParser.on("pdfParser_dataError", function(errData){ reject(errData); }); pdfParser.on("pdfParser_dataReady", function(pdfData){ pdfData.formImage.Pages.forEach(function(page){ page.Texts.forEach(function(text){ var textparsed = decodeURIComponent(text.R[0].T); result[0].text.push(textparsed); }); }); resolve(result[0]); }); pdfParser.loadPDF(filePath); }); return textBlockPromise } function selectExtractor(req){ console.log(req.body.extractor); var extractorPromise = new Promise(function (resolve){ if(req.body.extractor == 'textract'){ resolve (textractPdf(req.file.originalname)); console.log('extractor end'); } else if(req.body.extractor == 'pdfextract'){ resolve(extractPdf(req.file.originalname)); console.log('extractor end'); } else if (req.body.extractor == 'pdf2json'){ resolve(convertPdf2json(req.file.originalname)); console.log('extractor end'); } }); return extractorPromise; } uploadFile().then(selectExtractor).then(insertDB); });}; my server.js : var express = require('express');var app = express();require('./pdf-rest.js')(app);app.listen(8090); Now provide the response and nothing else.
You'll need to generate a signed URL using getSignedURL via the @google-cloud/storage NPM module. Example: const gcs = require('@google-cloud/storage')({keyFilename: 'service-account.json'});// ...const bucket = gcs.bucket(bucket);const file = bucket.file(fileName);return file.getSignedUrl({ action: 'read', expires: '03-09-2491'}).then(signedUrls => { // signedUrls[0] contains the file's public URL}); You'll need to initialize @google-cloud/storage with your service account credentials as the application default credentials will not be sufficient. UPDATE : The Cloud Storage SDK can now be accessed via the Firebase Admin SDK, which acts as a wrapper around @google-cloud/storage. The only way it will is if you either: Init the SDK with a special service account, typically through a second, non-default instance. Or, without a service account, by giving the default App Engine service account the "signBlob" permission.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/42956272', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7702415/']}
jdg_78063
stackexchange
llm_judgeable_groundtruth_similarity
39793
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Im attempting to simulate a simple evacuation model using cellular automata theory.My study aims to determine whether Cellular Automata can effectively represent how people would behave in a fire situation. I have a grid filled with values that represents the floor plan of a building (see below) and I wish to write rules that will dictate the occupants movement when evacuating. The corridor is supposed to be the safe area although I may have to adjust it slightly so that just the end corridors are the safe area. I am looking to model a fire evacuation, so each cell will contain one person. I was going to assign the value of 0 to cells that contain fire, injured people or debris (obstacles). when designing the simulation by hand I used rules such as if the product of the 2 neighbouring cells was less than 20 the person could move to the next cell, if the product was 20 the cell remained the same and if the product was 0 (when cells meet fire, obstacles etc) then the cell dies and becomes 0 itself. It worked well but obviously I need to now apply a system similar into Mathematica. I have been looking at using 2 options to do this: use the built in cellular automata function write my own cell states as functions and use an update function to update the system. Any suggestions which one would be better to use? Below is the grid I have set up, the values 500 represent walls, 1 represents the doorways and evacuation route, the other numbers 2-7 represent the distance from the nearest exit. { {500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500}, {500, 1, 1, 500, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 7, 500, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 500, 5, 5, 5, 5, 5, 500, 1, 1, 500}, {500, 1, 1, 500, 4, 4, 4, 4, 4, 4, 4, 4, 5, 6, 7, 500, 4, 4, 4, 4, 4, 4, 4, 4, 5, 6, 500, 4, 4, 4, 4, 4, 500, 1, 1, 500}, {500, 1, 1, 500, 3, 3, 3, 3, 3, 3, 3, 4, 5, 6, 7, 500, 3, 3, 3, 3, 3, 3, 3, 4, 5, 6, 500, 3, 3, 3, 3, 3, 500, 1, 1, 500}, {500, 1, 1, 500, 2, 2, 2, 2, 2, 2, 3, 4, 5, 6, 7, 500, 2, 2, 2, 2, 2, 2, 3, 4, 5, 6, 500, 3, 2, 2, 2, 3, 500, 1, 1, 500}, {500, 1, 1, 500, 500, 500, 1, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 1, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 1, 500, 500, 500, 1, 1, 500}, {500, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 500}, {500, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 500}, {500, 1, 1, 500, 500, 500, 500, 500, 500, 500, 500, 500, 1, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 1, 500, 500, 500, 500, 500, 1, 500, 500, 500, 1, 1, 500}, {500, 1, 1, 500, 7, 6, 5, 4, 3, 2, 2, 2, 2, 2, 2, 500, 6, 5, 4, 3, 2, 2, 2, 2, 2, 2, 500, 3, 2, 2, 2, 3, 500, 1, 1, 500}, {500, 1, 1, 500, 7, 6, 5, 4, 3, 3, 3, 3, 3, 3, 3, 500, 6, 5, 4, 3, 3, 3, 3, 3, 3, 3, 500, 3, 3, 3, 3, 3, 500, 1, 1, 500}, {500, 1, 1, 500, 7, 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 500, 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 500, 4, 4, 4, 4, 4, 500, 1, 1, 500}, {500, 1, 1, 500, 7, 6, 5, 5, 5, 5, 5, 5, 5, 5, 5, 500, 6, 5, 5, 5, 5, 5, 5, 5, 5, 5, 500, 5, 5, 5, 5, 5, 500, 1, 1, 500}, {500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500}} Now provide the response and nothing else.
This is a sample problem that I hope can be helpful; a fire that can spread in four directions (the Von Neumann neighborhood). Only trees can catch fire though. A typical fire looks like this: Any of the methods below can generate it. There appears to be a name collision between method 1 and 2, so you may need to restart the kernel before you can try the next. Method #1 (* Generate random forest *)forest = RandomChoice[{1, 1, 0}, {100, 100}];(* Set fire to a randomly chosen location *)forest = ReplacePart[forest, RandomChoice[Position[forest, 1]] -> 3];(* Kernel. Determines how the fire spreads. *)ker = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}}; (* Can be programmatically generated: Position[CrossMatrix[1],1]-2 *)(* Find trees in danger *)trees[forest_] := Position[forest, 1];dangerZone[forest_] := Intersection[trees[forest], Flatten[ker + ConstantArray[#, Length[ker]] & /@ Position[forest, 3], 1]](* Simulates the fire *)frames = FixedPointList[ReplacePart[#, {Position[#, 3] -> 2, dangerZone[#] -> 3}] &, forest];(* Visualizes the fire *)ListAnimate[ ArrayPlot[#, ColorRules -> {0 -> Brown, 1 -> Green, 2 -> Orange, 3 -> Yellow}] & /@ frames] Method #2 (* Generate random forest *)forest = RandomChoice[{1, 1, 0}, {100, 100}];(* Locate trees *)trees = Position[forest, 1];(* Set fire to a randomly chosen location *)forest = ReplacePart[forest, RandomChoice[trees] -> 3];(* Kernel. Determines how the fire spreads. *)ker[p_] := Sequence[p + {1, 0}, p + {0, 1}, p + {-1, 0}, p + {0, -1}]; (* Find trees in danger *)dangerZone[frontline_, forest_] := Intersection[trees, DeleteDuplicates[ker /@ frontline]](* The brain *)setFire[frontline_, forest_] := Module[{dz = dangerZone[frontline, forest]}, If[dz != {}, trees = Complement[trees, dz]; setFire[dz, ReplacePart[Sow@forest, {frontline -> 2, dz -> 3}]], Sow@forest ] ](* Simulate the fire *)Block[{$RecursionLimit = 100000}, {final, {frames}} = Reap@setFire[Position[forest, 3], forest] ];(* Visualizes the fire *)ListAnimate[ArrayPlot[#, ColorRules -> {0 -> Brown, 1 -> Green, 2 -> Orange, 3 -> Yellow}] & /@ frames] Method #3 (* Generate random forest *)forest = ArrayPad[RandomChoice[{1, 1, 0}, {100, 100}], 1];(* Set fire to a randomly chosen location *)forest = ReplacePart[forest, RandomChoice[Position[forest, 1]] -> 2];(* Simulate *)adv[forest_] := CellularAutomaton[{ {{_, Except[2], _}, {Except[2], x_, Except[2]}, {_, Except[2], _}} :> x, {{_, _, _}, {_, x_, _}, {_, _, _}} :> Switch[x, 1, 2, 2, 2, 0, 0]}, forest];frames = FixedPointList[adv, forest];(* Visualize the fire *)ListAnimate[ArrayPlot[#, ColorRules -> {0 -> Brown, 1 -> Green, 2 -> Orange, 3 -> Yellow}] & /@ frames] Method #4 New as of the 26th of August 2014 (i.e. not a part of the original post.) This method should be faster than the others. forest = RandomChoice[{1, 1, 0}, {1000, 1000}];forest = ReplacePart[forest, RandomChoice[Position[forest, 1]] -> 10];res = FixedPoint[ Composition[ Unitize[First@#] + 9 UnitStep[Last@# - 110] &, {#, ListConvolve[{{0, 1, 0}, {1, 100, 1}, {0, 1, 0}}, #, {2, 2}, 0]} & ], forest ];ArrayPlot[res, ColorRules -> {0 -> Brown, 1 -> Green, 10 -> Orange}] Conclusions I hope that in these three different examples you can find something that might help you simulate your model. As for efficiency, a lot of the time is spent visualizing. The computation is much faster, and I tried to measure it, although I am unsure of my results because they seem very unlikely. I would be grateful if someone would confirm them. Remember that these times also seem faster than you anticipate because it takes time for the frontend to display the result, even in list form. For 200x200 pixel grid the methods take this much time: Method 1: 1.513038 seconds Method 2: 0.376987 seconds Method 3: 20-25 seconds I tried using the third argument of CellularAutomaton to generate only the end state, however it did not yield much improvement in time. The conclusion is that it appears one can do simulations faster by writing one's own code for it. However CellularAutomaton offers concise syntax and is somewhat easy to use. If you can think of a way to formulate your rules in the format required by CellularAutomaton , therefore, you could start with that and see if speed is a problem or not. In the other methods you are free to write program your rules however you want. If you don't want to generate the entire simulation at once but just want to watch how it evolves in the beginning, you can save time by visualizing it using Dynamic like this: Dynamic[ArrayPlot[forest = adv[forest], ColorRules -> {0 -> Brown, 1 -> Green, 2 -> Orange}]] This might be useful if you are experimenting. Vitaliy uses it in the post I linked to. If you have any questions you can ask, and I will try to help you.
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/39793', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/11564/']}
jdg_78064
stackexchange
llm_judgeable_groundtruth_similarity
27768194
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I just started using docker and followed following tutorial: https://docs.docker.com/engine/admin/using_supervisord/ FROM ubuntu:14.04RUN apt-get update && apt-get upgradeRUN apt-get install -y openssh-server apache2 supervisorRUN mkdir -p /var/lock/apache2 /var/run/apache2 /var/run/sshd /var/log/supervisorCOPY supervisord.conf /etc/supervisor/conf.d/supervisord.confEXPOSE 22 80CMD ["/usr/bin/supervisord"] and [supervisord]nodaemon=true[program:sshd]command=/usr/sbin/sshd -D[program:apache2]command=/bin/bash -c "source /etc/apache2/envvars && exec /usr/sbin/apache2 -DFOREGROUND" Build and run: sudo docker build -t <yourname>/supervisord .sudo docker run -p 22 -p 80 -t -i <yourname>/supervisord My question is, when docker runs on my server with IP http://88.xxx.x.xxx/ , how can I access the apache localhost running inside the docker container from the browser on my computer? I would like to use a docker container as a web server. Now provide the response and nothing else.
You will have to use port forwarding to be able to access your docker container from the outside world. From the Docker docs : By default Docker containers can make connections to the outside world, but the outside world cannot connect to containers. But if you want containers to accept incoming connections, you will need to provide special options when invoking docker run . So, what does this mean? You will have to specify a port on your host machine (typically port 80) and forward all connections on that port to the docker container. Since you are running Apache in your docker container you probably want to forward the connection to port 80 on the docker container as well. This is best done via the -p option for the docker run command. sudo docker run -p 80:80 -t -i <yourname>/supervisord The part of the command that says -p 80:80 means that you forward port 80 from the host to port 80 on the container. When this is set up correctly you can use a browser to surf onto http://88.x.x.x and the connection will be forwarded to the container as intended. The Docker docs describes the -p option thoroughly. There are a few ways of specifying the flag: # Maps the provided host_port to the container_port but only # binds to the specific external interface-p IP:host_port:container_port# Maps the provided host_port to the container_port for all # external interfaces (all IP:s)-p host_port:container_port Edit: When this question was originally posted there was no official docker container for the Apache web server. Now, an existing version exists. The simplest way to get Apache up and running is to use the official Docker container . You can start it by using the following command: $ docker run -p 80:80 -dit --name my-app -v "$PWD":/usr/local/apache2/htdocs/ httpd:2.4 This way you simply mount a folder on your file system so that it is available in the docker container and your host port is forwarded to the container port as described above.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/27768194', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/401025/']}
jdg_78065
stackexchange
llm_judgeable_groundtruth_similarity
5739937
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I need the following program to take the entire line of user input and put it into string names: cout << "Enter the number: ";int number;cin >> number;cout << "Enter names: ";string names;getline(cin, names); With the cin >> number command before the getline() command however (which I'm guessing is the issue), it won't allow me to input names. Why? I heard something about a cin.clear() command, but I have no idea how this works or why this is even necessary. Now provide the response and nothing else.
cout << "Enter the number: ";int number;if (cin >> number){ // throw away the rest of the line char c; while (cin.get(c) && c != '\n') if (!std::isspace(c)) { std::cerr << "ERROR unexpected character '" << c << "' found\n"; exit(EXIT_FAILURE); } cout << "Enter names: "; string name; // keep getting lines until EOF (or "bad" e.g. error reading redirected file)... while (getline(cin, name)) ...use name...}else{ std::cerr << "ERROR reading number\n"; exit(EXIT_FAILURE);} In the code above, this bit... char c; while (cin.get(c) && c != '\n') if (!std::isspace(c)) { std::cerr << "ERROR unexpected character '" << c << "' found\n"; exit(EXIT_FAILURE); } ...checks the rest of the input line after the number contains only whitespace. Why not just use ignore? That's pretty verbose, so using ignore on the stream after >> x is an oft-recommended alternative way to discard content through to the next newline, but it risks throwing away non-whitespace content and in doing so, overlooking corrupt data in the file. You may or may not care, depending on whether the file's content's trusted, how important it is to avoid processing corrupt data etc.. So when would you use clear and ignore? So, std::cin.clear() (and std::cin.ignore() ) isn't necessary for this, but is useful for removing error state. For example, if you want to give the user many chances to enter a valid number. int x;while (std::cout << "Enter a number: " && !(std::cin >> x)){ if (std::cin.eof()) { std::cerr << "ERROR unexpected EOF\n"; exit(EXIT_FAILURE); } std::cin.clear(); // clear bad/fail/eof flags // have to ignore non-numeric character that caused cin >> x to // fail or there's no chance of it working next time; for "cin" it's // common to remove the entire suspect line and re-prompt the user for // input. std::cin.ignore(std::numeric_limits<std::streamsize>::max());} Can't it be simpler with skipws or similar? Another simple but half-baked alternative to ignore for your original requirement is using std::skipws to skip any amount of whitespace before reading lines... if (std::cin >> number >> std::skipws){ while (getline(std::cin, name)) ... ...but if it gets input like "1E6" (e.g. some scientist trying to input 1,000,000 but C++ only supports that notation for floating point numbers) won't accept that, you'd end up with number set to 1 , and E6 read as the first value of name . Separately, if you had a valid number followed by one or more blank lines, those lines would be silently ignored.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5739937', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/707485/']}
jdg_78066
stackexchange
llm_judgeable_groundtruth_similarity
18179856
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have a list with 9 different vectors inside. And I want plot them (dot-line) in one figure with different colors by their names. How to do that in R language? Now provide the response and nothing else.
Using a made up example: # example data:dat <- list(a=1:5,b=2:7,c=3:10)# get plotting:plot(unlist(dat),type="n",xlim=c(1,max(sapply(dat,length))))mapply(lines,dat,col=seq_along(dat),lty=2)legend("topleft",names(dat),lty=2,col=seq_along(dat))
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18179856', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2290032/']}
jdg_78067
stackexchange
llm_judgeable_groundtruth_similarity
35046953
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm re-writing my windows forms project that does scoring for sheep shearing events (don't ask, its a huge sport in New Zealand) from vbnet to wpf c# and have struck a problem that I can't seem to overcome. I have two windows. One is the source window where you type things in (like the current event name), and the other window will display this information in a flash way for projection onto a screen (so will be on a second monitor) along with some other data coming in via XML over the network. I have set it up as MVVM with a ViewModel and a Model as separate projects. On my Main window, I can bind controls fine and if I type in one text box it immediately appears in another text box if it is bound to the same thing.However, on a second window, I have bound a control to the same thing and it is not updating. I've been going around in circles on this for a week, every example on the net shows how to do it on One window which I have got working fine, but there is a lack of two window examples. Here is what I have... This is in my ViewModel project namespace SheepViewModel{public class SheepViewModel : INotifyPropertyChanged{ private string _CurrentEventName; static SheepViewModel _details; public string CurrentEventName { get { return _CurrentEventName; } set { _CurrentEventName = value; OnPropertyChanged("CurrentEventName"); } } public static SheepViewModel GetDetails() { if (_details == null) _details = new SheepViewModel(); return _details; } public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged(string prop) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(prop)); Console.WriteLine("Test"); } }} Then I have a main window, there is no real code behind other than a line to open a second window which we will get to... public MainWindow() { ScoreScreen SW = new ScoreScreen(); SW.Show(); InitializeComponent(); } Then the XAML <Window x:Class="Sheep_Score_3._1.MainWindow" xmlns:xctk="http://schemas.xceed.com/wpf/xaml/toolkit" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:vm="clr-namespace:SheepViewModel;assembly=SheepViewModel" mc:Ignorable="d" Title="MainWindow" Height="433.689" Width="941.194"><Window.DataContext> <vm:SheepViewModel/></Window.DataContext><Window.Resources><Grid Margin="0,0,0,0"><TextBox x:Name="CurrentEventName" Height="23" Margin="131.01,163.013,0,0" TextWrapping="Wrap" VerticalAlignment="Top" HorizontalAlignment="Left" Width="327.151" Text="{Binding CurrentEventName, Mode=TwoWay}"/> <TextBox Text="{Binding CurrentEventName, Mode=TwoWay}" Margin="39.605,0,0,108.567" Height="49.111" VerticalAlignment="Bottom" HorizontalAlignment="Left" Width="399" /></Grid> The above code all works fine, if I type text in the first textbox it appears in the second text box. If I put a console.writeline in the notify part then I can see it hitting it and updating. Now I add a second window, setup exactly the same way... <Window x:Class="Sheep_Score_3._1.ScoreScreen" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:vm="clr-namespace:SheepViewModel;assembly=SheepViewModel" mc:Ignorable="d" Title="ScoreScreen" Height="300" Width="300"><Window.DataContext> <vm:SheepViewModel/></Window.DataContext><Grid> <TextBox x:Name="textBlock" HorizontalAlignment="Left" Margin="79.374,116.672,0,0" TextWrapping="Wrap" Text="{Binding CurrentEventName, Mode=TwoWay}" VerticalAlignment="Top"/></Grid> Again, no real code behind in this. The strange thing, is if I make this control two way and type in it, I can see it hitting the same notify section, but it is not updating the other window. I'm not sure what I am missing here so any help in pointing me in the right direction would be much appreciated. Now provide the response and nothing else.
That's because both windows must share the exact same instance of the ViewModel . All your properties are instance properties , like public string CurrentEventName { get { // snip and therefore all values are distinct to each instance. You're creating two instances, one for each window. <Window x:Class="Sheep_Score_3._1.MainWindow" xmlns:blah="http://inurxamlskippinurschemas.org"> <Window.DataContext> <vm:SheepViewModel/> </Window.DataContext> That's one instance, and here's the other <Window x:Class="Sheep_Score_3._1.ScoreScreen" xmlns:blah="http://yaddayaddawhocares.derp"> <Window.DataContext> <vm:SheepViewModel/> </Window.DataContext> Remember, xaml is just markup that is deserialized into an object graph. You've got two different markup files, they contain distinct instances of everything described within them. There's nothing wrong with this, and nothing wrong with having a view model with instance properties. In fact, that's the preferred way over using statics and static bindings. The answer is luckily simple. You need to hand both windows the same instance of your view model. First, remove all the <Window.DataContext> nonsense from both of your windows. That's not for you. Now, simply change your constructor to public MainWindow(){ var viewModel = new SheepViewModel(); ScoreScreen SW = new ScoreScreen(); SW.DataContext = viewModel; SW.Show(); InitializeComponent(); //NOTICE! After Init is called! DataContext = viewModel;} And you're done.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/35046953', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5848676/']}
jdg_78068
stackexchange
llm_judgeable_groundtruth_similarity
422401
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Theorem 2.27: If $X$ is a metric space and $E \subset X$, then $\bar E$ (the closure of $E$) is closed. The proof says: If $p \in X$ and $p \not \in \bar E$ then $p$ is neither a point of $E$ nor a limit point of $E$. Hence $p$ has a neighborhood which does not intersect $E$. The complement of $\bar E$ is therefore open. Hence $\bar E$ is closed. I'm particularly questioning about ''Hence $p$ has a neighborhood which does not intersect $E$. The complement of $\bar E$ is therefore open.'' Should we also prove that the neighborhood of $p$ also does not intersect $E'$ (the set of all limit points of $E$)? Here's what I tried to prove, by contrapositive: ''For any $p \in {\bar E}^c$, if $N_r(p) \cap E' \ne \emptyset$ then $N_r(p) \cap E \ne \emptyset$''. Proof: For any $p \in {\bar E}^c$, if $N_r(p) \cap E' \ne \emptyset$, then take $q \in N_r(p) \cap E'$, $\exists N_h(q)$ s.t. $N_h(q) \subset N_r(p)$. Since $q \in E'$ is a limit point, $N_h(q) \cap E \ne \emptyset$, and hence $N_r(p) \cap E \ne \emptyset$. I'm not quite sure whether this is necessary. Or is there anything I missed from Rudin's proof? Now provide the response and nothing else.
$p$ was chosen randomly, so could be any point not in $E$, not in $E'$, as any such $p$ was explicitly ruled out as a limit point of $E$, hence the existence of a neighborhood of $p$ will not intersect $E'$. Your proof is fine. You explained nicely why Rudin's claim follows. Rudin is notorious for leaving some of the "links" between "stepping stones" (steps in his proofs) "to the reader". You've just filled in some of those unwritten details, and you are correct in those details. It's always a good idea to do so as you read any text, when anything is not immediately apparent to you while reading through a proof. In particular, that can often be the case when reading Rudin. When you revisit the proofs, then, that "extra work" will pay off, as you'll have made the connections, and will then be able to reread Rudin's proofs and follow them without so much effort. Sometimes filling in the details may amount to simply "unpacking" the definition(s) of the terms being used in a theorem (what it means to be a limit point, e.g.). You'll find that's a sound way to learn the definitions inside-out, and to review theorems when they are used in subsequent proofs. (In all honesty, I personally "wrote, expanded upon, rewrote, extended, rewrote again" virtually all of Baby Rudin when I first encountered the text.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/422401', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/44336/']}
jdg_78069
stackexchange
llm_judgeable_groundtruth_similarity
345653
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: In the circuit given below I can't understand what the second transmission gate TG2 is used for. It is connected both to the exit of a Transmission gate and an inverter... so what is the actual input and output of this circuit? Now provide the response and nothing else.
This is the simplified view of the transistor level implementation of a positive latch, you have in the figure. When CLK is high, TG1 is ON, TG2 is OFF. So you will get at output Q, whatever input you have in D. The latch is said to be in transparent mode. When CLK is low, TG2 is ON, TG1 is OFF. Now, the value of Q (which was there just before the moment clock went low) is fed back, inverted and fed to the next inverter. This value is circulated between the two inverters as long as TG2 is ON, and thus the value of Q remains stored. This is how the latch stores the data when the clock is low. The latch is said to be in opaque mode here.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/345653', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/-1/']}
jdg_78070
stackexchange
llm_judgeable_groundtruth_similarity
244037
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: It is needed to generate all 8th order(8 by 8) symmetric binary matrices(of 0's and 1's) such that the sum of the absolute eigenvalues is 8. Listing all the 8th order symmetric binary matrices and then finding the sum of the absolute eigen values is not a computationally feasible way. Can anybody help to generate the mentioned list of matrices only, which are supposed to be very less in number? Now provide the response and nothing else.
I will make an exception to the usual practice I try to follow on this site, and fully replicate my post from this answer of mine here, since it answers this question just as directly or even more, than the one I originally posted it for. I hope this will not cause objections. In addition to the standard Reap - Sow functionality, this one also allows access to intermediate accumulated results at any time during the execution - something that standard Reap - Sow don't. Here is a drop-in Reap - Sow replacement based on Internal`Bag structure, which is also the one that the actual Reap and Sow are based on: SetAttributes[withSideEffect, HoldRest];withSideEffect[code_, sideEffectCode_] := (sideEffectCode; code);$storage = <||>ClearAll[reap]SetAttributes[reap, HoldFirst]reap[expr_] := reap[expr, _]reap[expr_, patt_] := reap[expr, patt, #2&](call : reap[expr_, patt_, func_]) /; !TrueQ[ $inReap] := Block[{$storage = <||>, $ inReap = True}, call ]reap[expr_, patt:Except[_List], func_:Function[#2]] := MapAt[First, reap[expr, {patt}, func], 2]reap[expr_, patt_List, func_] := Module[{result = expr, reaped, tag, matchingTags}, {reaped, matchingTags} = Reap[ Map[ With[{matchingTagsData = KeySelect[ $storage, MatchQ[#]]}, Sow[Keys @ matchingTagsData, tag]; Composition[ KeyValueMap[func], Map[Internal`BagPart[#, All]&] ] @ matchingTagsData ]& , patt ], tag ]; If[matchingTags =!= {}, KeyDropFrom[$ storage, First @ matchingTags]; ]; {result, reaped} ]ClearAll[sow, $globalTag]sow[expr_] := sow[expr, $ globalTag]sow[expr_, _] /; !TrueQ[ $inReap] := exprsow[expr_, tags_List] := First @ Map[sow[expr, #]&, tags]sow[expr_, tag_] := withSideEffect[expr, If[!KeyExistsQ[$ storage, tag], $storage[tag] = Internal`Bag[{expr}], (* else *) Internal`StuffBag[$ storage[tag], expr] ]]ClearAll[getCurrentData]getCurrentData[part: _Integer | {__Integer} | _Span | All : All] := getCurrentData[part, $globalTag]getCurrentData[part: _Integer | {__Integer} | _Span | All : All, tag_] := Replace[ Lookup[$storage, tag, {}], bag: Except[{}] :> Internal`BagPart[bag, part] ] It can serve as an explanation of how Reap - Sow work, but it can also be used to access the sowed data at any time, something that built-in Reap - Sow can't do: reap[ sow[1, {h[1], h[2], g[1]}]; sow[2, g[2]]; Print["The current data for tag ", h[1], " is ", getCurrentData[h[1]]]; sow[3, {h[1], g[2], g[3]}] , {_h, _g} , f](* During evaluation of In[283]:= The current data for tag h[1] is {1} {3, {{f[h[1], {1, 3}], f[h[2], {1}]}, {f[g[1], {1}], f[g[2], {2, 3}], f[g[3], {3}]}}}*) In terms of performance, these will be slower, but should not be too much slower than the built-ins, since they are based on the same underlying data structure.
{}
{'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/244037', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/43620/']}
jdg_78071
stackexchange
llm_judgeable_groundtruth_similarity
338887
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm looking at some GXT code for GWT and I ran across this use of Generics that I can't find another example of in the Java tutorials. The class name is com.extjs.gxt.ui.client.data.BaseModelData if you want to look at all of the code. Here are the important parts: private RpcMap map;public <X> X get(String property) { if (allowNestedValues && NestedModelUtil.isNestedProperty(property)) { return (X)NestedModelUtil.getNestedValue(this, property); } return map == null ? null : (X) map.get(property);} X is defined nowhere else in the class or anywhere in the hierarchy, and when I hit "go to declaration" in eclipse it just goes to the <X> in the public method signature. I've tried to call this method with the following two examples to see what happens: public Date getExpiredate() { return get("expiredate");}public String getSubject() { return get("subject");} They compile and show no errors or warnings. I would think at the very least I would have to do a cast to get this to work. Does this mean that Generics allow a magic return value that can be anything and will just blow up at runtime? This seems counter to what generics are supposed to do. Can anyone explain this to me and possibly give me a link to some documentation that explains this a little better? I've went through Sun's 23 page pdf on generics and every example of a return value is defined either at the class level or is in one of the parameters passed in. Now provide the response and nothing else.
The method returns a type of whatever you expect it to be ( <X> is defined in the method and is absolutely unbounded). This is very, very dangerous as no provision is made that the return type actually matches the returned value. The only advantage this has is that you don't have to cast the return value of such generic lookup methods that can return any type. I'd say: use such constructs with care, because you lose pretty much all type-safety and gain only that you don't have to write an explicit cast at each call to get() . And yes: this pretty much is black magic that blows up at runtime and breaks the entire idea of what generics should achieve.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/338887', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/42994/']}
jdg_78072
stackexchange
llm_judgeable_groundtruth_similarity
102164
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am involved with a 4H project looking to take some weight measurements with bee hives and am trying to figure out some 3-wire load sensors to do just that. I have four 3-wire sensors (load sensors/strain gauges) from one bathroom scale (each sensor was at a corner). Each sensor has a red, black and white wire. The resistance between the red wire and either the black or white wire is 1k ohms. The resistance between the white and black wires is 2k ohms (the resistance between the leads on my load cells and each came away with R->B=1K, R->W=1K, B->W=2k). Because of this, I was told each 3-wire load sensor represents 1/2 of a Wheatstone bridge (each sensor containing two 1k resistance legs). I can get my head around the single wheatstone application but I'm confused how a scale would work when made from two wheatstone bridges. My question is, if this is so, why would a scale require two Wheatstone bridges (remember, all four 3-wire sensors came from one bathroom scale)? Now provide the response and nothing else.
The strain gauge elements come with a positively stress-sensitive portion and a negatively stress-sensitive portion. If you wire them up carefully by flipping them around so the stress sensitive portions unbalance the bridge constructively, you can use all four sensors without any extra resistors. jonk's link to the blog post at http://www.nerdkits.com/forum/thread/900/ has a good hint with Mongo's diagram (copied below), and the jonk - user37977 comments on jonk's answer also help. Basically, two diagonally-opposite sides of a wheatstone bridge are formed by the positive-strain elements of two gauges wired in series, while the other two sides of the bridge are formed from the two negative-strain elements. With compression on all the positive-strain sensors, the active resistances are reduced, and it pulls the bridge out of balance one way, and under tension, the positive-strain resistances increase, pulling the bridge out of balance the other way. Wire all four sensors in a big ring with maximum resistance, matching colors and initially ignoring the center tap wires. Choose two opposite center taps as E+ and E-, and the remaining two center taps as S+,S-. Put the excitation voltage on the E+/E- from the diagram above and read a force-sensitive voltage difference across S+/S-. See https://electronics.stackexchange.com/a/75717/30711 for a good schematic and Arduino Leonardo + 3 wire Load Cells + INA125P – Analog Signal Bounce / Noise for a wiring diagram of the colored wires combining into a wheatstone bridge. Edit: Actually, I am uncertain if OP's three wire load cells have only one active strain gauge as in Mongo's diagram. If they are like the 50kg load cell from SparkFun's https://www.sparkfun.com/products/10245 or Ebay's http://www.ebay.com/itm/4pcs-Body-Load-Scale-Weighing-Sensor-Resistance-Strain-Half-bridge-Sensors-50kg-/251873576571 they mught have a compression and tension gage both on the top surface. The Ebay site has a diagram like: ... which indicates a positive strain gauge on the red-white, and a negative strain on the red-black. (note that the coloring order in this diagram does not match the coloring order in this picture. I have a similar gauge with blue-red-black colors, and the positive strain gauge is the right pair, negative on the left.) The gauged surface on the center bar between the face-to-face coupled 'E's in the sensor should act like a parallel bar and has portions under compression and under tension, rather than purely under tension. In cross-section, the gauged bar in the center is sort of the cross-piece in a Z-shaped spring. In this case, the strains oppose each other, and, if manufactured well, the reduction of resistance in the negative strain portion will offset the increase in resistance in the positive strain portion and the total white-black resistance should be constant. One still needs to set up the bridge so that the voltage dividers move in opposite directions with added load, and 4 devices wired in a white-to-white and black-to-black loop should work as above. Here's a schematic with gauges 1-4 as G1 G2, G3, G4 per the above specs, applying an excitation on the G1 and G3 reds, and reading the signals off the G2 and G4 reds. The G4 gauge is loaded a bit with some positive strain increasing the G4+ resistance, and some negative strain reducing the G4- resistance. Ideally, loading G4 with 25kg would produce 0.5mV/V times its 2.5V excitation voltage, producing 1.250mV across Sig+/Sig-, and stretching R8 to be 1001 ohms and compressing R7 to 999 ohms as shown. One could increase the sensitivity by a factor of 4 by increasing V1 up to the 20V (=2*10V) specification (The schematic/simulator thing is pretty cool.) simulate this circuit – Schematic created using CircuitLab With only two devices, one should hook white-to-black and black-to white, imposing an excitation voltage from between these two junctions, and reading the differences across the reds, as increased load pulls one side high and the other side low.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/102164', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/37997/']}
jdg_78073
stackexchange
llm_judgeable_groundtruth_similarity
953789
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: This was my ring theory exam question which states: Let $R$ be a finite commutative ring with unity.Prove that every non-zero element of $R$ is either a zero-divisor or a unit.What happens if we drop "finite" condition on $R$? I know I am wrong but I thought $R$ to be an integral domain.What should be correct way to solve it? Now provide the response and nothing else.
What should be correct way to solve it? Proving the given statement (with the finiteness conditon) would be a duplicate question of Every nonzero element in a finite ring is either a unit or a zero divisor , so I will direct you to the very good solutions that already exist there. What happens if we drop "finite" condition on R? $\Bbb Z$ is a commutative ring with unity which has exactly two units and (in my convention) only one zero divisor, and everything else is neither unit nor zero divisor. So deleting the word finite pretty much wrecks the statement. I know I am wrong but I thought $R$ to be an integral domain. Well my example just now was an integral domain, but no, being a domain has nothing to do with it. The ring $F[x]/(x^2)$ for an infinite field $F$ is an infinite commutative ring with identity which isn't a domain and yet is partitioned between units and zero divisors. So you can't just delete finite, but you can easily replace it with far more general adjectives.$^\ast$ Being finite is in no way necessary for elements to be partitioned between units and zero divisors. There are huge classes of infinite rings that have that property. Probably the next simplest generalization of this question is to prove that for any right Artinian ring $R$, every element is a unit or zero divisor (I count $0$ among zero divisors.) Finite rings are of course left and right Artinian. But now you have, for example, every $n\times n$ matrix ring over a field, and every quotient of a polynomial ring over a field as examples beyond finite rings. Actually you can go to something even more general called a strongly $\pi$ regular ring$^{\ast\ast}$ . There is a simple proof for both claims at this question: Rings whose elements are partitioned between units and zero-divisors. and here .$^{\ast\ast\ast}$ $^\ast$ You can simply delete the word commutative, though. $^{\ast\ast}$ A strongly $\pi$-regular ring is one which has the descending chain condition on chains of the form $xR\supseteq x^2R\supseteq x^3R\supseteq\ldots$ $^{\ast\ast\ast}$ There is also a related (but more oddly worded) post about this.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/953789', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/178659/']}
jdg_78074
stackexchange
llm_judgeable_groundtruth_similarity
47528558
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: This may be a cheap question for some but I'm totally confused on how to populate my listbox. Using this line I can populate the listbox as shown below: ListBox1.List = Sheets("Sheet1").Cells(1, 1).CurrentRegion.Value or Dim rngName As RangeDim ws As WorksheetDim i As IntegerSet ws = Worksheets("Sheet1") For i = 1 To ws.Cells(ws.Rows.Count, 1).End(xlUp).Row Step 1 If ws.Cells(i, 1).Value <> vbNullString Then Me.ListBox1.AddItem ws.Cells(i, 1).ValueNext i Below is the data I'm planning to use to populate the list box and is progressive. Only the column has the fix count. Someone please enlighten me on how to populate a list box adapative to multiple columns and rows using FOR LOOP as shown in my code above. Any help appreciated. Thanks. Now provide the response and nothing else.
Methods It's always better to loop through an array than a range - it's much faster . It's even faster to create a variant data field array with a one liner instead of redimensioning a predeclared array and fill it in an extra loop as proposed by Siddharth Rout (though a good method :-) Note: The code below is based on his Approach referenced in the above comment just to demonstrate the difference. Fill ListBox1.List with the array (same method, but reverse direction). Code Private Sub CommandButton1_Click()' Purpose: fill listbox with range values after clicking on CommandButton1' (code could be applied to UserForm_Initialize(), too)' Note: based on @Siddharth-Rout 's proposal at https://stackoverflow.com/questions/10763310/how-to-populate-data-from-a-range-multiple-rows-and-columns-to-listbox-with-vb' but creating a variant data field array directly from range in a one liner' (instead of filling a redimensioned array with range values in a loop)Dim ws As WorksheetDim rng As RangeDim MyArray ' variant, receives one based 2-dim data field array'~~> Change your sheetname hereSet ws = Sheets("Sheet1")'~~> Set you relevant range hereSet rng = ws.Range("A1:C" & ws.Range("A" & ws.Rows.Count).End(xlUp).Row)With Me.ListBox1 .Clear .ColumnHeads = False .ColumnCount = rng.Columns.Count '~~> create a one based 2-dim datafield array MyArray = rng '~~> fill listbox with array values .List = MyArray '~~> Set the widths of the column here. Ex: For 5 Columns '~~> Change as Applicable .ColumnWidths = "50;50;50" .TopIndex = 0End WithEnd Sub Additional hints Another advantage of the array method - it overcomes the built-in limitation of only 10 columns when using the .AddItem method. Furthermore, keep in mind that listbox indexing is zero based , so for example you get the e-mail address (column 3, index 2) of your first item row (index 0) via ListBox1.List(0, 2) , whereas the data field array becomes automatically a one based 2-dim array. You aren't restricted to use the .List method to get Information out of the listbox, you can reverse the row - column order by using ListBox1.Column" or even create a new array out of it, which remains a 2-dim object, even if there is only ONE item (note: the Application.Transpose` method would redim a 2 dimensional array with only one row to a 1-dim array). A last point: you can easily dump back again the whole listbox to an Excel sheet via rng = ListBox1.List , but take care to define the correct range.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/47528558', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8854925/']}
jdg_78075
stackexchange
llm_judgeable_groundtruth_similarity
18058730
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have a python class object and I want to assign the value of one class variable class Groupclass(Workerclass): """worker class""" count = 0 def __init__(self): """initialize time""" Groupclass.count += 1 self.membercount = 0; self.members = [] def __del__(self): """delte a worker data""" Groupclass.count -= 1if __name__ == "__main__": group1 = Groupclass() This execution result is correct, but there's an error message that says: Exception AttributeError: "'NoneType' object has no attribute 'count'" in <bound method Groupclass.__del__ of <__main__.Groupclass instance at 0x00BA6710>> ignored Can someone tell me what me I did wrong? Now provide the response and nothing else.
Your __del__ method assumes that the class is still present by the time it is called. This assumption is incorrect. Groupclass has already been cleared when your Python program exits and is now set to None . Test if the global reference to the class still exists first: def __del__(self): if Groupclass: Groupclass.count -= 1 or use type() to get the local reference: def __del__(self): type(self).count -= 1 but do note that this means that the semantics for count change if Groupclass is subclassed (each subclass gets a .count attribute versus only Groupclass having a .count attribute). Quoting from the __del__ hook documentation: Warning : Due to the precarious circumstances under which __del__() methods are invoked, exceptions that occur during their execution are ignored, and a warning is printed to sys.stderr instead. Also, when __del__() is invoked in response to a module being deleted (e.g., when execution of the program is done), other globals referenced by the __del__() method may already have been deleted or in the process of being torn down (e.g. the import machinery shutting down). For this reason, __del__() methods should do the absolute minimum needed to maintain external invariants. Starting with version 1.5, Python guarantees that globals whose name begins with a single underscore are deleted from their module before other globals are deleted; if no other references to such globals exist, this may help in assuring that imported modules are still available at the time when the __del__() method is called. If you are using Python 3, two additional notes apply: CPython 3.3 automatically applies a randomized hash salt to the str keys used in a globals dictionary; this also affects the order in which globals are cleaned up, and it could be that you see the problem on only some of the runs. CPython 3.4 no longer sets globals to None (in most cases), as per Safe Object Finalization ; see PEP 442 .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18058730', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1355175/']}
jdg_78076
stackexchange
llm_judgeable_groundtruth_similarity
6941272
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have a settings bundle in my app.. containing root.plist now i have a screen which contains a checkbox .. on pressing the check box i want to change the BOOL value for DefaultValue key of PSToggleSwitchSpecifier in the plist. Since its being done at runtime.. my question is that .. can the file be changed at runtime and if yes.. give an idea how to do it?? here is the plist: <plist version="1.0"><dict> <key>PreferenceSpecifiers</key> <array> <dict> <key>DefaultValue</key> <string></string> <key>Key</key> <string>Username</string> <key>Title</key> <string>Username</string> <key>Type</key> <string>PSTextFieldSpecifier</string> </dict> <dict> <key>DefaultValue</key> <string></string> <key>IsSecure</key> <true/> <key>Key</key> <string>Password</string> <key>Title</key> <string>Password</string> <key>Type</key> <string>PSTextFieldSpecifier</string> </dict> <dict> <key>Type</key> <string>PSToggleSwitchSpecifier</string> <-----toggleSwitch <key>Title</key> <string>Remember</string> <key>Key</key> <string>CheckBox</string> <key>DefaultValue</key> <----- Default Value <false/> <---- want to change this value </dict> </array> <key>Title</key> <string>Settings</string></dict></plist> thank you in advance ;) Now provide the response and nothing else.
Because the settings bundle resides inside your app's bundle, you cannot change it at runtime, only at compile-time. You can, however, use NSUserDefaults to set the value at runtime, and the settings application will automatically reflect this. It will be saved elsewhere, though. You can just read it back the same way as you would do with the settings bundle, also through NSUserDefaults . Note that you shouldn't read from the settings bundle directly, as it makes no sense. You should always fetch and set user defaults using NSUserDefaults . When the user makes a change in the settings application, NSUserDefaults will reflect this automatically. They will always be kept in sync.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6941272', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/569789/']}
jdg_78077
stackexchange
llm_judgeable_groundtruth_similarity
26276207
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm getting the below error while installing ' redcarpet ' gem. It got installed without issue on my friends machine though. (I want to install this to run yard )Ruby version: 1.9.3 cmd output: D:\Learning\Common_POM_FW\SampleProjects>yard[error]: Missing 'redcarpet' gem for Markdown formatting. Install it with `gem install redcarpet`D:\Learning\Common_POM_FW\SampleProjects>gem install redcarpetTemporarily enhancing PATH to include DevKit...Building native extensions. This could take a while...ERROR: Error installing redcarpet: ERROR: Failed to build gem native extension. C:/Ruby193/bin/ruby.exe -r ./siteconf20141009-6544-978w4t.rb extconf.rbcreating Makefilemake cleanMakefile:165: *** target pattern contains no `%'. Stop.makeMakefile:165: *** target pattern contains no `%'. Stop.make failed, exit code 2Gem files will remain installed in C:/Ruby193/lib/ruby/gems/1.9.1/gems/redcarpet-3.1.2 for inspection.Results logged to C:/Ruby193/lib/ruby/gems/1.9.1/extensions/x86-mingw32/1.9.1/redcarpet-3.1.2/gem_make.out UPDATE: With the devkit installation instructions provided at https://github.com/oneclick/rubyinstaller/wiki/Development-Kit When I test the installation with json gem it fails there too :( I went through the link for troubleshoot in github Native gem extension Error and followed the instructions to solve, Yet the problem persists.. I added the two paths to Env var C:\\ruby_devkit\\bin;C:\\ruby_devkit\\mingw\\bin; This removes the line Temporarily enhancing PATH to include DevKit... from appearing on cmd Now provide the response and nothing else.
Finally after much research I found the culprit was the RubyGems version incompatibility with native extension gems!!! I had ruby gems ver 2.4.1 but seems like >2.4.0 has these issues gem update --system 2.3.0 did the trick for me :) Refer: https://github.com/rubygems/rubygems/issues/977
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/26276207', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2243534/']}
jdg_78078
stackexchange
llm_judgeable_groundtruth_similarity
9725986
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have an NSImage . I would like to read the NSColor for a pixel at some x and y. Xcode seems to thing that there is a colorAtX:y: method on NSImage , but this causes a crash saying that there is no such method for NSImage. I have seen some examples where you create an NSBitmapImageRep and call the same method on that, but I have not been able to successfully convert my NSImage to an NSBitmapImageRep . The pixels on the NSBitmapImageRep are different for some reason. There must be a simple way to do this. It cannot be this complicated. Now provide the response and nothing else.
Without seeing your code it's difficult to know what's going wrong. You can draw the image to an NSBitmapImageRep using the initWithData: method and pass in the image's TIFFRepresentation . You can then get the pixel value using the method colorAtX:y: , which is a method of NSBitmapImageRep , not NSImage : NSBitmapImageRep* imageRep = [[NSBitmapImageRep alloc] initWithData:[yourImage TIFFRepresentation]];NSSize imageSize = [yourImage size];CGFloat y = imageSize.height - 100.0;NSColor* color = [imageRep colorAtX:100.0 y:y];[imageRep release]; Note that you must make an adjustment for the y value because the colorAtX:y method uses a coordinate system that starts in the top left of the image, whereas the NSImage coordinate system starts at the bottom left. Alternatively, if the pixel is visible on-screen then you can use the NSReadPixel() function to get the color of a pixel in the current coordinate system.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9725986', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/339428/']}
jdg_78079
stackexchange
llm_judgeable_groundtruth_similarity
256196
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: At the moment, I have task that is configured to run as user "automatictask" But the task will not run, "unable to start" is shown. When I add this user to the Administrators group, then the task runs fine. But in real life.... I want this user to be SUPER restricted.... ONLY able to run this task, no login rights, no file system rights other than to the one batch file.... I have searched high and low for a document that says "here is the most stripped down, basic user that can run a task" .... There seems to be no such document! Suggestions? Thanks! Now provide the response and nothing else.
Other than the filesystem permissions, you'll need to allow Log on as a batch job . It controls allowing the session to be created for a scheduled task. The task scheduler should put the user in that allow list when you create the task. You can confirm with the Local Security Policy tool. The other possibility is that it's configured through group policy, in which case, do some digging in the resultant set of policy and find the GPO that needs changed. Here's the other thing: Check out the permissions on c:\windows\system32\cmd.exe . They're funky. If you've removed the user from the Users group, it can't run cmd.exe by default, which tends to be a big part of running a batch file. Add the user to that ACL, with read/execute. Check any and all executables the batch file needs to touch.
{}
{'log_upvote_score': 5, 'links': ['https://serverfault.com/questions/256196', 'https://serverfault.com', 'https://serverfault.com/users/13716/']}
jdg_78080
stackexchange
llm_judgeable_groundtruth_similarity
28037551
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm still not very clear about the difference between a column-based relational database vs. column-based NoSQL database. Google BigQuery enables SQL-like query so how can it be NoSQL? Column-based relational database I know of are InfoBright, Vertica and Sybase IQ. Column-based NoSQL database I know of are Cassandra and HBase. The following article about Redshift starts with saying "NoSQL" but ends with PostgreSQL (which is relational) being used: http://nosqlguide.com/column-store/intro-to-amazon-redshift-a-columnar-nosql-database/ Now provide the response and nothing else.
A few things to clarify here mostly about Google BigQuery. BigQuery is a hybrid system that allows you to store data in columns, but it takes into the NoSQL world with additional features, like the record type, and the nested feature. Also you can have a 2Mbyte STRING column in which you can store raw document like a JSON document. See other data formats and limits that apply. Also you can write User Defined Functions in Javascript, eg: you can paste in a library that does NLP javascript library. Now that you have all these capabilities to store data you can use JSON Functions for example to query your document stored in one of the columns, hence this can be used as no schema storage, because you didn't defined your JSON document structure for that column, you just stored it as JSON. Got it? Basic example to query from the meta column, which is a JSON document, the reason key, and doing a contains language construct to find out how many users have in that key the "unsubscribed" word: SELECT SUM(IF(JSON_EXTRACT_SCALAR(meta,'$.reason') contains 'unsubscribed',1,0)) FROM ... On the other hand you have table-wildcard querying . This is needed if you have your rows across many tables. Table wildcard functions are a cost-effective way to query data from a specific set of tables. When you use a table wildcard function, BigQuery only accesses and charges you for tables that match the wildcard. So this means that it's advised to store data in similar tables just partitioned in different tables per a set time frame eg: daily, monthly tables. We should not forget that BigQuery is append only by design , so you cannot update old records, there is no UPDATE language construct ( Update : There is now DML language construct to do some update/delete ops). Instead you need to append a new record and your queries must be written in a way that always work with the last version of your data. If your system is event driven, than this is very simple because each event will be appended in the BQ. But if the user updates it's profile, you need to store the profile again, you cannot update old row. You need to have a column version/date that tells you which is the most recent version, and your queries will be written first to obtain the most recent version of your rows then deal with the logic. You can use something like over/partition by that field and use the most recent value seqnum=1 . This returns from profile , the last email for each user_id defined by the most recent entry by timestamp column. SELECT email FROM (SELECT email row_number() over (partition BY user_id ORDER BY TIMESTAMP DESC) seqnum FROM [profile] ) WHERE seqnum=1
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/28037551', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/541624/']}
jdg_78081
stackexchange
llm_judgeable_groundtruth_similarity
39018765
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I want to build and deploy my Angular 2 front end to a Tomcat application server. For getting started I've followed exactly the steps of the following introduction: https://angular.io/docs/ts/latest/guide/webpack.html . So I have the following project structure (all files are exactly as in the introduction mentionend above): angular2-webpack ---config -------helpers.js -------karma.conf.js -------karma-test-shim.js -------webpack.common.js -------webpack.dev.js -------webpack.prod.js -------webpack.test.js ---dist ---node_modules ---public -------css --------------styles.css -------images --------------angular.png ---src -------app --------------app.component.css --------------app.component.html --------------app.component.spec.ts --------------app.component.ts --------------app.module.ts -------index.html -------main.ts -------polyfills.ts -------vendor.ts ---typings ---karma.conf.js ---package.json ---tsconfig.json ---typings.json ---webpack.config.js npm start respectively webpack-dev-server --inline --progress --port 3000 on the console or in Webstorm →works as expected When I run npm build respectively rimraf dist && webpack --config config/webpack.prod.js --progress --profile --bail it builds the app without errors and the output bundle files get physically placed in the dist folder as expected. dist ---assets -------angular.png ---app.css ---app.css.map ---app.js ---app.js.map ---index.html ---polyfills.js ---polyfills.js.map ---vendor.js ---vendor.js.map Next I copied the content of the dist folder to the webapps directory of a Tomcat 9.0. When I try to access the installed app I get an 404 error for the .css- and .js-files ( which can be seen in the attached picture ).It tries to get the files from the wrong URLs →"/obv/" is missing. I'm really stuck here and I have the feeling that I've tried already everything I could find in the Internet regarding this topic. Could someone please tell me what I'm doing wrong? Thank you in advance. Now provide the response and nothing else.
The problem is related to the tag <base href="/" /> . This is just wrong when using a webserver like tomcat or trying to load the app directly from filesystem with firefox index.html . This must be changed to <base href="./" /> . When the app still has problems check how the script files are imported. I tried to use angular2-webpack with tomcat and also needed to change all script tags to not use a leading slash in there src attribute. <script src="js/vendor.js" ></script> With webpack the behavior is controlled by the attribute output.publicPath . In the angular2 documentation and in the angular2-webpack this is set to output.publicPath="/" Which leads to absolute path in the links. When removed webpack will use relative paths and the links for scripts and images work.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/39018765', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4969882/']}
jdg_78082
stackexchange
llm_judgeable_groundtruth_similarity
14403383
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am struggling to understand the usefulness of the bloom filter. I get its underlying logic, space compaction, fast lookups, false positives etc. I just cannot put that concept into a real-life situation as being beneficial. One frequent application is use of bloom filters in web caching. We use bloom filter to determine whether a given URL is in the cache or not. Why don't we simply access the cache to determine that? If we get a yes, we still need to go to cache to retrieve the webpage (which might not be there), but in case of a no, we could have got the same answer using the cache (which is probably optimized for fast lookups anyway?). Now provide the response and nothing else.
Bloom filters are designed for situations where a false negative is a Very Bad Thing and a false positive is acceptable. For example, suppose that you are making a web browser and have a known blacklist of scam websites. Your blacklist is massive - in the hundreds of gigabytes - so you can't ship it with the browser. However, you can store it on your own servers. In that case, you could ship the browser with a Bloom filter of an appropriate size that holds all the URLs. Before visiting a site, you look it up in the filter. Then, if you get a "no" answer, you're guaranteed that the URL is not blacklisted and can just visit the site. If you get a "yes" answer, the site might be evil, so you can have the browser call up your main server to get the real answer. The fact that you can save a huge number of calls to the server here without ever sacrificing accuracy is important. The cache idea is similar to this setup. You can query the filter to see if the page is in the cache. If you get a "no" answer, you're guaranteed it's not cached and can do an expensive operation to pull the data from the main source. Otherwise, you can then check the cache to see if it really is there. In rare instances you might need to check the cache, see that it isn't there, then pull from the main source, but you will never accidentally miss something really in cache. Hope this helps!
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/14403383', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1094640/']}
jdg_78083
stackexchange
llm_judgeable_groundtruth_similarity
2394983
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Many system calls in Unix use overloading and default variables. This concept is absent in C, so Unix is coded in C++ also right? Now provide the response and nothing else.
Unix was first created at Bell Labs in 1969, well before C++ was conceived. (Src: Unix ), you can confirm this by reading Lions' Commentary on Unix , or the BSD 4.4-Lite (which is similar to BSD Net/2 ) which is available in tarball or via cvs (from FreeBSD). Or the archives from The Unix Heritage Society which is from the very old Bell Labs / AT&T versions. Bjarne Stroustrup created C++ in approximately 1983, prior to that he worked on " C with Classes ", according to History of C++ . Confirmed from Bjarne Stroustrup's FAQ , and the earliest date for C with Classes was 1979. I hope that clarifies the impossibility of the idea that Unix was based upon C++. Note that Object-Oriented languages have been around since 1960s in Simula 67 , so don't confuse objects and classes with C++.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2394983', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/288038/']}
jdg_78084
stackexchange
llm_judgeable_groundtruth_similarity
1222184
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Lets just say you have a simple operation that runs on a background thread. You want to provide a way to cancel this operation so you create a boolean flag that you set to true from the click event handler of a cancel button. private bool _cancelled;private void CancelButton_Click(Object sender ClickEventArgs e){ _cancelled = true;} Now you're setting the cancel flag from the GUI thread, but you're reading it from the background thread. Do you need to lock before accessing the bool? Would you need to do this (and obviously lock in the button click event handler too): while(operationNotComplete){ // Do complex operation lock(_lockObject) { if(_cancelled) { break; } }} Or is it acceptable to do this (with no lock): while(!_cancelled & operationNotComplete){ // Do complex operation} Or what about marking the _cancelled variable as volatile. Is that necessary? [I know there is the BackgroundWorker class with it's inbuilt CancelAsync() method, but I'm interested in the semantics and use of locking and threaded variable access here, not the specific implementation, the code is just an example.] There seems to be two theories. 1) Because it is a simple inbuilt type (and access to inbuilt types is atomic in .net) and because we are only writing to it in one place and only reading on the background thread there is no need to lock or mark as volatile. 2) You should mark it as volatile because if you don't the compiler may optimise out the read in the while loop because it thinks nothing it capable of modifying the value. Which is the correct technique? (And why?) [Edit: There seem to be two clearly defined and opposing schools of thought on this. I am looking for a definitive answer on this so please if possible post your reasons and cite your sources along with your answer.] Now provide the response and nothing else.
Firstly, threading is tricky ;-p Yes, despite all the rumours to the contrary, it is required to either use lock or volatile (but not both) when accessing a bool from multiple threads. For simple types and access such as an exit flag ( bool ), then volatile is sufficient - this ensures that threads don't cache the value in their registers (meaning: one of the threads never sees updates). For larger values (where atomicity is an issue), or where you want to synchronize a sequence of operations (a typical example being "if not exists and add" dictionary access), a lock is more versatile. This acts as a memory-barrier, so still gives you the thread safety, but provides other features such as pulse/wait. Note that you shouldn't use a lock on a value-type or a string ; nor Type or this ; the best option is to have your own locking object as a field ( readonly object syncLock = new object(); ) and lock on this. For an example of how badly it breaks (i.e. looping forever) if you don't synchronize - see here . To span multiple programs, an OS primitive like a Mutex or *ResetEvent may also be useful, but this is overkill for a single exe.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1222184', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/119738/']}
jdg_78085
stackexchange
llm_judgeable_groundtruth_similarity
29477654
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm interested in putting an opening brace for functions (but not if statements and other contexts). For example void foo(){ ...} Flamewars aside, is there a good rationale for not doing this? Although I use same-line open-brackets for if/else and smaller blocks, I think in this case visual organization of larger units of code (functions/methods/classes/structs) can trump perfect consistency. Moreover, how do I get clang-format to follow this style? Now provide the response and nothing else.
As the documentation says, invoke clang-format with -style=file , and use a .clang-format file placed in an enclosing directory to customize style options. The format style option specifying brace placement is called BreakBeforeBraces . From the docs, BreakBeforeBraces ( BraceBreakingStyle ) The brace breaking style to use. Possible values: BS_Attach (in configuration: Attach ) Always attach braces to surrounding context. BS_Linux (in configuration: Linux ) Like Attach , but break before braces on function, namespace and class definitions. BS_Stroustrup (in configuration: Stroustrup ) Like Attach , but break before function definitions, and ‘else’. BS_Allman (in configuration: Allman ) Always break before braces. BS_GNU (in configuration: GNU ) Always break before braces and add an extra level of indentation to braces of control statements, not to those of class, function or other definitions. The style that matches your description is BS_Stroustrup . Add the following entry to your .clang-format BreakBeforeBraces: Stroustrup In addition to the docs, clangformat.com lists all the options and illustrates many of them with examples.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/29477654', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/722869/']}
jdg_78086
stackexchange
llm_judgeable_groundtruth_similarity
8454573
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Question: Given a sorted array A find all possible difference of elements from A. My solution: for (int i=0; i<n-1; ++i) { for (int j=i+1; j<n; ++j) { System.out.println(Math.abs(ai-aj)); }} Sure, it's O(n^2), but I don't over count things at all. I looked online and I found this: http://www.careercup.com/question?id=9111881 . It says you can't do better, but at an interview I was told you can do O(n). Which is right? Now provide the response and nothing else.
A first thought is that you aren't using the fact that the array is sorted. Let's assume it's in increasing order (decreasing can be handled analogously). We can also use the fact that the differences telescope (i>j): a_i - a_j = (a_i - a_(i-1)) + (a_(i-1) - a_(i-2)) + ... + (a_(j+1) - a_j) Now build a new sequence, call it s, that has the simple difference, meaning (a_i - a_(i-1)) . This takes only one pass ( O(n) ) to do, and you may as well skip over repeats, meaning skip a_i if a_i = a_(i+1) . All possible differences a_i-a_j with i>j are of the form s_i + s_(i+1) + ... + s_(j+1) . So maybe if you count that as having found them, then you did it in O(n) time. To print them, however, may take as many as n(n-1)/2 calls, and that's definitely O(n^2) .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8454573', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/985031/']}
jdg_78087
stackexchange
llm_judgeable_groundtruth_similarity
43674781
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: react-native:0.43.3 The problem only occurs in Android system, iOS is fine.When I touch a TouchableOpacity component, the onTouch function won't be executed. Anyone found this problem? I built a Calendar with RN. The problem is that when I click the Day unit on Android devices or emulators I'll get the error undefined is not and object (evaluating '_props[registrationName]') . But it's okay to click it on iOS devices and emulators. The Day component' code is like this: <TouchableOpacity style={styles.calendarRowUnit} onPress={() => this.props.onSelect(this.props.date)}> <View style={dateWrapperStyle}> <Text style={dateTextStyle}>{dateString}</Text> </View> </TouchableOpacity> And the error image: error info iamge I've found that only when I touch the Text area the error will occur. I don't know it's a react-native bug or my fault. The error never occured before I updated the react-native version to 0.43.3. Now provide the response and nothing else.
/** * @param {object} inst The instance, which is the source of events. * @param {string} registrationName Name of listener (e.g. `onClick`). * @return {?function} The stored callback. */ getListener: function(inst, registrationName) { var listener; // TODO: shouldPreventMouseEvent is DOM-specific and definitely should not // live here; needs to be moved to a better place soon if (typeof inst.tag === 'number') { const props = EventPluginUtils.getFiberCurrentPropsFromNode( inst.stateNode ); if (!props) { // Work in progress. return null; } listener = props[registrationName]; if (shouldPreventMouseEvent(registrationName, inst.type, props)) { return null; } } else { if (typeof inst._currentElement === 'string') { // Text node, let it bubble through. return null; } if (!inst._rootNodeID) { // If the instance is already unmounted, we have no listeners. return null; } const props = inst._currentElement.props; listener = props[registrationName]; if (shouldPreventMouseEvent(registrationName, inst._currentElement.type, props)) { return null; } } invariant( !listener || typeof listener === 'function', 'Expected %s listener to be a function, instead got type %s', registrationName, typeof listener ); return listener; }, There's currently a bug where if the Text inside the TouchableOpacity has a number it will error out. The way to fix it for the moment is to cast the number to a string and it will trigger the String check and throw a null appropriately. EX: Before: <Text>16</Text> After: <Text>String(16)</Text>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/43674781', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7604288/']}
jdg_78088
stackexchange
llm_judgeable_groundtruth_similarity
4106031
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I can I check if FeedItem::populate_from_friend_to_user is called inside the user class? it "should auto populate feed after user.add_friend" do @user.add_friend(@friend1) @user.should_receive('FeedItem::populate_from_friend_to_user').with(@friend1, @user) end With the above code I get: undefined method `populate_from_friend_to_user' for :FeedItem:Symbol Now provide the response and nothing else.
You should not know where the method is called, just if the method is called.. You just know if the method is call: Before RSpec 3 it "should auto populate feed after user.add_friend" do FeedItem.should_receive(:populate_from_friend_to_user).with(@friend1, @user) @user.add_friend(@friend1) end In RSpec 3 the syntax is expect(Object).to receive(:method).with(params)
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/4106031', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/87610/']}
jdg_78089
stackexchange
llm_judgeable_groundtruth_similarity
338306
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm wondering what the FHS compliant mount points for internal harddrives and networkshares are? Many different tutorials are suggesting to mount them in subdirectories to /mnt or /media According to the FHS 3.0 (File Hierarchy Standard): /media : Mount point for removable media( This directory contains subdirectories which are used as mount points for removable media such as floppy disks, cdroms and zip disks. ) /mnt : Mount point for a temporarily mounted filesystem ( This directory is provided so that the system administrator may temporarily mount a filesystem as needed. The content of this directory is a local issue and should not affect the manner in which any program is run ) I assume that those mount points could go to /home/foo/extdrive /home/foo/nfsshare for a single user system, but where would I mount them accessible for all users? Update: FHS 3.0, Chapter 3.1, second "Rationale" paragraph new directory in / (ie /workspace and /nfsshare ) There are several reasons why creating a new subdirectory of the root filesystem is prohibited:It demands space on a root partition which the system administrator may want kept small and simple for either performance or security reasons.It evades whatever discipline the system administrator may have set up for distributing standard file hierarchies across mountable volumes.Distributions should not create new directories in the root hierarchy without extremely careful consideration of the consequences including for application portability. Now provide the response and nothing else.
You make your own mount point directories. If you want to ask why, I can only point to the great answer by Wouter Verhelst . Internal drives /mnt is a valid place to make your own if you like, and so is / . /mnt may have been used for this purpose by some historical installation systems, as well as for removable media (before /media ). It's still valid for you to do so, but the system itself is no longer supposed to set up anything in /mnt . I think it's reasonable to use /mnt if you might make multiple mount points. It makes it easy to see all of them together, and it's known as one of the locations people like to use. Some other people like to use /Volumes - following the OS X system, or /vol . /data is common for a single mount point. /d/ is also used. /disk/ is almost certainly used by some, but may be distracting for storage which is not disk-based. If you use /mnt, I would also create /mnt/tmp. Then there will still be a convenient directory for temporary mounts, the original use of /mnt which FHS mentions. Preferred mount points for internal HDDs It's possible that manually creating mount points under /media is a bad idea on some common systems. Modern Linux OS's will create mount points for removable media automatically, and it's possible the structure they create would conflict, or simply appear inconsistent with your own. You don't say what your system is, but you may be interested in portable guidelines, especially if you're asking about FHS. Note this reasoning is similar to why the FHS says the OS must not populate /mnt. Mount point for system-wide USB disk Network filesystems It is sometimes recommended to mount network filesystems in a dedicated sub-directory e.g. /n/host , /nfs/host or /net/host etc. For example, if you mount a network filesystem at /host and the network becomes unreachable, ls / may hang when it tries to stat the network filesystem. This could be undesirable and frustrating, at a time when you are already becoming frustrated.
{}
{'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/338306', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/53278/']}
jdg_78090
stackexchange
llm_judgeable_groundtruth_similarity
33281753
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Recently, I am learning boost C++ library. I want to use python to call exist C++ project. I have install boost under OSX 10.11 using brew install boost . My python version 2.7. I make a hello.c: char const* greet(){ return "hello, world";}#include <boost/python.hpp>BOOST_PYTHON_MODULE(hello){ using namespace boost::python; def("greet", greet);} and Makefile: PYTHON_VERSION = 2.7PYTHON_INCLUDE = /usr/include/python$(PYTHON_VERSION)# location of the Boost Python include files and library# BOOST_INC = /usr/local/includeBOOST_LIB = /usr/local/lib# # compile mesh classesTARGET = hello$(TARGET).so: $(TARGET).o g++ -shared -Wl $(TARGET).o -L$(BOOST_LIB) -lboost_python -L/usr/lib/python$(PYTHON_VERSION)/config -lpython$(PYTHON_VERSION) -o $(TARGET).so$(TARGET).o: $(TARGET).c g++ -I$(PYTHON_INCLUDE) -I$(BOOST_INC) -fPIC -c $(TARGET).c However, after I run make and got hello.so. I met following error when I run python code: import helloprint hello.greet() error: Traceback (most recent call last): File "test.py", line 4, in <module> import helloImportError: dlopen(/Users/einverne/boost_test/hello.so, 2): Library not loaded: libboost_python.dylib Referenced from: /Users/einverne/boost_test/hello.so Reason: unsafe use of relative rpath libboost_python.dylib in /Users/einverne/boost_test/hello.so with restricted binary Now provide the response and nothing else.
Take this link as a reference. To my problem, use otool -L hello.so : hello.so: hello.so (compatibility version 0.0.0, current version 0.0.0) libboost_python.dylib (compatibility version 0.0.0, current version 0.0.0) /System/Library/Frameworks/Python.framework/Versions/2.7/Python (compatibility version 2.7.0, current version 2.7.10) /usr/lib/libc++.1.dylib (compatibility version 1.0.0, current version 120.1.0) /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1225.1.1) you can see that libboost_python.dylib is not point to the really exist path. so use this command: install_name_tool -change libboost_python.dylib /usr/local/lib/libboost_python.dylib hello.so and run otool -L hello.so again: hello.so: hello.so (compatibility version 0.0.0, current version 0.0.0) /usr/local/lib/libboost_python.dylib (compatibility version 0.0.0, current version 0.0.0) /System/Library/Frameworks/Python.framework/Versions/2.7/Python (compatibility version 2.7.0, current version 2.7.10) /usr/lib/libc++.1.dylib (compatibility version 1.0.0, current version 120.1.0) /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1225.1.1) and finally run python test.py , I get the result.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/33281753', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1820217/']}
jdg_78091
stackexchange
llm_judgeable_groundtruth_similarity
43685799
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to create a UUID id in a table with PostgreSQL. I tried with: id uuid PRIMARY KEY DEFAULT uuid_generate_v4() But I get: ERROR: function uuid_generate_v4() does not exist HINT: No function matches the given name and argument types. You might need to add explicit type casts. I tried with adding the schema like: id uuid PRIMARY KEY DEFAULT public.uuid_generate_v4() (as seen in a comment here ) I also checked if the extension is there ( SELECT * FROM pg_available_extensions; ), and yes I have it installed in the PostgreSQL database: I read that if the Postgres is runing in --single mode, this may not work, but I don't know how to test it or if there is any way to do it. Somebody knows how I can resolve the problem? Or any other option?Is it a good idea to use like this: SET DEFAULT uuid_in(md5(random()::text || now()::text)::cstring); Now provide the response and nothing else.
Because the function uuid_generate_v4 is not found, it suggests that the extension uuid-ossp is not loaded pg_available_extensions lists the extensions available, but not necessarily loaded . to see the list of loaded extensions query the view pg_extension as such: select * from pg_extension; To load the uuid-ossp extension run the following: CREATE EXTENSION "uuid-ossp"; note : this will require super user privileges. After the uuid-ossp extension is successfully loaded, you should see it in the pg_extension view & the function uuid_generate_v4 should be available.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/43685799', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6058255/']}
jdg_78092
stackexchange
llm_judgeable_groundtruth_similarity
9258932
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am struggling converting image to byte array using client side script. I have to convert image to byte array, and pass this array to web service , so that the web services can save the image in sql server. Any one please help me. Now provide the response and nothing else.
i have found one solution. :) in html javascript file, first convert the uploaded image to base64 image format using following code. var p;var canvas = document.createElement("canvas");var img1=document.createElement("img"); function getBase64Image(){ p=document.getElementById("fileUpload").value; img1.setAttribute('src', p); canvas.width = img1.width; canvas.height = img1.height; var ctx = canvas.getContext("2d"); ctx.drawImage(img1, 0, 0); var dataURL = canvas.toDataURL("image/png"); alert("from getbase64 function"+dataURL ); return dataURL;} so we got base64 code of uploaded image in dataURL . NOW SEND THIS BASE64 CODE ( dataURL ) to web service and convert the base64 string to byte array using following code and save to sql server too c# code--for converting base64 to byte arry and to store on sql private void Form1_Load(object sender, EventArgs e) { int userid = 5; string base64="";// load base 64 code to this variable from js Byte[] bitmapData = new Byte[base64.Length]; bitmapData = Convert.FromBase64String(FixBase64ForImage(base64)); string connstr = @"user id=sa; password=*****"; database=ImageTest; server="192.168.1.104"; SqlConnection conn = new SqlConnection(connstr); conn.Open(); string query; query = "insert into imagetable(userid,image) values(" + userid + "," + " @pic)"; SqlParameter picparameter = new SqlParameter(); picparameter.SqlDbType = SqlDbType.Image; picparameter.ParameterName = "pic"; picparameter.Value = bitmapData; SqlCommand cmd = new SqlCommand(query, conn); cmd.Parameters.Add(picparameter); cmd.ExecuteNonQuery(); cmd.Dispose(); conn.Close(); conn.Dispose();}public static string FixBase64ForImage(string image) { StringBuilder sbText = new StringBuilder(image, image.Length); sbText.Replace("\r\n", String.Empty); sbText.Replace(" ", String.Empty); return sbText.ToString();} hope u understand :) ......
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9258932', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1187284/']}
jdg_78093
stackexchange
llm_judgeable_groundtruth_similarity
162899
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to create a script that act as a ps command with it's own properties that I want to display. Say this is how processes would look like in ps command: sas 24431 1 0 Oct10 ? 00:51:08 /usr/lib/jvm/java-1.7.0-oracle-1.7.0.25.x86_64/jre/bin/java -Denv=DEV -Dapp.name=myApp -Xms512m -Xmx1g -Dlog.dir=/apps/java/logs I want to display as below: UID PID APPNAMEsas 24431 -Dapp.name=myAppsas 24432 -Dapp.name=myApp2sas 24433 -Dapp.name=myApp3 Note: the app.name property is a command argument that is extracted from the ps command This is my script: echo -e "PID\tUSERID\t\tAPPNAME"ps -u $USER -f |grep "java"|grep -v "grep"|while read LINE do #Get pid from the line PID=$(cut -d" " -f2 <<< $LINE); #Get parameter value called "-Dapp.name or -DprojectName" #from the ps command for the process APPNAME=$(ps -f $PID | awk 'BEGIN {RS=" "}; /-Dapp.name|-DprojectName/'); USERID=$(cut -d" " -f1 <<< $LINE); echo -e $PID"\t"$USERID"\t"$APPNAME;done; Right now it works the way I want it. But sometimes the alignment getting screwed. Also can this script be optimized into one line command? Any help would be appreciated. Now provide the response and nothing else.
For general purpose tabular alignment, you want the column utility. For example: ( printf 'PID\tUSER\tAPPNAME\n' printf '%s\t%s\t%s\n' "1" "john" "foo bar" printf '%s\t%s\t%s\n' "12345678" "someone_with_a_long_name" "pop tart") | column -t -s $'\t' Results in: PID USER APPNAME1 john foo bar12345678 someone_with_a_long_name pop tart
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/162899', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/72369/']}
jdg_78094
stackexchange
llm_judgeable_groundtruth_similarity
24079736
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: LoDash's debounce accepts an option maxWait . From the docs: [options.maxWait] (number): The maximum time func is allowed to be delayed before it’s called. I'm confused, isn't that just the same as using throttle ? What's the difference? Now provide the response and nothing else.
They are a similar concept but quite different. maxWait - the amount of time to wait before the function is called. throttle - the amount of time to wait between calls. throttle is used when you are calling a function multiple times and don't want it to be called too often. maxWait is used when you are delaying execution of a single event. edit adding a bit more detail here: the difference between _throttle and _debounce is a bit subtle. _debounce creates a function which: Creates a function that will delay the execution of func until after wait milliseconds have elapsed since the last time it was invoked. while _throttle creates a function which: Creates a function that, when executed, will only call the func function at most once per every wait milliseconds. _debounce actually allows subsequent calls to occur, but delays their processing, while _throttle actually disallows calls during the wait period. You can debounce a function multiple times, delaying it theoretically indefinitely. maxWait can be used to ensure the function does eventually get called. The leading and trailing options do not cause additional runs of the function; instead, they control when the function is executed. Using leading causes the function to execute, and subsequent calls to be debounced. Using trailing causes the function to execute at the end of the debounce, which could be less than the timeout. Essentially, you are allowing the subsequent calls to happen as soon as the last debounce time ends, instead of forcing them to wait for their entire timeout if they started in the middle. Note: If leading and trailing options are true func will be called on the trailing edge of the timeout only if the the debounced function is invoked more than once during the wait timeout. so, in theory if you used all 3 options ( leading , maxWait , and trailing ), the maxWait wouldn't happen because you would never exceed the wait period, and trailing would only happen if you called the function twice in the same wait period.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/24079736', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/414825/']}
jdg_78095
stackexchange
llm_judgeable_groundtruth_similarity
1381
Below is a question asked on the forum softwarerecs.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have a home server on Ubuntu Server 12.04 that really doesn't need to be using power, making noise, etc. at night. I'm too lazy, though, to actually turn it off at night and back on in the morning. I'd like a command line tool that I can run in a cronjob that sleeps my laptop-server and wakes it at a set time automatically. In short: If it has a GUI, it must be optional. It must be able to be run from a cronjob. It must be able to awake the machine later without side effects. Is there a program that does such a thing? Now provide the response and nothing else.
You don't need new software to do this; here is how your existing software can handle this. Use cron to suspend the machine at a pre-configured time. Use the BIOS timer to wake it up at a pre-configured time. Shutdown For the last few releases Ubuntu has used their own home baked init system called upstart 1 . The power management utilities have gone through a couple of phases, so depending on what version you have there might be a couple ways of making this happen. This question on Ask Ubuntu should be helpful at figuring this part out, but you cat also just try to find which of these commands suspend your machine (as root): # From the powermanagement-interface packagepmi action suspend# From the pm-utils packagepm-suspend# Using DBUSdbus-send --system --print-reply --dest="org.freedesktop.UPower" /org/freedesktop/UPower org.freedesktop.UPower.Suspend# A little raw kernel api call echo -n mem > /sys/power/state Once you find one of those that suspends to your satisfaction on your version, stick it in a root cron job: 0 11 * * * <working command from previous step> This assumes that you go to bed at a reasonable hour like 11. Obviously you can change that part :) Startup For this you are going to need to bust around in your BIOS. What this feature is called is going to vary by manufacture, but most boards have a way to power on at a certain clock time. Here is one configured for a late morning rise: You can get an idea of what these settings are going to look like in various BIOSes from Google image search: bios wake timer . 1 This actually is changing in the next release as they have settled on systemd along with most other major distros. When that happens the commands above will be obsoleted by systemctl suspend .
{}
{'log_upvote_score': 5, 'links': ['https://softwarerecs.stackexchange.com/questions/1381', 'https://softwarerecs.stackexchange.com', 'https://softwarerecs.stackexchange.com/users/46/']}
jdg_78096
stackexchange
llm_judgeable_groundtruth_similarity
51382524
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: What is the difference between predict and predict_class functions in keras? Why does Model object don't have predict_class function? Now provide the response and nothing else.
predict will return the scores of the regression and predict_class will return the class of your prediction. Although it seems similar, there are some differences: Imagine you are trying to predict if the picture is a dog or a cat (you have a classifier): predict will return you: 0.6 cat and 0.4 dog (for example). predict_class will return the index of the class having maximum value. For example, if cat is 0.6 and dog is 0.4, it will return 0 if the class cat is at index 0) Now, imagine you are trying to predict house prices (you have a regressor): predict will return the predicted price predict_class will not make sense here since you do not have a classifier TL:DR: use predict_class for classifiers (outputs are labels) and use predict for regressions (outputs are non-discrete) Hope it helps! For your second question, the answer is here
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/51382524', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6502047/']}
jdg_78097
stackexchange
llm_judgeable_groundtruth_similarity
23964726
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: How do I create an a slider menu using Xamarin.Forms? Is it baked in or something custom? Now provide the response and nothing else.
You create a new class which contains all the definitions for both the Master - i.e. the menu - and the Detail - i.e. the main page. I know, it sounds back-to-front, but for example.. using System;using Xamarin.Forms;namespace testXamForms { public class HomePage : MasterDetailPage { public HomePage() { // Set up the Master, i.e. the Menu Label header = new Label { Text = "MENU", Font = Font.BoldSystemFontOfSize(20), HorizontalOptions = LayoutOptions.Center }; // create an array of the Page names string[] myPageNames = { “Main”, “Page 2”, “Page 3”, }; // Create ListView for the Master page. ListView listView = new ListView { ItemsSource = myPageNames, }; // The Master page is actually the Menu page for us this.Master = new ContentPage { Title = "The Title is required.", Content = new StackLayout { Children = { header, listView }, } }; // Define a selected handler for the ListView contained in the Master (ie Menu) Page. listView.ItemSelected += (sender, args) => { // Set the BindingContext of the detail page. this.Detail.BindingContext = args.SelectedItem; Console.WriteLine("The args.SelectedItem is {0}",args.SelectedItem); // This is where you would put your “go to one of the selected pages” // Show the detail page. this.IsPresented = false; }; // Set up the Detail, i.e the Home or Main page. Label myHomeHeader = new Label { Text = "Home Page", HorizontalOptions = LayoutOptions.Center }; string[] homePageItems = { “Alpha”, “Beta”, “Gamma” }; ListView myHomeView = new ListView { ItemsSource = homePageItems, }; var myHomePage = new ContentPage(); myHomePage.Content = new StackLayout { Children = { myHomeHeader, myHomeView } , }; this.Detail = myHomePage; } } }
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/23964726', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/30099/']}
jdg_78098
stackexchange
llm_judgeable_groundtruth_similarity
7951019
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: #include<stdio.h>#include<string.h>int main() { char s[100] ="4.0800" ; printf("float value : %4.8f\n" ,(float) atoll(s)); return 0; } I expect the output should be 4.08000000 whereas I got only 4.00000000 . Is there any way to get the numbers after the dot? Now provide the response and nothing else.
Use atof() or strtof() * instead: printf("float value : %4.8f\n" ,atof(s)); printf("float value : %4.8f\n" ,strtof(s, NULL)); http://www.cplusplus.com/reference/clibrary/cstdlib/atof/ http://www.cplusplus.com/reference/cstdlib/strtof/ atoll() is meant for integers. atof() / strtof() is for floats. The reason why you only get 4.00 with atoll() is because it stops parsing when it finds the first non-digit. *Note that strtof() requires C99 or C++11.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7951019', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/283501/']}
jdg_78099
stackexchange
llm_judgeable_groundtruth_similarity
32533
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Convex Optimization is a mathematically rigorous and well-studied field. In linear programming a whole host of tractable methods give your global optimums in lightning fast times. Quadratic programming is almost as easy, and there's a good deal of semi-definite, second-order cone and even integer programming methods that can do quite well on a lot of problems. Non-convex optimization (and particularly weird formulations of certain integer programming and combinatorial optimization problems), however, are generally heuristics like "ant colony optimization". Essentially all generalizable non-convex optimization algorithms I've come across are some (often clever, but still) combination of gradient descent and genetic algorithms. I can understand why this is - in non-convex surfaces local information is a lot less useful - but I would figure that there would at least be an algorithm that provably learns for a broad class of functions whether local features indicate a nearby global optimum or not. Also, perhaps, general theories of whether and how you can project a non-convex surface into higher dimensions to make it convex or almost convex. Edit: An example. A polynomial of known degree k only needs k + 1 samples to reconstruct - does this also give you the minimum within a given range for free, or do you still need to search for it manually? For any more general class of functions, does "ability to reconstruct" carry over at all to "ability to find global optima"? Now provide the response and nothing else.
If the question is "Are there non-convex global search algorithms with provably nice properties?" then the answer is "Yes, lots." The algorithms I'm familiar with use interval analysis. Here's a seminal paper from 1979: Global Optimization Using Interval Analysis . And here's a book on the topic . The requirements on the function are that it be Lipschitz or smooth to some order, and that it not have a combinatorial explosion of local optima. These techniques aren't as fast as linear or convex programming, but they're solving a harder problem, so you can't hold it against them. And from a practical point of view, for reasonable functions, they converge plenty fast.
{}
{'log_upvote_score': 6, 'links': ['https://mathoverflow.net/questions/32533', 'https://mathoverflow.net', 'https://mathoverflow.net/users/942/']}
jdg_78100
stackexchange
llm_judgeable_groundtruth_similarity
20181323
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have a basic controller that displays my products, App.controller('ProductCtrl',function($scope,$productFactory){ $productFactory.get().success(function(data){ $scope.products = data; });}); In my view I'm displaying this products in a list <ul> <li ng-repeat="product as products"> {{product.name}} </li></ul What I'm trying to do is when someone click on the product name, i have another view named cart where this product is added. <ul class="cart"> <li> //click one added here </li> <li> //click two added here </li> </ul> So my doubt here is, how do pass this clicked products from first controller to second? i assumed that cart should be a controller too. I handle click event using directive. Also i feel i should be using service to achieve above functionality just can't figure how? because cart will be predefined number of products added could be 5/10 depending on which page user is. So i would like to keep this generic. Update: I created a service to broadcast and in the second controller i receive it. Now the query is how do i update dom? Since my list to drop product is pretty hardcoded. Now provide the response and nothing else.
From the description, seems as though you should be using a service. Check out http://egghead.io/lessons/angularjs-sharing-data-between-controllers and AngularJS Service Passing Data Between Controllers to see some examples. You could define your product service (as a factory) as such: app.factory('productService', function() { var productList = []; var addProduct = function(newObj) { productList.push(newObj); }; var getProducts = function(){ return productList; }; return { addProduct: addProduct, getProducts: getProducts };}); Dependency inject the service into both controllers. In your ProductController , define some action that adds the selected object to the array: app.controller('ProductController', function($scope, productService) { $scope.callToAddToProductList = function(currObj){ productService.addProduct(currObj); };}); In your CartController , get the products from the service: app.controller('CartController', function($scope, productService) { $scope.products = productService.getProducts();});
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/20181323', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1263709/']}
jdg_78101
stackexchange
llm_judgeable_groundtruth_similarity
152750
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: A topological space $X$ satisfies the "Periodic orbit property", briefly POP, if for every continuous map $f:X \to X$ , there exist a natural number $n$ and a point $x_{0}\in X$ such that $f^{n}(x_{0})=x_{0}$ . Obviously fixed point property (FPP) implies POP. For a natural number $n$ , a topological space $X$ is called $n$ -POP if for every continuous map $f$ on $X$ , $f^{n}$ has a fixed point. (Ex: $\mathbb{S}^{2n}$ is a 2-POP manifold, because the degree of a fixed-point-free map on $\mathbb{S}^{2n}$ must be $-1$ .) The question: Is there an example of a manifold $M$ which satisfies POP but for every $n\in \mathbb{N}$ , there is a continuous map $f$ on $M$ such that $f^{n}$ has no fixed point? Namely: we search for a manifold for which every self-map has a periodic orbit, but there is no any control on periods. Equivalently: Is there a manifold $M$ which is POP but not $n$ -POP for all $n\in \mathbb{N}$ ? In particular, can we say: "every compact POP manifold is necessarily a $n$ -POP manifold, for some $n$ "? Motivated by the Lefschetz fixed-point theorem, we ask that: What algebraic topological criterion, can be introduced for consideration of this property(POP)? Edit: According to the very interesting answer of Qiaochu Yuan, in the orientable case, the question is equivalent to the following: Let M be a closed orientable manifold. Is it true that $M$ is not POP if and only if $\chi(M)=0$ ? Note1 For a related question see this post and it is natural to ask that "Does $S^{2}\vee S^{2}$ satisfy the periodic orbit property?" Note2 I think the continuation of the argument of Qiaochu Yuan for his first statement is not easy, for arbitrary manifold. Because for the simplest case $S^{3}$ we had the famous conjecture of "existence of a vector field on $S^{3}$ without periodic orbit. In fact consideration of non vanishing vector fields is necessary but not sufficient. Periodic orbits of vector fields are important, too. Moreover, perhaps an approach which is not based on "vector fields" could be useful, for example consideration of orientation-reversing diffeomorphisms. Note 3: "pointwise periodic homeomorphism' is a concept which is indirectly similar to the subject of this post. Now provide the response and nothing else.
Nice question! Here's what I can show. Let $X$ be a smooth closed manifold. Then: (1) If $\chi(X) = 0$ , then $X$ is not $n$ -POP for any $n$ . (2) If $\chi(X) \neq 0$ and $X$ is orientable, then $X$ is $\text{lcm}(1, 2, ... n)$ -POP with respect to maps $f : X \to X$ of nonzero degree, where $n = \text{max}(b_0 + b_2 + ..., b_1 + b_3 + ...)$ (where $b_i$ is the $i^{th}$ Betti number of $X$ ). Proof of 1. We will use the converse of the Poincaré-Hopf theorem: if $\chi(X) = 0$ , then $X$ admits a nonvanishing vector field. Let $\varphi(t)$ denote the flow of this vector field. Let $t_{0}>0$ be small enough so that $\varphi(t_0)$ has no fixed points. Such $t_{0}$ exists, because there is a positive uniform lower bound for the period of all periodic orbits.(As a consequence of the flow box theorem, around regular points of a vector field). For a given $n \in \mathbb{N}$ , let $f = \varphi \left( \frac{t_0}{n} \right)$ . Then $f^n$ has no fixed points, hence $X$ is not $n$ -POP. $\Box$ (I strongly suspect that in this case $X$ is not POP either; it seems like we should be able to consider a small flow of a sufficiently generic nonvanishing vector field. But I don't know how to finish this argument.) Proof of 2. We will need the following two observations. Lemma 1: Let $f_0, f_1$ be linear operators acting on two finite-dimensional vector spaces $V_0, V_1$ . If $\text{tr}(f_0^k) = \text{tr}(f_1^k)$ for $k$ between $1$ and $\text{max}(\dim V_0, \dim V_1)$ , then $f_0$ and $f_1$ have the same nonzero eigenvalues with the same multiplicities. Proof. The above condition implies, using the Newton-Girard identities, that $f_0$ and $f_1$ have the same characteristic polynomial up to factors of $t$ . $\Box$ Lemma 2: Let $X$ be an $n$ -dimensional smooth closed oriented manifold and let $f : X \to X$ be a map of nonzero degree. Then every eigenvalue of $f$ acting on cohomology (with complex coefficients) is nonzero. Proof. Let $e_1, ..., e_d$ be a basis of generalized eigenvectors for the action of $f$ on $H^k(X, \mathbb{C})$ . By Poincaré duality the cup product $H^k \otimes H^{n-k} \to H^n$ is nondegenerate, so we can find a dual basis $e_1^{\ast}, ..., e_d^{\ast}$ of $H^{n-k}(X, \mathbb{C})$ . Since $f$ acts by a nonzero scalar, namely $\deg f$ , on $e_i \smile e_i^{\ast}$ for all $i$ , the generalized eigenvalue of $e_i$ must also be nonzero. $\Box$ Now back to the proof of 2. With hypotheses as above, let $f_0$ denote the map induced by $f$ on the direct sum $V_0$ of the even-dimensional complex cohomology of $X$ and let $f_1$ denote the map induced by $f$ on the direct sum $V_1$ of the odd-dimensional complex cohomology of $X$ , so that the Lefschetz trace of $f^k$ can be written $$L(f^k) = \text{tr}(f_0^k) - \text{tr}(f_1^k).$$ By Lemma 2, the eigenvalues of $f_0$ and $f_1$ are all nonzero, so if $f_0$ and $f_1$ have the same nonzero eigenvalues then in particular $\dim V_0 = \dim V_1$ . By the contrapositive of Lemma 1, if $\chi(X) = \dim V_0 - \dim V_1 \neq 0$ , then there exists some $k$ between $1$ and $n = \text{max}(\dim V_0, \dim V_1)$ such that $L(f^k) \neq 0$ , hence, by the Lefschetz fixed point theorem, such that $f^k$ has a fixed point. In particular, $f^{\text{lcm}(1, 2, ... n)}$ has a fixed point. $\Box$
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/152750', 'https://mathoverflow.net', 'https://mathoverflow.net/users/36688/']}
jdg_78102
stackexchange
llm_judgeable_groundtruth_similarity
3278677
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Does there exist a sequence $(a_i)_{i \geq 0}$ of distinct positive integers such that $\sum_{i\geq 0}\frac{1}{a_i} \in \mathbb{Q}$ and $$\{ p \in \mathbb{P} \text{ }|\text{ } \exists\text{ } i\geq 0 \text{ s.t.}\text{ } p | a_i\}$$ is infinite? Motivation: All geometric series (corresponding to sets $\{ 1,n,n^2,n^3,... \}$ ) are rational and the terms obviously contain finitely many primes. The same is true for say, sums of reciprocals of all numbers whose prime factiorisation contains only the primes $p_1, p_2, ...,p_k$ : the sum is then $\prod_{i=1}^k\left(\frac{p_i}{p_i-1}\right)$ On the other side, series corresponding to sets $\{1^2, 2^2, 3^2, ...\}, \{1^3,2^3,3^3,...\},\{1!,2!,3!,...\}$ converge to $\frac{\pi^2}{6}$ , Apery's constant and $e$ respectively, which are all known to be irrationals. I am aware of the fact that if this statement is true then it has not been proven yet (since it implies that the values of the zeta function at positive integers are irrational, which to my knowledge has not been shown yet). Any counterexamples or other possible observations (such as, instead of requiring the set of primes to be infinite, requiring that it contains all primes except a finite set)? Now provide the response and nothing else.
The set $$ A=\{1\times 2, 2\times 3, ...,n\times (n+1),...\}$$ is such a set. Note that $$\sum _1^\infty \frac{1}{n(n+1)}=1$$ and every prime number $p$ divides $p(p+1)$ which is an element of the set $A$ .
{}
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/3278677', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/337265/']}
jdg_78103
stackexchange
llm_judgeable_groundtruth_similarity
31537316
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm having trouble working with an Enum where some attributes have the same value. I think Enums are so new to python that I can't find any other reference to this issue. In any case, let's say I have the following class CardNumber(Enum): ACE = 11 TWO = 2 THREE = 3 FOUR = 4 FIVE = 5 SIX = 6 SEVEN = 7 EIGHT = 8 NINE = 9 TEN = 10 JACK = 10 QUEEN = 10 KING = 10 Clearly these are the card numbers and their corresponding values in black jack. The ten through king have the same value. But if I do something like print(CardNumber.QUEEN) , I get back <CardNumber.TEN: 10> . What's more, if I iterate over these, it simply iterates over unique values. >>> for elem in CardNumber:... print(elem)CardNumber.ACECardNumber.TWOCardNumber.THREECardNumber.FOURCardNumber.FIVECardNumber.SIXCardNumber.SEVENCardNumber.EIGHTCardNumber.NINECardNumber.TEN How can I get around this issue? I want CardNumber.QUEEN and CardNumber.TEN to be unique, and both appear in any iteration. The only thing I could think of was to give each attribute a second value which would act as a distinct id, but that seems unpythonic. Now provide the response and nothing else.
Yes, labels with duplicate values are turned into aliases for the first such label. You can enumerate over the __members__ attribute, it is an ordered dictionary with the aliases included: >>> for name, value in CardNumber.__members__.items():... print(name, value)... ACE CardNumber.ACETWO CardNumber.TWOTHREE CardNumber.THREEFOUR CardNumber.FOURFIVE CardNumber.FIVESIX CardNumber.SIXSEVEN CardNumber.SEVENEIGHT CardNumber.EIGHTNINE CardNumber.NINETEN CardNumber.TENJACK CardNumber.TENQUEEN CardNumber.TENKING CardNumber.TEN However, if you must have label-and-value pairs that are unique (and not aliases), then enum.Enum is the wrong approach here; it doesn't match the usecases for a card game. In that case it'll be better to use a dictionary (consider using collections.OrderedDict() if order is important too).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/31537316', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3861449/']}
jdg_78104
stackexchange
llm_judgeable_groundtruth_similarity
38842454
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm using ReactJs with Redux and on some tutorials and codes I see people suggesting and using normalizr to keep the state flat . But what is the real advantage in keeping it flat ? Will I encounter any problems if I don't ? Is it necessary ? Now provide the response and nothing else.
Three main reasons: Updating nested Javascript objects immutably generally results in uglier code that is harder to maintain, unless you use a utility library to wrap up the process Immutably updating nested data requires that you return new copies of all items in the nesting hierarchy. Since components generally do shallow-equality reference comparisons on data to see if they need to update, updating nested data usually means that more objects are updated, and more components will probably have to re-render even if the actual data isn't different. Flat data, and in particular normalized data, enables some more optimized approaches for defining components (such as a list where each list item component is itself connected, given an item ID as a prop, and is responsible for looking up its own item's data by that ID)
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/38842454', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5607525/']}
jdg_78105
stackexchange
llm_judgeable_groundtruth_similarity
43445681
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am Integrating Paytm PGSDK_V2.0 in my android app. I have read all documentation on Github . I have understand everything.but the problem is in its earlier SDK where we can simply generate checksum using Paytm Merchant object Like: PaytmMerchant merchant=new PaytmMerchant("Checksum generation url","Checksum verification url"); and put this in Service Like this Service.initialize(Order,merchant,null); But in new SDK it change to Service.initialize(Order,null); So please help me how to generate checksum in new SDK Now provide the response and nothing else.
Paytm has change process to increase the security. now in PGSDK_V2.0 first you have to generate through calling the api Checksum Generation on your server sideLike this: @Override protected String doInBackground(String... params) { url ="http://xxx.co.in/generateChecksum.php"; JSONParser jsonParser = new JSONParser(MainActivity.this); param="ORDER_ID=" + orderId+ "&MID="+YourMID+ "&CUST_ID="+custId+ "&CHANNEL_ID=WAP&INDUSTRY_TYPE_ID=Retail110&WEBSITE=xxxwap&TXN_AMOUNT="+billAmt+"&CALLBACK_URL=http://xxx.co.in/verifyChecksum.php"; JSONObject jsonObject = jsonParser.makeHttpRequest(url,"POST",param); Log.e("CheckSum result >>",jsonObject.toString()); if(jsonObject != null){ Log.d("CheckSum result >>",jsonObject.toString()); try { CHECKSUMHASH=jsonObject.has("CHECKSUMHASH")?jsonObject.getString("CHECKSUMHASH"):""; Log.e("CheckSum result >>",CHECKSUMHASH); } catch (JSONException e) { e.printStackTrace(); } } return null; } now after getting CHECKSUM string in your onPostExecute initialize paytm Service object and do further process Like This: @Override protected void onPostExecute(String s) { super.onPostExecute(s); progressDialog.hide(); Service = PaytmPGService.getProductionService(); /*PaytmMerchant constructor takes two parameters 1) Checksum generation url 2) Checksum verification url Merchant should replace the below values with his values*/ //below parameter map is required to construct PaytmOrder object, Merchant should replace below map values with his own values Map<String, String> paramMap = new HashMap<String, String>(); //these are mandatory parameters paramMap.put("ORDER_ID", orderId); //MID provided by paytm paramMap.put("MID", yourMID); paramMap.put("CUST_ID", custId); paramMap.put("CHANNEL_ID", "WAP"); paramMap.put("INDUSTRY_TYPE_ID", "Retail"); paramMap.put("WEBSITE", "xxxwap"); paramMap.put("TXN_AMOUNT",billAmt); // paramMap.put("CALLBACK_URL" ,"http://xxx.co.in/verifyChecksum.php"); paramMap.put("CHECKSUMHASH" ,CHECKSUMHASH); PaytmOrder Order = new PaytmOrder(paramMap); Service.initialize(Order,null); Service.startPaymentTransaction(ReviewBooking.this, true, true, new PaytmPaymentTransactionCallback() { @Override public void someUIErrorOccurred(String inErrorMessage) { // Some UI Error Occurred in Payment Gateway Activity. // // This may be due to initialization of views in // Payment Gateway Activity or may be due to // // initialization of webview. // Error Message details // the error occurred. } @Override public void onTransactionResponse(Bundle inResponse) { Log.d("LOG", "Payment Transaction : " + inResponse); String response=inResponse.getString("RESPMSG"); if (response.equals("Txn Successful.")) { new ConfirmMerchent().execute(); }else { Toast.makeText(getApplicationContext(),response,Toast.LENGTH_SHORT).show(); } Toast.makeText(getApplicationContext(), "Payment Transaction response "+inResponse.toString(), Toast.LENGTH_LONG).show(); } @Override public void networkNotAvailable() { // If network is not // available, then this // method gets called. } @Override public void clientAuthenticationFailed(String inErrorMessage) { // This method gets called if client authentication // failed. // Failure may be due to following reasons // // 1. Server error or downtime. // 2. Server unable to // generate checksum or checksum response is not in // proper format. // 3. Server failed to authenticate // that client. That is value of payt_STATUS is 2. // // Error Message describes the reason for failure. } @Override public void onErrorLoadingWebPage(int iniErrorCode, String inErrorMessage, String inFailingUrl) { } // had to be added: NOTE @Override public void onBackPressedCancelTransaction() { // TODO Auto-generated method stub } @Override public void onTransactionCancel(String inErrorMessage, Bundle inResponse) { Log.d("LOG", "Payment Transaction Failed " + inErrorMessage); Toast.makeText(getBaseContext(), "Payment Transaction Failed ", Toast.LENGTH_LONG).show(); } }); } JsonParser Class public class JSONParser { static InputStream is = null; static JSONObject jObj = null; static String json = ""; HttpURLConnection urlConnection = null; // variable to hold context private Context context; // constructor public JSONParser(Context context){ this.context=context; } public JSONObject makeHttpRequest(String url,String method,String params) { // boolean isReachable =Config.isURLReachable(context); // Making HTTP request try { String retSrc=""; char current = '0'; URL url1 = new URL(url); // check for request method HttpURLConnection urlConnection = (HttpURLConnection) url1.openConnection(); if (method == "POST") { // request method is POST urlConnection.setDoOutput(true); urlConnection.setRequestMethod("POST"); urlConnection.setFixedLengthStreamingMode(params.getBytes().length); urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); PrintWriter out = new PrintWriter(urlConnection.getOutputStream()); out.print(params); out.close(); } InputStream in = urlConnection.getInputStream(); InputStreamReader isw = new InputStreamReader(in); byte[] bytes = new byte[10000]; StringBuilder x = new StringBuilder(); int numRead = 0; while ((numRead = in.read(bytes)) >= 0) { x.append(new String(bytes, 0, numRead)); } retSrc=x.toString(); jObj = new JSONObject(retSrc); } catch (Exception e) { e.printStackTrace(); new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { Toast.makeText(context, "Connectivity issue. Please try again later.", Toast.LENGTH_LONG).show(); } }); return null; }finally { if (urlConnection != null) { urlConnection.disconnect(); } } return jObj; }} and parameter values should be same both time.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/43445681', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6886100/']}
jdg_78106
stackexchange
llm_judgeable_groundtruth_similarity
6668577
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have a CSS class Modal which is absolutely positioned, z-indexed above it's parent, and nicely positioned with JQuery. I want to add a caret image (^) to the top of the modal box and was looking at using the :before CSS pseudo selector to do this cleanly. The image needs to be absolutely positioned and z-indexed above the modal, but I haven't found any way to add the appropriate class to the image in the content attribute: .Modal:before{ content:url('blackCarrot.png') /* with class ModalCarrot ??*/}.ModalCarrot{ position:absolute; left:50%; margin-left:-8px; top:-16px;} Second best option- can I add the styles inline in the content attribute? Now provide the response and nothing else.
http://caniuse.com/#search=::after ::after and ::before with content are better to use as they're supported in every major browser other than Internet Explorer at least 5 versions back. Internet Explorer has complete support in version 9+ and partial support in version 8. Is this what you're looking for? .Modal::after{ content:url('blackCarrot.png'); /* with class ModalCarrot ??*/ position:relative; /*or absolute*/ z-index:100000; /*a number that's more than the modal box*/ left:-50px; top:10px;}.ModalCarrot{ position:absolute; left:50%; margin-left:-8px; top:-16px;} If not, can you explain a little better? or you could use jQuery, like Joshua said: $(".Modal").before("<img src='blackCarrot.png' class='ModalCarrot' />");
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/6668577', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/526133/']}
jdg_78107
stackexchange
llm_judgeable_groundtruth_similarity
11979640
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have a button to change the BOOL showSquare equal to YES This is the code for the button - (IBAction)Tap_Square:(id)sender { [graphicsView setNeedsDisplay]; [graphicsView setShowSquare:YES];} and this is where the if statement is if (showSquare) { CGContextSetFillColorWithColor(context, white); CGContextFillRect(context, CGRectMake(90, 90, 100, 100));} Am i doing something wrong? Thanks Now provide the response and nothing else.
Yes, writing your own Format instance is the recommended approach . Given the following class, for example: case class User( id: Long, firstName: String, lastName: String, email: Option[String]) { def this() = this(0, "","", Some(""))} The instance might look like this: import play.api.libs.json._implicit object UserFormat extends Format[User] { def reads(json: JsValue) = User( (json \ "id").as[Long], (json \ "firstName").as[String], (json \ "lastName").as[String], (json \ "email").as[Option[String]] ) def writes(user: User) = JsObject(Seq( "id" -> JsNumber(user.id), "firstName" -> JsString(user.firstName), "lastName" -> JsString(user.lastName), "email" -> Json.toJson(user.email) ))} And you'd use it like this: scala> User(1L, "Some", "Person", Some("s.p@example.com"))res0: User = User(1,Some,Person,Some(s.p@example.com))scala> Json.toJson(res0)res1: play.api.libs.json.JsValue = {"id":1,"firstName":"Some","lastName":"Person","email":"s.p@example.com"}scala> res1.as[User]res2: User = User(1,Some,Person,Some(s.p@example.com)) See the documentation for more information.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/11979640', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1588929/']}
jdg_78108
stackexchange
llm_judgeable_groundtruth_similarity
2296087
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Hay, I wondering how to work out distance between 2 post codes using PHP and Google Maps Api. Any one got any idea or links to examples. Now provide the response and nothing else.
Assuming you are looking for the geographic distance , first you need to get the latitude and longitude of your two postcodes with the Google Maps server-side geocoding services as in the following example: $url = 'http://maps.google.com/maps/geo?q=EC3M,+UK&output=csv&sensor=false';$data = @file_get_contents($url);$result = explode(",", $data);echo $result[0]; // status codeecho $result[1]; // accuracyecho $result[2]; // latitudeecho $result[3]; // longitude Then you can calculate the distance between the coordinates of your two postcodes by using a great-circle distance implementation such as the following: Snipplr - Calculate distance between two coordinates in PHP Note that the server-side geocoding service may only be used in conjunction with displaying results on a Google map; geocoding results without displaying them on a map is prohibited by the Google Maps API Terms of Service License Restrictions . UPDATE: If you are looking for the driving distance instead of the geographical distance, note that there is no documented and approved method at the moment to access the Google Maps Directions API via an HTTP request on the server-side. Nevertheless, an undocumented method that returns a JSON output is the following: http://maps.google.com/maps/nav?q=from:London%20to:Dover This will return you the driving directions, along with the total driving distance in JSON format: "meters":122977 . The format of the q parameter should be from:xxx%20to:yyy . Replace xxx and yyy with the start and destination respectively. You can use latitude and a longitude coordinates instead of full addresses: http://maps.google.com/maps/nav?q=from:51.519894,-0.105667%20to:51.129079,1.306925 Note that not only this is undocumented, but it may also violate the restrictions 10.1 and 10.5 of the Google Maps API Terms and Conditions . You may also be interesting in checking out the following related articles: Stack Overflow: Calculate driving directions using PHP? Getting distance using GDirections via URL Retrieve driving directions from google maps with server-side HTTP calls and show results with static maps for WAP Google Maps and Directions, REST Interface?
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2296087', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/164230/']}
jdg_78109
stackexchange
llm_judgeable_groundtruth_similarity
49809545
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: When I try to update my custom text-area component's model data this.message='<span id="foo">bar</span> the text and html does not display in the htmltextarea tag like it should, but I can see the update applied in the Vue dev tool's console. I've also tried switching to an object instead of a string and using Vue.set , but this does not work either. Any suggestions on how to fix this? The goal with the htmlTextArea component is to get the users text from the htmlTextArea tag (this works), manipulate this text and bind it back to the textarea, but with HTML in it. Custom text-area component: <template> <div contenteditable="true" @input="updateHTML" class="textareaRoot"></div></template><script>export default { // Custom textarea name: 'htmlTextArea', props:['value'], mounted: function () { this.$el.innerHTML = this.value; }, methods: { updateHTML: function(e) { this.$emit('input', e.target.innerHTML); } }}</script> Other component: <template>...<htmlTextArea id="textarea" v-model="message"></htmlTextArea>...</template><script> data: { return { message: 'something'//this works } } ... methods: { changeText() { this.message='<span id="foo">bar</span>'//this does not } }, components: { htmlTextArea }</script> Now provide the response and nothing else.
You need to set the value explicitly after the value props change. you can watch for value change. <template> <div contenteditable="true" @input="updateHTML" class="textareaRoot"></div></template><script>export default { // Custom textarea name: "htmlTextArea", props: ["value"], mounted: function() { this.$el.innerHTML = this.value; }, watch: { value(v) { this.$el.innerHTML = v; } }, methods: { updateHTML: function(e) { this.$emit("input", e.target.innerHTML); } }};</script>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/49809545', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3539592/']}
jdg_78110
stackexchange
llm_judgeable_groundtruth_similarity
24811770
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: i am trying to write to to a file. i read the whole content of the file and now i want to change the content of the file based on some word that i have got from the file. but when i check, the content of the file, it is still the same and it has not change. this is what i used if strings.Contains(string(read), sam) { fmt.Println("this file contain that word") temp := strings.ToUpper(sam) fmt.Println(temp) err := ioutil.WriteFile(fi.Name(), []byte(temp), 0644)} else { fmt.Println(" the word is not in the file")} Now provide the response and nothing else.
Considering that your call to ioutil.WriteFile() is consistent with what is used in " Go by Example: Writing Files ", this should work. But that Go by example article check the err just after the write call. You check the err outside the scope of your test: if matched { read, err := ioutil.ReadFile(path) //fmt.Println(string(read)) fmt.Println(" This is the name of the file", fi.Name()) if strings.Contains(string(read), sam) { fmt.Println("this file contain that word") Value := strings.ToUpper(sam) fmt.Println(Value) err = ioutil.WriteFile(fi.Name(), []byte(Value), 0644) } else { fmt.Println(" the word is not in the file") } check(err) <===== too late } The err you are testing is the one you got when reading the file ( ioutil.ReadFile ), because of blocks and scope . You need to check the error right after the Write call err = ioutil.WriteFile(fi.Name(), []byte(Value), 0644) check(err) <===== too late Since WriteFile overwrite the all file, you could strings.Replace() to replace your word by its upper case equivalent: r := string(read)r = strings.Replace(r, sam, strings.ToUpper(sam), -1)err := ioutil.WriteFile(fi.Name(), []byte(r), 0644) For a replace which is case insensitive , use a regexp as in " How do I do a case insensitive regular expression in Go? ". The, use func (*Regexp) ReplaceAllString : re := regexp.MustCompile("(?i)\\b"+sam+"\\b")r = re.ReplaceAllString(r, strings.ToUpper(sam))err := ioutil.WriteFile(fi.Name(), []byte(r), 0644) Note the \b : word boundary to find the any word starting and ending with sam content (instead of finding substrings containing sam content). If you want to replace substrings, simply drop the \b : re := regexp.MustCompile("(?i)"+sam)
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/24811770', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3841581/']}
jdg_78111
stackexchange
llm_judgeable_groundtruth_similarity
15081463
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have a document in a collection like this, I need to find the record with form_Id:1 and Function_Id:2, how to write the mongo query. "Form_Id" : 1,"Function" : [{ "Function_Id" : 1, "Role" : [{ "Role_Id" : 1, "UserId" : ["Admin", "001"] }]}, { "Function_Id" : 2, "Role" : [{ "Role_Id" : 2, "UserId" : ["Admin", "005"] }]}] Now provide the response and nothing else.
You can use dot notation and the $ positional projection operator to do this: db.test.find({Form_Id: 1, 'Function.Function_Id': 2}, {_id: 0, 'Function.$': 1}) returns: {"Function": [{"Function_Id": 2, "Role": [{"Role_Id": 2, "UserId": ["Admin", "005"]}]}]}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/15081463', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2071655/']}
jdg_78112
stackexchange
llm_judgeable_groundtruth_similarity
86590
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: It seems that $G_s$ need not be normal to have an isomorphism ($G_s$ and $O_s$the are stabilizer and orbit of a group action): $G/G_s \cong O_s$ First, is this accurate? Then I was wondering how this reconciles with the First Isomorphism Theorem where the divisor, as the kernel of the map, is normal. In the case of the group action, an element of $G_s$ seems to be an element of the kernel, since $g(s) = 1s$. But $g$ $G_s$ $g^-1$ is the stabilizer $G_t$, where $g(s) = t$? I can't imagine that I have not made several mistakes here, so I appreciate your patience as well as setting me straight. Thanks. Now provide the response and nothing else.
You cannot get the whole of the First Isomorphism Theorem from the Orbit-Stabilizer Theorem, because the latter ignores any structure that your set $S$ may carry, whereas the First Isomorphism Theorem very much cares about the structure of your set $H$. But you can do the following: given a homomorphism $f\colon G\to H$, you can make $H$ into a $G$-set by the rule $g\cdot h = f(g)h$. This defines an action, since $e\cdot h = f(e)h = h$, and $$(xy)\cdot h = f(xy)h = \bigl(f(x)f(y)\bigr)h = f(x)\bigl(f(y)h\bigr) = x\cdot(y\cdot h).$$ Now consider the identity $1\in H$. The orbit of $1$ is precisely the image of $f$; the stabilizer of $1$ is$$G_1 = \{g\in G\mid f(g)1 = 1\} = \{g\in G\mid f(g)=1\} = \mathrm{ker}(f).$$ So the Orbit-Stabilizer Theorem tells you there is a bijection between cosets $G/\mathrm{ker}(f)$ and $f(G)$ given by $g(\mathrm{ker}(f)) \mapsto f(g)$. However, the Orbit-Stabilizer Theorem does not tell you that this bijection respects the group structures on $G/\mathrm{ker}(f)$ and on $H$. You have to prove this explicitly. So the Orbit-Stabilizer Theorem only gives you the set-theoretic bijection, you still need to prove that it is a group isomorphism.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/86590', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
jdg_78113
stackexchange
llm_judgeable_groundtruth_similarity
45871971
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have created this drawable: <?xml version="1.0" encoding="utf-8"?><layer-list xmlns:android="http://schemas.android.com/apk/res/android" > <item > <rotate android:fromDegrees="45" android:toDegrees="10" android:pivotX="100%" android:pivotY="-0%" > <shape android:shape="rectangle" > <solid android:color="@color/color_primary" /> </shape> </rotate> </item></layer-list> On the preview it looks like this: And I have put it into this View : <View android:id="@+id/my_view" android:layout_width="32dp" android:layout_height="32dp" android:background="@drawable/triangle" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintTop_toTopOf="parent" /> And this View looks like this on the preview (and on the phone): Why doesn't the View just show the triangle on the corner like on the triangle preview? Also, I should mention that I want it to fill half of the View square, basically go from the the top right corner to the bottom left corner. Thanks. Edit: I was given a suggestion to use: <?xml version="1.0" encoding="utf-8"?><layer-list xmlns:android="http://schemas.android.com/apk/res/android" > <item > <rotate android:fromDegrees="45" android:toDegrees="-135" android:pivotX="90%" android:pivotY="-45%" > <shape android:shape="rectangle" > <solid android:color="@color/color_primary" /> </shape> </rotate> </item></layer-list> And that does produce a corner triangle but it doesn't fill half of the View square. This is what it does: Now provide the response and nothing else.
I would solve this by using a <vector> drawable instead of a <layer-list> . <vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="24dp" android:height="24dp" android:viewportWidth="24.0" android:viewportHeight="24.0"> <path android:fillColor="@color/color_primary" android:pathData="M0 24v-24h24z"/></vector>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/45871971', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/704836/']}
jdg_78114
stackexchange
llm_judgeable_groundtruth_similarity
17304013
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: When a Java program calls System.out.println() or a Scala program calls println() does the thread block? I'm writing a Scala program with a huge amount of subtasks. Each subtask is executed inside a Future. It is recommended that code inside actors and futures does not block, so that subsequent tasks don't have to wait, too. But I want to print very much on the console. And if it is a blocking operation: What can I do to optimize performance? Should I use a dedicated thread for console output, so that thread is the only one that blocks? Any other advices? Of course I could try to reduce the amount of output or collect some output in a StringBuilder and print it together in a batch, which reduces the number of output operations. Now provide the response and nothing else.
When a Java program calls System.out.println() or a Scala program calls println() does the thread block? Yes and no. System.out is a PrintStream which is a synchronized class. So multiple threads writing large amounts to System.out will block each other for sure. Once a thread gets the lock however, whether or not the IO will block the thread is architecture dependent. If you write a large amount of IO that overwhelms the capacity of the underlying hardware then the write will block. Also, making a lot of small writes (as opposed to buffered), will slow the thread as well. Should I use a dedicated thread for console output, so that thread is the only one that blocks? Excellent idea, yes. Then this thread could write through a single BufferedWriter or some sort of log4j or other logging package which would be a lot more performant compared to System.out . You will need to use something like a BlockingQueue to queue up the messages which is synchronous but the IO will never block this queue unless your are producing messages faster than the IO channel can persist them. Of course I could try to reduce the amount of output or collect some output in a StringBuilder and print it together in a batch, which reduces the number of output operations. The BufferedWriter will take care of this for you. Any other advices? As mentioned, use a better logging package or a single-threaded writer. Write logs to a different physical disk that has more IO bandwidth. Switch to a memory file-system or hardware to increase your IO bandwidth. SSD++. Send it via the network to another box to do the actual persisting off box. Use a GzipOutputStream to compress it on the fly.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17304013', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/573215/']}
jdg_78115
stackexchange
llm_judgeable_groundtruth_similarity
6481068
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm having a problem: I have a db connection where I run stored procedures on. This same connection is used to create said stored procedures earlier on. When I attempt to call a given stored procedure, later on, I get the following message: Could not find stored procedure 'dbo.yaf_prov_upgrade'. The problem is it actually does exist on the database. And there's also the fact that it shows up on the SQL Server Profiler. RPC:Completed exec [dbo].[yaf_prov_upgrade] @PreviousVersion=46,@NewVersion=46 .Net SqlClient Data Provider Nico Matrix\Nico I was wondering what could be the causes a particular query would throw such an exception even when it exists, it's called, and the call reaches the database. It can't be a problem with the connection because it already executed other stored procedures. It can't be a problem with the procedure because it does exist, in fact the very same application, the very same web page, created it and put it there. Update: forgot to mention I'm used integrated security, and I did run the SP on the database with the same user the application connects with, and I had no problem running it. So what can it be? Now provide the response and nothing else.
Your RPC completed only means that the batch submitted to SQL Server was correct and completed. It doesn't mean the stored procedure ran and executed OK. It will be (don't argue, check) one of: wrong permissions wrong database context wrong server stored proc is in a different database To ensure that things are the same SELECT @@SERVERNAME, SUSER_SNAME(), DB_NAME(), USER_NAME(), OBJECT_ID('dbo.yaf_prov_upgrade') The OBJECT_ID will be NULL if the stored proc doesn't exist in that database or you don't have permissions.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6481068', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/389745/']}
jdg_78116
stackexchange
llm_judgeable_groundtruth_similarity
233210
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have a C# class that represents a content type in a web content management system. We have a field that allows a web content editor to enter an HTML template for how the object is displayed. It basically uses the handlebars syntax for substituting object property values into the HTML string: <h1>{{Title}}</h1><p>{{Message}}</p> From a class design perspective, should I expose the formatted HTML string (with substitution) as a property or method ? Example as property: public class Example{ private string _template; public string Title { get; set; } public string Message { get; set; } public string Html { get { return this.ToHtml(); } protected set { } } public Example(Content content) { this.Title = content.GetValue("title") as string; this.Message = content.GetValue("message") as string; _template = content.GetValue("template") as string; } private string ToHtml() { // Perform substitution and return formatted string. } } Example as method: public class Example{ private string _template; public string Title { get; set; } public string Message { get; set; } public Example(Content content) { this.Title = content.GetValue("title") as string; this.Message = content.GetValue("message") as string; _template = content.GetValue("template") as string; } public string ToHtml() { // Perform substitution and return formatted string. } } I'm not sure from a design standpoint does it make a difference or are there reasons why one approach is better than the other? Now provide the response and nothing else.
UPDATE: This question was the subject of my blog in May 2014 . Thanks for the great question! To add to Robert Harvey's answer : a property should be: logically a property of the class, the way that say its color or year or model are the properties of a car. not more than, let's say, ten times slower to compute than fetching from a field. something you don't mind being computed while debugging. The VS debugger automatically computes properties. unable to fail. Getters should always return a value no matter what the state of the object is. I don't think your proposed Html property hits any of those. Don't make it a property unless it hits all of them.
{}
{'log_upvote_score': 6, 'links': ['https://softwareengineering.stackexchange.com/questions/233210', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/80895/']}
jdg_78117
stackexchange
llm_judgeable_groundtruth_similarity
10584502
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am using Node.js and a Redis Database . I am new to Redis . I am using the https://github.com/mranney/node_redis driver for node. Initialization code - var redis = require("redis"),client = redis.createClient(); I tried setting up some key value pairs - client.hset("users:123" ,"name", "Jack"); I wish to know I can get the name parameter from Redis via Node . I tried var name = client.hget("users:123", "name"); //returns 'true' but it just returns 'true' as the output. I want the value ( i.e - Jack ) What is the statement I need to use ? Now provide the response and nothing else.
This is how you should do it: client.hset("users:123", "name", "Jack");// returns the complete hashclient.hgetall("users:123", function (err, obj) { console.dir(obj);});// OR// just returns the name of the hashclient.hget("users:123", "name", function (err, obj) { console.dir(obj);}); Also make sure you understand the concept of callbacks and closures in JavaScript as well as the asynchronous nature of node.js. As you can see, you pass a function (callback or closure) to hget . This function gets called as soon as the redis client has retrieved the result from the server. The first argument will be an error object if an error occurred, otherwise the first argument will be null. The second argument will hold the results.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/10584502', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/609235/']}
jdg_78118
stackexchange
llm_judgeable_groundtruth_similarity
435514
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I had to prove the following for a trial calculus exam: $A\subset B$ if and only if $P(A) \subset P(B)$ where $P(A)$ is the set of all subsets of $A$. Can someone tell me if my approach is correct and please give the correct proof otherwise? $PROOF$: $\Big(\Longrightarrow\Big)$ assume $A\subset B$ is true. Then $\forall$ $a\in A$, $a\in B$ Then for $\forall$ A, the elements $a_1, a_2,$ ... , $a_n$ in A are also in B. Hence $P(A)\subset P(B)$ $\Big(\Longleftarrow\Big) $ assume $P(A) \subset P(B)$ is true. We prove this by contradiction so assume $A\not\subset B$ Then there is a set $A$ with an element $a$ in it, $a\notin$ B. Hence $P(A) \not\subset P(B)$ But we assumed $P(A) = P(B)$ is true. We reached a contradiction. Hence if $P(A) = P(B)$ then $A\subset B$. I proved it both sides now, please improve me if I did something wrong :-) Now provide the response and nothing else.
Neither direction seems to be valid. Here is the correct approach. $(\Rightarrow)$ Assume $A \subseteq B$. Then for any $C \in P(A)$, we have $C \subseteq A \subseteq B$. Hence, $C \in P(B)$. $(\Leftarrow)$ Assume $P(A) \subseteq P(B)$. Since $A \in P(A)$, $A \in P(B)$, meaning $A \subseteq B$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/435514', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/61493/']}
jdg_78119
stackexchange
llm_judgeable_groundtruth_similarity
21832364
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to load an Excel file from a certain source with PHPExcel. I have no control over how these Excel files are generated and they need to be opened automatically with PHPExcel without human interaction (re-saving the file, etc). I'm getting the following error: Fatal error: Uncaught exception 'Exception' with message 'Invalid character found in sheet title' in C:\path\to\PHPExcel\Worksheet.php on line 418 The error is occurring on the load() line, using the following code to open the file: $reader = PHPExcel_IOFactory::createReader('Excel5');$excel = $reader->load($filename_xls); The sheet title is irrelevant to us, so is it possible to just ignore it? Thus ignoring the error? Now provide the response and nothing else.
We've just done this to get it sorted for now. It's probably horribly bad and I wouldn't really advise other people doing it, but hey, it should work for us! On version 1.7.8 of PHPExcel, in /Classes/PHPExcel/Worksheet.php around line 414 - swap the checkSheetTitle() function for the following: private static function _checkSheetTitle($pValue){ // Some of the printable ASCII characters are invalid: * : / \ ? [ ] if (str_replace(self::$_invalidCharacters, '', $pValue) !== $pValue) { //throw new Exception('Invalid character found in sheet title'); //Hack to remove bad characters from sheet name instead of throwing an exception return str_replace(self::$_invalidCharacters, '', $pValue); } // Maximum 31 characters allowed for sheet title if (PHPExcel_Shared_String::CountCharacters($pValue) > 31) { throw new Exception('Maximum 31 characters allowed in sheet title.'); } return $pValue;}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/21832364', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/332807/']}
jdg_78120
stackexchange
llm_judgeable_groundtruth_similarity
22391548
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have two domain names for my Rails app: app.example.com, short.net. The longer domain is the standard domain and requires HTTPS, the shorter domain is a convenience domain for providing short URLs and requires HTTP. Currently I am forcing SSL: config.force_ssl = true But I really only want to force SSL for the longer domain name. How can I conditionally force SSL depending on domain name? The short domain name will redirect to the main domain name and then be forced to use SSL. This would avoid requiring a SSL certificate for the short domain name. Thoughts? Now provide the response and nothing else.
Add some configuration to your ApplicationController : class ApplicationController < ActionController::Base force_ssl if: :ssl_required? [...] private def ssl_required? request.host == 'app.example.com' endend Source: http://api.rubyonrails.org/classes/ActionController/ForceSSL/ClassMethods.html
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/22391548', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2274821/']}
jdg_78121
stackexchange
llm_judgeable_groundtruth_similarity
45267275
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: The job of an allocator is to obtain "raw" memory via its allocate method. What the caller constructs in the memory returned by the allocator is of no concern to the allocator (right?). So why is std::allocator a template when this only seems to add unnecessary complexity? What does the allocator actually do with that type information? Why does it have to know the type of object the memory is for? I'm assuming that there is some obvious reason that I'm missing, so what is that reason? Now provide the response and nothing else.
Well, std::allocator , and the Allocator concept itself, were invented to deal with issues like near- and far-pointers, or generally pointers to different address-spaces. And they deal with that ... adequately. The allocator determines the pointer-type used. They can also be used to deal with different memory-allocators, though the amount of boilerplate for that is somewhat staggering. And finally, an allocator-aware container can coupled with an allocator taking advantage of that provide a sub-allocator to child-elements, which might help reduce overhead. The first point is nowadays mostly obsolete, though it can be used with the second point to have a mapping-address-invariant container in a shared memory segment, or a file. The second point can be used for taking advantage of specialized allocators, though the interface is not really good for that. An example where I used it to hack me a secure std::basic_string . And the last point is rarely used. The one huge disadvantage of the Allocator concept as defined is the fact that it uses a template. All use already goes through std::allocator_traits<Allocator> , so it just leads to types inadvertently being almost the same, were there not the template-argument to the allocator. And also to much duplicated code to rebind the allocator appropriately.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/45267275', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/354633/']}
jdg_78122
stackexchange
llm_judgeable_groundtruth_similarity
74722
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: What should I consider when taking an application (web) from a few users to hundreds or thousands? Basically, what should I be considering when thinking about escalating? Now provide the response and nothing else.
In general, when we talk about scalability, it's more about going from few thousands to few millions or billions of requests. In such case, scalability requires an application to work on several servers, which has some very specific issues which scalability tends to solve. In your case on the other hand, it seems that you just has to face the increase of users, without being forced to use several servers instead of one (unless the current server is pretty slow, in which case the upgrade must be considered, or the website has an impact on the resources of the server, in which case the bottlenecks have to be found and removed). There are several points to consider in your case: Do you use cache enough? Don't forget that cache can be implemented on several levels, from caching database results to avoid doing the same queries again and again, to output caching to avoid using more CPU than needed, to client caching , to reduce the number of requests (for example avoiding the client to request the same CSS file again and again every time just to receive again and again the 304 response). Do you use SQL profiler? If not, it is a good idea to start using one to be sure that there are no repetitive queries , and to find what queries must be optimized . Do you use a profiler? Profiling your application may show where does it use too much memory or too much CPU. Working on those bottlenecks can strongly reduce the load . What is the weakest part of your server? If you see that RAM is used up to 20% while the CPU is used up to 95-99% all the time, you should probably upgrade your CPU, but don't need to buy more RAM. Do you use your server to the full extent? If you see that RAM is used up to 20%, why not implement more caching and use it up to 75 - 85%? If your application spends lots of time querying data from hard disk, why not buying a second hard disk and use it in RAID1 (if in your case, given your hardware and your disk usage, RAID1 can provide faster access)? How the server is used outside your web application? In other words, are there other processes which may use the resources, and if yes, do you need them and do you know what they're doing? It also applies to the scheduled processes. Running a backup at 3 A.M. when there are at most two-three users on your website is fine. Running the same backup at 6 P.M. when you observe a peak of visits on your website is clearly not a good idea .
{}
{'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/74722', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/2781/']}
jdg_78123
stackexchange
llm_judgeable_groundtruth_similarity
29963542
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I got some operations in my Controller class which could take some time. So I want to show a loading dialog while this operation is running. I tried this: Platform.runLater(new Runnable() { @Override public void run() { loadingDialog.show(); }});Boolean opSuccess = myService.operate();Platform.runLater(new Runnable() { @Override public void run() { loadingDialog.hide(); }});if (opSuccess) { // continue} Now, the Problem is, the loadingDialog is never show. The UI only blocks for some time and than continues on "//continue". So it seems, the runLater call is blocked by the blocking operation (operate)? I also tried CoundDownLatch, to wait for loadingDialog.show() to complete, before running myService.operate(). But the latch.await() method never completes. So my question is, how my I show the loadingDialog until myService.operate() finished and returned true or false? Do I have to put the operate() call into another thread and run it async or is there an easier way? Thanks for help. Now provide the response and nothing else.
Are you sure your entire code does not run in the JavaFX Thread?Methods of your controller class usually do and I assume it due to your description. However, better use the Task class. Here you'll find a tutorial and a short snippet for your application: // here runs the JavaFX thread// Boolean as generic parameter since you want to return itTask<Boolean> task = new Task<Boolean>() { @Override public Boolean call() { // do your operation in here return myService.operate(); }};task.setOnRunning((e) -> loadingDialog.show());task.setOnSucceeded((e) -> { loadingDialog.hide(); Boolean returnValue = task.get(); // process return value again in JavaFX thread});task.setOnFailed((e) -> { // eventual error handling by catching exceptions from task.get() });new Thread(task).start(); I assumed Java 8 and the possibility to use Lambda expressions. Of course it is possible without them.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/29963542', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1250213/']}
jdg_78124
stackexchange
llm_judgeable_groundtruth_similarity
3887970
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have the following insert stored procedure: CREATE Procedure dbo.APPL_ServerEnvironmentInsert( @ServerEnvironmentName varchar(50), @ServerEnvironmentDescription varchar(1000), @UserCreatedId uniqueidentifier, @ServerEnvironmentId uniqueidentifier OUTPUT)WITH RECOMPILEAS -- Stores the ServerEnvironmentId. DECLARE @APPL_ServerEnvironment TABLE (ServerEnvironmentId uniqueidentifier) -- If @ServerEnvironmentId was not supplied. IF (@ServerEnvironmentId IS NULL) BEGIN -- Insert the data into the table. INSERT INTO APPL_ServerEnvironment WITH(TABLOCKX) ( ServerEnvironmentName, ServerEnvironmentDescription, DateCreated, UserCreatedId ) OUTPUT Inserted.ServerEnvironmentId INTO @APPL_ServerEnvironment VALUES ( @ServerEnvironmentName, @ServerEnvironmentDescription, GETDATE(), @UserCreatedId ) -- Get the ServerEnvironmentId. SELECT @ServerEnvironmentId = ServerEnvironmentId FROM @APPL_ServerEnvironment END ELSE BEGIN -- Insert the data into the table. INSERT INTO APPL_ServerEnvironment WITH(TABLOCKX) ( ServerEnvironmentId, ServerEnvironmentName, ServerEnvironmentDescription, DateCreated, UserCreatedId ) VALUES ( @ServerEnvironmentId, @ServerEnvironmentName, @ServerEnvironmentDescription, GETDATE(), @UserCreatedId ) ENDGO I could have simplified the above as: CREATE Procedure dbo.APPL_ServerEnvironmentInsert( @ServerEnvironmentName varchar(50), @ServerEnvironmentDescription varchar(1000), @UserCreatedId uniqueidentifier, @ServerEnvironmentId uniqueidentifier OUTPUT)WITH RECOMPILEAS-- Ensure @ServerEnvironmentId IS NOT NULLSELECT ISNULL(@ServerEnvironmentId, newid())-- Insert the data into the table.INSERT INTO APPL_ServerEnvironment WITH(TABLOCKX)( ServerEnvironmentId, ServerEnvironmentName, ServerEnvironmentDescription, DateCreated, UserCreatedId)VALUES( @ServerEnvironmentId, @ServerEnvironmentName, @ServerEnvironmentDescription, GETDATE(), @UserCreatedId)GO But by doing so, i loose the performance improvements of the newsequentialid() over newid(). newsequentialid() can not be set in code as newid() , it can only be supplied as a default value on a table column level. Any ideas anyone on simplifying the original query, but utilising newsequentialid() ? Or, is the original query the most simplified solution in achieving this? Now provide the response and nothing else.
The lambdas are accessing i which is being held in closure so they are all referencing the same value (the value of i in youre parse function when the lambdas are called). A simpler reconstruction of the phenomenon is: >>> def do(x):... for i in range(x):... yield lambda: i... >>> delayed = list(do(3))>>> for d in delayed:... print d()... 222 You can see that the i 's in the lambdas are all bound to the value of i in the function do . They will return whatever value it currently has and python will keep that scope alive as long as any of the lambdas are alive to preserve the value for it. This is what's referred to as a closure. A simple but ugly work around is >>> def do(x):... for i in range(x):... yield lambda i=i: i... >>> delayed = list(do(3))>>> for d in delayed:... print d()... 012 This works because, in the loop, the current value of i is bound to the paramater i of the lambda. Alternatively (and maybe a little bit clearer) lambda r, x=i: (r, x) . The important part is that by making an assignment outside the body of the lambda (which is only executed later) you are binding a variable to the current value of i instead of the value that it takes at the end of the loop. This makes it so that the lambdas are not closed over i and can each have their own value. So all you need to do is change the line yield Request(link, callback=lambda r:self.parse2(r, i)) to yield Request(link, callback=lambda r, i=i:self.parse2(r, i)) and you're cherry.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3887970', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/441137/']}
jdg_78125
stackexchange
llm_judgeable_groundtruth_similarity
718363
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: For a $m \times n$ matrix $A$, what's the relationship of $A*A^T$ and $A^T*A$? The background of this question is that if we see the row of $A$ as observations and column as variables, $A*A^T$ is the covariance across variables, and $A^T*A$ are the covariance across observations. How is these two matrix related? Now provide the response and nothing else.
I don't know what you're looking for, but $\text{rank}\left(AA^T\right)=\text{rank}\left(A^TA\right)=\text{rank}\left(A\right)=\text{rank}\left(A^T\right),$ The matrices $AA^T$ and $A^TA$ share the same non-null eigenvalues (they also share multiplicities of these eigenvalues). Since both are symmetric matrices, they both produce an orthonormal basis of eigenvectors of $\mathbb R^m$ and $\mathbb R^n$, respectively for $AA^T$ and $A^TA$. In the notation of the SVD decomposition article on wikipedia ($A=U\Sigma V^T$). The orthonormal eigenvectors of $AA^T$written by columns in a matrix yield $U$, where as those of $A^TA$ yield $V$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/718363', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/83558/']}
jdg_78126
stackexchange
llm_judgeable_groundtruth_similarity
4103689
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am attempting to work through the problem below and am experiencing some difficulty in solving it, and moreover, in understanding it. I would appreciate any insights. Problem Use the fact that $\mathbb{R}$ is a countable union of open intervals to show that $\mathcal{B}_{\mathbb{R}}$ is generated by the collection of all open intervals. Confusions My naive belief is that this statement just follows from the definition of $\mathcal{B}_{\mathbb{R}}$ - "Let $E$ be a topological space, then the $\sigma$ -algebra generated by the collection of all open subsets of $E$ is called the Borel $\sigma$ -algebra on $E$ ; it is denoted $\mathcal{B}_{\mathbb{E}}$ " - as each open interval of $\mathbb{R}$ is an open subset of $\mathbb{R}$ . For this problem should I verify that for any open interval in $\mathcal{B}_{\mathbb{R}}$ , the complement of that interval is also in $\mathcal{B}_{\mathbb{R}}$ ? As you can see, I am somewhat lost. Attempt Following Assistance $\text{ }$ Let $\mathcal{C}$ be the collection of all open intervals of $\mathbb{R}$ . By definition, $\sigma \mathcal{C}$ is the smallest $\sigma$ -algebra containing $\mathcal{C}$ . Let $\mathcal{D}$ denote the collection of all open subsets of $\mathbb{R}$ . We know that $\mathcal{B}_{\mathbb{R}}$ is the smallest $\sigma$ -algebra containing $\mathcal{D}$ . $\text{ }$ To begin, consider any open interval in $\mathcal{C}$ . Every open interval of $\mathbb{R}$ is also an open subset of $\mathbb{R}$ , this open interval is contained in $\mathcal{D}$ , thus $\mathcal{C} \subseteq \mathcal{D}$ . $\text{ }$ Now consider any open subset in $\mathcal{D}$ . Since every open subset in $\mathcal{D}$ can we written as a countable union of open intervals of $\mathbb{R}$ and $\sigma \mathcal{C}$ is closed under countable unions of open intervals of $\mathbb{R}$ , we have that $\mathcal{D} \subseteq \sigma \mathcal{C}$ . $\text{ }$ Since $\mathcal{C} \subseteq \mathcal{D} \subseteq \sigma \mathcal{C}$ , we have that $\sigma \mathcal{C} = \mathcal{B}_{\mathbb{R}}$ , i.e. $\mathcal{B}_{\mathbb{R}}$ is generated by all open intervals. Now provide the response and nothing else.
Well, you seem to know how to telescope summing: $$\frac1{k(k-1)} = \frac1{k-1} - \frac1k$$ Similarly, note $$\frac1{(k-2)^2(k+2)^2} = \frac1{8k}\left(\frac1{(k-2)^2}- \frac1{(k+2)^2}\right)$$ $$\implies \frac1{(k-2)^2(k-1)^2k(k+1)^2(k+2)^2} = \frac1{8(k-1)^2k^2(k+1)^2}\left(\frac1{(k-2)^2}- \frac1{(k+2)^2}\right)$$ which can be noted to telescope, hence the sum is $\dfrac1{8\cdot 2^2\cdot3^2\cdot4^2}\cdot\dfrac1{1^2}=\dfrac1{4608}$ .
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4103689', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/719288/']}
jdg_78127
stackexchange
llm_judgeable_groundtruth_similarity
11092877
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm presenting a problem my professor showed in class, with my O(n*log(n)) solution: Given a list of n numbers we'd like to perform the following n-1 times: Extract the two minimal elements x,y from the list and present them Create a new number z , where z = x+y Put z back into the list Suggest a data structure and algorithm for O(n*log(n)) , and O(n) Solution: We'll use a minimal heap: Creating the heap one time only would take O(n). After that, extracting the two minimal elements would take O(log(n)). Placing z into the heap would take O(log(n)). Performing the above n-1 times would take O(n*log(n)), since: O(n)+O(n∙(logn+logn ))=O(n)+O(n∙logn )=O(n∙logn ) But how can I do it in O(n)? EDIT: By saying: "extract the two minimal elements x,y from the list and present them ", I mean printf("%d,%d" , x,y) , where x and y are the smallest elements in the current list. Now provide the response and nothing else.
This is not a full answer. But if the list was sorted, then your problem is easiy doable in O(n) . To do it, arrange all of the numbers in a linked list. Maintain a pointer to a head, and somewhere in the middle. At each step, take the top two elements off of the head, print them, advance the middle pointer until it is where the sum should go, and insert the sum. The starting pointer will move close to 2n times and the middle pointer will move about n times, with n inserts. All of those operations are O(1) so the sum total is O(n) . In general you cannot sort in time O(n) , but there are a number of special cases in which you can. So in some cases it is doable. The general case is, of course, not solvable in time O(n) . Why not? Because given your output, in time O(n) you can run through the output of the program, build up the list of pairwise sums in order as you go, and filter them out of the output. What is left is the elements of the original list in sorted order. This would give a O(n) general sorting algorithm. Update: I was asked to show how could you go from the output (10, 11), (12, 13), (14, 15), (21, 25), (29, 46) to the input list? The trick is that you always keep everything in order then you know how to look. With positive integers, the next upcoming sum to use will always be at the start of that list. Step 0: Start input_list: (empty) upcoming sums: (empty)Step 1: Grab output (10, 11) input_list: 10, 11 upcoming_sums: 21Step 2: Grab output (12, 13) input_list: 10, 11, 12, 13 upcoming_sums: 21, 25Step 3: Grab output (14, 15) input_list: 10, 11, 12, 13, 14, 15 upcoming_sums: 21, 25, 29Step 4: Grab output (21, 25) input_list: 10, 11, 12, 13, 14, 15 upcoming_sum: 29, 46Step 5: Grab output (29, 46) input_list: 10, 11, 12, 13, 14, 15 upcoming_sum: 75
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11092877', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/779111/']}
jdg_78128
stackexchange
llm_judgeable_groundtruth_similarity
26190689
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am trying create and write to a text file in a C# application using the following code System.IO.Directory.CreateDirectory(Server.MapPath("~\\count"));using (System.IO.FileStream fs = new System.IO.FileStream("~/count/count.txt", System.IO.FileMode.Create))using (System.IO.StreamWriter sw = new System.IO.StreamWriter("~/count/count.txt")){ sw.Write("101");}string _count = System.IO.File.ReadAllText("~/count/count.txt");Application["NoOfVisitors"] = _count; but I get an error: The process cannot access the file 'path' because it is being used by another process. What is my error? Now provide the response and nothing else.
You're trying to open the file twice; your first using statements creates a FileStream that is not used, but locks the file, so the second using fails. Just delete your first using line, and it should all work fine. However, I'd recommend replacing all of that with File.WriteAllText , then there would be no using in your code, it'd be much simpler. var dir = Server.MapPath("~\\count");var file = Path.Combine(dir, "count.txt");Directory.CreateDirectory(dir);File.WriteAllText(file, "101");var _count = File.ReadAllText(file);Application["NoOfVisitors"] = _count;
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/26190689', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3852732/']}
jdg_78129
stackexchange
llm_judgeable_groundtruth_similarity
125232
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have a vps server with 130GB hard disk. Recently, the server is crash down, I access ssh and use dh -h , Filesystem Size Used Avail Use% Mounted on/dev/vzfs 130G 130G 0 99% /none 2.0G 4.0K 2.0G 1% /dev Then use du -sh /* I find root fold with 59GB. then du -sh /root/* , a long list with some file like ...43M /root/core.785659M /root/core.785959M /root/core.786243M /root/core.788343M /root/core.788543M /root/core.788959M /root/core.789259M /root/core.790443M /root/core.790659M /root/core.791343M /root/core.791559M /root/core.794059M /root/core.794243M /root/core.794743M /root/core.7951... I access my server with fileZilla , 1204 core.* files create in recent 3 days. So what is centos /root/core.* files? How are they created? Could I delete them without damage my server? And how to avoid them to be created again? FIX THE PROBLEM The problem caused by linux mail system. I changed /etc/mail/trusted-users permission in etc/mail/submit.cf line 552. then, no /root/core.* files be created again. Now provide the response and nothing else.
These are so-called core dumps . Some signals' default handler besides killing the receiver of the signal is writing out the memory contents and process state at the time of death for post-mortem analysis. Unless you're planning to dissect those files you can safely remove them. You could also inhibit the creation of core dumps by setting the appropriate resource limit to 0 (this is done by setting the core item in /etc/security/limits.conf to 0 ). You should note that the fact that your system creates those files rather rapidly should alarm you that there's something not going too well because some process regularly dies in a non-intended way. This could be caused by a buggy (automatically respawning) program or be caused by more serious problems like memory defect. You might want to look into your log files and dmesg output to get a hold on that.
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/125232', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/48597/']}
jdg_78130
stackexchange
llm_judgeable_groundtruth_similarity
6829
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Why can one bend glass fibers without breaking it, whereas glasses one comes across in real life is usually solid? Is there also a good high-school level explanation of this? Now provide the response and nothing else.
In addition to the question of bend radius - there is also an effect of surface scratches. Most materials are very strong - they fail because a surface flaw allows a stress concentration - ie a crack to form. glass fibre has a very smooth surface because of the way it is made and can be put under high stress without cracking. You can show this with a thick glass rod (or you could before we were banned from doing anything interesting by 'safety'). Clean the surface with acid, or heating and annealing, so any defects are removed you can then bend the rod like rubber. But touch the bent part with a metal ruler to create scratches and it will shatter
{}
{'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/6829', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/667/']}
jdg_78131
stackexchange
llm_judgeable_groundtruth_similarity
4116252
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to prove (or disprove) the following: $$ \sum_{i=1}^{N} \sum_{j=1}^{N} c_i c_j K_{ij} \geq 0$$ where $c \in \mathbb{R}^N$ , and $K_{ij}$ is referring to a kernel matrix : $$K_{ij} = K(x_i,x_j) = \frac{\sum_{k=1}^{N} \min(x_{ik}, x_{jk})}{\sum_{k=1}^{N} \max(x_{ik}, x_{jk})}$$ Here, $x \in \mathbb{R}^N \geq 0$ . I'm basically trying to prove that $K_{ij}$ is a positive definite matrix, so I can use it as a Kernel, but I'm really stuck trying to work with $\max$ Edit: the function I'm refering to is: $$K(u,v) = \frac{\sum_{k=1}^{N} \min(u_{k}, v_{k})}{\sum_{k=1}^{N} \max(u_{k}, v_{k})}$$ where $u, v \in \mathbb{R}^N \geq 0$ Now provide the response and nothing else.
Fix $x_i\in\mathbb{R}^n$ , $i = 1, 2, \ldots, N$ . We will assume without loss of generality that no $x_i$ is identically $0$ . Define $N\times N$ matrices $A = (\sum_{k=1}^n\min(x_{i(k)}, x_{j(k)}))$ and $B = (\sum_{k=1}^n\max(x_{i(k)}, x_{j(k)}))$ , where $x_{(k)}$ denotes the $k$ th coordinate of $x$ . Note that $K = A\odot B^{\odot-1}$ where $\odot$ denotes the Hadamard product and $B^{\odot-1}$ is the Hadamard inverse (entrywise reciprocal) of $B$ . By the Schur product theorem, it suffices to show that $A$ and $B^{\odot-1}$ are positive definite. We will use the fact that a positive linear combination of positive definite matrices is positive definite. To show that $A$ is positive definite, note that $A$ can be written as the sum $A = \sum_{k=1}^n A_k$ with $A_k = \min(x_{i(k)}, x_{j(k)})$ . It suffices to show that e.g. $A_1$ is positive definite. For $i \in [N]$ , let $y_i = x_{i(1)}$ . By conjugating $A_1$ by a permutation matrix, we may assume without loss that $y_1\leq y_2\ldots \leq y_N$ . For $i \in [N]$ , let $f_i\in\mathbb{R}^N$ denote the vector with $f_{i(j)} = 0$ for $j < i$ and $f_{i(j)} = 1$ for $j \geq i$ . Then, setting $y_0 = 0$ , \begin{equation}A_1 = \sum_{i=1}^N(y_i - y_{i-1})f_if_i^t \geq 0.\end{equation} We now show that $B^{\odot-1}$ is positive definite. By scaling, we may assume that $x_{i(j)} \in [0, 1/n]$ for all $i$ and $j$ . Using the identity $1/x = \sum_{i=0}^{\infty}(1-x)^i$ valid for $x\in (0, 2)$ , we may write $B^{\odot-1} = J + \sum_{i=1}^{\infty} (J-B)^{\odot i}$ , where $J=f_1f_1^t$ denotes the all ones matrix. Now \begin{equation}(J-B)_{ij} = 1 - \sum_{k=1}^n\max(x_{i(k)}, x_{j(k)}) = \sum_{k=1}^n \min(\frac{1}{n}-x_{i(k)}, \frac{1}{n}-x_{j(k)}).\end{equation} The above argument that showed that $A$ is positive definite now shows that $J-B$ is positive definite (by replacing $x_i$ with $x_i' = \frac{1}{n}f_1 - x_i$ ). Finally, the Schur product theorem and the fact that positive definite matrices are closed under positive linear combinations show that $B^{\odot-1}$ is positive definite.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4116252', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/917150/']}
jdg_78132
stackexchange
llm_judgeable_groundtruth_similarity
19121695
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have a shiny application consisting of three files. server.R, ui.R and the file to launch the application with require(shiny)require(rCharts)runApp("shinyApp") The application starts, but the plot is not visible. It works with a normal r-plot and with polycharts, but after trying a lot, I still have no success with rCharts (which includes rHighcharts). This is the files of the last try: server.R: library(rCharts)shinyServer(function(input, output) { output$myChart <- renderChart({ h1 <- Highcharts$new() h1$chart(type = "spline") h1$series(data = c(1, 3, 2, 4, 5), dashStyle = "longdash") h1$series(data = c(NA, 4, 1, 3, 4), dashStyle = "shortdot") h1$legend(symbolWidth = 80) return(h1) })}) ui.R: require(rCharts)shinyUI(pageWithSidebar( headerPanel("rCharts: Highcharts"), sidebarPanel( selectInput(inputId = "x", label = "Choose X", choices = c('SepalLength', 'SepalWidth', 'PetalLength', 'PetalWidth'), selected = "SepalLength") ), mainPanel(showOutput("myChart", "Highcharts") ))) My assumption is that the second argument of "showOutput" might be wrong, but I didn't find anything. Now provide the response and nothing else.
There are two ways to get this working. The first way is to add h1$set(dom = "myChart") in your server.R . This is required so that both server.R and ui.R are communicating about the correct chart. The alternative is to use renderChart2 , which is in the dev branch of rCharts , that is a upgraded version of renderChart and will eventually replace it. I am attaching the entire code for everyone's benefit. require(rCharts)require(shiny)runApp(list( ui = pageWithSidebar( headerPanel("rCharts: Highcharts"), sidebarPanel(selectInput( inputId = "x", label = "Choose X", choices = c('SepalLength', 'SepalWidth', 'PetalLength', 'PetalWidth'), selected = "SepalLength" )), mainPanel(showOutput("myChart", "Highcharts")) ), server = function(input, output){ output$myChart <- renderChart2({ h1 <- Highcharts$new() h1$chart(type = "spline") h1$series(data = c(1, 3, 2, 4, 5), dashStyle = "longdash") h1$series(data = c(NA, 4, 1, 3, 4), dashStyle = "shortdot") h1$legend(symbolWidth = 80) return(h1) }) }))
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19121695', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1542011/']}
jdg_78133
stackexchange
llm_judgeable_groundtruth_similarity
4210138
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: The View() method can load Partial Views. Is the difference between View() and PartialView() is that View() can load views and partial views and PartialView() can only load partial views? Now provide the response and nothing else.
It's up to a view engine to decide if they want to treat partial views different from regular views. For example, in the WebFormViewEngine there is no difference. In the new ASP.NET MVC 3 RazorViewEngine there are some differences. Only regular views will have the "_viewstart.cshtml" pages run because they are meant for things such as setting up layout pages.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4210138', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/89605/']}
jdg_78134
stackexchange
llm_judgeable_groundtruth_similarity
212265
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: We use in Dirac formalism of QM the tool of operators and kets in spatial and spin spaces to obtain eigenvalues and eigenkets. But the operation here is simply that of a matrix multiplication. Now the question is that why is the emphasis on saying an "operator" instead of simply a matrix. Are there examples in which we cannot have a matrix representation? Or it is because of some abstract algebra involving group theory and "operations" or mapping on vectors? Put the question another way, for someone unfamiliar with group theory, is it reasonable to replace the object of an operator with a matrix in a textbook without losing much in Dirac formalism of QM theory? Now provide the response and nothing else.
Now the question is that why is the emphasis on saying an "operator" instead of simply a matrix. A matrix is a representation of an operator expressed in a particular basis.Consider the operation $T$ which mirrors the 2D plane about the line $x=y$.If we construct the obvious basis vectors $\hat{x}$ and $\hat{y}$, then $T$ is represented as$$[T]_{xy} =\left[ \begin{array}{cc}0 & 1 \\ 1 & 0\end{array}\right]$$where $[\cdot]_{xy}$ means "representation in the $\hat{x}\hat{y}$ basis.To see that this is true, consider the action of $T$ on $\hat{x}$.Flipping $\hat{x}$ about the line $y=x$ gives $\hat{y}$.Since $\hat{x}$ is represented as$$[x]_{xy} = \left[ \begin{array}{c} 1 \\ 0 \end{array} \right]$$we get$$[T]_{xy} [x]_{xy} =\left[ \begin{array}{cc} 0 & 1 \\ 1 & 0 \end{array}\right]\left[ \begin{array}{c} 1 \\ 0 \end{array}\right]= \left[ \begin{array}{c} 0 \\ 1 \end{array}\right]= [y]_{xy} \, .$$You can check that the case for $T$ acting on $\hat{y}$ works too.Now suppose we use a different basis .Define$$ \hat{p} \equiv \frac{1}{\sqrt{2}} \left( \hat{x} + \hat{y} \right)\quad \text{and} \quad\hat{q} \equiv \frac{1}{\sqrt{2}} \left( \hat{x} - \hat{y} \right) \, .$$Now you can pretty clearly envision that $T\hat{p} = \hat{p}$ and $T\hat{q} = - \hat{q}$.Therefore, the matrix for $T$ in the $\hat{p}\hat{q}$ basis is$$[T]_{pq} = \left[ \begin{array}{cc} 1 & 0 \\ 0 & -1 \end{array} \right] \, .$$This is a different matrix from the one we had in the $\hat{x}\hat{y}$ basis.$^{[a]}$ The emphasis on "operator" is supposed to remind you that the thing you're dealing with is more general than any one possible matrix representation.Keeping this in mind and using notation which brings that out is extremely helpful in understanding how to solve lots of problems. Are there examples in which we cannot have a matrix representation? Yes.A very simple example is the derivative.First, note that functions are vectors; they satisfy all properties of a vector space: Adding two functions gives another function. Multiplication of a function by a scalar gives another function. There is a zero function, which when added to another function $r$ yields $f$. Since functions are vectors you might expect that we can construct linear operators on the set of functions.The derivative is a linear operator because $D_x(f + g) = D_x f + D_x g$ where here $D_x$ means the derivative with respect to $x$.Thus $D_x$ is a linear operator.However, it's not always possible to write it as a matrix, and it's never possible to write it as a finite dimensional matrix. Put the question another way, for someone unfamiliar with group theory, is it reasonable to replace the object of an operator with a matrix in a textbook without losing much in Dirac formalism of QM theory? No!It's important to keep the Dirac notation.Any matrix representation is just one possible representation.It's often much easier to solve problems without going to a particular basis until the end of the calculation. $[a]$: Note that $[T]_{pq}$ is diagonal. I did that on purpose. If you pick your basis vectors right you can often find a basis in which the matrix representation of an operator is diagonal. A lot of physics problems ranging from coupled oscillators to expansions of electric potential, to solutions to Schrodinger's equation rely heavily on diagonalizing an operator. The physical states represented by the vectors which make up the diagonalizing basis are called "normal modes".
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/212265', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/-1/']}
jdg_78135
stackexchange
llm_judgeable_groundtruth_similarity
9608534
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I just converted my app to ARC , and while it builds fine, I get like 600 warnings, all pertaining to my properties. Such as: Default property attribute 'assign' not appropriate for non-gc object No 'assign', 'retain' or 'copy' attribute is specified - 'assign' is assumed After Xcode converted my code, here is what my properties look like: @property (nonatomic) EKEventStore *eventStore;@property (nonatomic) EKCalendar *defaultCalendar;@property (nonatomic) UIActionSheet *currentActionSheet;@property (nonatomic) UILabel *noEventLabel; Someone talked about needing to add strong to all of these. Is this the case? Did Xcode forget to add something? Now provide the response and nothing else.
ARC is right. You cannot have no memory-management qualifer; you must say assign, retain (or strong which is the same thing), or weak. Previously, assign was the default. But that is probably not what you want, because is it is the worst possible option - it is an old-style non-ARC weak reference. You either want a smart ARC weak reference (goes to nil when the object goes out of existence) or a strong reference (memory-managed for you by ARC).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9608534', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/144695/']}
jdg_78136
stackexchange
llm_judgeable_groundtruth_similarity
1643
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: How do Intrusion Detection Systems (IDS) work? As I understand it, they monitor network traffic but what exactly do they look for? How can they tell apart regular activity from intrusions? Now provide the response and nothing else.
You typically have two kinds of IDS, network-based and host-based, and these can be signature or statistical response types. Signature IDS's are simple, fast, and can be updated easily. Usually vendors supply signature files - similar to the way anti-virus vendors supply virus signatures. For this reason most IDS's use signature recognition. The downside is that they will not identify a new attack unless it has a signature which matches an existing attack. Statistical or heuristic IDS's learn what 'good' or normal traffic looks like and alert on anything which isn't normal. This does mean they are much better at spotting new attacks, but does require learning periods when initially installed and regularly on the implementation of new servers, services and when any new traffic types or volumes are expected. Network based IDS's are usually implemented at the perimeter of an organisation, and they have visibility of all traffic entering (and sometimes exiting) the organisation. Where traffic has indications that it may be malicious it is logged or flagged to a response system or person. For a large organisation, the amount of different valid traffic types can be very high, and the traffic types can vary over time so the ongoing configuration and tuning of a perimeter network based IDS can take a lot of resource. For this reason, the majority of large companies outsource this to vendors who provide the service to many organisations. These vendors have better visibility of attacks happening, a scale advantage on tuning and response, and the ability to update signatures for all their clients at once. Host based IDS's are more usually implemented in-house for specific high-value servers. The traffic types and load are usually much lower and more predictable so the resource requirement is usually lower. Also have a look at this question - some discussion on anomaly based (statistical) IDS.
{}
{'log_upvote_score': 5, 'links': ['https://security.stackexchange.com/questions/1643', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/45/']}
jdg_78137
stackexchange
llm_judgeable_groundtruth_similarity
508045
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: If the sum and the product of two sequences converges to zero, does that mean that each sequence converges to zero ? Thanks Now provide the response and nothing else.
(Fill in the details.) Prove that if $|a_n + b_n | \leq \epsilon$ and $|a_n b_n | \leq \epsilon^2$, then $|a_n - b_n| \leq \sqrt{5} \epsilon$. Use the fact that $(a_n - b_n)^2 = (a_n+b_n)^2 - 4 a_n b_n$. Hence conclude that $|a_n| \leq \frac{1 + \sqrt{5} }{2} \epsilon$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/508045', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/97484/']}
jdg_78138
stackexchange
llm_judgeable_groundtruth_similarity
8722407
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I want to call a method of an abstract class in my own class. The abstract class is: public abstract class Call { public Connection getEarliestConnection() { Connection earliest = null; ... return earliest; } } I want to call the above method, and the calling class is: public class MyActivity extends Activity { Connection c = new Connection(); private void getCallFailedString(Call cal) { c = cal.getEarliestConnection(); if (c == null) { System.out.println("** no connection**"); } else { System.out.println("** connection"); } }} Whenever I try to run the above class, it throws a NullPointerException on the line c = cal.getEarliestConnection() . Can anyone tell me how to resolve this problem? Now provide the response and nothing else.
Firstly, Call an abstract class, therefore you cannot instantiate it directly. You must create a subclass, say MyCall extends Call which overrides any abstract methods in Call. Getting a NullPointerException means that whatever you are passing in as an argument to getCallFailedString() hasn't been initialized. So after you create your subclass of Call, you'd have to instantiate it and then pass this in to your method, so something like: class MyCall extends Call { //override any abstract methods here... } Wherever you are calling getCallFailedString() would then require something above it like: Call cal = new MyCall();Activity activity = new MyActivity();activity.getCallFailedString(cal);
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8722407', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1093242/']}
jdg_78139
stackexchange
llm_judgeable_groundtruth_similarity
5523031
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: What is different between this two variable definitions? object oVar;dynamic dVar; Performance? Memory allocation? Benefits? Now provide the response and nothing else.
One variable is typed as object by the compiler and all instance members will be verified as valid by the compiler. The other variable is typed as dynamic and all instance members will be ignored by the compiler and called by the DLR at execution time. It has nothing to do with either performance or memory allocation. The dynamic type is a static type that the compiler somewhat ignores. It gives you the ability to use duck typing in a statically typed language which provides a lot of flexibility (especially when dealing with components written in languages that are more dynamic). I would definitely recommend that you read up on the following topics: dynamic (C# Reference) Using Type dynamic (C# Programming Guide) Dynamic Language Runtime Overview
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5523031', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/678877/']}
jdg_78140