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
63413728
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 attribute can be used to allow unique values,we used [PXUniqueCheck(typeof(Name))]But if List view is used and records are updated with same name, it allows the same name values More Details -HI, Column is marked with IsKey = True for Name, My View is ListView, with 2 fields Name and Description where Name has IsKey =True and another column ID has DBIdentity Attribute. SO i think there is everything OK with the DAC, UI Add Behavior - when existing value is added then it updates the old row with newly added value description as Name is Same. Update Behavior - Change name column to the same value as of other then it allows to have 2 rows with same Key, but both rows shows the same description on UI, but in DB there are 2 rows with same Name value and different Description DAC - [System.SerializableAttribute()][PXPrimaryGraph(typeof(TestCategoryMaint))]public class TestCategory : PX.Data.IBqlTable{ #region TestCategoryID public abstract class testCategoryID : PX.Data.BQL.BqlInt.Field<testCategoryID>{ } protected int? _TestCategoryID; [PXDBIdentity()] [LicenseExpiration][PXReferentialIntegrityCheck]public virtual int? TestCategoryID { get { return this._TestCategoryID; } set { this._TestCategoryID = value; } } #endregion #region Name public abstract class name : PX.Data.IBqlField { } protected string _Name; [PXDBString(50, IsKey = true, IsUnicode = true, InputMask = "")] [PXDefault()] [PXUIField(DisplayName = "Test Category")] [PXCheckUnique(typeof(name))] public virtual string Name { get { return this._Name; } set { this._Name = value; } } #endregion #region Description public abstract class description : PX.Data.IBqlField { } protected string _Description; [PXDBString(255,IsUnicode =true)] [PXUIField(DisplayName = "Description")] public virtual string Description { get { return this._Description; } set { this._Description = value; } }#endregion Now provide the response and nothing else.
I was having this exact problem. After some debugging I saw that my URL was being created incorrectly. My code was nearly identical to yours. Where I found the culprit was the following line: var url_base = theSpreadSheet.getUrl().replace(/edit$/,''); This was not actually clearing out the 'edit' to the end of the line like it had for years. I cannot say why this is, but the proof was in the logs. So, instead I crafted the url by hand: var url = 'https://docs.google.com/spreadsheets/d/'+SpreadsheetApp.getActiveSpreadsheet().getId()+'/'; This seemed to solve the problem. This is not a perfect futureproof resolution, because if Google changes how the URLs are crafted, this will fail. But it works for now. I hope this helps. You can send the url your code is creating to logs and check them to see if you have the same issue I did.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/63413728', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9235411/']}
jdg_370541
stackexchange
llm_judgeable_groundtruth_similarity
20098
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'm trying to understand the policy gradient approach for solving the cartpole problem.In this approach, we're expressing the gradient of the loss w.r.t each parameter of our policy as an expectation of the sum of gradients of our policy gradient for all actions in a sequence, weighted by the sum of discounted rewards in that sequence: $$\nabla_\theta L(\theta) = E[ G(S_{0:T}, A_{0:T})\sum_{t=0}^{T}\nabla_\theta log\pi_\theta (A_t|S_t) ]$$ and we estimate it using an empirical average across all samples in an episode - which makes sense intuitively. BUT the less intuitive part is that I saw a common practice to normalize advantages in between episodes in several implementations (and indeed it works better). So after they calculate the they wouldn't directly use the advantage, but rather would normalize it, e.g. here they do after every episode: discounted_epr = discount_rewards(epr)discounted_epr -= np.mean(discounted_epr)discounted_epr /= np.std(discounted_epr) what's the justification for that - both in theory and in intuition? It seems to me that if an episode is long and as such has large advantages, it's worth learning more from that episode than from a 3 moves episode. What am I missing? Now provide the response and nothing else.
In general we prefer to normalize the returns for stability purposes. If you work out the backpropagation equations you will see that the return affects the gradients. Thus, we would like to keep its values in a specific convenient range. We don't follow this practice for theoretical guarantees but for practical reasons. The same goes with clipping $Q$ value functions in Q-learning combined with NNs. Of course, there are some drawbacks with these approaches but in general the algorithm behaves better as the backpropagation does not lead your network weights to extreme values. Please take a look at this excellent post by Andrej Karpathy (I attach the part related to your question as a blockquote) which gives additional insights: More general advantage functions. I also promised a bit more discussion of the returns. So far we have judged the goodness of every individual action based on whether or not we win the game. In a more general RL setting we would receive some reward $r_t$ at every time step. One common choice is to use a discounted reward, so the “eventual reward” in the diagram above would become $R_t=∑^∞_{k=0}γ^kr_{t+k}$, where $\gamma$ is a number between 0 and 1 called a discount factor (e.g. 0.99). The expression states that the strength with which we encourage a sampled action is the weighted sum of all rewards afterwards, but later rewards are exponentially less important. In practice it can can also be important to normalize these. For example, suppose we compute $R_t$ for all of the 20,000 actions in the batch of 100 Pong game rollouts above. One good idea is to “standardize” these returns (e.g. subtract mean, divide by standard deviation) before we plug them into backprop. This way we’re always encouraging and discouraging roughly half of the performed actions. Mathematically you can also interpret these tricks as a way of controlling the variance of the policy gradient estimator. A more in-depth exploration can be found here.
{}
{'log_upvote_score': 4, 'links': ['https://datascience.stackexchange.com/questions/20098', 'https://datascience.stackexchange.com', 'https://datascience.stackexchange.com/users/16050/']}
jdg_370542
stackexchange
llm_judgeable_groundtruth_similarity
39277638
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 know that in numpy I can compute the element-wise minimum of two vectors with numpy.minimum(v1, v2) What if I have a list of vectors of equal dimension, V = [v1, v2, v3, v4] (but a list, not an array)? Taking numpy.minimum(*V) doesn't work. What's the preferred thing to do instead? Now provide the response and nothing else.
*V works if V has only 2 arrays. np.minimum is a ufunc and takes 2 arguments. As a ufunc it has a .reduce method, so it can apply repeated to a list inputs. In [321]: np.minimum.reduce([np.arange(3), np.arange(2,-1,-1), np.ones((3,))])Out[321]: array([ 0., 1., 0.]) I suspect the np.min approach is faster, but that could depend on the array and list size. In [323]: np.array([np.arange(3), np.arange(2,-1,-1), np.ones((3,))]).min(axis=0)Out[323]: array([ 0., 1., 0.]) The ufunc also has an accumulate which can show us the results of each stage of the reduction. Here's it's not to interesting, but I could tweak the inputs to change that. In [325]: np.minimum.accumulate([np.arange(3), np.arange(2,-1,-1), np.ones((3,))]) ...: Out[325]: array([[ 0., 1., 2.], [ 0., 1., 0.], [ 0., 1., 0.]])
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/39277638', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2829764/']}
jdg_370543
stackexchange
llm_judgeable_groundtruth_similarity
1652126
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: NOTE: I know there are many questions that talked about that but I'm still a beginner and I couldn't understand the examples. I got a function prototype that goes like this: int someFunction(const char * sm); Here, as you know, const char* means that this function can accept const or non-const pointer-to-char. I tried something like that in the function body: someMemberVar = sm; someMemberVar is just a pointer-to-char. The compiler gives me an error telling me:cannot convert from const char* to char*. Here, I didn't pass a constant, so either sm or someMemberVar aren't constants. So, what constant the compiler is talking about? Now provide the response and nothing else.
I'll try to put in simpler terms what others are saying: The function someFunction takes a read-only string (for simplicity's sake, though char * could be used in umpteen other cases). Whether you pass in a readonly string to someFunction or not, the parameter is treated as read-only by the code executing in the context of this function. Within this function therefore, the compiler will try to prevent you from writing to this string as much as possible. A non-const pointer is such an attempt to disregard the read-only tag to the string and the compiler, rightly and loudly informs you of such disregard for its type system ;) What's the difference between: int someFunction(const char * sm) const{...} and this: int someFunction(const char * sm){...} The first is a function which takes a readonly parameter. The second const written after the closing parentheses is valid only for member functions. It not only takes a read-only parameter, but also gurantees to not alter the state of the object. This is typically referred to as design level const.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1652126', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/61250/']}
jdg_370544
stackexchange
llm_judgeable_groundtruth_similarity
74343
Below is a question asked on the forum dsp.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: The bandwidth of human hearing by empirical data is $20 \; Hz$ to $20 \; kHz$ . A cochlear implant stimulates the auditory or acoustic or Cochlear nerve directly so that the hearing can be improved in the case of stimulation mechanism upstream of the Cochlear nerve has degraded. Let us assume that the ear mechanism has not degraded (such as in a young and healthy adult). The Cochlear implant can likely improve hearing, even in this case, by increasing the bandwidth by amplifying the effect of the ear drum vibration (sensor actuation). However the neurons connecting the Cochlear nerve to the hearing region of the brain have an upper limit on the sampling rate on the order of $1 \; kHz$ . Does the the Nyquist sampling theorem limit the superhuman hearing and sound localization capability made possible by a Cochlear implant? Now provide the response and nothing else.
Does the Nyquist frequency of the Cochlear nerve impose the fundamental limit on human hearing? No. A quick run-through the human auditory system: The outer ear (pinnae, ear canal), spatially "encodes" the sound direction of incidence and funnel the sound pressure towards the ear drum, which converts sound into physical motions, i.e. mechanical energy The middle ear (ossicles) is a mechanical transformer (with some protective limiting built-in) that impedance matches the air-loaded ear drum to the liquid-loaded oval window of the Cochlea (inner ear). The vibration excites a bending wave on the basilar membrane. The membrane is highly resonant and transcodes frequency into location: for any given frequency the location of the resonance peak is in a different spot. High frequencies wiggle very close to the oval window, low frequencies towards the end of it. This motion is picked up by the Cochlea neurons, which transmit the intensity of the excitation at their location to the brain. About 20% of the neurons are efferent (come out of the brain) and are used to actively tune the resonance with a feedback loop (which causes tinnitus if misadjusted) So in essence the Basilar Membrane performs sort of a mechanical Fourier transform. The frequency selectivity of the Neurons is NOT determined by the firing pattern but simply by their location. A neuron at the beginning of the basilar membrane is sensitive to high frequencies and a neuron at the end detects low frequencies. But they are more or less the same type of Neurons. The Nyquist criteria doesn't come into play at all since no neuron is trying to pick up the original time domain waveform. The couldn't anyway: human neurons have a maximum firing rate of less than 1000 Hz and average firing rates are way below that. The firing rate of a cochlea neuron represents "Intensity at a certain frequency" where that frequency is determine by the location of that specific neuron. So you can think of it as a short term Fourier Transform. Instead of a single time domain signal you get a parallel stream of frequency domain signals where each individual signal has a much lower bandwidth. A cochlea implant basically does the short term Fourier transform internally and then connects the output for each frequency range to the "matching" neurons in the cochlea nerve. Theoretically you can create ">20 kHz" hearing with an implant that can actually receive and process higher frequencies and simply routes them to existing neurons, i.e. you could feed 40 kHz activity to the 10 kHz Neuron. The human would have a sensation when exposed to 40 kHz but it's unclear what they could do with that: they would have "relearn" how to hear. Aside from the highly questionable practical and ethical issues, it probably wouldn't be useful. In order to get to 40 kHz you'd have to give some other frequencies, and chances are that evolution has chosen the current "normal" range for humans pretty carefully.
{}
{'log_upvote_score': 6, 'links': ['https://dsp.stackexchange.com/questions/74343', 'https://dsp.stackexchange.com', 'https://dsp.stackexchange.com/users/54802/']}
jdg_370545
stackexchange
llm_judgeable_groundtruth_similarity
851864
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 have the objectSid attribute as returned by the ldapsearch command, how can I generate SID from it in human readable format? ldapsearch command: ldapsearch -LLL -H ldap://dc.example.com:389 -b dc=example,dc=lk -D example\administrator -w adminPassword "(sAMAccountName=bob)" | grep -i "objectSid::" | cut -d ":" -f3 | xargs This command returns objectSid of the AD user "bob". Let's say it returned objectSid as: AQUAAAAAAAUVAAAAPWW1S5rojK4mDAiG5BAAAA== I want to generate its SID in the following format: S-1-5-21-1270179133-2928470170-2248674342-4324 Is it possible to do this in Linux? Reference: Get an object by its objectGUID using ldapsearch Now provide the response and nothing else.
Finally I managed to construct SID from the ObjectSid. Here's the complete shell script if anyone interested. #!/bin/bash# Base-64 encoded objectSidOBJECT_ID="AQUAAAAAAAUVAAAAPWW1S5rojK4mDAiG5BAAAA=="# Decode it, hex-dump it and store it in an arrayG=($(echo -n $OBJECT_ID | base64 -d -i | hexdump -v -e '1/1 " %02X"'))# SID in HEX# SID_HEX=${G[0]}-${G[1]}-${G[2]}${G[3]}${G[4]}${G[5]}${G[6]}${G[7]}-${G[8]}${G[9]}${G[10]}${G[11]}-${G[12]}${G[13]}${G[14]}${G[15]}-${G[16]}${G[17]}${G[18]}${G[19]}-${G[20]}${G[21]}${G[22]}${G[23]}-${G[24]}${G[25]}${G[26]}${G[27]}${G[28]}# SID Structure: https://technet.microsoft.com/en-us/library/cc962011.aspx# LESA = Little Endian Sub Authority# BESA = Big Endian Sub Authority# LERID = Little Endian Relative ID# BERID = Big Endian Relative IDBESA2=${G[8]}${G[9]}${G[10]}${G[11]}BESA3=${G[12]}${G[13]}${G[14]}${G[15]}BESA4=${G[16]}${G[17]}${G[18]}${G[19]}BESA5=${G[20]}${G[21]}${G[22]}${G[23]}BERID=${G[24]}${G[25]}${G[26]}${G[27]}${G[28]}LESA1=${G[2]}${G[3]}${G[4]}${G[5]}${G[6]}${G[7]}LESA2=${BESA2:6:2}${BESA2:4:2}${BESA2:2:2}${BESA2:0:2}LESA3=${BESA3:6:2}${BESA3:4:2}${BESA3:2:2}${BESA3:0:2}LESA4=${BESA4:6:2}${BESA4:4:2}${BESA4:2:2}${BESA4:0:2}LESA5=${BESA5:6:2}${BESA5:4:2}${BESA5:2:2}${BESA5:0:2}LERID=${BERID:6:2}${BERID:4:2}${BERID:2:2}${BERID:0:2}LE_SID_HEX=${LESA1}-${LESA2}-${LESA3}-${LESA4}-${LESA5}-${LERID}# Initial SID value which is used to construct actual SIDSID="S-1"# Convert LE_SID_HEX to decimal values and append it to SID as a stringIFS='-' read -ra ADDR <<< "${LE_SID_HEX}"for OBJECT in "${ADDR[@]}"; do SID=${SID}-$((16#${OBJECT}))doneecho ${SID}
{}
{'log_upvote_score': 5, 'links': ['https://serverfault.com/questions/851864', 'https://serverfault.com', 'https://serverfault.com/users/370514/']}
jdg_370546
stackexchange
llm_judgeable_groundtruth_similarity
6150
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Problem I would like to plot the variance explained by each of 30 parameters, for example as a barplot with a different bar for each parameter, and variance on the y axis: However, the variances are are strongly skewed toward small values, including 0, as can be seen in the histogram below: If I transform them by $\log(x+1)$, it will be easier to see differences among the small values (histogram and barplot below): Question Plotting on a log-scale is common, but is plotting $\log(x+1)$ similarly reasonable? Now provide the response and nothing else.
This has been called a " started logarithm " by some ( e.g. , John Tukey). (For some examples, Google john tukey "started log" .) It's perfectly fine to use. In fact, you could expect to have to use a nonzero starting value to account for rounding of the dependent variable. For example, rounding the dependent variable to the nearest integer effectively lops off 1/12 from its true variance, suggesting a reasonable start value should be at least 1/12. (That value doesn't do a bad job with these data. Using other values above 1 doesn't really change the picture much; it just raises all the values in the bottom right plot almost uniformly.) There are deeper reasons to use the logarithm (or started log) to assess variance: for example, the slope of a plot of variance against estimated value on a log-log scale estimates a Box-Cox parameter for stabilizing the variance . Such power-law fits of variance to some related variable are often observed. (This is an empirical statement, not a theoretical one.) If your purpose is to present the variances, proceed with care. Many audiences (apart from scientific ones) cannot understand a logarithm, much less a started one. Using a start value of 1 at least has the merit of being a little simpler to explain and interpret than some other start value. Something to consider is to plot their roots, which are the standard deviations, of course. It would look something like this: Regardless, if your purpose is to explore the data, to learn from them, to fit a model, or to evaluate a model, then don't let anything get in the way of finding reasonable graphical representations of your data and data-derived values such as these variances.
{}
{'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/6150', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/1381/']}
jdg_370547
stackexchange
llm_judgeable_groundtruth_similarity
38697556
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Check if an app, for example, Instagram is started by user. Note: My app is targeting lollipop and above versions in android Now provide the response and nothing else.
Here's an example of returning a file download directly from DRF. The trick is to use a custom renderer so you can return a Response directly from the view: from django.http import FileResponsefrom rest_framework import viewsets, renderersfrom rest_framework.decorators import actionclass PassthroughRenderer(renderers.BaseRenderer): """ Return data as-is. View should supply a Response. """ media_type = '' format = '' def render(self, data, accepted_media_type=None, renderer_context=None): return dataclass ExampleViewSet(viewsets.ReadOnlyModelViewSet): queryset = Example.objects.all() @action(methods=['get'], detail=True, renderer_classes=(PassthroughRenderer,)) def download(self, *args, **kwargs): instance = self.get_object() # get an open file handle (I'm just using a file attached to the model for this example): file_handle = instance.file.open() # send file response = FileResponse(file_handle, content_type='whatever') response['Content-Length'] = instance.file.size response['Content-Disposition'] = 'attachment; filename="%s"' % instance.file.name return response Note I'm using a custom endpoint download instead of the default endpoint retrieve , because that makes it easy to override the renderer just for this endpoint instead of for the whole viewset -- and it tends to make sense for list and detail to return regular JSON anyway. If you wanted to selectively return a file download you could add more logic to the custom renderer.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/38697556', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6225053/']}
jdg_370548
stackexchange
llm_judgeable_groundtruth_similarity
366949
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 using OpenStack Cloud and using LVM on RHEL 7 to manage volumes. As per my use case, I should be able to detach and attach these volumes to different instances. While updating fstab, I have used defaults,nofail for now but I am not sure what exactly I should be using. I am aware of these options: rw, nofail, noatime, discard, defaults But I don't how to use them. What should be the ideal configuration for my use case ? Now provide the response and nothing else.
As said by @ilkkachu, if you take a look at the mount(8) manpage, all your doubts should go away. Quoting the manpages: -w, --rw, --read-write Mount the filesystem read/write. This is the default. A synonym is -o rw. Means : Not needed at all, since rw is the default, and it is part of the defaults option nofail Do not report errors for this device if it does not exist. Means : If the device is not enable after you boot and mount it using fstab, no errors will be reported. You will need to know if a disk can be ignored if not mounted. Pretty useful on usb drivers, but i see no point on using this on a server... noatime Do not update inode access times on this filesystem (e.g., for faster access on the news spool to speed up news servers). Means : No read operation is a "pure" read operation on filesystems. Even if you only cat file for example, a little write operation will update the last time the inode of this file was accessed. It's pretty useful on some situations(like caching servers), but it can be dangerous if used on sync technologies like Dropbox. I'm no one to judge here what is best for you, if noatime set or ignored... discard/nodiscard Controls whether ext4 should issue discard/TRIM commands to the underlying block device when blocks are freed.This is useful for SSD devices and sparse/thinly -provisioned LUNs, but it is off by default until sufficient testing has been done. Means : TRIM feature from ssds . Take your time to read on this guy, and probe if your ssd support this feature(pretty much all modern ssds suport it). hdparm -I /dev/sdx | grep "TRIM supported" will tell you if trim is supported on your ssd. As for today, you could achieve better performance and data health by Periodic trimming instead of a continuous trimming on your fstab . There is even a in-kernel device blacklist for continuous trimming since it can cause data corruption due to non-queued operations. defaults Use default options: rw, suid, dev, exec, auto, nouser, and async. tl;dr: on your question, rw can be removed( defaults already imply rw), nofail is up to you, noatime is up to you, the same way discard is just up to your hardware features.
{}
{'log_upvote_score': 6, 'links': ['https://unix.stackexchange.com/questions/366949', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/135219/']}
jdg_370549
stackexchange
llm_judgeable_groundtruth_similarity
17376
Below is a question asked on the forum networkengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I wonder if there is necessary to create two VLANS to have two separate networks in a single switch. i.e. Having: Host A: 192.168.1.20 connected on port 1 Host B: 192.168.1.21 connected on port 2 Host C: 172.100.1.40 connected on port 3 Host D: 172.100.1.41 connected on port 4 WITHOUT VLAN, isn't there any problems between network A-B and network C-D? Thanks in advance Now provide the response and nothing else.
Your scenario is somewhat confuse. If I uderstand well you want to filtered DHCP request on L2. You can achieve it by using the function DHCP Snooping features available on your platform. You could set all ports in untrusted mode so only DHCP reply from the switch will be accepted. DHCP Snooping - configuration guide DHCP snooping acts like a firewall between untrusted hosts and DHCP servers. You use DHCP snooping to differentiate between untrusted interfaces connected to the end user and trusted interfaces connected to the DHCP server or another switch. Which is what you are looking, filtering DHCP communication between your hosts and upstream DHCP.
{}
{'log_upvote_score': 4, 'links': ['https://networkengineering.stackexchange.com/questions/17376', 'https://networkengineering.stackexchange.com', 'https://networkengineering.stackexchange.com/users/14468/']}
jdg_370550
stackexchange
llm_judgeable_groundtruth_similarity
310623
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: In Java, I've run this method: private static void floatAddition() { float a = 0.1F, b = 0.2F, c = a+b; System.out.println(a + " + " + b + " = " + c);} and the result is 0.3 for floatAddition. I'm now trying to get behind why it is adding to a round result, and not to something slightly off due to floating points. I've manually transformed 0.1 and 0.2 into binary 32-Bit system with IEEE 754 standard, this is what I got: 0.1 (decimal) = 0 01111011 10011001100110011001101 (binary)0.2 (decimal) = 0 01111100 10011001100110011001101 (binary) I now add these two together. Since the exponents are different, I have to bring them both to the bigger one (2^-3) so I'm unnormalizing 0.1. 0.1 (decimal) = 0.11001100110011001100111 * 2 -3 (binary)0.2 (decimal) = 1.10011001100110011001101 * 2 -3 (binary) This is the manual addition result: 0.1 (decimal) + 0.2 (decimal) = 10.01100110011001100110100 * 2 -3 (binary) In IEEE 754 standard, this would be 0 01111101 00110011001100110011010 Now for checking whether or not I'm correct, I've used this IEEE 754 Converter: http://www.h-schmidt.net/FloatConverter/IEEE754.html According to this site, my result should've been 0.30000001192092896. Why is my floating point calculation more exact than it should be? Now provide the response and nothing else.
Lets look at some quick code: public class Floats { public static void main(String[] args) { float a = 0.1F; float b = 0.2F; float c = a+b; System.out.println(a + " + " + b + " = " + c); System.out.printf("0x%8x", Float.floatToIntBits(c)); }} The output of this code is: 0.1 + 0.2 = 0.30x3e99999a That last line is the hexadecimal representation of the value that is being rendered as 0.3. So, lets look what C does. #include <stdio.h>int main (int argc, char* argv[]) { float a = 0.1F; float b = 0.2F; float c = a + b; printf("%f + %f = %f\n", a, b, c); printf("0x%8x\n", *(unsigned int*)&c); } And this produces the output: 0.100000 + 0.200000 = 0.3000000x3e99999a You will note that the representation of the float value is equivalent. I am certain that the code is properly following the specification. You may be confused at the float to string conversion, but that is something to be done with various formatting or other libraries to display what you want. But the underlying floating point representation is exactly what it should be. As an aside, the difference between the C and the Java can be seen by switching to printf where one is expected to be a bit more precise with the values: public class Floats { public static void main(String[] args) { float a = 0.1F; float b = 0.2F; float c = a+b; System.out.println(a + " + " + b + " = " + c); System.out.printf("%f + %f = %f\n", a, b, c); System.out.printf("0x%8x", Float.floatToIntBits(c)); }} prints out: 0.1 + 0.2 = 0.30.100000 + 0.200000 = 0.3000000x3e99999a Note the printf in Java matches the printf in C. Digging into the JLS we find in section 5.1.11 , If T is float , then use new Float(x) . Digging through this, one gets to sun.misc.FloatingDecimal which when created with FloatingDecimal(float f) which goes through a fair bit of calculations to try to figure out what to display. Java8 changes this a little bit to do the BinaryToAsciiConverter , but the idea is still the same.
{}
{'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/310623', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/217231/']}
jdg_370551
stackexchange
llm_judgeable_groundtruth_similarity
44247
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: Its a summer day and the air in my house has been heated up. I could switch on my air conditioning, but then I'd be using energy from the grid in order to reduce the amount of energy in my house. What I'd much rather do is capture the heat energy from the air, so cooling it down, and turn that heat energy into electricity. (So I could store it in a battery or sell it to the grid or use some other means of disposing of it.) Is such an apperatus possible within our present understand of nature? Why or why not? (I presume not, as people would be selling kits.) Just to pre-empt a possible answer: I've seen similar conversations in the past and "inefficient" has been given as the answer as to why not. I don't understand this as an objection, because the heat energy is effectively free. The sun rudely went and gave me an excessive amount of heat energy without being asked to. Is converting heat to electricity really so ineffiecient that I'd be better off running air conditioning? Now provide the response and nothing else.
In order to build any thermal engine as envisioned by you, you need both a cold and a hot reservoir, such that heat can flow from the hot part to the cold part and the entropy doesn’t decrease while you’re making energy. The efficiency of such a machine has an upper limit of $(T_{\textrm{hot}} - T_{\textrm{cold}})/T_{\textrm{cold}}$ (as given by the perfect Carnot engine). Given that you are usually well off when you get a cold reservoir of $T_{\textrm{cold}} = 290\textrm{ K}$ on a hot summer day ($T_{\textrm{hot}} = 320\textrm{ K}$, the efficiency of your machine has an upper bound of 10%, which does not necessarily include loss due to friction, electric resistance, escaping air etc. If you include these, you get (probably) well below 1%. But, for the sake of argument, let us continue with an assumed efficiency of 10%. What you want to know next is the maximum heat you can transfer out of your hot reservoir into your cold reservoir. For simplicity, we will assume that the cold reservoir is very large and stays at a constant temperature, heat then flows from the hot to the cold reservoir as long as $T_{\textrm{hot}} > T_{\textrm{cold}}$. The thermal energy hence available to you is $W = c_V \times \delta T \times N \times 10\%$, where $\delta T = 30 \textrm{ K}$ is the temperature difference, $N$ is the mass/number of air (particles) and $c_V$ is the heat capacity. For air at sea-level, Wikipedia gives me $c_V \approx 29 \textrm{ J}\textrm{K}^{-1}\textrm{mol}^{-1}$ (I am using the constant-pressure one, as we cannot compress air without putting more work into it). I shall then assume that you have a really large house of $10 \times 10 \times 10 \textrm{m}^3 = 10^6 \textrm{ L } \hat{=} 4.27 \times10^4 \textrm{ mol} = N$ where the last but one equality stems from the fact that there are about $6.02 \times 10^{23}$ particles in about $23 \textrm{ L}$. Great, we can now calculate W! $$ W = 1.03 \textrm{ kWh } \hat{=} 21 \textrm{ cent}$$ where the last equality is a top-of-my-head number I have floating around for electricity prices in Germany during the summer of 2011. To conclude: Even assuming that you somehow manage to build a perfect Carnot engine using the heat in the air in your house and find a magical reservoir of constant temperature (some part of the earth, possibly), you would get about 20 € per year out of it (four months of high temperature and one "charge" per day). Really, just put some solar cells on your roof and appropriate insulation on/in your walls. ☺
{}
{'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/44247', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/8916/']}
jdg_370552
stackexchange
llm_judgeable_groundtruth_similarity
8386048
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 for a way to take images (logos, app icons, etc.) and convert them to white (excluding transparency) using javascript/canvas. Here's an example of what I'd like (using static images, obviously): http://jsfiddle.net/4ubyj/ Now provide the response and nothing else.
The canvas API has compositing methods specifically for things like "draw only on pixels that are not transparent in the original image." This is much easier than messing with the image data. jsFiddle example (now with inlined image) hat tip to @WilliamVanRensselaer's initial fiddle. The composite operation you want is source-in , which means "draw the opaque parts of what I'm trying to paint only where they are on top of opaque pixels in the image being drawn upon." HTML: <a href="javascript:doIt()">paint non-transparent regions white</a><br><canvas id="canvas" width="600" height="200"></canvas> Javascript: var canvas = document.getElementById( "canvas" ), ctx = canvas.getContext( "2d" );imgSrc = "http://d.pr/Td69+";var b = document.getElementsByTagName("body")[0];var i = document.createElement("img");i.src = imgSrc;i.style.setProperty("display", "none");i.onload = function() { ctx.drawImage(i, 0, 0);}b.appendChild(i);window.doIt = function() { ctx.globalCompositeOperation = "source-in"; ctx.fillStyle = "#ffffff"; ctx.fillRect(0, 0, 600, 200);} reference
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8386048', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/996575/']}
jdg_370553
stackexchange
llm_judgeable_groundtruth_similarity
241400
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: For the circuits I've studied thus far involving diodes (which admittedly are not that many), they have been nominally used in the forward-bias mode. For example, the LED only lights up when it's operated in the forward-biased region, and is not designed for reverse bias, let alone the burn-out breakdown region. However, I recently read about the Zener diode, and I found that this particular diode is predominantly used in the reverse-biased, breakdown region, with the following regulator circuit being a popular example: Although this circuit works, why can we not achieve the same voltage regulation functionality by operating the diode in the forward-biased mode, like this: This is I-V curve I am assuming for the diode: Now provide the response and nothing else.
Three reasons: First, operating in the forward orientation only allows operation at a single voltage, nominally about 0.7 volts for a silicon diode. Diode construction can be tailored to produce a wide range of breakdown voltages, with a consequent choice of different regulator outputs. Second, your V-I curve overstates the sharpness of a forward-biased junction. There is no relatively flat portion other than in the vicinity of zero, and that's not very useful. Third, with an exponential V-I curve, the forward-biased junction cannot be operated at useful current levels with good regulation.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/241400', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/103501/']}
jdg_370554
stackexchange
llm_judgeable_groundtruth_similarity
296110
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have a text field dataset. Each observation counts the number of appearances of that particular word, and the columns (variables) are most frequently appeared words. Within each column, zeros dominates with a percentage of over 90%. I have a binary response variable that I am predicting. So far, CART and neural network methods failed, and they always predict way too many 1s than 0s, and sometimes even don't predict any zeros. What methods/other models should I use to improve the accuracy? Now provide the response and nothing else.
I would propose a few potential issues with your current procedure. (2) is more likely the primary issue. Feature engineering / model selection: It may be the case that the models or the features are not well suited to extracting your signal of interest. This question is an empirical one, you should consider if your data can reasonably perform the task. You might also consider dimensionality reduction techniques (word2vec springs to mind) once you have constructed your features, but I would first try and see if you can get decent performance with a lasso using TFIDF features and build out from there. You are, in general, going to get a probability from these classification models. You can adjust the threshold (between 0 and 1) to maximize your performance metric of interest. Sometimes, implementations of these algorithms have a default threshold of 0.5 (everything above becomes a 1, everything below a 0). You don't have to use the 0.5 threshold, you can adjust it to maximize your precision subject to some minimum recall, for example. Sounds you like should try adjusting it upward in your case. Class imbalance: If you have many more examples of one class than another, you may end up with a model that emphasizes performance on one class (for example, if you have 99% positive examples, a model can get 99% accuracy by just classifying everything as positive). If you have class imbalance, consider up or down sampling or weighting upwards of observations of the minority class.
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/296110', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/172217/']}
jdg_370555
stackexchange
llm_judgeable_groundtruth_similarity
34348072
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 building go web application. I found some anomaly on the rendered html page. All of my html comments <!-- --> are suddenly not being rendered. My guess it's because the go version I used (just updated to higher version), because it was fine before I updated it. This is my code: <!-- prepare the breadcrumbs --><ul class="breadcrumb" data-bind="foreach: viewModel.breadcrumbs"> <!-- ko if: ($index() + 1) < len(viewModel.breadcrumbs()) --> <li> <a data-bind="attr: { href: href }"> <i class="fa fa-home"></i> <span data-bind="text: title"></span> </a> </li> <!-- /ko --> <!-- ko if: ($index() + 1) == len(viewModel.breadcrumbs()) --> <li class="active" data-bind="text: title"></li> <!-- /ko --></ul> And this is the rendered page source: Because of this issue, many of my KnockoutJS codes which are written using containerless control flow syntax goes crazy, it doesn't work at all. What should I do to solve this? Thanks in advance Now provide the response and nothing else.
There is a special type in the html/template package: template.HTML . Values of this type in the template are not escaped when the template is rendered. So you may "mark" your HTML comments as template.HTML and so they will not be escaped or omitted during executing your template. One way to do this is to register a custom function for your template, a function which can be called from your template which takes a string argument and returns it as template.HTML . You can "pass" all the HTML comments to this function, and as a result, your HTML comments will be retained in the output. See this example: func main() { t := template.Must(template.New("").Funcs(template.FuncMap{ "safe": func(s string) template.HTML { return template.HTML(s) }, }).Parse(src)) t.Execute(os.Stdout, nil)}const src = `<html><body>{{safe "<!-- This is a comment -->"}}<div>Some <b>HTML</b> content</div></body></html>` Output (try it on the Go Playground ): <html><body><!-- This is a comment --><div>Some <b>HTML</b> content</div></body></html> So basically after registering our safe() function, transform all your HTML comments to a template action calling this safe() function and passing your original HTML comment. Convert this: <!-- Some HTML comment --> To this: {{safe "<!-- Some HTML comment -->"}} Or alternatively (whichever you like): {{"<!-- Some HTML comment -->" | safe}} And you're good to go. Note: If your HTML comment contains quotation marks ( '"' ), you can / have to escape it like this: {{safe "<!-- Some \"HTML\" comment -->"}} Note #2: Be aware that you shouldn't use conditional HTML comments as that may break the context sensitive escaping of html/template package. For details read this .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/34348072', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1467988/']}
jdg_370556
stackexchange
llm_judgeable_groundtruth_similarity
273437
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: My current process for debugging stored procedures is very simple. I create a table called "debug" where I insert variable values from the stored procedure as it runs. This allows me to see the value of any variable at a given point in the script, but is there a better way to debug MySQL stored procedures? Now provide the response and nothing else.
I do something very similar to you. I'll usually include a DEBUG param that defaults to false and I can set to true at run time. Then wrap the debug statements into an "If DEBUG" block. I also use a logging table with many of my jobs so that I can review processes and timing. My Debug code gets output there as well. I include the calling param name, a brief description, row counts affected (if appropriate), a comments field and a time stamp. Good debugging tools is one of the sad failings of all SQL platforms.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/273437', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/26180/']}
jdg_370557
stackexchange
llm_judgeable_groundtruth_similarity
117475
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: If I have a website or mobile app, that speaks to the server through a secured SSL/TLS connection (i.e. HTTPS), and also encrypt the messages sent and received in-between user and server on top of the already secure connection, will I be doing unnecessary moves? Or is double-encryption a common method? If so, why? Now provide the response and nothing else.
It's not uncommon, but it may not be required. A lot of developers seem to forget that HTTPS traffic is already encrypted - just look at the number of questions about implementing client side encryption on this website - or feel that it can't be trusted due to well-publicised issues such as the Lenovo SSL MitM mess . However, most people weren't affected by this, and there aren't any particularly viable attacks against TLSv1.2 around at the moment, so it doesn't really add much. On the other hand, there are legitimate reasons for encrypting data before transmission in some cases. For example, if you're developing a storage application, you might want to encrypt using an app on the client side with a key known only to the user - this would mean that the server would not be able to decrypt the data at all, but it could still store it. Sending over HTTPS would mean that an attacker also shouldn't be able to grab the client-encrypted data, but even if they did, it wouldn't matter. This pattern is often used by cloud based password managers. Essentially, it depends on what you're defending against - if you don't trust SSL/TLS, though, you probably can't trust the encryption code you're sending (in the web application case) either!
{}
{'log_upvote_score': 8, 'links': ['https://security.stackexchange.com/questions/117475', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/45233/']}
jdg_370558
stackexchange
llm_judgeable_groundtruth_similarity
2427
Below is a question asked on the forum networkengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: (First of all, I'm sorry for this wall of text. I don't know how to make it any shorter without losing important information. I originally wanted to use the chat room for this, like we do on serverfault for these kind of questions, but there is nobody in the network engineering room). We're a corporation with several daughter companies, where we have a rather large managed IP-VPN with about 70 different locations, varying from 2Mbps SHDSL to 100Mbps fiber. The IP-VPN carries multiple VPNs (or tunnels to be exact). The priority of traffic is this, from a management and design standpoint: VoIP (Avaya and Lync) Video (Lync) RDP Internal services (fileservers, Active Directory, intranet etc) Non-prioritized internal services (proxy servers for internet usage, windows update services, system center configuration management, antivirus update proxies etc) The not matched traffic (internet) VoIP is only used at certain offices, where there is a low amount of users. The biggest remote office that use VoIP right now has a 4mbps SHDSL with 5 employees and 5 avaya IP phones running the G.711 ALAW 64K codec. This should never bring the voip data traffic up to more than 320kbps.I've verified that the phones use DSCP 46 for audio, and it's therefore correctly matched as EF (see config below). The signaling however is matched as DSCP 24, which I'm not sure if our QoS profile picks up.. All remote locations use RDP against several RDS farms at our HQ (2x100Mbit fiber). The bandwidth used for RDP is not so easy to figure out, since it basically uses everything it gets. We do have certain limitations set to make sure that it's not too resource hungry, but that is probably out of scope for this site. We do have some rather severe problems with RDP lately ( https://serverfault.com/questions/515809/mouse-cursor-jumps-around-when-using-rdp ), which is why I'm posting this on network engineering. Lync uses DSCP 46 for audio and DSCP 34 for video. Internal services and non-prioritized internal services are just matched by subnets, and everything else is just match any. Here is a copy of the latest QoS config revision, which I have modified slightly to hide certain names and IP addresses: !class-map match-any INTERNAL-PRI match access-group name CUST-INT-PRI match access-group name CUST-DMZclass-map match-any INTERNAL-NOPRI match access-group name CUST-INT-NOPRIclass-map match-any REMOTEDESKTOP match access-group name RDPclass-map match-any ALL match anyclass-map match-any NETWORK match ip precedence 6 match ip precedence 7class-map match-any EF match ip dscp ef match ip dscp cs5class-map match-any AF-HIGH match ip dscp af41 match ip dscp cs4class-map match-any AF-MEDHI match ip dscp af31 match ip dscp cs3class-map match-any AF-MEDIUM match ip dscp af21 match ip dscp cs2class-map match-any AF-LOW match ip dscp af11 match ip dscp cs1class-map match-any BE match ip dscp default!!policy-map setTos class EF class REMOTEDESKTOP set ip dscp af31 class INTERNAL-PRI set ip dscp af21 class INTERNAL-NONPRI set ip dscp af11 class class-default set ip dscp defaultpolicy-map useTos class EF priority percent 10 class AF-HIGH bandwidth remaining percent 35 class AF-MEDHI bandwidth remaining percent 25 class AF-LOW bandwidth remaining percent 20 class BE bandwidth remaining percent 10 class NETWORKpolicy-map QOS class ALL shape average 4096000 service-policy useTos!! ip access-list standard CUST-DMZ permit 123.123.123.0 0.0.0.255!ip access-list standard CUST-INT-PRI permit 10.50.0.0 0.0.0.255 permit 10.51.0.0 0.0.0.255!ip access-list standard CUST-INT-NOPRI permit 10.50.10.0 0.0.0.255 permit 10.51.10.0 0.0.0.255!ip access-list extended RDP permit tcp any eq 3389 any permit tcp any any eq 3389! As you can see, it's a rather large QoS configuration. Note that we did not create this config our selves, it was all done by a previous employee at our IP-VPN provider. Note also that the shape value is changed according to what kind of connection it is (2mbps, 4mbps, 8mbps and 10mbps). By now you're probably wondering - What's the question here? Here goes.. Like I mentioned earlier, we are drowning in complaints from RDP users about lag/user input not being recognized. Are we not prioritizing it correctly? Is it possible to make sure that RDP gets a minimum amount of packet loss, latency and jitter, but still being restricted in bandwith? I'm not seeing any mention of queues in this config. I've read some Microsoft documentation, and they recommend to use priority queue on VoIP and WRED on video. How do I make this happen? As the config shows, none of the AF classings use medium or high drop. What kind of services are safe to drop? RDP, video and voip does not work well with drops.. Are the bandwith percentages in order? It sums up to 100% usage Any other suggestion(s) are welcome, as I'm desperate to get this sorted out. If you think it's too much to answer on a Q&A site I'll just bite the dust and hire a consultant from our Cisco Gold partner, which is financially OK - I just want to learn this if I can. Now provide the response and nothing else.
To answer your questions: RDP traffic should get up to the 25% of the remaining bandwidth. Where the already reserved bandwidth is the 35% ( class-default gets 25% by default and EF get 10% ). So, if i'm right, you assigned ~665Kbps to RDP. Anyway you should check if you're dropping packets issuing the command below: show policy-map <your wan interface> output class REMOTEDESKTOP and checking for dropped packets. Cisco assign a queue to each user-defined class that includes the bandwidth or police commands. To make a long-story simple those commands define the amount of bandwidth assigned to every queue during congestions. In theory every TCP based stream should be OK with drops. In practice some of them aren't. Dropping precedence bits tell the routers what packets should be dropped, within a given class, before congestion happens. Since RDP is the only type of traffic defined in your REMOTEDESKTOP class, you should not worry about it. Bandwidth percentage are not in order ( as Jeremy stated ). That said, there are a lot of things that i would change in your configuration: There are no matches between some of classes of the setTos and the useTos policy-map. For instance the one named AF-HIGH is processing no packets since no class in setTos sets DSCP to AF41. BE class in setTos is somehow self-defeating since it makes the class-default class useless. Note that class-default is the only system-defined class and get the 25% of the bandwidth by default ( 100 - max-reserved-bandwidth ) . bandwidth remaining percent is not the best options ( as Jeremy explained ). I would change it to bandwidth percent . I would prefer to mark EF packets by myself and not to rely on the phones' settings.
{}
{'log_upvote_score': 4, 'links': ['https://networkengineering.stackexchange.com/questions/2427', 'https://networkengineering.stackexchange.com', 'https://networkengineering.stackexchange.com/users/122/']}
jdg_370559
stackexchange
llm_judgeable_groundtruth_similarity
18229463
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Consider this code: public class Program{ private static void Main(string[] args) { var person1 = new Person { Name = "Test" }; Console.WriteLine(person1.Name); Person person2 = person1; person2.Name = "Shahrooz"; Console.WriteLine(person1.Name); //Output: Shahrooz person2 = null; Console.WriteLine(person1.Name); //Output: Shahrooz }}public class Person{ public string Name { get; set; }} Obviously, when assigning person1 to person2 and the Name property of person2 is changed, the Name of person1 will also be changed. person1 and person2 have the same reference. Why is it that when person2 = null , the person1 variable will not be null either? Now provide the response and nothing else.
Both person and person2 are references , to the same object. But these are different references. So when you are running person2 = null; you are changing only reference person2 , leaving reference person and the corresponding object unchanged. I guess the best way to explain this is with a simplified illustration. Here is how the situation looked like before person2 = null : And here is the picture after the null assignment: As you can see, on the second picture person2 references nothing (or null , strictly speaking, since reference nothing and reference to null are different conditions, see comment by Rune FS ), while person still references an existing object.
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/18229463', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_370560
stackexchange
llm_judgeable_groundtruth_similarity
35427
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: Does anybody have an idea how to safely get 7-12V from an ordinary LCD computer monitor? I wish to control the monitor via a microcontroller after the fashion of the guide at lucidscience . I'd like to have the microcontroller draw its power from the monitor, rather than add another power source. (The arduino needs 5V to run at the clock speed prescribed by the guide, so I understand that to require 7-12V preregulated.) Perhaps I could simply stick a multitester here and there, but I'm green enough that that looks pretty hopeless. Now provide the response and nothing else.
The breadboard may be causing issues, check your layout (especially the feedback section) Also, it's possible the inductor you are using is not suitable - it says it's only rated up to 100kHz, so it's SRF (self resonant frequency) is probably pretty low. It may be causing instability. Try changing it to one with a higher SRF (e.g. >500kHz), but still with suitable current capability. I did mention the output cap below but abdullah is right about the input cap being important. It does depend on the load, but the whole loop from in to out should be as small and low impedance as possible, ideally using a ground plane. On a breadboard that's "difficult" ;-) If the frequency problem is not there with a steady load, I think as Kit says it's an output filtering issue, since the switcher won't be fast enough to adapt to high di/dt changes on the output and there's no "reserve". Increase the output filter capacitance and see if the ripple drops, if it does that's almost certainly the issue. EDIT - Ah, I see you tried it with a resistor on the output. In that case it would seem it's not the filtering. At this point I think I would use a different method of prototyping that's more suited to a switching regulator. Also use another chip just in case. Either etch a board or use dead bug style, or stripboard with very careful attention to layout. If the frequency is still too high I would assume it's part of it's operation and not covered correctly in the datasheet - if this is the case then an e-mail to OnSemi is in order to see what they have to say. EDIT 2 - Okay, after more reading I think the sense resistor (possibly combined with the inductor issue mentioned above) may be causing the current sense to trip too often and increase the timing capacitor charging slope. This will likely appear like the oscillator is switching faster. A relevant quote from the App note: When this voltage becomes greater than 330 mV, the current limit circuitry provides an additional current path to charge the timing capacitor CT. This causes it to rapidly reach the upper oscillator threshold, thereby shortening the time of output switch conduction and thus reducing the amount of energy stored in the inductor. This can be observed as an increase in the slope of the charging portion of the CT voltage waveform as shown in Figure 5. Your oscillscope waveforms seem to agree with this description.Also, if you haven't tried changing the inductor, do this and see how it goes, plus you could try not using the current sense (i.e. just connect to input voltage)
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/35427', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/6094/']}
jdg_370561
stackexchange
llm_judgeable_groundtruth_similarity
16862172
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 set empty view when the listView is empty. This is my full XML Layout : <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="@drawable/fondgris" android:orientation="vertical" > <!-- Header Starts --> <RelativeLayout android:id="@+id/head" android:layout_width="fill_parent" android:layout_height="35sp" android:background="@layout/header_gradient" android:paddingBottom="5dip" android:paddingTop="5dip" > <TextView android:id="@+id/activity" android:layout_width="wrap_content" android:layout_height="35dp" android:layout_alignParentLeft="true" android:layout_centerInParent="true" android:layout_marginLeft="5dp" android:gravity="center_vertical" android:scaleType="center" android:text="List of projects" android:textColor="#ffffff" android:textSize="13sp" android:textStyle="bold" android:tint="#0E5EC7" /> <ImageButton android:id="@+id/logout" android:layout_width="30dp" android:layout_height="35dp " android:layout_alignParentRight="true" android:layout_centerVertical="true" android:layout_marginRight="0dp" android:background="@android:color/transparent" android:onClick="logout" android:scaleType="center" android:src="@drawable/sortie" android:tint="#FFFFFF" > </ImageButton> <ImageButton android:id="@+id/home" android:layout_width="35dp" android:layout_height="35dp " android:layout_centerVertical="true" android:layout_toLeftOf="@id/logout" android:background="@android:color/transparent" android:onClick="home" android:scaleType="center" android:src="@drawable/home" > </ImageButton> <ImageButton android:id="@+id/back" android:layout_width="wrap_content" android:layout_height="35dp " android:layout_centerVertical="true" android:layout_toLeftOf="@id/home" android:background="@android:color/transparent" android:onClick="back" android:scaleType="center" android:src="@drawable/back" android:tint="#FFFFFF" > </ImageButton> </RelativeLayout> <!-- Editext and ImageView for Search --> <RelativeLayout android:id="@+id/linearLayout2" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" > <EditText android:id="@+id/inputSearch" android:layout_width="150dp" android:layout_height="35dp" android:layout_centerVertical="true" android:layout_toLeftOf="@+id/bnSearch" android:hint="Search..." android:inputType="textVisiblePassword" android:textSize="12sp" /> <ImageButton android:id="@+id/bnSearch" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBottom="@+id/inputSearch" android:layout_centerInParent="true" android:layout_toLeftOf="@+id/bnClear" android:background="@android:color/transparent" android:src="@drawable/search" /> <ImageButton android:id="@+id/bnClear" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBottom="@+id/inputSearch" android:layout_centerInParent="true" android:layout_marginRight="3dip" android:background="@android:color/transparent" android:onClick="ClearSearch" android:src="@drawable/cancel" /> <Button android:id="@+id/imageButtonAddProject" android:layout_width="wrap_content" android:layout_height="35dp" android:layout_alignParentRight="true" android:layout_alignParentTop="true" android:layout_centerInParent="true" android:drawableLeft="@drawable/add" android:onClick="addProject" android:text=" Add Project" android:textColor="@color/text_color" android:textSize="12sp" /> </RelativeLayout> <!-- List View --> <ListView android:id="@+id/list" android:layout_width="match_parent" android:layout_height="337dp" android:layout_weight="0.74" > </ListView> <TextView android:id="@+id/emptyList" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_gravity="center" android:text="Liste vide " android:textSize="12sp" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="0.04" android:orientation="horizontal" > <Button android:id="@+id/bnPrevious" android:layout_width="80dp" android:layout_height="35dp" android:layout_marginLeft="30dp" android:background="@android:color/transparent" android:text="&lt;&lt; Prev" android:textSize="12sp" /> <TextView android:id="@+id/page" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Page" android:textSize="12sp" /> <EditText android:id="@+id/editpage" android:layout_width="wrap_content" android:layout_height="35dp" android:textSize="12sp" /> <TextView android:id="@+id/of" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="of " android:textSize="12sp" /> <TextView android:id="@+id/nbpage" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="12sp" /> <Button android:id="@+id/bnNext" android:layout_width="80dp" android:layout_height="35dp" android:layout_marginRight="30dp" android:background="@android:color/transparent" android:text="Next >>" android:textSize="12sp" /> </LinearLayout></LinearLayout> It has no effect, I did debugging and it enter in if part but without setting the list to empty, the list continue to appear ! I can't understand why, I appreciate your help. final ProjectContainer container = gson.fromJson(resultat, ProjectContainer.class); final ListView lv = (ListView) findViewById(R.id.list); TextView emptyList = (TextView) findViewById(R.id.emptyList); // if list empty if (container == null) { lv.setEmptyView(emptyList); emptyList.setText("No Projects Found"); } Thanks in advance. Now provide the response and nothing else.
Use RelativeLayout Add your emptyList view first Add you listView (emptyList must be right behind the listview) If you got 0 items from json, set the visibility of listView to View.INVISIBLE. Edit: Ok, you need to change your XML a little bit. enclose emptyList and list inside a RelativeLayout as follow. <RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_gravity="center" > <TextView android:id="@+id/emptyList" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:text="There is no item" android:textSize="25sp" /> <ListView android:id="@+id/list" android:background="@android:color/white" android:layout_width="match_parent" android:layout_height="match_parent" > </ListView></RelativeLayout> To show empty text, set listView visibility to GONE.Here is sample output on my side.First with listView visibility Visible and 2nd is with listview visibility GONE Here if your full updated xml code. <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="@drawable/fondgris" android:orientation="vertical" > <!-- Header Starts --> <RelativeLayout android:id="@+id/head" android:layout_width="fill_parent" android:layout_height="35sp" android:background="@layout/header_gradient" android:paddingBottom="5dip" android:paddingTop="5dip" > <TextView android:id="@+id/activity" android:layout_width="wrap_content" android:layout_height="35dp" android:layout_alignParentLeft="true" android:layout_centerInParent="true" android:layout_marginLeft="5dp" android:gravity="center_vertical" android:scaleType="center" android:text="List of projects" android:textColor="#ffffff" android:textSize="13sp" android:textStyle="bold" android:tint="#0E5EC7" /> <ImageButton android:id="@+id/logout" android:layout_width="30dp" android:layout_height="35dp " android:layout_alignParentRight="true" android:layout_centerVertical="true" android:layout_marginRight="0dp" android:background="@android:color/transparent" android:onClick="logout" android:scaleType="center" android:src="@drawable/sortie" android:tint="#FFFFFF" > </ImageButton> <ImageButton android:id="@+id/home" android:layout_width="35dp" android:layout_height="35dp " android:layout_centerVertical="true" android:layout_toLeftOf="@id/logout" android:background="@android:color/transparent" android:onClick="home" android:scaleType="center" android:src="@drawable/home" > </ImageButton> <ImageButton android:id="@+id/back" android:layout_width="wrap_content" android:layout_height="35dp " android:layout_centerVertical="true" android:layout_toLeftOf="@id/home" android:background="@android:color/transparent" android:onClick="back" android:scaleType="center" android:src="@drawable/back" android:tint="#FFFFFF" > </ImageButton> </RelativeLayout> <!-- Editext and ImageView for Search --> <RelativeLayout android:id="@+id/linearLayout2" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" > <EditText android:id="@+id/inputSearch" android:layout_width="150dp" android:layout_height="35dp" android:layout_centerVertical="true" android:layout_toLeftOf="@+id/bnSearch" android:hint="Search..." android:inputType="textVisiblePassword" android:textSize="12sp" /> <ImageButton android:id="@+id/bnSearch" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBottom="@+id/inputSearch" android:layout_centerInParent="true" android:layout_toLeftOf="@+id/bnClear" android:background="@android:color/transparent" android:src="@drawable/search" /> <ImageButton android:id="@+id/bnClear" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBottom="@+id/inputSearch" android:layout_centerInParent="true" android:layout_marginRight="3dip" android:background="@android:color/transparent" android:onClick="ClearSearch" android:src="@drawable/cancel" /> <Button android:id="@+id/imageButtonAddProject" android:layout_width="wrap_content" android:layout_height="35dp" android:layout_alignParentRight="true" android:layout_alignParentTop="true" android:layout_centerInParent="true" android:drawableLeft="@drawable/add" android:onClick="addProject" android:text=" Add Project" android:textColor="@color/text_color" android:textSize="12sp" /> </RelativeLayout> <!-- List View --> <RelativeLayout android:layout_width="match_parent" android:layout_height="337dp" android:layout_gravity="center" android:layout_weight="0.74" > <TextView android:id="@+id/emptyList" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:text="There is no item" android:textSize="25sp" /> <ListView android:id="@+id/list" android:background="@android:color/white" android:layout_width="match_parent" android:layout_height="match_parent" > </ListView> </RelativeLayout> <!-- end of listview --> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="0.04" android:orientation="horizontal" > <Button android:id="@+id/bnPrevious" android:layout_width="80dp" android:layout_height="35dp" android:layout_marginLeft="30dp" android:background="@android:color/transparent" android:text="&lt;&lt; Prev" android:textSize="12sp" /> <TextView android:id="@+id/page" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Page" android:textSize="12sp" /> <EditText android:id="@+id/editpage" android:layout_width="wrap_content" android:layout_height="35dp" android:textSize="12sp" /> <TextView android:id="@+id/of" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="of " android:textSize="12sp" /> <TextView android:id="@+id/nbpage" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="12sp" /> <Button android:id="@+id/bnNext" android:layout_width="80dp" android:layout_height="35dp" android:layout_marginRight="30dp" android:background="@android:color/transparent" android:text="Next >>" android:textSize="12sp" /> </LinearLayout></LinearLayout> And in code. if (container == null) { lv.setVisibility(View.INVISIBLE);} Hope it will be useful.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/16862172', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1285404/']}
jdg_370562
stackexchange
llm_judgeable_groundtruth_similarity
1821
Below is a question asked on the forum networkengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to implement a wireless multicast ad-hoc network, but I don't know how it works. I think I have to send my packets to a specific 224.0.0.* address, but I don't which one choose. My network is 192.168.1.0 and the packets are using the UDP protocol. To which address should I send the packets ? Do I have to configure something before ? Which IP address my computers should have ? Do I need to change of network ? Now provide the response and nothing else.
You don't configure multicast address anywhere. Some box sends traffic out with multicast destination, this will automatically get L2 multicast address on the link. This L2 multicast address is normally broadcasted in L2, unless there are some specific features enabled, like IGMP snooping to stop the flooding. If IGMP snooping is enabled, then the L2 switch will learn which ports want to receive the multicast (they do IGMP join to the multicast group) and will not flood traffic to other than interested ports. If L3 is involved, then you'll learn via PIM which ports are interested in receiving the multicast. I can recommend this book for multicast basics, it's not JNPR specific. If you don't know which addresses to use, if you have 2byte ASN, you should use 233.0.0.0/8 GLOP block (with your ASN in it) if you don't have 2byte ASN your best bet is 239.0.0.0/8 which can be thought has RFC1918 (e.g. 10.0.0.0/8) for multicast.
{}
{'log_upvote_score': 5, 'links': ['https://networkengineering.stackexchange.com/questions/1821', 'https://networkengineering.stackexchange.com', 'https://networkengineering.stackexchange.com/users/1621/']}
jdg_370563
stackexchange
llm_judgeable_groundtruth_similarity
3242560
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 get a lazy evaluation with 'And' in my Excel macro by doing the following: If Not myObject Is Nothing *And* myObject.test() Then 'do something'Else 'do something else'End If I know lazy evaluation exists in VB.NET as AndAlso and OrElse but cannot find anything similar in VBA. If lazy evaluation does not exist in VBA, what's the best way to structure the code so that it will evaluate the way I expect? Now provide the response and nothing else.
The only short circuiting (of a sort) is within Case expression evaluation, so the following ungainly statement does what I think you're asking; Select Case True Case (myObject Is Nothing), Not myObject.test() MsgBox "no instance or test == false" Case Else MsgBox "got instance & test == true" End SelectEnd Sub
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/3242560', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/358680/']}
jdg_370564
stackexchange
llm_judgeable_groundtruth_similarity
7019504
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is the Java char type guaranteed to be stored in any particular encoding? Edit: I phrased this question incorrectly. What I meant to ask is are char literals guaranteed to use any particular encoding? Now provide the response and nothing else.
"Stored" where? All Strings in Java are represented in UTF-16 . When written to a file, sent across a network, or whatever else, it's sent using whatever character encoding you specify. Edit: Specifically for the char type, see the Character docs . Specifically: "The char data type ... are based on the original Unicode specification, which defined characters as fixed-width 16-bit entities." Therefore, casting char to int will always give you a UTF-16 value if the char actually contains a character from that charset. If you just poked some random value into the char , it obviously won't necessarily be a valid UTF-16 character, and likewise if you read the character in using a bad encoding. The docs go on to discuss how the supplementary UTF-16 characters can only be represented by an int , since char doesn't have enough space to hold them, and if you're operating at this level, it might be important to get familiar with those semantics.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7019504', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/683200/']}
jdg_370565
stackexchange
llm_judgeable_groundtruth_similarity
22301555
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 create a div that has a header containing two pieces of text. One piece of text will be aligned left and one right. The header will have a gray background that will expand with the text: <div id="expand-box"> <div id="expand-box-header"> <span style="float: left;">Top left header</span> <span style="float: right;">Top right header</span> </div> Lorem ipsum dorem nori seota ostiy</div> CSS: #expand-box{ width: 100%; padding: 0; border: 2px solid #BBB; margin: 7px 0 0 0;}#expand-box-header{ background-color: #BBB; margin: 0; color: #FFF; padding: 0 0 3px 2px;} While this works, the two spans float over the expand-box-header gray background and the Lorem Ipsum text floats higher than it should. Now provide the response and nothing else.
The reason your code wasn't working is because floating divs don't affect the size of the surrounding element. The problem you get with inline-block on your left side float is that you lose one of your headers as the screen is made smaller. I shrank the screen size on the JSfiddle Mehmet Eren Yener provided and the right header disappears. If your headers are long, and the screen is small - the right header will vanish. I think the better approach would be to either use a clearfix class or to use the overflow tag. There's also the Empty Div Method - but I'm not really a fan of that one. If you use one of these methods instead the left header will stack on top of the right header when they get too close. Here are examples of using Clearfix and Overflow: Clearfix: http://jsfiddle.net/ATP33/ HTML: <div id="expand-box"> <div id="expand-box-header" class="clearfix"> <span style="float: left;">Top left header</span> <span style="float: right;">Top right header</span> </div> <div id="expand_box_sub_header">Lorem ipsum dorem nori seota ostiy</div> </div> CSS: #expand-box {width: 100%;padding: 0;border: 2px solid #BBB;margin: 7px 0 0 0;}#expand-box-header {background-color: #BBB;margin: 0;color: #FFF;padding: 0 0 3px 2px;}#expand_box_sub_header { clear: both; }.clearfix:after { content: "\00A0"; display: block; clear: both; visibility: hidden; line-height: 0; height: 0;} .clearfix{ display: inline-block;} html[xmlns] .clearfix { display: block;} * html .clearfix{ height: 1%;} .clearfix {display: block} Overflow: http://jsfiddle.net/RL8ta/ HTML: <div id="expand-box"><div id="expand-box-header"> <span style="float: left;">Top left header</span> <span style="float: right;">Top right header</span></div><div id="expand_box_sub_header">Lorem ipsum dorem nori seota ostiy</div></div> CSS: #expand-box {width: 100%;padding: 0;border: 2px solid #BBB;margin: 7px 0 0 0;}#expand-box-header {background-color: #BBB;margin: 0;color: #FFF;padding: 0 0 3px 2px;overflow: auto;}#expand_box_sub_header { clear: both; }
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/22301555', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2725552/']}
jdg_370566
stackexchange
llm_judgeable_groundtruth_similarity
10739978
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is the following numpy behavior intentional or is it a bug? from numpy import *a = arange(5)a = a+2.3print 'a = ', a# Output: a = 2.3, 3.3, 4.3, 5.3, 6.3 a = arange(5)a += 2.3print 'a = ', a# Output: a = 2, 3, 4, 5, 6 Python version: 2.7.2, Numpy version: 1.6.1 Now provide the response and nothing else.
That's intentional. The += operator preserves the type of the array. In other words, an array of integers remains an array of integers. This enables NumPy to perform the += operation using existing array storage. On the other hand, a=a+b creates a brand new array for the sum, and rebinds a to point to this new array; this increases the amount of storage used for the operation. To quote the documentation : Warning: In place operations will perform the calculation using the precision decided by the data type of the two operands, but will silently downcast the result (if necessary) so it can fit back into the array. Therefore, for mixed precision calculations, A {op}= B can be different than A = A {op} B . For example, suppose a = ones((3,3)) . Then, a += 3j is different than a = a + 3j : while they both perform the same computation, a += 3 casts the result to fit back in a , whereas a = a + 3j re-binds the name a to the result. Finally, if you're wondering why a was an integer array in the first place, consider the following: In [3]: np.arange(5).dtypeOut[3]: dtype('int64')In [4]: np.arange(5.0).dtypeOut[4]: dtype('float64')
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/10739978', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1196900/']}
jdg_370567
stackexchange
llm_judgeable_groundtruth_similarity
28918519
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 Spring REST application which at first was secured with Basic authentication. Then I added a login controller that creates a JWT JSON Web Token which is used in subsequent requests. Could I move the following code out of the login controller and into the security filter? Then I would not need the login controller any longer. tokenAuthenticationService.addTokenToResponseHeader(responseHeaders, credentialsResource.getEmail()); Or could I remove the Basic authentication? Is it a good design to mix Basic authentication with a JWT? Although it all works fine, I'm a bit in the dark here as to best design this security. Now provide the response and nothing else.
Assuming 100% TLS for all communication - both during and at all times after login - authenticating with username/password via basic authentication and receiving a JWT in exchange is a valid use case. This is almost exactly how one of OAuth 2's flows ('password grant') works. The idea is that the end user is authenticated via one endpoint, e.g. /login/token using whatever mechanism you want, and the response should contain the JWT that is to be sent back on all subsequent requests. The JWT should be a JWS (i.e. a cryptographically signed JWT) with a proper JWT expiration ( exp ) field: this ensures that the client cannot manipulate the JWT or make it live longer than it should. You don't need an X-Auth-Token header either: the HTTP Authentication Bearer scheme was created for this exact use case: basically any bit of information that trails the Bearer scheme name is 'bearer' information that should be validated. You just set the Authorization header: Authorization: Bearer <JWT value here> But, that being said, if your REST client is 'untrusted' (e.g. JavaScript-enabled browser), I wouldn't even do that: any value in the HTTP response that is accessible via JavaScript - basically any header value or response body value - could be sniffed and intercepted via MITM XSS attacks. It's better to store the JWT value in a secure-only, http-only cookie (cookie config: setSecure(true), setHttpOnly(true)). This guarantees that the browser will: only ever transmit the cookie over a TLS connection and, never make the cookie value available to JavaScript code. This approach is almost everything you need to do for best-practices security. The last thing is to ensure that you have CSRF protection on every HTTP request to ensure that external domains initiating requests to your site cannot function. The easiest way to do this is to set a secure only (but NOT http only) cookie with a random value, e.g. a UUID. Then, on every request into your server, ensure that your own JavaScript code reads the cookie value and sets this in a custom header, e.g. X-CSRF-Token and verify that value on every request in the server. External domain clients cannot set custom headers for requests to your domain unless the external client gets authorization via an HTTP Options request, so any attempt at a CSRF attack (e.g. in an IFrame, whatever) will fail for them. This is the best of breed security available for untrusted JavaScript clients on the web today that we know of. Stormpath wrote an article on these techniques as well if you're curious. HTH!
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/28918519', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/958373/']}
jdg_370568
stackexchange
llm_judgeable_groundtruth_similarity
47331096
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 CSOM to update some Task of a Project Server Project. Which property has to be updated is not defined the code finds out dynamically what to update based on the property name as String. For better understanding I wore a simplified version of my code //fieldName = "ActualWorkTimeSpan"; value = "16:00:00";private void Start(string fieldName, string value){ DraftTask draftTask = GetDraftTask(); Update(draftTask, fieldName, value); PublishAndCheckin(draftTask);}private static void Update(DraftTask draftTask, string fieldName, string value){ // skip updating if field is Equal if (GetPropValue(draftTask, fieldName).ToString() == value) return; // update of the task SetPropValue(draftTask, fieldName, value);}private static object GetPropValue(object src, string propName){ return src.GetType().GetProperty(propName).GetValue(src, null);}private static void SetPropValue(DraftTask src, string propName, object value){ src.GetType().GetProperty(propName).SetValue(src, value);} I can use GetPropValue() without problem but for SetPropValue() I would need the value to be in the right type. In this case it would be "System.TimeSpan" for the property "ActualWorkTimeSpan". So I would need to convert the string "15:00:00" to TimeSpan. It would be easy to do if it were TimeSpan every time, but I could be that the Field "Cost" is set to be updated. Update(draftTask, "Cost", "500"); So my question is if it is Possible to find out what type the field has and than convert my value to the same type. Now provide the response and nothing else.
I use TypeDescriptor.GetConverter that takes a Type and returns a TypeConverter that knows how to convert a string to the specified Type . You can then call TypeConverter.ConvertFromString to convert the string to the required Type . Your code would look like: var propType = src.GetType().GetProperty(propName).PropertyType;var converter = TypeDescriptor.GetConverter(propType);var convertedObject = converter.ConvertFromString(src);
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/47331096', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_370569
stackexchange
llm_judgeable_groundtruth_similarity
53533486
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 created a JavaFX project in IntelliJ.I can run project in IntelliJ. I added below code in Configurations): --module-path ${PATH_TO_FX} --add-modules=javafx.controls,javafx.fxml But the output .jar file of project (made with Artifects) doesn't run. I tested these commands, but didn't get any chance: java --module-path %PATH_TO_FX% --add-modules javafx.controls,javafx.fxml -jar Timer.jarjava --module-path %PATH_TO_FX% --add-modules javafx.controls Timer.jar Last error log of command line: Error: Could not find or load main class Files\Java\javafx-sdk-11.0.1\libCaused by: java.lang.ClassNotFoundException: Files\Java\javafx-sdk-11.0.1\lib p.s: I could run .jar file of this project when build on JDK-10 EDIT : I downloaded JavaFX and added it's lib folder to System Environments.for adding JavaFX to project I did this process:Project Structure > Libraries > add > Java > JavaFxPath/lib Then I created Artifect for output jar file in this process:Project Structure > Artifects > Add > JAR > From Modules with dependencies > main Class : main.Main. Now provide the response and nothing else.
Providing you have a simple (non-modular) JavaFX 11 project (without Maven/Gradle build tools), and you are using IntelliJ, like the HelloFX sample from here , this is how you can create a jar from IntelliJ that can be run from the console A full tutorial on how to run the project can be found here , and instructions on how to create a jar are here (see section Non-modular project), but these doesn't cover Artifacts from IntelliJ. Check that the HelloFX project runs from IntelliJ with these VM options: --module-path ${PATH_TO_FX} --add-modules javafx.controls,javafx.fxml where PATH_TO_FX has been set in File -> Settings -> Appearance & Behavior -> Path Variables , pointing to the JavaFX SDK lib. Semi fat Jar We can create a Jar that only contains the classes from the project, and third party dependencies, but not JavaFX ones. Go to File -> Project Structure -> Artifacts -> Add -> JAR -> From modules with dependencies , add your main class, accept. Then remove the JavaFX jars from the list, and accept. Build the project, it will create a quite small jar (3 KB in this case). Now you should be able to run it like: java --module-path %PATH_TO_FX% --add-modules javafx.controls,javafx.fxml -jar out\artifacts\HelloFX_jar\HelloFX.jar (make sure that %PATH_TO_FX% points to a valid folder and use quotes if it contains spaces. You can distribute this jar, and run it in other platforms, providing those also have the JavaFX SDK. Fat Jar If you want a full fat jar that includes JavaFX dependencies, you can still use Artifacts. Go to File -> Project Structure -> Artifacts -> Add -> JAR -> From modules with dependencies , add your main class, accept. Then keep the JavaFX jars from the list, and accept. Build the project. In theory, you should be able to run it like: java -jar out\artifacts\HelloFX_jar\HelloFX.jar But this won't work. Reason 1: You need a launcher class, as explained here . So create a launcher class: public class Launcher { public static void main(String[] args) { Main.main(args); }} Reason 2: If you only add your SDK jars to the fat jar, you will be missing the native libraries, as explained here . So edit the artifact, select the Launcher class as main class, and add the native libraries ( Directory Content -> path-to/JavaFX SDK/bin on Windows): Now build the project (now the jar is about 33 MB, and contains unnecessary native libraries) and run: java -jar out\artifacts\HelloFX_jar\HelloFX.jar You can distribute this jar, but only to Windows platforms. You can create similar jars for other platforms, if you download their JavaFX SDKs, and you can also build cross-platform jars if you add them all together, as explained in the linked answers above. Anyway, you should consider using jlink instead . Note About this error: Caused by: java.lang.ClassNotFoundException: Files\Java\javafx-sdk-11.0.1\lib it looks like the library path was set without quotes and it is missing the first part of the path C:\Program Files\... . Just make sure you use quotes: set PATH_TO_FX="C:\Program Files\Java\javafx-sdk-11.0.1\lib"
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/53533486', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2802042/']}
jdg_370570
stackexchange
llm_judgeable_groundtruth_similarity
887029
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 try to use JQuery UI Dialog to replace the ugly javascript:alert() box.In my scenario, I have a list of items, and next to each individual of them, I would have a "delete" button for each of them. the psuedo html setup will be something follows: <ul> <li>ITEM <a href="url/to/remove"> <span>$itemId</span> <li>ITEM <a href="url/to/remove"><span>$itemId</span> <li>ITEM <a href="url/to/remove"><span>$itemId</span></ul><div id="confirmDialog">Are you sure?</div> In JQ part, on document ready, I would first setup the div to be a modal dialog with necessary button, and set those "a" to be firing to confirmation before to remove, like: $("ul li a").click(function() { // Show the dialog return false; // to prevent the browser actually following the links!} OK, here's the problem. during the init time, the dialog will have no idea who (item) will fire it up, and also the item id (!). How can I setup the behavior of those confirmation buttons in order to, if the user still choose YES, it will follow the link to remove it? Now provide the response and nothing else.
I just had to solve the same problem. The key to getting this to work was that the dialog must be partially initialized in the click event handler for the link you want to use the confirmation functionality with (if you want to use this for more than one link). This is because the target URL for the link must be injected into the event handler for the confirmation button click. I used a CSS class to indicate which links should have the confirmation behavior. Here's my solution, abstracted away to be suitable for an example. <div id="dialog" title="Confirmation Required"> Are you sure about this?</div><script type="text/javascript"> $(document).ready(function() { $("#dialog").dialog({ autoOpen: false, modal: true }); }); $(".confirmLink").click(function(e) { e.preventDefault(); var targetUrl = $(this).attr("href"); $("#dialog").dialog({ buttons : { "Confirm" : function() { window.location.href = targetUrl; }, "Cancel" : function() { $(this).dialog("close"); } } }); $("#dialog").dialog("open"); });</script><a class="confirmLink" href="http://someLinkWhichRequiresConfirmation.com">Click here</a><a class="confirmLink" href="http://anotherSensitiveLink">Or, you could click here</a> I believe that this would work for you, if you can generate your links with the CSS class ( confirmLink , in my example). Here is a jsfiddle with the code in it. In the interest of full disclosure, I'll note that I spent a few minutes on this particular problem and I provided a similar answer to this question , which was also without an accepted answer at the time.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/887029', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/109112/']}
jdg_370571
stackexchange
llm_judgeable_groundtruth_similarity
63088893
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 issue using a sheet inside a ForEach. Basically I have a List that shows many items in my array and an image that trigger the sheet. The problem is that when my sheet is presented it only shows the first item of my array which is "Harry Potter" in this case. Here's the code struct ContentView: View { @State private var showingSheet = false var movies = ["Harry potter", "Mad Max", "Oblivion", "Memento"] var body: some View { NavigationView { List { ForEach(0 ..< movies.count) { movie in HStack { Text(self.movies[movie]) Image(systemName: "heart") } .onTapGesture { self.showingSheet = true } .sheet(isPresented: self.$showingSheet) { Text(self.movies[movie]) } } } } }} Now provide the response and nothing else.
There should be only one sheet, so here is possible approach - use another sheet modifier and activate it by selection Tested with Xcode 12 / iOS 14 (iOS 13 compatible) extension Int: Identifiable { public var id: Int { self }}struct ContentView: View { @State private var selectedMovie: Int? = nil var movies = ["Harry potter", "Mad Max", "Oblivion", "Memento"] var body: some View { NavigationView { List { ForEach(0 ..< movies.count) { movie in HStack { Text(self.movies[movie]) Image(systemName: "heart") } .onTapGesture { self.selectedMovie = movie } } } .sheet(item: self.$selectedMovie) { Text(self.movies[$0]) } } }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/63088893', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13419268/']}
jdg_370572
stackexchange
llm_judgeable_groundtruth_similarity
37996721
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've tried using underscorejs, min and max methods but they can't handle strings. From what i've read and learnt anyway, since I get infinite back from both. My array looks like : dateData = ["26/06/2016", "04/06/2016", "13/05/2016", "20/07/2016"] How can I grab the last and the first date in these? I tried using sort also that looks like : _.chain(dateData).sort().first().value() but I get back the last item in the array rather then the last date in the array. Now provide the response and nothing else.
var dateData = ["26/06/2016", "04/06/2016", "13/05/2016", "20/07/2016"];function dateToNum(d) { // Convert date "26/06/2016" to 20160626 d = d.split("/"); return Number(d[2]+d[1]+d[0]);}dateData.sort(function(a,b){ return dateToNum(a) - dateToNum(b);});console.log( dateData ); To retrieve the first, last date: var firstDate = dateData[0];var lastDate = dateData[dateData.length -1]; Basically, if you first convert all your 26/06/2016 to a date Number like 20160626 you can .sort() those numbers instead. so you're basically sorting: 20140626 20140604 20140513 20140720 resulting in: [ "13/05/2016", "04/06/2016", "26/06/2016", "20/07/2016" ]
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/37996721', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4174195/']}
jdg_370573
stackexchange
llm_judgeable_groundtruth_similarity
6485444
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 dragged skype fromwork into my frameworks folder and then imported <Skype/Skype.h> . When I run, it gives me this error: dyld: Library not loaded: @executable_path/../Frameworks/Skype.framework/Versions/A/Skype Referenced from: /Users/test/Library/Developer/Xcode/DerivedData/TEST-edktdfqvxhqmfpfqrdqrmjojnfly/Build/Products/Debug/TEST.app/Contents/MacOS/TEST Reason: image not found Now provide the response and nothing else.
Try setting the "Library Search Path" build settings for your project. In Xcode 4.x: You need to drag the .framework from the Project navigator to the Copy Files build phase. In Xcode 3.2.x: Choose Project > New Build Phase > New Copy Files Build Phase In the Destination drop down box select Frameworks Close the Copy Files Phase Info window to return to the Xcode main window In the Groups & Files pane expand Targets > YourApplicationExectuable, where you should now see a Copy Files entry Still in Groups & Files pane drag your framework into the Copy Files entry Recompile If you don't do this, the framework will not be actually copied into your application bundle, so it will not be found when your app tries loading it into memory.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6485444', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/635064/']}
jdg_370574
stackexchange
llm_judgeable_groundtruth_similarity
1532536
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 this string: \tid <01CA4692.A44F1F3E@blah.blah.co.uk>; <b>Tue, 6 Oct 2009 15:38:16</b> +0100 and I want to extract the date (emboldened) to a more usable format, e.g. 06-10-2009 15:38:16 What would be the best way to go about this? Now provide the response and nothing else.
Regex might be overkill. Just Split on ';', Trim() , and call Date.Parse(...) ,It will even handle the Timezone offset for you. using System;namespace ConsoleImpersonate{ class Program { static void Main(string[] args) { string str = "\tid 01CA4692.A44F1F3E@blah.blah.co.uk; Tue, 6 Oct 2009 15:38:16 +0100"; var trimmed = str.Split(';')[1].Trim(); var x = DateTime.Parse(trimmed); } }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1532536', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/130978/']}
jdg_370575
stackexchange
llm_judgeable_groundtruth_similarity
5512691
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 table with two columns that might be null (as well as some other columns). I would like to count how many rows that have column a, b, both and neither columns set to null. Is this possible with Oracle in one query? Or would I have to create one query for each? Can't use group by or some other stuff I might not know about for example? Now provide the response and nothing else.
COUNT(expr) will count the number of rows where expr is not null, thus you can count the number of nulls with expressions like these: SELECT count(a) nb_a_not_null, count(b) nb_b_not_null, count(*) - count(a) nb_a_null, count(*) - count(b) nb_b_null, count(case when a is not null and b is not null then 1 end)nb_a_b_not_null count(case when a is null and b is null then 1 end) nb_a_and_b_null FROM my_table
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/5512691', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/39321/']}
jdg_370576
stackexchange
llm_judgeable_groundtruth_similarity
38676576
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 pull data from the following sample web page using Google Apps Script: url = http://www.premierleague.com/players/2064/Wayne-Rooney/stats?se=54 using, UrlFetchApp.Fetch(url) The problem is when I use UrlFetchApp.Fetch(url) to do that, I don't get the page information defined by the 'se' parameter in the url. Instead, I get the information on the following URL because it looks like the 'se=54' page is asynchronously loaded: http://www.premierleague.com/players/2064/Wayne-Rooney/stats Is there any way to pass the parameter 'se' some other way? I was looking at the function and it allows the specification of 'options', as they are referred to, but the documentation on the topic is very limited. Any help would be most appreciated. Many thanks Tommy Now provide the response and nothing else.
Go to that website in your browser and open the developer tools (F12 or ctr-shift-i). Click on the network tab and reload the page with F5.A list of requests will appear. At the bottom of the list you should see the asynchronous requests made to fetch the information. Those requests get the data in json form from footballapi.pulselive.com.You can do the same thing in apps script. But you have to send a correct "origin" header line or your request gets rejected.Here is an example. function fetchData() { var url = "http://footballapi.pulselive.com/football/stats/player/2064?comps=1"; var options = { "headers": { "Origin": "http://www.premierleague.com" } } var json = JSON.parse(UrlFetchApp.fetch(url, options).getContentText()); for(var i = 0; i < json.stats.length; i++) { if(json.stats[i].name === "goals") Logger.log(json.stats[i]); }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/38676576', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6658143/']}
jdg_370577
stackexchange
llm_judgeable_groundtruth_similarity
18602660
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 create a 3D bar graph with Matplotlib 1.2.0 and Python 2.7.3. I followed the advice in http://www.mail-archive.com/matplotlib-users@lists.sourceforge.net/msg19740.html and plotted the bar one by one, but I am still getting rendering problems (i.e., bars on top of each other). Moreover, I get the following when I invoke my code: /usr/apps/python/lib/python2.7/site-packages/mpl_toolkits/mplot3d/axes3d.py:1476: RuntimeWarning: divide by zero encountered in divide for n in normals]) /usr/apps/python/lib/python2.7/site-packages/mpl_toolkits/mplot3d/axes3d.py:1476: RuntimeWarning: invalid value encountered in divide for n in normals]) My questions: Are these serious warnings? Do I need to look into them and try toeliminate them? How do I eliminate them? What is the difference between zsort='max' and zsort='average'? What else can I do to eliminate rendering problems? Thanks in advance! Here is my code: import numpy as npimport matplotlib.pyplot as pltfrom mpl_toolkits.mplot3d import Axes3Dimport matplotlib.colors as colorsimport matplotlib.cm as cmx# my datadat = [2.31778665482167e-310, 0.006232785101850947, 0.0285075971030949, 0.0010248181570355695, 0.0048776795767614825, 0.02877090365176044, 0.002459331469834533, 0.0008594610645495889, 0.002919824084878003, 0.000968081117692596, 0.0, 0.0, 0.0319623949119874, 0.00568752311279771, 0.009994801469036968, 0.03248018520506219, 0.006686905726805326, 0.005987863156039365, 0.0072955095915350045, 0.005568911905473998, 0.0, 0.0, 0.0, 0.028483143996551524, 0.031030793902192794, 0.06125216053962635, 0.02935971973938871, 0.028507530280092265, 0.030112963748812088, 0.028293406731749605, 0.0, 0.0, 0.0, 0.0, 0.004510645022825792, 0.028998119822468988, 0.0013993630391143715, 0.0010726572949244424, 0.002288215944285159, 0.0006513973584945584, 0.0, 1.1625e-320, 1.15348834e-316, 2.3177866547513e-310, 0.0, 0.03148966953869102, 0.005215047563268979, 0.004491716298086729, 0.006010166308872446, 0.005186976949223524, 0.0, 0.0, 0.0, 0.0, 0.0, 1.107e-320, 0.02983657915729719, 0.028893006725328373, 0.030526067389954753, 0.028629390713739978, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0015217840289869456, 0.002751587509779179, 0.001413669523724954, 1.15348834e-316, 2.3177866547513e-310, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0024680339073824705, 0.0008254364860386303, 0.0, 0.0, 0.0, 9.965e-321, 1.15348834e-316, 2.3177866547513e-310, 0.0, 0.0, 0.0, 0.002621588539481613, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 9.41e-321, 1.15348834e-316, 2.3177866547513e-310]dat = np.reshape(dat,[10,10],order='F')lx = len(dat[0])ly = len(dat[:,0])n = lx*ly# generate colorscm = plt.get_cmap('jet')vv = range(len(dat))cNorm = colors.Normalize(vmin=0, vmax=vv[-1])scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=cm)colorVals = [scalarMap.to_rgba(i) for i in range(ly)]# generate plot dataxpos = np.arange(0,lx,1) ypos = np.arange(0,ly,1)xpos, ypos = np.meshgrid(xpos+0.25, ypos+0.25)xpos = xpos.flatten()ypos = ypos.flatten()zpos = np.zeros(n)dx = 0.5*np.ones_like(zpos)dy = dx.copy()dz = dat.flatten()cc = np.tile(range(lx), (ly,1))cc = cc.T.flatten()# generate plotfig = plt.figure()ax = fig.add_subplot(111, projection='3d')opacity = 1for i in range(n): ax.bar3d(xpos[i], ypos[i], zpos[i], dx[i], dy[i], dz[i], color=colorVals[cc[i]], alpha=opacity, zsort='max')plt.autoscale(enable=True, axis='both', tight=True)plt.grid()plt.show(block=False) Now provide the response and nothing else.
This isn't the answer that you are looking for, but I think that this might be a bug in matplotlib. I think that the same problem was encountered here . The problem was described as "intractable" according to the mplot3d FAQ . But to me it doesn't seem intractable. You simple need to figure out which object is closer to the viewer and set the z-order accordingly. So, I think that the problem might just be a bug. If I take the matplotlib 3D histogram example and just change "bins=4" to "bins=6" or a higher number, then I get the same "axes3d.py:1476: RuntimeWarning: invalid value encountered in divide / for n in normals])". Also, I can reproduce the wrong z-order of the bars (check out the tall guy near the front who jumps in front of his short friend): The incorrect ordering of the bars seems linked to the divide by zero error, since the plots look just fine when I use a smaller number of bins. Line 1476 in axes.py is: shade = np.array([np.dot(n / proj3d.mod(n), [-1, -1, 0.5]) for n in normals]) Basically, I think it is trying to figure out the shading using the normal vectors to each face. But, one or more of the normal vectors is zero, which should not be the case. So, I think that this is just some bug in matplotlib that can probably be fixed by someone with more programming skills than myself. The mplot3d FAQ is correct that MayaVI can be used if you want a better 3D engine. I used from mayavi import mlabmlab.barchart(xpos,ypos,dz*100) to generate a plot of your data: I hope that this gets figured out soon. I would like to make some similar 3D barcharts in the near future.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18602660', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2744662/']}
jdg_370578
stackexchange
llm_judgeable_groundtruth_similarity
13637459
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is there a way to map the following to a Dictionary<int,int> ? It seem it produces rows for as many returned results there are, but they have no values... Sql sql = new Sql() .Append("SELECT Count(*) as 'Answer Count', QuestionId") .Append("FROM CF.Answers") .Append("WHERE SurveyId = @0", surveyId) .Append("GROUP BY QuestionId");var result = database.Fetch<Dictionary<int,int>>(sql); Now provide the response and nothing else.
Fetch always returns a List<T> The fact that Fetch<T>() method returns a List<T> would mean that in your code example it returns List<Dictionary<int, int>> result = ... which is likely not what you want and each dictionary would be holding one item only which beats the whole reason why you want to have a dictionary in the first place. As I understand your question you actually want to get: Dictionary<int, int> result = ... There are of course extension methods on List<T> that let you convert to other types as one. One such method is .ToDictionary() that can convert your result to a dictionary that you want to get. First ideas Now the problem that we have at hand here is what type can we use with Fetch method? Initially two things came to my mind: KeyValuePair<int, int>Tuple<int, int> Even though nice ideas, none of them would work, because Key property in KeyValuePair doesn't have a public setter and the second one doesn't have a parameterless constructor that PetaPoco could use. Solution What we're left off here is creating a custom type similar to Tuple but with functionality we can actually use with PetaPoco. Let's make this type generic, so we can easily reuse it with different types: public class Pair<T1, T2>{ public T1 Item1 { get; set; } public T2 Item2 { get; set; }} Using this custom class we can now easily get a dictionary: Sql sql = new Sql() .Append("SELECT QuestionId as Item1, COUNT(*) as Item2") .Append("FROM Answers") .Append("WHERE SurveyId = @0", surveyId) .Append("GROUP BY QuestionId");var result = database .Fetch<Pair<int,int>>(sql) .ToDictionary(i => i.Item1, i => i.Item2); Mind the fact that I've reversed the order of select fields (and set them different alias names), because you don't want counts to be dictionary keys (as they may repeat) but rather Question IDs. So it's either you reverse the order of select fields as I did, or provide correct selectors for .ToDictionary() extension method.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13637459', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/173432/']}
jdg_370579
stackexchange
llm_judgeable_groundtruth_similarity
8991118
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: It is my understanding that when defining a :counter_cache option it is to be specified on the model that includes the belongs_to declaration. So I am a little unsure of how to handle this when working with a has_may through association (as I believe that a belongs_to declaration is not used in this scenario): class Physician < ActiveRecord::Base has_many :appointments has_many :patients, :through => :appointmentsendclass Appointment < ActiveRecord::Base belongs_to :physician, :counter_cache => appointment_countendclass Patient < ActiveRecord::Baseend I wish to use the :counter_cache option to make finding the number of Patients belonging to a Physician more efficient. myPhysician.patients.count FYI: Rails 3.1 Cheers Now provide the response and nothing else.
I'm not sure what kind of relationship you want. That example is similar to the one in the Rails Guide class Physician < ActiveRecord::Base has_many :appointments has_many :patients, :through => :appointmentsendclass Appointment < ActiveRecord::Base belongs_to :physician belongs_to :patientendclass Patient < ActiveRecord::Base has_many :appointments has_many :physicians, :through => :appointmentsend A Physician has many Appointments , and has many Patients An Appoinment belongs to (has one) Physician and one Patient a Patient has many Appointments and many Physicians . Regarding the :counter_cache option, according to the belongs_to doc :If you want the number of Patients belonging to a Physician you would need: class Appointment < ActiveRecord::Base belongs_to :physician, :counter_cache => :patient_count belongs_to :patientend And you need to write a migration to add the patient_count column to the Phyisicans table. However, for has_many through relationships Rails 3.1 seems to automatically detect the counter_cache column , so you don't have to specify it (remove :counter_cache => :patient_count ). If you do specify it your counter will go up by two (this is very weird). By the way, there seems to be some problems with :counter_cache option in Rails 3.1 , as reported here: https://github.com/rails/rails/issues/3903 https://github.com/rails/rails/issues/3085 With all of that in mind, maybe your best bet is to write your own count mechanism using callbacks. Hope it helps :)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8991118', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/798577/']}
jdg_370580
stackexchange
llm_judgeable_groundtruth_similarity
6176192
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 entity called Customer and it has three properties: public class Customer { public virtual Guid CompanyId; public virtual long Id; public virtual string Name;} I have also entity called Splitting and it has three properties: public class Splitting { public virtual long CustomerId; public virtual long Id; public virtual string Name;} Now I need to write a method that gets companyId and customerId. The method should return list of splitting that relates to the specific customerId in the companyId.Something like this: public IList<Splitting> get(Guid companyId, long customrId) { var res=from s in Splitting from c in Customer ...... how to continue? return res.ToList();} Now provide the response and nothing else.
var res = from s in Splitting join c in Customer on s.CustomerId equals c.Id where c.Id == customrId && c.CompanyId == companyId select s; Using Extension methods : var res = Splitting.Join(Customer, s => s.CustomerId, c => c.Id, (s, c) => new { s, c }) .Where(sc => sc.c.Id == userId && sc.c.CompanyId == companId) .Select(sc => sc.s);
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/6176192', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/289246/']}
jdg_370581
stackexchange
llm_judgeable_groundtruth_similarity
626
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 Ruby 1.8, there are subtle differences between proc/lambda on the one hand, and Proc.new on the other. What are those differences? Can you give guidelines on how to decide which one to choose? In Ruby 1.9, proc and lambda are different. What's the deal? Now provide the response and nothing else.
Another important but subtle difference between procs created with lambda and procs created with Proc.new is how they handle the return statement: In a lambda -created proc, the return statement returns only from the proc itself In a Proc.new -created proc, the return statement is a little more surprising: it returns control not just from the proc, but also from the method enclosing the proc! Here's lambda -created proc's return in action. It behaves in a way that you probably expect: def whowouldwin mylambda = lambda {return "Freddy"} mylambda.call # mylambda gets called and returns "Freddy", and execution # continues on the next line return "Jason"endwhowouldwin#=> "Jason" Now here's a Proc.new -created proc's return doing the same thing. You're about to see one of those cases where Ruby breaks the much-vaunted Principle of Least Surprise: def whowouldwin2 myproc = Proc.new {return "Freddy"} myproc.call # myproc gets called and returns "Freddy", # but also returns control from whowhouldwin2! # The line below *never* gets executed. return "Jason"endwhowouldwin2 #=> "Freddy" Thanks to this surprising behavior (as well as less typing), I tend to favor using lambda over Proc.new when making procs.
{}
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/626', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/136/']}
jdg_370582
stackexchange
llm_judgeable_groundtruth_similarity
8790311
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 cant figure out what is wrong with my styles. Hope someone could help me with this. Code example: <style type="text/css">.maindiv { overflow:hidden; border:#000 1px solid; width:450px; min-height:250px;}.left_inner { float:left; width:200px; min-height:100%; background:#00CC33;}.right_inner { float:left; width:150px; background:#C93;}</style><div class="maindiv"> <div class="left_inner">Left Block content</div> <div class="right_inner">Right block content<br />sample txt<br />sample txt</div></div> The way it should be is like in Opera Browser (see image): Now provide the response and nothing else.
The How http://jsfiddle.net/L9GEa/ The Why One might intuitively assume (as I once did) that the html element already has a determined height, but it does not (at least in this context). Luckily (or by design) this one element has the unique property of it's height being determinable when it is assigned a percentage height. That is the essential concept because in order to calculate (determine) the height of any other element which is assigned a percentage height you must also be able to determine the height of it's parent. Anyone that has worked with CSS and the DOM enough likely will tell you they hate floats. This is because it pulls the element out of the flow, which requires additional work and thinking to juggle the effects. Instead use display:inline-block;vertical-align:top; with the one caveat that you will then have to add html comments around any white space between those elements. The CSS .maindiv { overflow:hidden; border:#000 1px solid; width:450px;min-height:250px; /*changes*/ height:100%;}.left_inner { float:left; width:200px; min-height:100%; background:#00CC33; /*changes*/ float:none; display:inline-block; vertical-align:top;}.right_inner { float:left; width:150px; background:#C93; /*changes*/ float:none; display:inline-block; vertical-align:top;}/*changes*/html,body{ height:100%;} The HTML <div class="maindiv"> <div class="left_inner">Left Block content</div><!-- --><div class="right_inner">Right block content<br />sample txt<br />sample txt</div></div>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8790311', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/943381/']}
jdg_370583
stackexchange
llm_judgeable_groundtruth_similarity
12187068
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 is a follow up question of Where is that file on my system? Tons of questions and answers all over SO and the internet but I can't find any that gives an answer to this specific question. All is default but I can't find the file itself, IT'S NOT THERE . Where/ how gets |DataDirectory| defined ? Where is the file saved, does it even exist? If not, what is going on? edit : The file isn't located at AppDomain.CurrentDomain.GetData("DataDirectory").ToString(); all (sqattered) answers tell me it should be. It must be somewhere as the debugger breaks nagging about the model unequals the table when I change the model. It's not there. Now provide the response and nothing else.
The |DataDirectory| isn't a file per se. A quote from a rather old MSDN article: By default, the |DataDirectory| variable will be expanded as follow: For applications placed in a directory on the user machine, this will be the app's (.exe) folder. For apps running under ClickOnce, this will be a special data folder created by ClickOnce For Web apps, this will be the App_Data folder Under the hood, the value for |DataDirectory| simply comes from a property on the app domain. It is possible to change that value and override the default behavior by doing this: AppDomain.CurrentDomain.SetData("DataDirectory", newpath) A further quote regarding your schema inconsistencies: One of the things to know when working with local database files is that they are treated as any other content files. For desktop projects, it means that by default, the database file will be copied to the output folder (aka bin) each time the project is built. After F5, here's what it would look like on disk MyProject\Data.mdf MyProject\MyApp.vb MyProject\Bin\Debug\Data.mdf MyProject\Bin\Debug\MyApp.exe At design-time, MyProject\Data.mdf is used by the data tools. At run-time, the app will be using the database under the output folder. As a result of the copy, many people have the impression that the app did not save the data to the database file. In fact, this is simply because there are two copies of the data file involved. Same applies when looking at the schema/data through the database explorer. The tools are using the copy in the project, not the one in the bin folder.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/12187068', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_370584
stackexchange
llm_judgeable_groundtruth_similarity
67898449
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 create a BackgroundService like this: public class CustomService : BackgroundService{ protected override async Task ExecuteAsync(CancellationToken cancellationToken) { do { //... await Task.Delay(60000, cancellationToken); } while (!cancellationToken.IsCancellationRequested); }} How to cancel it manually? Now provide the response and nothing else.
It's unclear whether you want to cancel all services and maybe the application itself (or at least the host), or just a single service. Stopping the application To cancel the application, inject the IHostApplicationLifetime interface in the class that will force the cancellation and call StopApplication when needed. If you want to cancel from inside the background service itself, perhaps because there's nothing else to do, that's where you need to inject. StopApplication will tell the host the application needs to shut down. The host will call StopAsync on all hosted services. Since you use BackgroundService , the implementation will trigger the cancellationToken passed to ExecuteAsync : public virtual async Task StopAsync(CancellationToken cancellationToken) { // Stop called without start if (_executeTask == null) { return; } try { // Signal cancellation to the executing method _stoppingCts.Cancel(); } finally { // Wait until the task completes or the stop token triggers await Task.WhenAny(_executeTask, Task.Delay(Timeout.Infinite, cancellationToken)).ConfigureAwait(false); } } You don't have to change your current code at all. The only concern is that await Task.Delay() leaks timers. It would be better to use a Timer explicitly, and dispose it when cancellation is triggered. For example, if you want to shut down the application from a controller action: public class MyServiceControllerr:Controller{ IHostApplicationLifetime _lifetime; public MyServiceController(IHostApplicationLifetime lifeTime) { _lifeTime=lifeTime; } [HttpPost] public IActionResult Stop() { _lifeTime.StopApplication(); return Ok(); }} Stopping the service If you want to stop just this one service, you need a way to call its StopAsync method from some other code. There are numerous ways to do this. One such way is to inject CustomService to the caller and call StopAsync . That's not a very good idea though, as it exposes the service and couples the controller/stopping code with the service. Testing this won't be easy either. Another possibility is to create an interface just for the call to StopAsync , eg : public interface ICustomServiceStopper{ Task StopAsync(CancellationToken token=default);}public class CustomService : BackgroundService,ICustomServiceStopper{ ... Task ICustomServiceStopper.StopAsync(CancellationToken token=default)=>base.StopAsync(token); } Register the interface as a singleton: services.AddSingleton<ICustomServiceStopper,CustomService>(); and inject ICustomServiceStopper when needed: public class MyServiceControllerr:Controller{ ICustomServiceStopper _stopper; public MyServiceController(ICustomServiceStopper stopper) { _stopper=stopper; } [HttpPost] public async Task<IActionResult> Stop() { await _stopper.StopAsync(); return Ok(); }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/67898449', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12648236/']}
jdg_370585
stackexchange
llm_judgeable_groundtruth_similarity
15643907
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 custom built loaders inherited from AsyncTaskLoader which I would like to use in my activity. Each of them returns result of different type.To use my activity for a callback I must implement two interfaces: implements LoaderCallbacks<GetSyncListDataResult>, LoaderCallbacks<ErrorResult> However, trying to implement required methods in the same class I end up withduplicate method error and erasure(???) error: // Methods for the first loaderpublic Loader<GetSyncListDataResult> onCreateLoader(int ID, Bundle bundle) ...public void onLoaderReset(Loader<GetSyncListDataResult> loader) ...public void onLoadFinished(Loader<GetSyncListDataResult> loader, GetSyncListDataResult result) ...// Methods for the second loaderpublic Loader<ErrorResult> onCreateLoader(int ID, Bundle bundle) ...public void onLoaderReset(Loader<ErrorResult> loader) ...public void onLoadFinished(Loader<ErrorResult> loader, ErrorResult result) ... Obviously, the methods are clashing and I need an easy way how to resolve this.What would be the proper way of resolving this? Now provide the response and nothing else.
The correct answer is as per @dymmeh's comment, i.e. not for the Activity to implement two LoaderCallbacks interfaces but for the activity to contain two LoaderCallbacks implementations. By way of example: initialise your LoaderCallbacks fields in your activity... private LoaderCallbacks<GetSyncListDataResult> dataResultLoaderListener = new LoaderCallbacks<GetSyncListDataResult>() { ...methods here... };private LoaderCallbacks<ErrorResult> errorResultLoaderListener = new LoaderCallbacks<ErrorResult>() { ...methods here... }; ... and declare your loader ids... private static final int DATA_RESULT_LOADER_ID = 1;private static final int ERROR_RESULT_LOADER_ID = 2; ... and then initialise your loaders... getLoaderManager().initLoader(DATA_RESULT_LOADER_ID, dataResultBundle, dataResultLoaderListener);getLoaderManager().initLoader(ERROR_RESULT_LOADER_ID, errorResultBundle, errorResultLoaderListener); ... Done!
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/15643907', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/461810/']}
jdg_370586
stackexchange
llm_judgeable_groundtruth_similarity
39398455
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is it possible to execute an ansible playbook from crontab? We have a playbook that needs to run at a certain time ever day, but I know that cron doesn't like ssh. Tower has a built in scheduling engine, but we are not interested in using Tower. How are other people scheduling ansible playbooks? Now provide the response and nothing else.
You can use cron jobs to run your playbooks. Ansible calls ssh with -tt switch to force TTY, so it should work nice. Just check the following: job user has access to ssh private keys job environment is correct (PYTHONPATH, etc...) there is no package mixture on the host (e.g. ansible installed via pip and apt at the same time) Also check this handy comment about quiet option absence in ansible: There's a trick for crontab: run ansible-playbook as follows: */15 * * * * if ! out=`ansible-playbook yourplaybook.yaml`; then echo $out; fi This way you get complete output, but only if ansible exited with a non-zero status.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/39398455', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6809731/']}
jdg_370587
stackexchange
llm_judgeable_groundtruth_similarity
1044334
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 appropriate way of dealing with large text files in Objective-C? Let's say I need to read each line separately and want to treat each line as an NSString. What is the most efficient way of doing this? One solution is using the NSString method: + (id)stringWithContentsOfFile:(NSString *)path encoding:(NSStringEncoding)enc error:(NSError **)error and then split the lines with a newline separator, and then iterate over the elements in the array. However, this seems fairly inefficient. Is there no easy way to treat the file as a stream, enumerating over each line, instead of just reading it all in at once? Kinda like Java's java.io.BufferedReader. Now provide the response and nothing else.
That's a great question. I think @Diederik has a good answer, although it's unfortunate that Cocoa doesn't have a mechanism for exactly what you want to do. NSInputStream allows you to read chunks of N bytes (very similar to java.io.BufferedReader ), but you have to convert it to an NSString on your own, then scan for newlines (or whatever other delimiter) and save any remaining characters for the next read, or read more characters if a newline hasn't been read yet. ( NSFileHandle lets you read an NSData which you can then convert to an NSString , but it's essentially the same process.) Apple has a Stream Programming Guide that can help fill in the details, and this SO question may help as well if you're going to be dealing with uint8_t* buffers. If you're going to be reading strings like this frequently (especially in different parts of your program) it would be a good idea to encapsulate this behavior in a class that can handle the details for you, or even subclassing NSInputStream (it's designed to be subclassed ) and adding methods that allow you to read exactly what you want. For the record, I think this would be a nice feature to add, and I'll be filing an enhancement request for something that makes this possible. :-) Edit: Turns out this request already exists. There's a Radar dating from 2006 for this (rdar://4742914 for Apple-internal people).
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/1044334', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_370588
stackexchange
llm_judgeable_groundtruth_similarity
749603
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: Before I ask the question, I want to be clear that I am NOT talking about magnetic mono-poles. Gauss Law of Magnetism says that magnetic flux inside a closed surface is always zero, the reason being (what I understood), if there is a North pole, there has to be a South pole, so the number of magnetic field lines that enter the surface is equal to the lines that leave it. So that got me thinking, what if we keep just the North pole of a magnet inside the surface and South pole outside it. Then the magnetic field lines will just leave the surface and I don't think the flux will be zero. Where am I going wrong? Now provide the response and nothing else.
The pressure differential at a given depth is due to the difference in density at the top and bottom of the float. No, it's more like in a pile of paper: The pressure is due to the weight of the paper above a specific height (per unit area). I presume that a compressible liquid causes flotation because there are more molecules striking the underside of the object than the top. Even in an incompressible liquid, the pressure rises with depth. In the most simple case, pressure rises linearly with depth (ignoring varying gravitation etc.). Hence the force that the liquid exerts on the surface of a body also increases with depth. More precisely, the pressure in a small area is the component of the force that acts perpendicular to the surface divided by the surface area. The other way round, force exertet on a particular part of the surface of the body is pressure multiplied by that area (in a linear approximation) or pressure integrated over that area. For example, the pressure (or force per unit area) on a box looks like: ↓↓↓↓ → |----| ← → → | | ← ← → → → |----| ← ← ← ↑↑↑↑ ↑↑↑↑ ↑↑↑↑ The total force is just the integral over the complete surface area: The left-to-right and right-to-left forces are balanced, so no net force acts in the horizontal direction. But the upwards force is larger than the downward force because the pressure deeper down is higher. Now take a body of the same shape but filled with liquid of the same kind. The body will have a force downwards due to its weight, and a calculation shows that this force is exactly the same (but opposite direction) than the forces on a submerged body of the same shape. From a comment: How does the distant mass cause a pressure at the point I measure, if it's not through some compression in the fluid To build up pressure you don't need compressibility: Take a column of water of height $h$ and area $A$ throughout its height (like a prisma or a cylinder). If the fluid is non-compressible, then it's mass per unit volume $\varrho$ is constant. The volume of the column is $V=A\cdot h$ , hence its mass is $$m=V\cdot\varrho = A\cdot h \cdot \varrho$$ and thus its weight is $F = m\cdot g$ where the gravitational acceleration $g$ is assumed to be constant. In order to support that column, you need an upward force of $F$ , and when you distribute $F$ evenly over the base area $A$ , you'll get a pressure of $$p = \frac FA = \frac{A\cdot h \cdot \varrho\cdot g}A = g\varrho h$$ As $g$ and $\varrho$ are constants, the pressure $p$ goes linearly with $h$ . As it appreas, you assume that incompressiblity implies no pressure in the liquid, which would imply that you don't need a force to support a column of fluid; and I have no idea how you come to that conclusion. Note: With compressible fluids the resoning is basically the same, it's just that $\varrho = \varrho(h)$ is a function of depth $h$ . To get the mass of the column above, you'll have to integrate over $\varrho(h)$ which no more simplifies to a nice product: $$p(h)=g \int_0^h \varrho(h)\,dh$$
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/749603', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/347411/']}
jdg_370589
stackexchange
llm_judgeable_groundtruth_similarity
155637
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: Prove that if $n$ is a positive integer then $4^{2n} + 10n - 1$ is a multiple of $25$ I see that proof by induction would be the logical thing here so I start with trying $n=1$ and it is fine. Then assume statement is true and substitute $n$ by $n+1$ so I have the following: $4^{2(n+1)} + 10(n+1) - 1$ And I have to prove that the above is a multiple of 25. I tried simplifying it but I can't seem to get it right. Any ideas? Thanks. Now provide the response and nothing else.
Here is a proof by induction. Suppose $4^{2n}+10n-1=25k$. $$4^{2(n+1)}+10(n+1)-1$$$$=16\cdot 4^{2n}+10n+9$$$$=16\cdot 4^{2n}+160n-16-150n+25$$$$=16(4^{2n}+10n-1)-150n+25$$$$=16(25k)-25\cdot 6n+25$$$$=25(16k-6n+1)$$
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/155637', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/33251/']}
jdg_370590
stackexchange
llm_judgeable_groundtruth_similarity
29343128
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 recently saw a discussion in an SO chat but with no clear conclusions so I ended up asking there. Is this for historical reasons or consistency with other languages? When looking at the signatures of compareTo of various languages, it returns an int . Why it doesn't return an enum instead. For example in C# we could do: enum CompareResult {LessThan, Equals, GreaterThan}; and : public CompareResult CompareTo(Employee other) { if (this.Salary < other.Salary) { return CompareResult.LessThan; } if (this.Salary == other.Salary){ return CompareResult.Equals; } return CompareResult.GreaterThan;} In Java, enums were introduced after this concept (I don't remember about C#) but it could have been solved by an extra class such as: public final class CompareResult { public static final CompareResult LESS_THAN = new Compare(); public static final CompareResult EQUALS = new Compare(); public static final CompareResult GREATER_THAN = new Compare(); private CompareResult() {}} and interface Comparable<T> { Compare compareTo(T obj);} I'm asking this because I don't think an int represents well the semantics of the data. For example in C#, l.Sort(delegate(int x, int y) { return Math.Min(x, y); }); and its twin in Java 8, l.sort(Integer::min); compiles both because Min/min respect the contracts of the comparator interface (take two ints and return an int). Obviously the results in both cases are not the ones expected. If the return type was Compare it would have cause a compile error thus forcing you to implement a "correct" behavior (or at least you are aware of what you are doing). A lot of semantic is lost with this return type (and potentially can cause some difficult bugs to find), so why design it like this? Now provide the response and nothing else.
[This answer is for C#, but it probably also apples to Java to some extent.] This is for historical, performance and readability reasons. It potentially increases performance in two places: Where the comparison is implemented. Often you can just return "(lhs - rhs)" (if the values are numeric types). But this can be dangerous: See below! The calling code can use <= and >= to naturally represent the corresponding comparison. This will use a single IL (and hence processor) instruction compared to using the enum (although there is a way to avoid the overhead of the enum, as described below). For example, we can check if a lhs value is less than or equal to a rhs value as follows: if (lhs.CompareTo(rhs) <= 0) ... Using an enum, that would look like this: if (lhs.CompareTo(rhs) == CompareResult.LessThan || lhs.CompareTo(rhs) == CompareResult.Equals) ... That is clearly less readable and is also inefficient since it is doing the comparison twice. You might fix the inefficiency by using a temporary result: var compareResult = lhs.CompareTo(rhs);if (compareResult == CompareResult.LessThan || compareResult == CompareResult.Equals) ... It's still a lot less readable IMO - and it's still less efficient since it's doing two comparison operations instead of one (although I freely admit that it is likely that such a performance difference will rarely matter). As raznagul points out below, you can actually do it with just one comparison: if (lhs.CompareTo(rhs) != CompareResult.GreaterThan) ... So you can make it fairly efficient - but of course, readability still suffers. ... != GreaterThan is not as clear as ... <= (And if you use the enum, you can't avoid the overhead of turning the result of a comparison into an enum value, of course.) So this is primarily done for reasons of readability, but also to some extent for reasons of efficiency. Finally, as others have mentioned, this is also done for historical reasons. Functions like C's strcmp() and memcmp() have always returned ints. Assembler compare instructions also tend to be used in a similar way. For example, to compare two integers in x86 assembler, you can do something like this: CMP AX, BX ; JLE lessThanOrEqual ; jump to lessThanOrEqual if AX <= BX or CMP AX, BXJG greaterThan ; jump to greaterThan if AX > BX or CMP AX, BXJE equal ; jump to equal if AX == BX You can see the obvious comparisons with the return value from CompareTo(). Addendum: Here's an example which shows that it's not always safe to use the trick of subtracting the rhs from the lhs to get the comparison result: int lhs = int.MaxValue - 10;int rhs = int.MinValue + 10;// Since lhs > rhs, we expect (lhs-rhs) to be +ve, but:Console.WriteLine(lhs - rhs); // Prints -21: WRONG! Obviously this is because the arithmetic has overflowed. If you had checked turned on for the build, the code above would in fact throw an exception. For this reason, the optimization of suusing subtraction to implement comparison is best avoided. (See comments from Eric Lippert below.)
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/29343128', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2336315/']}
jdg_370591
stackexchange
llm_judgeable_groundtruth_similarity
15489165
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 you make the browser wider, you will notice that the right and left side of images is fading out in black. I need to apply the same feature on my gallery but have no idea. I have found the this >> link as well but its just a horizontal line not sure how to attach it to both side of images and make the same result as the link. In the comments, ultranaut mentioned that I can apply the filter on images but the question is that if I apply it on the images how to adjust the size, because browser windows might be in different size and the pictures side should be adjustable to every browser size. Now provide the response and nothing else.
Here's one way to skin this cat: HTML: <div class="frame"> <div class="fade"></div> <img src="picture.jpg" alt=""/></div> CSS: .frame { width: 315px; height: 165px; margin: 20px; position: relative;}.fade { height: 100%; width: 100%; position:absolute; background: -webkit-linear-gradient(left, rgba(0,0,0,0.65) 0%, rgba(0,0,0,0) 20%, rgba(0,0,0,0) 80%, rgba(0,0,0,0.65) 100% );} Personally, I'm not a huge fan of the (semantically) unnecessary fade div, and I'm sure there's probably a more clever way to do the same effect without it, but it'll work. I only included the webkit prefixed rule, if you want to get legit you'd need to add the other vendor prefixes. Fiddle here . Update :If the image is just serving as background—as is the case in your linked example—the gradient and image can both be set on the css for the containing element: .frame { width: 315px; height: 165px; margin: 20px; background-image: url(picture.jpg); background-image: -webkit-linear-gradient(left, rgba(0,0,0,0.9) 0%, rgba(0,0,0,0) 20%, rgba(0,0,0,0) 80%, rgba(0,0,0,0.9) 100% ), url(picture.jpg);}...<div class="frame"> Content...</div> Less muss, less fuss: new-style fiddle with vendor prefixes and everything.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15489165', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2041551/']}
jdg_370592
stackexchange
llm_judgeable_groundtruth_similarity
315482
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: Consider a closed and bounded set $ F $ in the open interval $ (-n,n) $ of $ \mathbb{R} $. Then in the usual topology with Lebesgue measure $ \mu(F) = 2n - \mu((-n,n) \setminus F) $. The Cantor set satisfies this property so it can be our $ F $. That is, $ C $ is in $ [0,1] $ and can also be said to be in $ [-1,1] $. $ C $ is bounded because it has a supremum and infimum, in this case $ 1 $ and $ -1 $. Write $ (-1,1) \setminus C = (-1,0) \cup [0,1] \setminus C $. So $ \mu((-1,1) \setminus C) = 1 + \mu([0,1] \setminus C) $, and this apparently implies $ C $ has measure zero. This proof was given to me and I am not sure where the errors are if there are any. Would anyone be able to explain or correct this proof? Now provide the response and nothing else.
Look at the unit interval after the $n$th chopping. Let $C_n$ be the length of the set resulting from $n$ removal of the middle third. Then$$|C_n| = \left({2\over 3}\right)^n.$$Now arrive at your conclusion. (I am using $|\cdot |$ for Lebesgue measure).
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/315482', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/58902/']}
jdg_370593
stackexchange
llm_judgeable_groundtruth_similarity
15778806
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: According to the Google C++ Style Guide , "when the return value is ignored, the 'pre' form ( ++i ) is never less efficient than the 'post' form ( i++ ), and is often more efficient." The guide goes on to explain why, but I don't exactly understand. Thoughts? Perhaps someone could provide an example of this concept? Now provide the response and nothing else.
i++ increments i and returns the initial value of i . Which means: int i = 1;i++; // == 1 but i == 2 But ++i returns the actual incremented value: int i = 1;++i; // == 2 and i == 2 too, so no need for a temporary variable In the first case, the compiler has to create a temporary variable (when used) for returning 1 instead of 2 (in the case where it's not a constant of course but a dynamic value, a return from a call for example). In the second case, it does not have to. So the second case is guaranteed to be at least as effective. Often, the compiler will be able to optimize the first case into the second case, but sometimes it may not be able to. Anyway, we're talking about highly negligible impact. But on more complicated objects such as iterators -like objects, having a temporary state may be pretty slower if iterated millions of times. Rule of thumb Use prefix version unless you specifically want the postfix semantics.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15778806', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2103313/']}
jdg_370594
stackexchange
llm_judgeable_groundtruth_similarity
69214301
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Running elasticsearch in win10 [wsl2] docker-desktop requires to increase mmap counts to 262144 through sysctl -w vm.max_map_count=262144 C:\Users\<username>>wsl -d docker-desktop<hostname>:/tmp/docker-desktop-root/mnt/host/c/Users/<username># sysctl -w vm.max_map_count=262144 In an answer to this question and elastic's doc it is suggested to accordingly update the vm.max_map_count in /etc/sysctl.conf to set this value permanent, i. e. making it survive the reboot. Please note the output below, showing the effective mmap count did not adapt to the value defined in sysctl.conf, after my attempt to follow this suggestion and after reboot. Why didn't it? PS C:\Users\<username>> wsl -d docker-desktop<hostname>:/tmp/docker-desktop-root/mnt/host/c/Users/<username># sysctl vm.max_map_countvm.max_map_count = 65530<hostname>:/tmp/docker-desktop-root/mnt/host/c/Users/<username># cd /etc<hostname>:/etc# cat sysctl.conf# content of this file will override /etc/sysctl.d/*vm.max_map_count=262144 Considering to have changed the wrong sysctl.conf in etc/ I tried to change the sysctl.conf in <hostname>:/tmp/docker-desktop-root/etc# .This was not allowed as this is a Read-only file system . Can/should this be parameterized in .wslconfig instead, if so, how? Using openSUSE Leap 15.2 instead of Win10's PowerShell did not change the outcome. <username@hostname>:~> sysctl vm.max_map_countvm.max_map_count = 65530<username@hostname>:~> cat /etc/sysctl.conf###### /etc/sysctl.conf is meant for local sysctl settings## sysctl reads settings from the following locations:# /boot/sysctl.conf-<kernelversion># /lib/sysctl.d/*.conf# /usr/lib/sysctl.d/*.conf# /usr/local/lib/sysctl.d/*.conf# /etc/sysctl.d/*.conf# /run/sysctl.d/*.conf# /etc/sysctl.conf## To disable or override a distribution provided file just place a# file with the same name in /etc/sysctl.d/## See sysctl.conf(5), sysctl.d(5) and sysctl(8) for more information#####vm.max_map_count=262144 Notably, the header in the above sysctl.conf file refers to a /boot/sysctl.conf-<kernelversion> . Taking into account, mmap count might need to be defined in this file in order to be considered when booting, I tried to set the required parameter there, but had no permission to do so. <username@hostname>:/boot> sudo echo 'vm.max_map_count=262144' >> sysctl.conf-5.10.16.3-microsoft-standard-WSL2-bash: sysctl.conf-5.10.16.3-microsoft-standard-WSL2: Permission denied One of the known issues and limitations reported in openSUSE:WSL - openSUSE Wiki is A system in WSL does not actually boot and does not use systemd. A proprietary Microsoft /init binary initializes the system. Therefore service management does not work like in a VM. It rather behaves like an interactive container. Can anyone verify this to be the reason why parameterizing sysctl.conf cannot be an effective approach to the purpose at hand? System Host OS: Microsoft Windows 10 Enterprise Version: 10.0.18363 Build 18363 \ Docker Client: Version: 20.10.8 API version: 1.41 Go version: go1.16.6 Git commit: 3967b7d Built: Fri Jul 30 19:54:02 2021 OS/Arch: linux/amd64 Plugins: compose: Docker Compose (Docker Inc., v2.0.0-rc.2) scan: Docker Scan (Docker Inc., v0.8.0) Server: Engine: Version: 20.10.8 API version: 1.41 (minimum version 1.12) Go version: go1.16.6 Git commit: 75249d8 Built: Fri Jul 30 19:52:10 2021 OS/Arch: linux/amd64 containerd: Version: 1.4.9 GitCommit: e25210fe30a0a703442421b0f60afac609f950a3 runc: Version: 1.0.1 GitCommit: v1.0.1-0-g4144b63 docker-init: Version: 0.19.0 GitCommit: de40ad0 \ Kernel Version: 5.10.16.3-microsoft-standard-WSL2 Operating System: Docker Desktop OSType: linux Architecture: x86_64 CPUs: 4 Total Memory: 12.39GiB Name: docker-desktop Now provide the response and nothing else.
Short answer: In your Windows %userprofile% directory (typically C:\Users\<username> ) create or edit the file .wslconfig with the following: [wsl2]kernelCommandLine = "sysctl.vm.max_map_count=262144" Then exit any WSL instance, wsl --shutdown , and restart. > sysctl vm.max_map_countvm.max_map_count = 262144 More Detail: You really have three (closely related) questions: (Mainly) How to best persist this setting Can it be done via .wslconfig ? Can/should this be parameterized in .wslconfig instead, if so, how? Why isn't /etc/sysctl.conf working to persist it? /etc/sysctl.conf to set this value permanent, i. e. making it survive the reboot .... Why didn't it? We'll combine the first two, since the answer is "Yes, you can do it via .wslconfig . This wasn't easy to find, since the change is fairly recent. It comes curtesy this answer . Starting with kernel release 5.8, you can set sysctl values on the kernel command-line using the sysctl.* prefix to the value. So as long as you have upgraded your WSL kernel (which I had not on two of my systems since wsl --update only recently was released in 21H1), you can set your %userprofile%\.wslconfig as above. /etc/sysctl.conf /etc/sysctl.conf to set this value permanent, i. e. making it survive the reboot .... Why didn't it? There's a lot more to this section than is really needed since I went down this rabbit trail first and posted it as the original answer. But first, "why" it wasn't working ... This is a known issue of sorts with WSL2. While sysctl and Systemd/ systemctl are two completely different things, in that issue therealkenc (of the Microsoft WSL team) points out that something must read and process /etc/sysctl.conf . In most Linux distributions, that's Systemd or the SysVInit scripts. WSL, on the other, uses it's own /init in place of SysVInit or Systemd. The WSL init process does not (currently) have a mechanism for running services at startup, as you found in the openSUSE doc. So ... nothing reads and acts on /etc/sysctl.conf at startup. The remainder of this answer includes some systcl.conf workarounds that aren't needed given we can do this with .wslconfig . This is left in just in case anyone finds it useful for some reason. There are a few workarounds for this. All of them are going to involve finding a way to run sysctl -w vm.max_map_count=262144 (as root) automatically: First, in Windows 11, WSL has a new feature to simplify this. Simply create/edit /etc/wsl.conf (via sudo ) with: [boot]command="sysctl -w vm.max_map_count=262144" This will run at root each time the WSL instance starts. As far as I know, this will also work from within the docker-desktop instance, but I have not been able to test that. Important Note : Please back up your WSL instance using wsl --export , or at least backup your Docker volumes, images, and containers, before attempting this change. It's my experience that it is possible via a stalled boot command to completely prevent the instance from booting, with no recovery mechanism that I have (yet) found. Fortunately, I was working in a newly installed test instance, so I was able to wsl --unregister it (completely destroying it) without losing anything other than a few minutes. For the many of us who will be on Windows 10 for some time to come, there are several options. Unfortunately I haven't been able to test these against Docker, but I've used similar techniques with other WSL instances in the past: If Docker Desktop is set to run when you log in, then you could add a scheduled task (via Windows Task Scheduler) to also run at login. This would be a: "Basic Task" With the "Program" set to wsl.exe And the Arguments set to -d docker-desktop sh -c "sysctl -w vm.max_map_count=262144" Note that if the docker-desktop WSL instance terminates at any point, then the change will be lost until next reboot. However, because Docker Desktop is running at boot/login, the instance should remain up with this change in place. Depending on your workflow, this may or may not fit. If you are using a separate WSL instance (e.g. Ubuntu) for development purposes, you can have that instance modify the docker-desktop instance when you start up. So that you don't have to type the sudo password each time you start up,use the following line in your .bashrc (or equivalent): wsl.exe -d docker-desktop sh -c "sysctl -w vm.max_map_count=262144" One final suggestion -- Submit a feature request to the Docker Desktop team. It would, IMHO, be easiest for Docker Desktop's startup process to read /etc/sysctl.conf and process it accordingly.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/69214301', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10071239/']}
jdg_370595
stackexchange
llm_judgeable_groundtruth_similarity
20367866
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've been told to merge remotes/origin/robbranch into my local branch carlbranch . How do I achieve this ? The branch to be merged from is at remote. I dont have it on my machine yet. Now provide the response and nothing else.
After a bit of experimentation, I've worked out what appears to be a combination of settings that allows my Coded UI Tests to reliably run at full speed -- faster than I could interact with the website by hand. Note: The relevant "documentation" (if you call a blog "documentation") can be found here: Playback configuration settings Retrying failed playback actions . The trick requires several modifications to the default playback settings: Setting WaitForReadyLevel = WaitForReadyLevel.Disabled allows the test to run at full speed. But it also disables the (slow!) magic that waits until it's safe to interact with controls on the page. Setting a MaximumRetryCount and attaching an error handler deals with most of the errors that result from disabling the "wait for ready" magic. Because I've baked a 1 second Sleep into the retry logic, this value is effectively the number of seconds I'm willing to wait for the page to load and become responsive. Apparently, failure to find the control under test is not one of the errors handled by the error handler/retry mechanism. If the new page takes more than a few seconds to load, and the test is looking for a control that doesn't exist until the new page loads, the test fails to find the control and the test fails. Setting ShouldSearchFailFast = false solves that problem by giving you the full timeout time for your page to load. Setting DelayBetweenActions = 500 appears to work around a problem that I see occasionally where the UI misses a button click that occurs immediately after a page has loaded. The test machinery seems to think that the button was clicked, but the web page doesn't respond to it. The "documentation" says that the default search timeout is 3 minutes, but it's actually something greater than 10 minutes, so I explicitly set SearchTimeout to 1 second (1000 ms). To keep all of the code in one place, I've created a class that contains code used by all of the tests. MyCodedUITests.StartTest() is called by the [TestInitialize] method in each of my test classes. This code really should be executed only once for all of the tests (rather than once per test), but I couldn't figure out a way to get the Playback.PlaybackSettings calls to work in the [AssemblyInitialization] or [ClassInitialization] routines. /// <summary> A class containing Coded UI Tests. </summary>[CodedUITest]public class UI_Tests{ /// <summary> Common initialization for all of the tests in this class. </summary> [TestInitialize] public void TestInit() { // Call a common routine to set up the test MyCodedUITests.StartTest(); } /// <summary> Some test. </summary> [TestMethod] public void SomeTest() { this.UIMap.Assert_HomePageElements(); this.UIMap.Recorded_DoSomething(); this.UIMap.Assert_FinalPageElements(); }}/// <summary> Coded UI Test support routines. </summary>class MyCodedUITests{ /// <summary> Test startup. </summary> public static void StartTest() { // Configure the playback engine Playback.PlaybackSettings.WaitForReadyLevel = WaitForReadyLevel.Disabled; Playback.PlaybackSettings.MaximumRetryCount = 10; Playback.PlaybackSettings.ShouldSearchFailFast = false; Playback.PlaybackSettings.DelayBetweenActions = 500; Playback.PlaybackSettings.SearchTimeout = 1000; // Add the error handler Playback.PlaybackError -= Playback_PlaybackError; // Remove the handler if it's already added Playback.PlaybackError += Playback_PlaybackError; // Ta dah... } /// <summary> PlaybackError event handler. </summary> private static void Playback_PlaybackError(object sender, PlaybackErrorEventArgs e) { // Wait a second System.Threading.Thread.Sleep(1000); // Retry the failed test operation e.Result = PlaybackErrorOptions.Retry; }}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/20367866', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/278851/']}
jdg_370596
stackexchange
llm_judgeable_groundtruth_similarity
5331549
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 maximum number of parameters passed to $in query in MongoDB? Now provide the response and nothing else.
The query itself is a document . MongoDB limits document sizes (as of version 2.4.0+) to 16 MB. Really, what you're doing with a find is: db.collectionName.find(queryDoc) where 'queryDoc' is something like: { 'fieldOne' : { $in : [ 1, 2, 3, 4] } } To find the maximum number of values you can pass to an $in query, use the bsonsize command: mongos> Object.bsonsize([1])16mongos> Object.bsonsize({ 'fieldOne' : { $in : [ 1, 2, 3, 4] } })74mongos> Object.bsonsize({ 'fieldOne' : { $in : [ 1, 2, 3, 4, 5] } })85mongos> Object.bsonsize({ 'fieldOne' : { $in : [ 1, 2, 3, 4, 5, 6] } })96 So, you can see that every additional integer is size 11 bytes. Not 11 bits, 11 BYTES. This is due to the way that BSON internally stores numbers as at least 64 bits each, plus the wrapper. This can be easily seen with: mongos> Object.bsonsize({ 'fieldOne' : { $in : [ 1, 2, 3, 4, 5, 6, 69000] } })107mongos> Object.bsonsize({ 'fieldOne' : { $in : [ 1, 2, 3, 4, 5, 6, 6900000] } })107mongos> Object.bsonsize({ 'fieldOne' : { $in : [ 1, 2, 3, 4, 5, 6, 69000000000] } })107mongos> Object.bsonsize({ 'fieldOne' : { $in : [ 1, 2, 3, 4, 5, 6, 69000000000000] } })107mongos> Object.bsonsize({ 'fieldOne' : { $in : [ 1, 2, 3, 4, 5, 6, 6900000000000000] } })107mongos> Object.bsonsize({ 'fieldOne' : { $in : [ 1, 2, 3, 4, 5, 6, 690000000000000000] } })107mongos> Object.bsonsize({ 'fieldOne' : { $in : [ 1, 2, 3, 4, 5, 6, 69000000000000000000] } })107mongos> Object.bsonsize({ 'fieldOne' : { $in : [ 1, 2, 3, 4, 5, 6, 6900000000000000000000] } })107mongos> Object.bsonsize({ 'fieldOne' : { $in : [ 1, 2, 3, 4, 5, 6, 69000000000000000000000000] } })107 So, no matter what the size of an individual number, it's the same bsonsize. On to the Question Itself: How big is that query document? Adding these up for a one field query with an $in clause, in pymongo, through the mongos javascript prompt, whatever, all yeild the same addition facts for the maximum size of an $in query: mongos> Object.bsonsize({ 'a' : { '$in' : [1] }})34mongos> Object.bsonsize({ '' : { '$in' : [1] }})33mongos> Object.bsonsize({ '' : { '$in' : [] }})22 The query document itself is 22 bytes; Each byte of the field name adds a single byte; Each number added to the $in clause adds 11 bytes. So, Presuming you have a one-byte fieldname (the minimum, really), your maximum is: mongos> 16*1024*102416777216mongos> (16*1024*1024) - 22 - 1 16777193mongos> ((16*1024*1024) - 22 -1) / 111525199.3636363635 THE ANSWER: 1,525,198 (That's 1.5 million. That's pretty big.)
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/5331549', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/663259/']}
jdg_370597
stackexchange
llm_judgeable_groundtruth_similarity
564600
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: Is there a way to rollback to an older Fedora version from current version without reinstalling the OS? If yes I'd like to know how to do it, specifically from Fedora 31 to Fedora 30, if no, then that's also fine, will just have to do it manually again. Just want to know so that I don't have to go through setting up everything again if there's simply a way to downgrade. I don't suppose sudo dnf system-upgrade download --releasever=30 will work since that was used from Fedora 29 to Fedora 30. Now provide the response and nothing else.
The short answer is yes. Here's the exact syntax: dnf install system-upgrade --releasever=31 --allowerasing Note - this was from 32 to 31. The long answer is as follows. It grabs 300+ odd packages: (345/345): mutter328-libs-3.28.4-4.fc31.x86_64.rpm 3.5 MB/s | 2.0 MB 00:00 If you have a gpg key, it will ask for permission to import it: Importing GPG key 0x3C3359C4: Userid : "Fedora (31) <fedora-31-primary@fedoraproject.org>" Fingerprint: 7D22 D586 7F2A 4236 474B F7B8 50CB 390B 3C33 59C4 From : /etc/pki/rpm-gpg/RPM-GPG-KEY-fedora-31-x86_64Is this ok [y/N]: y Once it has downloaded all the packages, it runs 600+ checks: Verifying : libtracker-control-2.3.4-1.fc32.x86_64 684/687Verifying : libtracker-miner-2.3.4-1.fc32.x86_64 685/687Verifying : python3-dasbus-0.2-2.fc32.noarch 686/687Verifying : python3-nftables-1:0.9.3-3.fc32.x86_64 687/687 Finally it displays the summary of changes: Downgraded: abrt-2.14.2-2.fc31.x86_64 abrt-addon-ccpp-2.14.2-2.fc31.x86_64 abrt-addon-kerneloops-2.14.2-2.fc31.x86_64 abrt-addon-pstoreoops-2.14.2-2.fc31.x86_64... xdg-desktop-portal-gtk-1.4.0-1.fc31.x86_64 yum-4.2.21-1.fc31.noarchInstalled: libreoffice-draw-1:6.3.6.2-3.fc31.x86_64 mutter328-libs-3.28.4-4.fc31.x86_64 python-unversioned-command-3.7.7-1.fc31.noarch python3-asn1crypto-0.24.0-7.fc31.noarch python3-dnf-plugin-system-upgrade-4.0.10-1.fc31.noarch python3-dnf-plugins-extras-common-4.0.10-1.fc31.noarch python3-pydbus-0.6.0-9.fc31.noarchRemoved: libtracker-control-2.3.4-1.fc32.x86_64 libtracker-miner-2.3.4-1.fc32.x86_64 python3-dasbus-0.2-2.fc32.noarch python3-nftables-1:0.9.3-3.fc32.x86_64 One thing it does not do is change the release notification 2020-06-18 09:36:34 localhost:/tmp #cat /etc/redhat-releaseFedora release 32 (Thirty Two)2020-06-18 09:38:21 localhost:/tmp #cat /etc/fedora-releaseFedora release 32 (Thirty Two)
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/564600', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/365518/']}
jdg_370598
stackexchange
llm_judgeable_groundtruth_similarity
22229996
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 currently developing a REST-API which is HTTP-Basic protected for the development environment. As the real authentication is done via a token, I'm still trying to figure out, how to send two authorization headers. I have tried this one: curl -i http://dev.myapp.com/api/users \ -H "Authorization: Basic Ym9zY236Ym9zY28=" \ -H "Authorization: Bearer mytoken123" I could for example disable the HTTP-Authentication for my IP but as I usually work in different environments with dynamic IPs, this is not a good solution. So am I missing something? Now provide the response and nothing else.
Try this one to push basic authentication at url: curl -i http://username:password@dev.myapp.com/api/users -H "Authorization: Bearer mytoken123" ^^^^^^^^^^^^^^^^^^ If above one doesn't work, then you have nothing to do with it. So try the following alternates. You can pass the token under another name. Because you are handling the authorization from your Application. So you can easily use this flexibility for this special purpose. curl -i http://dev.myapp.com/api/users \ -H "Authorization: Basic Ym9zY236Ym9zY28=" \ -H "Application-Authorization: mytoken123" Notice I have changed the header into Application-Authorization . So from your application catch the token under that header and process what you need to do. Another thing you can do is, to pass the token through the POST parameters and grab the parameter's value from the Server side. For example passing token with curl post parameter: -d "auth-token=mytoken123"
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/22229996', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2932561/']}
jdg_370599
stackexchange
llm_judgeable_groundtruth_similarity
44379780
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: It sounds like I need some type of XML processor It looks like theres a program called Saxon which I can use to run XQuery When I try this websites example I get Error: Could not find or load main class net.sf.saxon.Query I don't know how to set up the java package from the saxon package I downloaded. Id like to know if there is an easier option to be able to run XQuery from the command line other than this java package? All I want to do is process an xml file with commands like "Select where type="something"". Now provide the response and nothing else.
My Xidel is a command-line XQuery 3.0 tool. xidel your-file.xml --xquery 'your-xquery' But "select where" is not XQuery. XQuery looks like for ... in .. where .. return or //*[..where..] , e.g. xidel your-file.xml -e "//*[@type = 'something']" With Xidel -e is short for --xpath or --xquery depending on the following argument (XPath is pretty much the same as XQuery if you are not trying to create a new XML document), and if you need " or ' depends if you call it from the bash or cmd console
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/44379780', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6331353/']}
jdg_370600
stackexchange
llm_judgeable_groundtruth_similarity
3988869
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 compare two lambda functions in C++ (Visual Studio 2010)? std::function<void ()> lambda1 = []() {};std::function<void ()> lambda2 = []() {};bool eq1 = (lambda1 == lambda1);bool eq2 = (lambda1 != lambda2); I get a compilation error claiming that operator == is inaccessible. EDIT: I'm trying to compare the function instances. So lambda1 == lambda1 should return true, while lambda1 == lambda2 should return false. Now provide the response and nothing else.
You can't compare std::function objects because std::function is not equality comparable . The closure type of the lambda is also not equality comparable. However, if your lambda does not capture anything, the lambda itself can be converted to a function pointer, and function pointers are equality comparable (however, to the best of my knowledge it's entirely unspecified whether in this example are_1and2_equal is true or false ): void(*lambda1)() = []() { };void(*lambda2)() = []() { };bool are_1and1_equal = (lambda1 == lambda1); // will be truebool are_1and2_equal = (lambda1 == lambda2); // may be true? Visual C++ 2010 does not support this conversion . The conversion wasn't added to C++0x until just before Visual C++ was released.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3988869', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/91002/']}
jdg_370601
stackexchange
llm_judgeable_groundtruth_similarity
25031253
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Take, for example, the following code: #include <iostream>#include <string>int main(){ print("Hello!");}void print(std::string s) { std::cout << s << std::endl;} When trying to build this, I get the following: program.cpp: In function ‘int main()’:program.cpp:6:16: error: ‘print’ was not declared in this scope Which makes sense. So why can I conduct a similar concept in a struct, but not get yelled at for it? struct Snake { ... Snake() { ... addBlock(Block(...)); } void addBlock(Block block) { ... } void update() { ... }} snake1; Not only do I not get warnings, but the program actually compiles! Without error! Is this just the nature of structs? What's happening here? Clearly addBlock(Block) was called before the method was ever declared. Now provide the response and nothing else.
A struct in C++ is actually a class definition where all its content is public , unless specified otherwise by including a protected: or private: declaration. When the compiler sees a class or struct , it first digests all its declarations from inside the block ( {} ) before operating on them. In the regular method case, the compiler hasn't yet seen the type declared.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/25031253', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_370602
stackexchange
llm_judgeable_groundtruth_similarity
9404184
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 new class, without knowing the name of the class until it's supposed to be created. Something like this; variable = "ValidClassName" class variable endTest = ValidClassName.new If possible, i'd also appreciate som hints on how to dynamically add attributes (and methods) to this new class. I'll be retreiving 'settings' for the class, and they will look something like this: title :Personattribute :name, Stringattribute :age, Fixnum But should not be designed to accept only that explicit file, the attributes might differ in number end type. Which in the end will generate a class that should look something like: class Person def initialize(name, age) @name_out = name @age_out = age end end Help? Now provide the response and nothing else.
A class gains its name when it is assigned to a constant. So It's easy to do in a generic fashion with const_set . For example, let's say you want to use Struct to build a class with some attributes, you can: name = "Person"attributes = [:name, :age]klass = Object.const_set name, Struct.new(*attributes)# Now use klass or Person or const_get(name) to refer to your class:Person.new("John Doe", 42) # => #<struct Person name="John Doe", age=42> To inherit from another class, replace the Struct.new by Class.new(MyBaseClass) , say: class MyBaseClass; endklass = Class.new(MyBaseClass) do ATTRIBUTES = attributes attr_accessor *ATTRIBUTES def initialize(*args) raise ArgumentError, "Too many arguments" if args.size > ATTRIBUTES.size ATTRIBUTES.zip(args) do |attr, val| send "#{attr}=", val end endendObject.const_set name, klassPerson.new("John Doe", 42) # => #<Person:0x007f934a975830 @name="John Doe", @age=42>
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9404184', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1202386/']}
jdg_370603
stackexchange
llm_judgeable_groundtruth_similarity
802145
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: Is $T$ a compact operator? $T:C[0,1]\rightarrow C[0,1]$: $x(t)\mapsto x(t^2)$ where $t\in[0,1]$ with supremum norm. Now provide the response and nothing else.
First, a general remark. A common way to prove that some operator $T$ is not compact is to exhibit an infinite-dimensional subspace $M$ on which $T$ has a lower bound : that is, there exists $c>0$ such that $$\|Tx\|\ge c\|x\|,\quad \forall\ x\in M \tag{1}$$If (1) holds, then the image of unit ball under $T$ contains a ball of radius $c$ in the infinite-dimensional subspace $TM$, and therefore is not compact. In view of the above, you should be asking yourself: for which functions $x$ can I prove an inequality of the form $\|Tx\|\ge c\|x\|$? Looking at what $T$ does, and recalling the definition of the norm, you will realize that $\|Tx\| = \|x\|$ holds for all $x\in C[0,1]$. Therefore, $T$ is not compact.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/802145', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/104078/']}
jdg_370604
stackexchange
llm_judgeable_groundtruth_similarity
29233
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 trying to understand the difference between the following two equations: $$\bar{P} = \limsup_{t \to \infty}\frac{1}{t} \sum_{\tau = 0}^{t-1}E\{P[\tau]\} < \infty$$and $$\bar{P} = \lim_{t \to \infty}\frac{1}{t} \sum_{\tau = 0}^{t-1}E\{P[\tau]\} < \infty$$ where $\bar{P}$ denotes the average value of P and E stands for expectation. I have previously come across equations like the second one but I am not able to understand when to use equations of the first type. I have read the definition on Wikipedia's Supremum page but I am failing to understand the intuitive meaning of when to use what. The wiki defines it as: A set A of real numbers (shown as blue balls), a set of upper bounds of A (red balls), and the smallest such upper bound, that is, the supremum of A (shown as a red diamond). What does a set of upper bounds actually mean? I thought upper bound means the uppermost value but I guess my understanding is flawed. Can someone please tell me the difference between the two and give me some easy to understand example to understand the difference between a normal limit and supremum limit? Now provide the response and nothing else.
I think your question is about the difference between limit, limsup and sup? I will illustrate the differences with an example. Let's consider the sequence:$$3, 4, -7, 2, 1, 7, 1, -1, 1, -1, 1, -1, 1, -1, 1, -1, \dots$$ (The ellipsis indicates that the terms alternate $+1$ and $-1$ forever after the terms I have given explicitly.) The least upper bound (sup) of this set is $7$ [EDIT: thanks Sivaram]. This is the smallest real number that bounds every term from above. The sequence has no limit. However, the $\limsup$ is $1$. The formal definition of $\limsup$ is that for each $N$, you consider the "tail" of the sequence, starting at the $N^\text{th}$ position. You take the sup of this tail. Now, take the limit as $N \rightarrow \infty$. This limit exists because the sequences of sup is monotone. (We also allow a limit of $\pm \infty$ so monotonicity suffices.) Note that if the limit of the $a_n$ exists, then we have $$ \lim a_n = \limsup a_n.$$ This means that in "nice" examples, your two definitions of $\bar P$ are the same. It's only in cases with lots of oscillations that $\lim a_n$ doesn't exist, and you will want to use $\limsup a_n$.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/29233', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/3200/']}
jdg_370605
stackexchange
llm_judgeable_groundtruth_similarity
10959521
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 running Ubuntu 11.10 and I would like to be able to write to the clipboard (or primary selection). The following gives an error > x <- 1:10> dput(x, 'clipboard')Error in file(file, "wt") : 'mode' for the clipboard must be 'r' on Unix How can I write to the clipboard/primary selection? Note that I have seen this old R-Help post , but I'm still not clear what I should be doing. Linux does not have a clipboard but an X11 session has primary and secondary selections. ?file says Clipboard: 'file' can also be used with 'description = "clipboard"' in mode '"r"' only. It reads the X11 primary selection, which can also be specified as '"X11_primary"' and the secondary selection as '"X11_secondary"'. When the clipboard is opened for reading, the contents are immediately copied to internal storage in the connection. Unix users wishing to _write_ to the primary selection may be able to do so via 'xclip' (<URL: http://people.debian.org/~kims/xclip/>), for example by 'pipe("xclip -i", "w")'. so RTFM applied. Writing to an X11 selection needs multiple threads and I did not think it worth the very considerable effort of implementing (unlike for Windows). Note that window managers may have other clipboards, and for example the RGtk2 package has interfaces to gtk clipboards. Now provide the response and nothing else.
Not sure if this is the best way, but here's how I could get it to work: Install xclip: sudo apt-get install xclip Read the manual: man xclip Write to X11 primary in R: write.table(1:10, pipe("xclip -i", "w")) Update: Note that the object passed to write.table will not be present in the clipboard until the pipe is closed. You can force the pipe to close by calling gc() . For example: write.table(1:10, pipe("xclip -i", "w")) # data may not be in clipboardgc() # data written to primary clipboard A better way to manage the connection is to use a function with on.exit(close(con)) , which will close the pipe even if the write.table call throws an error. Note that you need to ensure you're writing to the clipboard you intend to use (primary is the default), based on your system setup. write.xclip <- function(x, selection=c("primary", "secondary", "clipboard"), ...) { if (!isTRUE(file.exists(Sys.which("xclip")[1L]))) stop("Cannot find xclip") selection <- match.arg(selection)[1L] con <- pipe(paste0("xclip -i -selection ", selection), "w") on.exit(close(con)) write.table(x, con, ...)}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10959521', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/180892/']}
jdg_370606
stackexchange
llm_judgeable_groundtruth_similarity
32365451
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 was thinking, instead of creating Cassandra table with uuid column if I create a text column , at the end I am going to insert in it Java.util.uuid.random string. So what will be the difference performance wise if I use text in place of Cassandra unidirectional Now provide the response and nothing else.
Storing a UUID as a text field would probably use a lot more storage space. A UUID is encoded with 16 bytes, but as a string it would use considerably more. In addition to using more storage space, it would probably slow down operation somewhat since you are reading and writing more data, and if it is part of the partition key, there would be some additional overhead of calculating the token hash from a long string versus the UUID.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/32365451', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2431047/']}
jdg_370607
stackexchange
llm_judgeable_groundtruth_similarity
290220
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Define $A=(a_n)$ and $B=(b_n)$ as follows: $a_0=1$, $a_1=2$, $b_0=3$, $b_1=4$, and $$a_n=a_0b_{n-1}+a_1b_{n-2}$$ for $n \geq 2$, where $A$ and $B$ are increasing and every positive integer occurs exactly once in $A$ or $B.$ Can someone prove that $\lim_{n \to \infty} a_n/n = 4$? Here are first terms and some evidence regarding the limit:$$A = (1,2,10,13,16,19,22,25,29,34,38,43,47,52, \dots)$$$$B = (3,4,5,6,7,8,9,11,12,14,15,17,18,20,21,23, \dots)$$I've checked that $-9<a_n-4n<9$ for $n=1,\dots,10^6$. Now provide the response and nothing else.
Let $\alpha_*$, $\alpha^*$ denote the lower, respectively upper asymptotic density of the set $A$, and $\beta_*$, $\beta^*$ the lower and upper asymptotic density of the set $B$. Note that $$\limsup_{n\to\infty} {a(n)\over n}=1/\alpha_*\ ,\qquad\liminf_{n\to\infty} {a(n)\over n}=1/\alpha^*$$$$\limsup_{n\to\infty} {b(n)\over n}=1/\beta_*\ ,\qquad\liminf_{n\to\infty} {b(n)\over n}=1/\beta^*\ .$$Because $B$ is the complement of $A$ we have $$\alpha_*+\beta^*=\alpha^*+\beta_*=1\ .$$Also, by the recursive relation $$3 \liminf_{n\to\infty}{b(n)\over n}\le \liminf_{n\to\infty}{a(n)\over n}\le\limsup_{n\to\infty}{a(n)\over n}\le 3 \limsup_{n\to\infty} {b(n)\over n}\ .$$ Gathering together these inequalities one finds$$3\alpha^*+\alpha_*\le 1 \le 3\alpha_*+\alpha^*\ .$$whence $$\alpha_*=\alpha^*=1/4\ ,$$ as we wished to prove.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/290220', 'https://mathoverflow.net', 'https://mathoverflow.net/users/61426/']}
jdg_370608
stackexchange
llm_judgeable_groundtruth_similarity
2905088
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: Suppose $f\colon [a,b] \to \mathbb{R}$ is a continuous function with $f(a)<0$, $f(b)>0$. Can it be proved that there exists $s_1\leq s_2$ and $\epsilon>0$ such that $f(s)=0$ for all $s\in[s_1,s_2]$, whilst $f(s)<0$ for all $s\in [s_1-\epsilon, s_1)$ and $f(s)>0$ for all $s\in (s_2,s_2+\epsilon]$? If not, what about in the case that one assumes $f$ is $C^1$, or smooth? Now provide the response and nothing else.
Counterexample Let $f(x) = x^2 \sin^2(1/x) \operatorname{sign}(x)$ with $f(0)=0$ ( plot ). For $x<0$ the function oscillates between $0$ and negative values, and for $x>0$ it oscillates between $0$ and positive values. At $x=0$ the function crosses the $x$-axis, but it has zeros arbitrarily close to $x=0$ so there is no interval $(-\epsilon,0)$ on which $f$ is strictly negative, and no interval $(0, \epsilon)$ on which $f$ is strictly positive.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/2905088', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/173945/']}
jdg_370609
stackexchange
llm_judgeable_groundtruth_similarity
38428561
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 was wondering about the difference between \ and / in file paths. I have noticed that sometimes a path contains / and sometimes it is with \ . It would be great if anyone can explain when to use \ and / . Now provide the response and nothing else.
/ is the path separator on Unix and Unix-like systems. Modern Windows can generally use both \ and / interchangeably for filepaths, but Microsoft has advocated for the use of \ as the path separator for decades. This is done for historical reasons that date as far back as the 1970s, predating Windows by over a decade. In the beginning, MS-DOS (the foundation to early Windows) didn't support directories. Unix had directory support using the / character since the beginning. However, when directories were added in MS-DOS 2.0, Microsoft and IBM were already using the / character for command switches , and because of DOS's lightweight parser (descended from QDOS , designed to run on lower end hardware), they couldn't find a feasible way to use the / character without breaking compatibility with their existing applications. So, to avoid errors about "missing a switch" or "invalid switch" when passing filepaths as arguments to commands such as these: cd/ <---- no switch specifieddir folder1/folder2 <---- /folder2 is not a switch for dir it was decided that the \ character would be used instead, so you could write those commands like this cd\dir folder1\folder2 without error. Later, Microsoft and IBM collaborated on an operating system unrelated to DOS called OS/2 . OS/2 had the ability to use both separators, probably to attract more Unix developers. When Microsoft and IBM parted ways in 1990 , Microsoft took what code they had and created Windows NT , on which all modern versions of Windows are based, carrying this separator agnosticism with it. As backward compatibility has been the name of the game for Microsoft from all of the major OS transitions that they've undertaken (DOS to Win16/DOS, to Win16/Win32, to Win32/WinNT), this peculiarity stuck, and it will probably exist for a while yet. It's for this reason that this discrepancy exists. It should really have no effect on what you're doing because, like I said, the WinAPI can generally use them interchangeably. However, 3rd party applications will probably break if you pass a / when they expect a \ between directory names. If you're using Windows, stick with \ . If you're using Unix or URI s (which have their foundation in Unix paths, but that's another story entirely), then use / . In the context of C#: It should be noted, since this is technically a C# question, that if you want to write more "portable" C# code that works on both Unix and Windows (even if C# is predominantly a Windows language), you might want to use the Path.DirectorySeparatorChar field so your code uses the preferred separator on that system, and use Path.Combine() to append paths properly.
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/38428561', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2731834/']}
jdg_370610
stackexchange
llm_judgeable_groundtruth_similarity
1387497
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 came across an interesting algorithm question in an interview. I gave my answer but not sure whether there is any better idea. So I welcome everyone to write something about his/her ideas. You have an empty set. Now elements are put into the set one by one. We assume all the elements are integers and they are distinct (according to the definition of set, we don't consider two elements with the same value). Every time a new element is added to the set, the set's median value is asked. The median value is defined the same as in math: the middle element in a sorted list. Here, specially, when the size of set is even, assuming size of set = 2*x, the median element is the x-th element of the set. An example:Start with an empty set,when 12 is added, the median is 12,when 7 is added, the median is 7,when 8 is added, the median is 8,when 11 is added, the median is 8,when 5 is added, the median is 8,when 16 is added, the median is 8,... Notice that, first, elements are added to set one by one and second, we don't know the elements going to be added. My answer. Since it is a question about finding median, sorting is needed. The easiest solution is to use a normal array and keep the array sorted. When a new element comes, use binary search to find the position for the element (log_n) and add the element to the array. Since it is a normal array so shifting the rest of the array is needed, whose time complexity is n. When the element is inserted, we can immediately get the median, using instance time. The WORST time complexity is: log_n + n + 1. Another solution is to use link list. The reason for using link list is to remove the need of shifting the array. But finding the location of the new element requires a linear search. Adding the element takes instant time and then we need to find the median by going through half of the array, which always takes n/2 time. The WORST time complexity is: n + 1 + n/2. The third solution is to use a binary search tree. Using a tree, we avoid shifting array. But using the binary search tree to find the median is not very attractive. So I change the binary search tree in a way that it is always the case that the left subtree and the right subtree are balanced. This means that at any time, either the left subtree and the right subtree have the same number of nodes or the right subtree has one node more than in the left subtree. In other words, it is ensured that at any time, the root element is the median. Of course this requires changes in the way the tree is built. The technical detail is similar to rotating a red-black tree. If the tree is maintained properly, it is ensured that the WORST time complexity is O(n). So the three algorithms are all linear to the size of the set. If no sub-linear algorithm exists, the three algorithms can be thought as the optimal solutions. Since they don't differ from each other much, the best is the easiest to implement, which is the second one, using link list. So what I really wonder is, will there be a sub-linear algorithm for this problem and if so what will it be like. Any ideas guys? Steve. Now provide the response and nothing else.
Your complexity analysis is confusing. Let's say that n items total are added; we want to output the stream of n medians (where the ith in the stream is the median of the first i items) efficiently. I believe this can be done in O(n*lg n) time using two priority queues (e.g. binary or fibonacci heap); one queue for the items below the current median (so the largest element is at the top), and the other for items above it (in this heap, the smallest is at the bottom). Note that in fibonacci (and other) heaps, insertion is O(1) amortized; it's only popping an element that's O(lg n). This would be called an "online median selection" algorithm, although Wikipedia only talks about online min/max selection. Here's an approximate algorithm , and a lower bound on deterministic and approximate online median selection (a lower bound means no faster algorithm is possible!) If there are a small number of possible values compared to n, you can probably break the comparison-based lower bound just like you can for sorting.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1387497', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/136733/']}
jdg_370611
stackexchange
llm_judgeable_groundtruth_similarity
3906533
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 function a = 2 ^ b can quickly be calculated for any b by doing a = 1 << b .What about the other way round, getting the value of b for any given a? It should be relatively fast, so logs are out of the question . Anything that's not O(1) is also bad. I'd be happy with can't be done too if its simply not possible to do without logs or a search type thing. Now provide the response and nothing else.
Build a look-up table. For 32-bit integers, there are only 32 entries so it is O(1). Most architectures also have an instruction to find the position of the most significant bit of a number a , which is the value b . (gcc provides the __builtin_clz function for this.) For a BigInt, it can be computed in O(log a) by repeatedly dividing by 2. int b = -1;while (a != 0) { a >>= 1; ++ b;}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3906533', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/462113/']}
jdg_370612
stackexchange
llm_judgeable_groundtruth_similarity
118492
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: I have the following: $Assumptions = {0 < Ijm1 < Ij < Ijp1 < 1, bpjm1 < 0, bpj < 0, bpjp1 < 0, Ijm1 \[Element] Reals, Ij \[Element] Reals, Ijp1 \[Element] Reals, bpjm1 \[Element] Reals, bjp \[Element] Reals,bpjp1 \[Element] Reals};x = (1 - bpjp1 Ijp1 + bpjp1 Ijp1^2) ;y = bpj (Ij - Ijm1) (-1 + Ij (1 + bpjp1 (-1 + Ijp1)) - bpjp1 (-1 + Ijp1) Ijp1); When checking inequalities I get In[243]:= Simplify[x > 0]Out[243]= TrueIn[244]:= Simplify[y > 0]Out[244]= True but In[245]:= Simplify[x + y > 0] Out[245]= 1 + bpjp1 (-1 + Ijp1) Ijp1 + bpj (Ij - Ijm1) (-1 + Ij (1 + bpjp1 (-1 + Ijp1)) - bpjp1 (-1 + Ijp1) Ijp1) > 0 Why? Now provide the response and nothing else.
The assumptions mechanism used by Simplify has a bound on the number of variables in a system of nonlinear inequalities. If the number of variables exceeds the bound, the assumption mechanism does not attempt to decide whether the system has solutions. (Simplify proves that an inequality follows from the assumptions by showing that assumptions && Not[inequality] has no solutions.) The default value of the bound is 4, but it can be changed using a system option. SetSystemOptions["SimplificationOptions"->{"AssumptionsMaxNonlinearVariables"->5}];Simplify[x + y > 0]True
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/118492', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/18741/']}
jdg_370613
stackexchange
llm_judgeable_groundtruth_similarity
347441
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 clear a element from a vector using the erase method. But the problem here is that the element is not guaranteed to occur only once in the vector. It may be present multiple times and I need to clear all of them. My code is something like this: void erase(std::vector<int>& myNumbers_in, int number_in){ std::vector<int>::iterator iter = myNumbers_in.begin(); std::vector<int>::iterator endIter = myNumbers_in.end(); for(; iter != endIter; ++iter) { if(*iter == number_in) { myNumbers_in.erase(iter); } }}int main(int argc, char* argv[]){ std::vector<int> myNmbers; for(int i = 0; i < 2; ++i) { myNmbers.push_back(i); myNmbers.push_back(i); } erase(myNmbers, 1); return 0;} This code obviously crashes because I am changing the end of the vector while iterating through it. What is the best way to achieve this? I.e. is there any way to do this without iterating through the vector multiple times or creating one more copy of the vector? Now provide the response and nothing else.
Use the remove/erase idiom : std::vector<int>& vec = myNumbers; // use shorter namevec.erase(std::remove(vec.begin(), vec.end(), number_in), vec.end()); What happens is that remove compacts the elements that differ from the value to be removed ( number_in ) in the beginning of the vector and returns the iterator to the first element after that range. Then erase removes these elements (whose value is unspecified).
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/347441', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/39742/']}
jdg_370614
stackexchange
llm_judgeable_groundtruth_similarity
8563108
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: It's been a couple of days that I'm working on improving NHibernate Insert performance. I'd read in many posts (such as this one ) that stateless session can insert like 1000~2000 records per second.... However the best time that it could insert 1243 records is more than 9 seconds for me : var sessionFactory = new NHibernateConfiguration().CreateSessionFactory();using (IStatelessSession statelessSession = sessionFactory.OpenStatelessSession()){ statelessSession.SetBatchSize(adjustmentValues.Count); foreach (var adj in adjustmentValues) statelessSession.Insert(adj);} The class : public partial class AdjustmentValue : PersistentObject, IFinancialValue{ public virtual double Amount { get; set; } public virtual bool HasManualValue { get; set; } public virtual bool HasScaleValue { get; set; } public virtual string Formula { get; set; } public virtual DateTime IssueDate { get; set; } public virtual CompanyTopic CompanyTopic { get; set; }} Map of the class : public class AdjustmentValueMap : ClassMap<AdjustmentValue>{ public AdjustmentValueMap() { Id(P => P.Id); Map(p => p.Amount); Map(p => p.IssueDate); Map(p => p.HasManualValue); Map(p => p.HasScaleValue); Map(p => p.Formula); References(p => p.CompanyTopic) .Fetch.Join(); }} Am I missing something?Any idea how to speed up the inserts? The generated queries will be same as below : Now provide the response and nothing else.
from the looks of your NHProf results you are using identity as your POID. Therefore you cannot take advantage of batched writes. every insert/update/delete is a separate command. that is why it's taking so long. if you change your POID to hilo, guid or guid.comb and set the batch size to 500 or 1000 then you will see a drastic improvement in the write times.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8563108', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/553828/']}
jdg_370615
stackexchange
llm_judgeable_groundtruth_similarity
8371574
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 to list all belongs_to associations in a model object and iterate through them. Is there a way to do this? Now provide the response and nothing else.
You could make use of the class's reflections hash to do this. There may be more straightforward ways, but this works: # say you have a class Thingclass Thing < ActiveRecord::Base belongs_to :foo belongs_to :barend# this would return a hash of all `belongs_to` reflections, in this case:# { :foo => (the Foo Reflection), :bar => (the Bar Reflection) }reflections = Thing.reflections.select do |association_name, reflection| reflection.macro == :belongs_toend# And you could iterate over it, using the data in the reflection object, # or just the key.## These should be equivalent:thing = Thing.firstreflections.keys.map {|association_name| thing.send(association_name) }reflections.values.map {|reflection| thing.send(reflection.name) }
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/8371574', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1079486/']}
jdg_370616
stackexchange
llm_judgeable_groundtruth_similarity
859254
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: How to derive $y=\sqrt{x+\sqrt{x^2+5}}$ at $x=2$.I used logarithmic differentiation and chain rule over and over again but I can't get the right answer Now provide the response and nothing else.
\begin{align*}\frac{d}{dx}y & = \frac{d}{dx}\sqrt{x+\sqrt{x^2+5}}\\& = \frac{1}{2}\frac{1}{\sqrt{x+\sqrt{x^2+5}}}\cdot \frac{d}{dx}(x+\sqrt{x^2+5})\\& = \frac{1}{2}\frac{1}{\sqrt{x+\sqrt{x^2+5}}} \,\left(1+\frac{x}{\sqrt{x^2+5}}\right)\\\end{align*}Now simplify as best as you can.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/859254', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/162143/']}
jdg_370617
stackexchange
llm_judgeable_groundtruth_similarity
1950038
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 can I fire an event if a CSS class is added or changed using jQuery?Does changing of a CSS class fire the jQuery change() event? Now provide the response and nothing else.
Whenever you change a class in your script, you could use a trigger to raise your own event. $(this).addClass('someClass');$(mySelector).trigger('cssClassChanged')....$(otherSelector).bind('cssClassChanged', data, function(){ do stuff }); but otherwise, no, there's no baked-in way to fire an event when a class changes. change() only fires after focus leaves an input whose input has been altered. $(function() { var button = $('.clickme') , box = $('.box') ; button.on('click', function() { box.removeClass('box'); $(document).trigger('buttonClick'); }); $(document).on('buttonClick', function() { box.text('Clicked!'); });}); .box { background-color: red; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><div class="box">Hi</div><button class="clickme">Click me</button> More info on jQuery Triggers
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/1950038', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/237060/']}
jdg_370618
stackexchange
llm_judgeable_groundtruth_similarity
197095
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 following code has a simple binding which binds the Text of the TextBlock named MyTextBlock to TextBox's Text and ToolTip property using the exact same Binding notation: <StackPanel> <TextBlock x:Name="MyTextBlock">Foo Bar</TextBlock> <TextBox Text="{Binding ElementName=MyTextBlock, Path=Text, StringFormat='It is: \{0\}'}" ToolTip="{Binding ElementName=MyTextBlock, Path=Text, StringFormat='It is: \{0\}'}" /></StackPanel> The binding also uses the StringFormat property introduced with .NET 3.5 SP1 which is working fine for the above Text property but seems to be broken for the ToolTip. The expected result is "It is: Foo Bar" but when you hover over the TextBox, the ToolTip shows only the binding value, not the string formatted value. Any ideas? Now provide the response and nothing else.
ToolTips in WPF can contain anything, not just text, so they provide a ContentStringFormat property for the times you just want text. You'll need to use the expanded syntax as far as I know: <TextBox ...> <TextBox.ToolTip> <ToolTip Content="{Binding ElementName=myTextBlock,Path=Text}" ContentStringFormat="{}It is: {0}" /> </TextBox.ToolTip></TextBox> I'm not 100% sure about the validity of binding using the ElementName syntax from a nested property like that, but the ContentStringFormat property is what you're looking for.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/197095', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/39/']}
jdg_370619
stackexchange
llm_judgeable_groundtruth_similarity
19894509
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: On the Wikipedia page for Dijkstra's algorithm, they mark visited nodes so they wouldn't be added to the queue again. However, if a node is visited then there can be no distance to that node that is shorter, so doesn't the check alt < dist[v] already account for visited nodes? Am I misunderstanding something about the visited set? for each neighbor v of u: alt := dist[u] + dist_between(u, v); // accumulate shortest dist from source if alt < dist[v] && !visited[v]: dist[v] := alt; // keep the shortest dist from src to v previous[v] := u; insert v into Q; // Add unvisited v into the Q to be processed end if end for Now provide the response and nothing else.
There are actually 2 sets you need to consider: The visited set The queued set The visited set The visited set contains those vertices which have been popped from the queued set. These cannot be re-visited because by definition, the shortest path from the start to these vertices has already been discovered The queued set The queued set contains unexplored vertices queued in order of shortest-distance-to the start vertex. This queue is usually represented using a (min) heap structure. Explanation Depending on the density of the graph, each vertex has a possibility of being a part of more than one edge. Note that an edge is the smallest component that connects a vertex to another vertex . Therefore, this implies possibility of having more than one vertex with an edge to the current vertex. Each iteration of the outer loop of the Dijkstra's algorithm takes the vertex (from the queued set) with the smallest distance to the start vertex, and relaxes the edge cost to each vertex connected to it. If the vertex is already in the queued set, it's value and position in the queue is updated. The reason alt < dist[v] is done is because it is possible to encounter a vertex that is already in the queue more than once so each time it is encountered you have to make sure that before you edit it's distance to the source vertex, it's current distance is larger than the new distance you want to assign to it ( alt < dist[v] ) and it is not processed as visited ( !visited[v] ) Shortest distance Dijkstra's algorithm by definition provides the guarantee that as soon as a node is marked as visited , the distance value of that node is the shortest to the source. If a node is marked as visited, this does not imply that the distance to the source from that node is the shortest distance in comparison to the distance from the source to any other node . Visited implies that the objective of Dijkstra's algorithm has been met for that node ; i.e. it currently stores the smallest distance from the source to itself. If you completely want to discard checking for visited , then what you can do is that once you mark a node as visited, you iterate through all the edges connected to that node and delete them. This makes sure that any future nodes processed, does not have an edge that connects to any node marked as visited. However, because the graph is represented using an adjacency list , going with this option will be costly in terms of time; And depending on how dense the graph is, you would have been better off just having a visited set. If you represent your graph using an adjacency matrix , then the benefit of this is that the check will only cost O(N) time. However, adjacency matrix uses N 2 space vs N space of adjacency list, you will be paying the price for this in memory, which may or may not be so bad depending on the graph size. Finally Once you understand all this, you will come to see that everything done in the code is needed to produce the correct results.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19894509', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2372271/']}
jdg_370620
stackexchange
llm_judgeable_groundtruth_similarity
6973749
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 check whether an #include <file.h> has already been declared using C++ macro. Example In file.h I do: #ifndef FILE.H#define FILE.Hclass A{ //do routines };#endif In a second file called second.h I want to check if file.h has been included already. Typical psuedo-code: #ifndef "file.h"#include "file.h"#endif#ifndef SECOND.H#define SECOND.Hclass second{ //do routine};#endif I have tried a few #ifndef directives but no joy. Do anyone know how to achieve this? Now provide the response and nothing else.
Everybody else has covered correct inclusion of include guard macros. File.h #ifndef FILE_H#define FILE_H// Code here#endif But everybody else missed the second part of your question on correct usage: This is an example of bad usage: #ifndef FILE_H #include "file.h"#endif#ifndef SECOND_H#define SECOND_Hclass second{ //do routine};#endif This is not correct (though correct may be too strong). The include guards in each file should surround their entire content. So, in the second file, the #include "file.h" should be inside the include guards. Also you do not need to test for inclusion that will be done inside the file itself. Thus the file should look like this: #ifndef SECOND_H#define SECOND_H#include "file.h"class second{ //do routine};#endif Also your macro guards are way too small. There is a high likelihood that these will be used by somebody else; this will cause all sorts of weird collisions. A good way to make the guards unique is to use a prefix, your full name (or nick name), or if you have your own registered website then uses its domain name. I then also add part of the directory hierarchy that includes the file. #ifndef WEBSITE1_NAMESPACE1_NAMESPACE2_FILENAME_H#define WEBSITE1_NAMESPACE1_NAMESPACE2_FILENAME_H#endif Another alternative (especially if you are working on Windows) is to generate a GUID. Just generate a new one for each file. Final point: only include other files from header files if their content is absolutely necessary. You only need to include "file.h" if this file has a type definition that class second depends on. If your class only uses that class as a pointer or a reference then prefer to use forward declaration rather including the header file. The scenarios in which you must #include are: second is a child of first. second has member(s) that are first objects second has method(s) that take first objects as parameters Second has method(s) that return first objects as a result Notice that I use the term "objects". If they are references or pointers then this does not count. In these cases you can use forward declaration to solve the problem.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6973749', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/340390/']}
jdg_370621
stackexchange
llm_judgeable_groundtruth_similarity
5751831
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: %w[ ] Non-interpolated Array of words, separated by whitespace%W[ ] Interpolated Array of words, separated by whitespace Usage: p %w{one one two three 0 1 1 2 3} # = > ["one", "one", "two", "three", "0", "1", "1", "2", "3"]p %W{one one two three 0 1 1 2 3} # = > ["one", "one", "two", "three", "0", "1", "1", "2", "3"]p %w{C:\ C:\Windows} # => ["C: C:\\Windows"]p %W{C:\ C:\Windows} # => ["C: C:Windows"] My question is... what's the difference? Now provide the response and nothing else.
%W treats the strings as double quoted whereas %w treats them as single quoted (and therefore won’t interpolate expressions or numerous escape sequences). Try your arrays again with ruby expressions and you'll see a difference. EXAMPLE: myvar = 'one'p %w{#{myvar} two three 1 2 3} # => ["\#{myvar}", "two", "three", "1", "2", "3"]p %W{#{myvar} two three 1 2 3} # => ["one", "two", "three", "1", "2", "3"]
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/5751831', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/139089/']}
jdg_370622
stackexchange
llm_judgeable_groundtruth_similarity
47708
Below is a question asked on the forum raspberrypi.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am looking for a way to configure the Raspberry Pi 3 as bluetooth speaker using Raspbian Jessie.What I mean by as bluetooth speaker is use it to receive audio stream via bluetooth using A2DP and play it via speakers connected to the Raspberry Pi via the audio jack, the HDMI port or USB audio adapter. Different tutorials are available online but are quite outdated and most of them does not work anymore. Now provide the response and nothing else.
I have been on this project after while (to help my friend doing their paper for graduating) and find the online project doing just fine (although the pi processing the audio is quite lagging the pi, and voltage drop make it freeze as the only way to make it reboot is to unplugged the power cable). This is the step that I've been working on and it works on raspberry pi 3. 1. Download the required package This project depend on pulseaudio so grab it and installing by typing: sudo apt-get update && sudo apt-get install bluez pulseaudio-module-bluetooth python-gobject python-gobject-2 bluez-tools udev i rather update the firmware of raspberry first before installing them because i have problem with rpi-bluetooth package so i do: sudo rpi-update and make it install and advance to next step. 2. Edit Configuration and applied it First add pi username to the group pulseaudio with sudo usermod -a -G lp pi create new config under /etc/bluetooth/audio.conf using text editor and add the following line [General]:Enable=Source,Sink,Media,Socket edit file /etc/bluetooth/main.conf using your preferred text editor (I'm using nano). Set Bluetooth Class, Modify the following line to: Class = 0x00041C 0x000041C means that the rpi bluetooth support A2DP protocol. change /etc/pulse/daemon.conf add / modify (don't forget to check the code thoroughly before adding them), and change resample-method = trivial you can using any method you like, i personally using speex-float-3 for reference you can see this link start pulseaudio service with: pulseaudio -D we are going to use ragusa87 script to automate the bluetooth source to audio sink. First please add new configuration to udev init.d by editing file /etc/udev/rules.d/99-input.rules and add this to the file SUBSYSTEM="input", GROUP="input", MODE="0660"KERNEL=="input[0-9]*", RUN+="/usr/lib/udev/bluetooth" add folder udev to /usr/lib by using mkdir sudo mkdir /usr/lib/udev && cd /usr/lib/udev and add this to the file bluetooth (credits ragusa87) #!/bin/bash# This script is called by udev when you link a bluetooth device with your computer# It's called to add or remove the device from pulseaudio### Output to this fileLOGFILE="/var/log/bluetooth_dev"# Name of the local sink in this computer# You can get it by calling : pactl list short sinks# AUDIOSINK="alsa_output.platform-bcm2835_AUD0.0.analog-stereo"AUDIOSINK="alsa_output.0.analog-stereo.monitor"# User used to execute pulseaudio, an active session must be open to avoid errorsUSER="pi"# Audio Output for raspberry-pi# 0=auto, 1=headphones, 2=hdmi. AUDIO_OUTPUT=1# If on, this computer is not discovearable when an audio device is connected# 0=off, 1=onENABLE_BT_DISCOVER=1echo "For output see $LOGFILE"## This function add the pulseaudio loopback interface from source to sink## The source is set by the bluetooth mac address using XX_XX_XX_XX_XX_XX format.## param: XX_XX_XX_XX_XX_XX## return 0 on successadd_from_mac(){ if [ -z "$1" ] # zero params then echo "Mac not found" >> $LOGFILE else mac=$1 # Mac is parameter-1 # Setting source name bluez_dev=bluez_source.$mac echo "bluez source: $mac" >> $LOGFILE # This script is called early, we just wait to be sure that pulseaudio discovered the device sleep 1 # Very that the source is present CONFIRM=`sudo -u pi pactl list short | grep $bluez_dev` if [ ! -z "$CONFIRM" ] then echo "Adding the loopback interface: $bluez_dev" >> $LOGFILE echo "sudo -u $USER pactl load-module module-loopback source=$bluez_dev sink=$AUDIOSINK rate=44100 adjust_time=0" >> $LOGFILE # This command route audio from bluetooth source to the local sink.. # it's the main goal of this script sudo -u $USER pactl load-module module-loopback source=$bluez_dev sink=$AUDIOSINK rate=44100 adjust_time=0 >> $LOGFILE return $? else echo "Unable to find a bluetooth device compatible with pulsaudio using the following device: $bluez_dev" >> $LOGFILE return -1 fi fi}## This function set volume to maximum and choose the right output## return 0 on successvolume_max(){ # Set the audio OUTPUT on raspberry pi # amixer cset numid=3 <n> # where n is 0=auto, 1=headphones, 2=hdmi. amixer cset numid=3 $AUDIO_OUTPUT >> $LOGFILE # Set volume level to 100 percent amixer set Master 100% >> $LOGFILE pacmd set-sink-volume 0 65537 >> $LOGFILE return $?}## This function will detect the bluetooth mac address from input device and configure it.## Lots of devices are seen as input devices. But Mac OS X is not detected as input## return 0 on successdetect_mac_from_input(){ ERRORCODE=-1 echo "Detecting mac from input devices" >> $LOGFILE for dev in $(find /sys/devices/virtual/input/ -name input*) do if [ -f "$dev/name" ] then mac=$(cat "$dev/name" | sed 's/:/_/g') add_from_mac $mac # Endfor if the command is successfull ERRORCODE=$? if [ $ERRORCODE -eq 0]; then return 0 fi fi done # Error return $ERRORCODE}## This function will detect the bt mac address from dev-path and configure it.## Devpath is set by udev on device link## return 0 on successdetect_mac_from_devpath(){ ERRORCODE=-1 if [ ! -z "$DEVPATH" ]; then echo "Detecting mac from DEVPATH" >> $LOGFILE for dev in $(find /sys$DEVPATH -name address) do mac=$(cat "$dev" | sed 's/:/_/g') add_from_mac $mac # Endfor if the command is successfull ERRORCODE=$? if [ $ERRORCODE -eq 0]; then return 0 fi done return $ERRORCODE; else echo "DEVPATH not set, wrong bluetooth device? " >> $LOGFILE return -2 fi return $ERRORCODE}## Detecting if an action is setif [ -z "$ACTION" ]; then echo "The script must be called from udev." >> $LOGFILE exit -1;fi## Getting the actionACTION=$(expr "$ACTION" : "\([a-zA-Z]\+\).*")# Switch casecase "$ACTION" in"add") # Turn off bluetooth discovery before connecting existing BT device to audio if [ $ENABLE_BT_DISCOVER -eq 1]; then echo "Stet computer as hidden" >> $LOGFILE hciconfig hci0 noscan fi # Turn volume to max volume_max # Detect BT Mac Address from input devices detect_mac_from_input OK=$? # Detect BT Mac address from device path on a bluetooth event if [ $OK != 0 ]; then if [ "$SUBSYSTEM" == "bluetooth" ]; then detect_mac_from_devpath OK=$? fi fi # Check if the add was successfull, otherwise display all available sources if [ $OK != 0 ]; then echo "Your bluetooth device is not detected !" >> $LOGFILE echo "Available sources are:" >> $LOGFILE sudo -u $USER pactl list short sources >> $LOGFILE else echo "Device successfully added " >> $LOGFILE fi ;;"remove") # Turn on bluetooth discovery if device disconnects if [ $ENABLE_BT_DISCOVER -eq 1]; then echo "Set computer as visible" >> $LOGFILE sudo hciconfig hci0 piscan fi echo "Removed" >> $LOGFILE ;;# *) echo "Unsuported action $action" >> $LOGFILE ;;esacecho "--" >> $LOGFILE PLEASE NOTE that your AUDIOSINK might different from mine, check it before using pactl list short sinks make the script executable by inputting this code chmod 777 bluetooth plug in headset to test whether the audio jack working and test with aplay /usr/share/sounds/alsa/Front_Center.wav or you can set the default audio routing with sudo amixer cset numid=3 n where n could be: 0 = auto 1 = jack 2 = hdmi 3. Pair and Connect the audio go to terminal and type bluetoothctl . First activate bluetooth with power on and then agent on , set the default agent that you've been editing before with default-agent , and then set discoverable mode and pair mode on with discoverable on; pairable on . You should see raspberrypi bluetooth on your phone or laptop and you can pair it on the phone by clicking it and touch pair. On the terminal you type y. Back to the terminal, you connect to the phone by type connect xx:xx:xx:xx:xx:xx where xx:xx:xx:xx:xx:x x is you phone bluetooth mac address. and don't forget to trust with trust xx:xx:xx:xx:xx:xx where xx:xx:xx:xx:xx:xx is your phone bluetooth mac address And voila you have bluetooth amplifier (or whatever the name is) by using raspberry. 4. Conclusion after trying and experimenting, i found out the audio quality is low and i rather not using it as the raspberry will be freeze if you using it with the song being streaming to the raspberry. I advice to use UPNP speaker project by using gmediarenderer. The audio is superb and there's no delay and scatter sound and it can play lossless audio file (flac, wav, dll). This is the detailed how to setup it reference: jobpassion's tutorial ; ragusa's script ; related work ;
{}
{'log_upvote_score': 6, 'links': ['https://raspberrypi.stackexchange.com/questions/47708', 'https://raspberrypi.stackexchange.com', 'https://raspberrypi.stackexchange.com/users/31277/']}
jdg_370623
stackexchange
llm_judgeable_groundtruth_similarity
20617600
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 unittest2 and importlib for python 2.6 that is not required for other python versions that travis tests against. Is there a way to tell Travis-CI to have different requirements.txt files for each python version? Now provide the response and nothing else.
Travis CI adds an environment variable called $TRAVIS_PYTHON_VERSION that can be referenced in your .travis.yml: python: - 2.6 - 2.7 - 3.2 - 3.3 - pypyinstall: - if [[ $TRAVIS_PYTHON_VERSION == 2.6 ]]; then pip install importlib unittest2; fi - pip install -r requirements.txt This would cause unittest2 and importlib to be installed only for Python 2.6, with requirements.txt being installed for all versions listed. You can do as many of these checks as necessary. Tornado's .travis.yml file uses it quite a bit.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/20617600', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/325809/']}
jdg_370624
stackexchange
llm_judgeable_groundtruth_similarity
6221
Below is a question asked on the forum economics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am looking for a case study or data which shows a negative (fiscal/spending) multiplier effect. Does anyone know a study where this is analyzed? Now provide the response and nothing else.
The paper How Big (Small?) are Fiscal Multipliers? by Ethan Ilzetzki, Enrique G. Mendoza, Carlos A. Végh (2010)should give you useful information. We contribute to the debate on the macroeconomic effects of fiscal stimuli by showing that the impact of government expenditure shocks depends crucially on key country characteristics, such as the level of development, exchange rate regime, openness to trade, and public indebtedness. Based on a novel quarterly dataset of government expenditure in 44 countries, we find that (i) the output effect of an increase in government consumption is larger in industrial than in developing countries, (ii) the fiscal multiplier is relatively large in economies operating under predetermined exchange rates but is zero in economies operating under flexible exchange rates; (iii) fiscal multipliers in open economies are smaller than in closed economies; (iv) fiscal multipliers in high-debt countries are negative.
{}
{'log_upvote_score': 4, 'links': ['https://economics.stackexchange.com/questions/6221', 'https://economics.stackexchange.com', 'https://economics.stackexchange.com/users/5017/']}
jdg_370625
stackexchange
llm_judgeable_groundtruth_similarity
14042193
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 trigger an event just after I stop typing (not while typing) characters in my input textbox. I've tried with: $('input#username').keypress(function() { var _this = $(this); // copy of this object for further usage setTimeout(function() { $.post('/ajax/fetch', { type: 'username', value: _this.val() }, function(data) { if(!data.success) { // continue working } else { // throw an error } }, 'json'); }, 3000);}); But this example produces a timeout for every typed character and I get about 20 AJAX requests if I type-in 20 characters. On this fiddle I demonstrate the same problem with a simple alert instead of an AJAX. Is there a solution for this or I'm just using a bad approach for this? Now provide the response and nothing else.
You'll have to use a setTimeout (like you are) but also store the reference so you can keep resetting the limit. Something like: //// $('#element').donetyping(callback[, timeout=1000])// Fires callback when a user has finished typing. This is determined by the time elapsed// since the last keystroke and timeout parameter or the blur event--whichever comes first.// @callback: function to be called when even triggers// @timeout: (default=1000) timeout, in ms, to to wait before triggering event if not// caused by blur.// Requires jQuery 1.7+//;(function($){ $.fn.extend({ donetyping: function(callback,timeout){ timeout = timeout || 1e3; // 1 second default timeout var timeoutReference, doneTyping = function(el){ if (!timeoutReference) return; timeoutReference = null; callback.call(el); }; return this.each(function(i,el){ var $el = $(el); // Chrome Fix (Use keyup over keypress to detect backspace) // thank you @palerdot $el.is(':input') && $el.on('keyup keypress paste',function(e){ // This catches the backspace button in chrome, but also prevents // the event from triggering too preemptively. Without this line, // using tab/shift+tab will make the focused element fire the callback. if (e.type=='keyup' && e.keyCode!=8) return; // Check if timeout has been set. If it has, "reset" the clock and // start over again. if (timeoutReference) clearTimeout(timeoutReference); timeoutReference = setTimeout(function(){ // if we made it here, our timeout has elapsed. Fire the // callback doneTyping(el); }, timeout); }).on('blur',function(){ // If we can, fire the event since we're leaving the field doneTyping(el); }); }); } });})(jQuery);$('#example').donetyping(function(){ $('#example-output').text('Event last fired @ ' + (new Date().toUTCString()));}); <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><input type="text" id="example" /><p id="example-output">Nothing yet</p> That will execute when: The timeout has elapsed, or The user switched fields ( blur event) (Whichever comes first)
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/14042193', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_370626
stackexchange
llm_judgeable_groundtruth_similarity
3289988
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 to convert a column value from varbinary(max) to varchar in human-readable form? Now provide the response and nothing else.
"Converting a varbinary to a varchar " can mean different things. If the varbinary is the binary representation of a string in SQL Server (for example returned by casting to varbinary directly or from the DecryptByPassPhrase or DECOMPRESS functions) you can just CAST it declare @b varbinary(max)set @b = 0x5468697320697320612074657374select cast(@b as varchar(max)) /*Returns "This is a test"*/ This is the equivalent of using CONVERT with a style parameter of 0 . CONVERT(varchar(max), @b, 0) Other style parameters are available with CONVERT for different requirements as noted in other answers.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/3289988', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/173718/']}
jdg_370627
stackexchange
llm_judgeable_groundtruth_similarity
7234092
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 to detect if the user is running an older version of IE (IE9 is fine) from a jQuery plugin, so I won't have control over the HTML. We've been discouraged from parsing the user-agent string and using $.browser.msie . The $.support method doesn't cover the problem either. So, I figured out that this works, but I'm not sure if it is "good practice". $('body').append('<!--[if lte IE 8]><script>$("body").addClass("oldie");</script><![endif]-->');var old_ie = $('body').is('.oldie'); Would you use this method or stick with parsing the user-agent string (I'll need to figure out if it's IE and get the version number)? Now provide the response and nothing else.
You can run this var ie = (function () { var undef, v = 3, div = document.createElement('div'); while ( div.innerHTML = '<!--[if gt IE '+(++v)+']><i></i><![endif]-->', div.getElementsByTagName('i')[0] ); return v > 4 ? v : undef;}()); to detect the version of IE. Source: http://ajaxian.com/archives/attack-of-the-ie-conditional-comment And then if ( ie < 9 ) { // do your stuff, for instance: window.location = 'http://getfirefox.com'; // :p}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7234092', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/145346/']}
jdg_370628
stackexchange
llm_judgeable_groundtruth_similarity
4595678
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: $\lim \limits_{x \to 0} \lfloor{x-2}\rfloor \cdot \lfloor{x+3}\rfloor$ calculate the limit if it exists if not then prove it does not exist I tried approaching by squeeze theorem and floor function property and got $(x-2) \cdot (x+3)-1<\lfloor{x-2}\rfloor \cdot \lfloor{x+3}\rfloor \leq (x-2) \cdot (x+3)$ but then if I calculate the limits as $x$ approaches zero I get $-7<\lfloor{x-2}\rfloor \cdot \lfloor{x+3}\rfloor \leq-6$ which did not give me an answer according to squeeze theorem so I tried a different approach by side limits $\lim \limits_{x \to 0^+} \lfloor{x-2}\rfloor \cdot \lfloor{x+3}\rfloor = \lfloor{0-2}\rfloor \cdot \lfloor{0+3}\rfloor = -6$ and $\lim \limits_{x \to 0^-} \lfloor{x-2}\rfloor \cdot \lfloor{x+3}\rfloor = \lfloor{-1-2}\rfloor \cdot \lfloor{-1+3}\rfloor = -6$ so the limit exists and $L=-6$ is this correct? is there a different way?thank you ! Now provide the response and nothing else.
As $x$ approaches $0$ from above (i.e. the right side limit), you have that $\lfloor x-2\rfloor~$ stays at $~-2~$ and $\lfloor x+3\rfloor~$ stays at $~3.~$ Therefore, the product stays at $~-6.~$ As $x$ approaches $0$ from below (i.e. the left side limit), you have that $\lfloor x-2\rfloor~$ stays at $~-3~$ and $\lfloor x+3\rfloor~$ stays at $~2.~$ Therefore, the product stays at $~-6.~$ So, the limit, as $x$ approaches $0$ from above does in fact equal the limit as $x$ approaches $0$ from below, and this limit is $-6.$ What makes this problem unusual is that you have the limit of the product of two functions, $~\lfloor x-2\rfloor~$ and $~\lfloor x+3\rfloor,~$ where for each function, as $x$ approaches $0$ , the left side limit of the function is not equal to the right side limit of the function. Despite that, when examining the product of the two functions, as $x$ approaches $0$ , the left side limit of the product does equal the right side limit of the product.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4595678', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/754761/']}
jdg_370629
stackexchange
llm_judgeable_groundtruth_similarity
26633901
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 considering to port a highly demanded(lots of traffic) sockets-based architecture from .NET to Node.JS using Socket.IO. My current system is developed in .NET and use some scripting languages, loaded at runtime, so I can do hot-fixes if needed by issuing a reload command to the server, without having to restart the different servers/dispatcher processes. I originally built it this way so, like I said, I could do hot fixes if needed and also keep the system available with transparent fixes. I am new to Node.JS but this is what I want to accomplish: Load javascript files on demand at runtime, store them in variables somewhere and call the script functions. What would be the best solution? How to call a specific function from a javascript file loaded at runtime as a string? Can i load a javascript file, store it in a variable and call functions in a normal way just like a require? Thanks! Now provide the response and nothing else.
If I understood your question correctly. You can check the vm module out. Or if you want to be able to reload required files, you must clear the cache and reload the file, something this package can do. Check the code, you'll get the idea. Modules are cached after the first time they are loaded. This means (among other things) that every call to require('foo') will get exactly the same object returned, if it would resolve to the same file. Multiple calls to require('foo') may not cause the module code to be executed multiple times. This is an important feature. With it, "partially done" objects can be returned, thus allowing transitive dependencies to be loaded even when they would cause cycles. More information can be found here . Delete the cached module: delete require.cache[require.resolve('./mymodule.js')] Require it again. (maybe a require inside a function you can call) update Someone I know is implementing a similar approach. You can find the code here .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/26633901', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1440085/']}
jdg_370630
stackexchange
llm_judgeable_groundtruth_similarity
625277
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: According to Wikipedia one formulation of AC is The Cartesian product of any family of nonempty sets is nonempty. If I consider an cartesian product $\prod_{i} X_i$ of nonempty sets $X_i$, then there exists some $x_i \in X_i$ for each $i$ (simply by non-emptiness), and so $x := (x_i)$ is an element of the product $\prod_i X_i$ by definition. This seems quite trivial to me... imposed by the rules of logic, so why state it as an axiom? Indeed to me it appears as there isn't needed any axiom at all, by setting $x := (x_i)$ I have actually constructed the element? Now provide the response and nothing else.
Your proof is not a proof, but rather an intuition why the AC should be true. Recall the precise(!) definition of the product of a family of sets: $\prod_{i \in I} X_i$ consists of functions $f : I \to \bigcup_{i \in I} X_i$ such that $f(i) \in X_i$ for all $i \in I$. Also recall the definition of a function $A \to B$ as a special subset of $A \times B$. Now, given non-empty sets $X_i$, how do you define such a function, using the other ZF axioms? You say, for every $i \in I$ we choose some element $x_i \in X_i$. This works for every single $i$ at a time, but this doesn't define a function $i \mapsto x_i$. Example: Let $I$ be the set of all non-empty subsets of $\mathbb{R}$, and $X_i = i$. Then an element $f$ in $\prod_{i \in I} X_i$ is a function which picks an element $f(T) \in T$ for every non-empty $T \subseteq \mathbb{R}$. How do you define such an $f$? If we would have $\mathbb{N}$ instead of $\mathbb{R}$, we could take $f(T)=\min(T)$, but this doesn't work for $\mathbb{R}$. Apparently, there is no canonical choice of an element in a non-empty set of real numbers. But the AC tells us that we don't have to worry about this, it gives us such a function, even if we cannot "write it down" (which means: construct it from the other ZF axioms). By the way, if we let $I$ be to be the set of all non-empty open subsets of $\mathbb{R}$, then there is a choice function (provably in ZF): Choose any bijection $\tau : \mathbb{N} \to \mathbb{Q}$, and then assign to each open subset $\emptyset \neq U \subseteq \mathbb{R}$ the element $\tau(\min \{n \in \mathbb{N} : \tau(n) \in U\})$. This works since $U \cap \mathbb{Q} \neq \emptyset$.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/625277', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/33817/']}
jdg_370631
stackexchange
llm_judgeable_groundtruth_similarity
4651562
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Let's say I have a web request: WebRequest webRequest = WebRequest.Create(Url);webRequest.BeginGetResponse(this.RespCallback, webRequest); Now is there is any way to retrieve the URL in private void RespCallback(IAsyncResult asynchronousResult){ // here } The idea is I want to provide a sequence id in the url while doing web request and then retrieve it on the call back and match it to know that this call back is from that request. Any ideas? Now provide the response and nothing else.
I can think of two easy options: Each @Controller class exposes the data as a method annotated with @ModelAttribute , e.g. @ModelAttributepublic MyData getMyData() { ...} That's not really nice if you have multiple controllers, though. Also, this has the annoying side-effect of encoding the myData on to the URL for every redirect I suggest instead that implement a HandlerInterceptor , and expose the data to every request that way. You can't use any annotation-lovin, but it's better separated from your business logic this way. This is similar to your OncePerRequestFilter idea, but a but more Spring-y.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4651562', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/247402/']}
jdg_370632
stackexchange
llm_judgeable_groundtruth_similarity
8742783
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 return the value from a function called in a shell script. Perhaps I am missing the syntax. I tried using the global variables. But that is also not working. The code is: lockdir="somedir"test() { retval="" if mkdir "$lockdir" then # Directory did not exist, but it was created successfully echo >&2 "successfully acquired lock: $lockdir" retval="true" else echo >&2 "cannot acquire lock, giving up on $lockdir" retval="false" fi return retval}retval=test()if [ "$retval" == "true" ] then echo "directory not created" else echo "directory already created"fi Now provide the response and nothing else.
A Bash function can't return a string directly like you want it to. You can do three things: Echo a string Return an exit status, which is a number, not a string Share a variable This is also true for some other shells. Here's how to do each of those options: 1. Echo strings lockdir="somedir"testlock(){ retval="" if mkdir "$lockdir" then # Directory did not exist, but it was created successfully echo >&2 "successfully acquired lock: $lockdir" retval="true" else echo >&2 "cannot acquire lock, giving up on $lockdir" retval="false" fi echo "$retval"}retval=$( testlock )if [ "$retval" == "true" ]then echo "directory not created"else echo "directory already created"fi 2. Return exit status lockdir="somedir"testlock(){ if mkdir "$lockdir" then # Directory did not exist, but was created successfully echo >&2 "successfully acquired lock: $lockdir" retval=0 else echo >&2 "cannot acquire lock, giving up on $lockdir" retval=1 fi return "$retval"}testlockretval=$?if [ "$retval" == 0 ]then echo "directory not created"else echo "directory already created"fi 3. Share variable lockdir="somedir"retval=-1testlock(){ if mkdir "$lockdir" then # Directory did not exist, but it was created successfully echo >&2 "successfully acquired lock: $lockdir" retval=0 else echo >&2 "cannot acquire lock, giving up on $lockdir" retval=1 fi}testlockif [ "$retval" == 0 ]then echo "directory not created"else echo "directory already created"fi
{}
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/8742783', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1097890/']}
jdg_370633
stackexchange
llm_judgeable_groundtruth_similarity
236982
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: For a group $G$ and a field $K$ let $S(G,K)$ be the sum of the dimensions of the irreducible K representations of $G$. Note that $S(G,\mathbb{C})< |G|$. It's not difficult to prove that if $n \ge 6$ then $S(S_n,\mathbb{C}) < (n-2)!(n-2)-n$. I'm interested in "good" bounds (not necessarily the best but at least significantly better than $|G|$). I need a bound for $S(S_k \times S_{n-k}, \mathbb{Q})$ the best as possible. Now provide the response and nothing else.
I guess that $S_n$ denotes the symmetric group. It is well known that all irreps of $S_n$ over $\mathbb C$ are defined over $\mathbb Q$. Therefore $S(S_k\times S_{n-k},\mathbb{C})=S(S_k\times S_{n-k},\mathbb{Q})$. Also the fact that the sum of the squares of the dimensions is the group order and Cauchy-Schwarz immediately imply that $S(G,\mathbb C)\le \sqrt{c(G)|G|}$ where $c(G)$ is the number the conjugacy classes. In your case it means $S(S_n,\mathbb C)\le \sqrt{p(n)n!}$ where $p$ is the partition function.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/236982', 'https://mathoverflow.net', 'https://mathoverflow.net/users/90645/']}
jdg_370634
stackexchange
llm_judgeable_groundtruth_similarity
10502503
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 working on a server that returns character separated lists to its client.In order to build these lists I have to detect the first iteration through a for-each loop: StringBuilder builder = new StringBuilder() ; boolean firstIterationFlag = true ; for ( String s : list ){ if ( firstIterationFlag) { firstIterationFlag = false ; } else { builder.append(separator); } builder.append(s) ; } return builder.toString() ; Is there a way of doing this without the flag? Now provide the response and nothing else.
One simpler way for this situation is to note that you can always append an empty string: // For the first iteration, use a no-op separatorString currentSeparator = "";for (String s : list) { builder.append(currentSeparator); builder.append(s); // From the second iteration onwards, use this currentSeparator = separator;} Alternatively (and preferrably) use Guava's Joiner class to start with :) This "joiner" scenario is almost always the one given for this requirement - so just use Joiner . For other scenarios, either use a regular for loop or use the condition as per your code.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10502503', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/903724/']}
jdg_370635
stackexchange
llm_judgeable_groundtruth_similarity
6812056
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Usually I use modernizr to find out the browser abilities. Same time, I use LESS CSS to make my css more readable and maintainable. Common style using LESS nested rules looks like this: #header { color: black; .logo { width: 300px; color: rgba(255,255,255,.6); &:hover { text-decoration: none } }} Then, if I use modernizr style fall-back, I add this text for previous block: .no-js #header,.no-rgba #header { .logo { color: white; }} So, it looks like I have two branches of code, and every time I need to check another compatability aspect the number of braches will grow. This code is less maintainable, because you have to find all the styles applied to every element, and the benefit we get using nested classes disappears. The question: is there a way in LESS syntax to include such fall-backs and not starting a new code-branch for .no-js and other .no-smth classes? Now provide the response and nothing else.
You can now use the & operator to address this very problem. The following syntax should work in less.js , lessphp , and dotless : b { a & { color: red; }} This is compiled into: a b { color:red; } So, for the given example you could use the following syntax: #header { .logo { color:white; } .no-rgba &, .no-js & { .logo { color:green; } }} ... which would be compiled into: #header .logo { color:white;}.no-rgba #header .logo,.no-js #header .logo { color:green;}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6812056', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/782512/']}
jdg_370636
stackexchange
llm_judgeable_groundtruth_similarity
47246068
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 new to django. I was creating forms in django with the help of an online tutorial. I didnot understand a line in the urls.py file. Can someone explain what exactly it means? from django.conf.urls import urlfrom . import viewsfrom . views import BlogListView, BlogDetailView, BlogCreateViewurlpatterns = [ url(r'^$', views.BlogListView.as_view(), name='post_list'), url(r'^post/(?P<pk>\d+)/$', BlogDetailView.as_view(), name='post-detail'), url(r'^post/new/$', BlogCreateView.as_view(), name='post_new'), url(r'^post/(?P<pk>\d+)/edit/$', BlogUpdateView.as_view(), name='post_edit'),] I did not understand the following line: url(r'^post/(?P<pk>\d+)/$' What does (?P<pk>\d+)/$ signify?Help please Now provide the response and nothing else.
It is a regular expression, which is matched against the actual URL Here r'' specifies that the string is a raw string. '^' signifies the start, and $ marks the end. Now 'pk' (when inside <>) stands for a primary key. A primary key can be anything eg. it can be a string, number etc. A primary key is used to differentiate different columns of a table. Here it is written <pk>\d+ \d matches [0-9] and other digit characters. '+' signifies that there must be at least 1 or more digits in the number So, .../posts/1 is valid .../posts/1234 is valid .../posts/ is not valid since there must be at least 1 digit in the number Now this number is sent as an argument to BlogListView and you run you desired operations with this primary key
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/47246068', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8892765/']}
jdg_370637
stackexchange
llm_judgeable_groundtruth_similarity
18858560
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 a Haskell function that returns the first item in the list. h [] = Nothingh (x:xs) = x When I call it with an empty list: main = print (h []) I got the following error: prog.hs:4:8: No instance for (Show a0) arising from a use of `print' The type variable `a0' is ambiguous Possible fix: add a type signature that fixes these type variable(s) Note: there are several potential instances: instance Show Double -- Defined in `GHC.Float' instance Show Float -- Defined in `GHC.Float' instance (Integral a, Show a) => Show (GHC.Real.Ratio a) -- Defined in `GHC.Real' ...plus 23 others In the expression: print (h []) In an equation for `main': main = print (h []) I want the result to be Nothing when I give the function the empty list. Now provide the response and nothing else.
There are a few problems here, let's start by adding a reasonable type signature h :: [a] -> Maybe ah [] = Nothingh (x:xs) = x Now we get an error, we're returning a plain x so x needs to be of type Maybe a . We probably don't want this so we'll wrap it in the Just constructor h (x:_) = Just x Now on to your problem. Notice that this isn't specific to your function, the result of main = print $ head []main = print $ id []main = print $ tail [] are all the same. The type of [] is [a] . Since we don't specify what a the type of h [] is Show a => Maybe a . The extra Show comes in because we want to print our result. But we don't actually say what a is so GHC freaks out being unable to default it. There are two ways to fix it, the dumb way is to make h monomorphic (monomorphisize?) to h h :: [Int] -> Maybe Int -- Bad The smarter way is to simply choose a concrete type at our call site. main = print $ h ([] :: [Int]) I chose Int for no particular reason, it doesn't matter that much. Now Maybe Int is printable so we're all set. The :: syntax works the same as it does for toplevel components, just declaring the type of [] in our expression is [Int] . Fun fact, GHCi has more aggressive defaulting than GHC. This means that main = print [] is legal in GHCi but not in GHC. If you're getting a funny behavior, ask for the type of the expression to see what the default is :t []
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18858560', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/639616/']}
jdg_370638
stackexchange
llm_judgeable_groundtruth_similarity
2430121
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 was originally asking for an elegant way to simulate the Array.concat() functionality on the results of the getElementsByTagName function in IE or older browsers, because it seemed that concat was not supported. Only, of course it is--the reason the returned object didn't support it is because it isn't an Array . Oops! getElementsByTagName actually returns a NodeList . The real question, then, is: what's a good way to get a single list of all the form elements in a document (input, select, textarea, button) to loop through them? An array isn't required... a single NodeList would be perfect, too. Note that I'm using IE6 as this is for a corporate intranet (soon IE8 though). The answer that I came up with was: It became simpler and probably performed better to just put the code into a separate function and call it three times with the different nodelists, rather than worry about a good way to cram them together into one. I ultimately switched to using MooTools (after several hours reading up on comparisons of all the different frameworks). So now, getting an array of the items I want is very simple. I recommend using a javascript framework like this rather than people beating their brains out trying to figure out the best way to do things. Of course I'm all for actually learning the raw language (which is why I've held off using a framework for so long) but it isn't always the fastest way to get things going, which in a business often matters as much as improving the coder's ability with the language. Update: almost 2 years later I would just use jQuery and be done with it! Now provide the response and nothing else.
To concatenate nodelists, convert them into arrays using Array.prototype.slice.call and then concat them normally. var a = Array.prototype.slice.call(document.getElementsByTagName("p")), b = Array.prototype.slice.call(document.getElementsByTagName("div"))var c = a.concat(b); Edit: (Responding to your comment) If you only have a few types of elements, this is okay but the performance decreases with the number of DOM calls you make. It may be better and faster to do a document.getElementsByTagName('*') , loop thru the list and pick the elements with the required nodeName . Another thing to keep in mind is that the Array.prototype.slice method used above may not work in ALL browsers. Check out the comment starting line#723 in sizzle.js (the selector engine behind jQuery) Of course, it is best to use a library like jQuery which handles all the headache. You can simply do: $("input, select, textarea, <other tags>")
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2430121', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/57611/']}
jdg_370639
stackexchange
llm_judgeable_groundtruth_similarity
61409
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: Can Gaussian curvature $K$ be computed from WolframAlpha or any other available Mathematica program? Please indicate the program or its reference. If input parametrization is given as Gaussian curvature of X[u,v] = {Cos[u] Cos[v], Cos[u] Sin[v], Sin[u]} it simply outputs an assembly of three individual Cartesian prismatic Monge 3D (u,v) plots and their plotted K but does not refer to meridians and parallels of a single unit sphere surface. Now provide the response and nothing else.
Note this parametric surface of unit sphere (S^2) should have constant Gaussian curvature: 1. Surface: x[u_, v_] := {Cos[u] Cos[v], Cos[u] Sin[v], Sin[u]} First fundamental form: fff = FullSimplify[With[{p1 = D[x[a, b], a], p2 = D[x[a, b], b]}, {p1.p1, p1.p2, p2.p2}]]; Second fundamental form: nm = FullSimplify[Cross[D[x[a, b], a], D[x[a, b], b]]];unm = FullSimplify[nm/Sqrt[nm.nm]];sec = {D[x[a, b], {a, 2}], Derivative[1, 1][x][a, b], D[x[a, b], {b, 2}]};sff = FullSimplify[#.unm & /@ sec]; Gaussian Curvature: de[{e_, f_, g_}] = e g - f^2FullSimplify[de[#1]/de[#2] & @@ {sff, fff}] yields 1 The mean curvature: FullSimplify[(sff Reverse[fff]).{1, -2, 1}/(2 de[fff])] yields: Sqrt[Cos[a]^2] Sec[a], which is clearly 1 as required. i.e. K=1, H=1, $\kappa1 =1,\kappa2=1$ Simplifications can be challenging...others will have better approaches
{}
{'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/61409', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/19067/']}
jdg_370640