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
33682536
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 remove blank spaces from the begining and ending of inputs in general without adding a class or id or event I tried this live demo but is using onchange event <javascript> function trim(el) { el.value = el.value. replace(/(^\s*)|(\s*$)/gi, ""). // removes leading and trailing spaces replace(/[ ]{2,}/gi, " "). // replaces multiple spaces with one space replace(/\n +/, "\n"); // Removes spaces after newlines return; }</script><p>Search1: <input type="text" onchange="return trim(this)" /></p><p>Search2: <input type="text" onchange="return trim(this)" /></p><p>Search3: <input type="text" onchange="return trim(this)" /></p><p>Search4: <input type="text" onchange="return trim(this)" /></p><p>Search5: <input type="text" onchange="return trim(this)" /></p> Somebody can help me about how to make all my inputs trim input values (CSS OR JAVASCRIPT) like this: <script> Here in this script will trim blank spaces starting or ending so don't need to add anything in the input </script> <input type="text" /> I tried this but is not working $(.input).text().trim() Please somebody can help me?. Thanks in advance. Now provide the response and nothing else.
try $.trim on change input with type text:- jQuery $(function(){ $('input[type="text"]').change(function(){ this.value = $.trim(this.value); });}); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><p>Search1: <input type="text"/></p><p>Search2: <input type="text"/></p><p>Search3: <input type="text"/></p><p>Search4: <input type="text"/></p><p>Search5: <input type="text"/></p> Vanilla window.onload = function() { var inputs = document.getElementsByTagName('input'); for (var i = 0; i < inputs.length; i++) { if (inputs[i].type == 'text') { inputs[i].onchange = function() { this.value = this.value.replace(/^\s+/, '').replace(/\s+$/, ''); }; } }} <p>Search1: <input type="text"/></p><p>Search2: <input type="text"/></p><p>Search3: <input type="text"/></p><p>Search4: <input type="text"/></p><p>Search5: <input type="text"/></p>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/33682536', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2847322/']}
jdg_74141
stackexchange
llm_judgeable_groundtruth_similarity
16020
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: Forgive me as I have very little domain knowledge in this area, I'm helping out at my parent's office and was asked to look into speeding up the internet. They've been using this IT guy that I think is ripping them off... They have a T1 line which costs a ton and only provides 3 Up, 3 Down. The IT guy is convinced that it is necessary for the VPN which is used by employees to access documents on the office server when they're out of the office. They also use it to access some applications which run on the server. I understand that this is for reliability but if you don't have a T1 line going to your house, how are you going to see that reliability? Am I missing something about VPNs? Is the T1 necessary at all? I'd think you need T1's from point to point? Why can't we just put a VPN on a normal cable connection? I'm just about to finish my CS degree, but know very little about networking, so be gentle please. Now provide the response and nothing else.
First of all, T1 gives you around 1.5Mbit/s in both directions, not 3Mbit/s. If you're seeing 3Mbit/s, it may be bundled from two separate lines. Now, for VPN, if that's IP-based VPN as 99% of VPNs currently are, of course it doesn't matter if your physical interface is T1, E1, ATM OC-3 or 10GE WAN PHY - it's just used to provide higher-layer connectivity - which for VPNs (IPsec, DTLS or whatever) is usually IP connectivity. As soon as you obtain IP connectivity, you should be able to establish VPN sessions. From the description you provide, that T1 line (or bundled T1 line) is used as a hub for employee remote connectivity. This may mean, that the VPN device has T1 ports built-in and that's why the "IT guy" claims T1 is needed to provide the connectivity, or there are some other constraints. Given the costs of dedicated circuits, I'd rather ask local available ISPs about Ethernet line - be it 10Mbit/s, 100Mbit/s or sub-rate 1GE/full-rate 1GE. You'll get more for less (propably), and still get IP connectivity which is needed for VPN sessions.
{}
{'log_upvote_score': 5, 'links': ['https://networkengineering.stackexchange.com/questions/16020', 'https://networkengineering.stackexchange.com', 'https://networkengineering.stackexchange.com/users/13247/']}
jdg_74142
stackexchange
llm_judgeable_groundtruth_similarity
200574
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: Chirped Pulse Amplification (CPA) is an optics technique, winner of the 2018 Nobel Prize in physics, which is used for producing short laser pulses at intensities which are high enough that the gain medium would destroy itself through nonlinear phenomena if it tried to amplify the pulse directly, by sandwiching the amplifier between a pulse stretcher and a compressor. It is common folklore in optics that the technique was originally developed for amplification of radar signals somewhere in the early reaches of electronics history, and it sort of makes sense that if you have a fragile vacuum-tube amplifier or something, you can swap out the optical diffraction gratings for appropriately dispersive microwave waveguides, or whatever they used in the sixties, and it would do wonders to protect sensitive electronics from frying. To try and go beyond that vague understanding, I tried to have a look at exactly what problems of radar amplification were the target of the original stretch-amplify-compress work (I'm unsure whether the name CPA was already in use during its development, even whether it's really used to describe such systems in an electronics context), what it was used for in electronics when it made the jump to optics in 1985, and more generally what the history of its development is. However, there's a few rough edges I'm not so sure on and I'm hoping this SE is a good place to ask about them. The original CPA paper, Compression of amplified chirped optical pulses. D. Strickland and G. Mourou. Optics Comms. 55 , 447 (1985) . acknowledges that the technique is analogous to solutions then already in use in radar, and it sends the reader to a beginner-friendly review in Phased-array radars. E. Brookner. Scientific American 252 , Feb. 1985, pp. 94-102. . but this is a bit of a bibliographic dead end as it has no references. In particular, I'm struck by the fact that the techniques have significant differences. In optics, we want to have a short pulse and we want to make it strong. This then allows us to investigate nonlinear optical phenomena, which can reach some pretty extreme degrees . This means we need to compress the pulse before we use it to do whatever it is we want to get up to. In Strickland and Brookner's description, on the other hand, it's clear that the electronics only really care about compressing the pulse right before its final analysis, and that the system is perfectly happy with beaming the uncompressed pulse out to interact with whatever planes or 'grapefruit-sized metallic objects' are out there, and doing the compression afterwards. This view is emphasized by a more accessible Rochester report, LLE Review , Quarterly Report, October-December 1985 . Laboratory for Laser Energetics, Rochester, NY. §3B, pp. 42-46 . Trying to go a bit more into detail, I get a bit more confused. Wikipedia refers the interested reader to a review from 1960, after the technology had been declassified, Pulse Compression-Key to More Efficient Radar Transmission. C.E. Cook. Proc. IRE 48 , 310 (1960) . but I am struggling to understand what the issues were that they were trying to solve. From Cook's introduction, In most instances, the demand for increased detection range has not been at the expense of normal tactical requirements for a certain minimum amount of range resolving capability. Faced with this situation, radar tube designers have been forced to concentrate on stepping up the peak powers of their tubes, since the tactical considerations have not permitted extending detection ranges by increasing average power by means of a wider transmitted pulse. As a consequence, in many situations high-powered tubes are being used inefficiently as far as average power is concerned. To compensate for this inefficiency, engineers have developed post-detection integration techniques to extend the radar detection range. These techniques also lead to further inefficiencies as far as the use of total available average power is taken into consideration. It will be the purpose of this paper to study a technique for increasing the average power capability of a pulse radar so that there is neither an increase in peak power nor a degradation of pulse resolution. It is not clear here what 'tactical requirements' are at stake here, and why and how they impact both the pulse width, the average power, and the peak power requirements on the system. The patents by Dicke and Darlington help somewhat in establishing what the problem was, particularly with the references to sparking on the antennas as a limit on the peak power of the radar pulse both inside the amplifier as well as the output elements that come after it. (This is in contrast with the optical CPA case, where the problem is that laser gain media have an intensity threshold above which nonlinear effects like self-focusing and laser filamentation will destroy the gain medium, but it's perfectly fine to shine high-intensity pulses at mirrors or other such 'output' elements.) However, Cook's mention at a later date of specific requirements on both the peak power and the average power makes me suspect that there's more going on here that I'm not seeing clearly. To wrap up this bunch of confusions into some more concrete questions: What specific requirements on the peak and average powers and the widths of radar pulses was chirped-radar designed to overcome? Were these purely 'internal' concerns regarding the electronics, or were there external goals and restrictions that were hard to meet otherwise? Is the name 'chirped pulse amplification' ever used in a radar context? Is the optics-style CPA - stretch, amplify, compress, and then use the pulse - used at all in radar applications, or in broader electronics fields? Now provide the response and nothing else.
I'm not a radar expert by any means, but I think I understand the general concepts well enough to try to answer your questions. What specific requirements on the peak and average powers and the widths of radar pulses was chirped-radar designed to overcome? Were these purely 'internal' concerns regarding the electronics, or were there external goals and restrictions that were hard to meet otherwise? The basic problem in radar is to get both adequate power for total range and good timing resolution for range resolution. It is hard to build high-power amplifiers for microwave frequencies. You want to have a lot of energy in each transmitted pulse, but you also want to keep the pulse short. The solution, as you have found in optics, is to stretch the pulse by chirping it, which allows the power amplifier to operate at a lower power for a longer time in order to get the same pulse energy. Now, in radar, it doesn't matter if you don't compress the pulse again before feeding it to the antenna — the chirped pulse works just as well as the compressed pulse in terms of detecting objects. In fact, you gain additional advantages when the reflections come back, because now you can amplify the chirped signal in the receiver (getting some of the same advantages as in the transmitter amplifier regarding peak-to-average power), and you can use a "matched filter" to compress the pulse just prior to detection, which has the additional advantage of rejecting a lot of potential interference sources as well. The narrow pulses coming out of the receiver filter give you the time resolution you need. Is the name 'chirped pulse amplification' ever used in a radar context? Generally not, because amplification isn't the only reason that chirping is used. Is the optics-style CPA - stretch, amplify, compress, and then use the pulse - used at all in radar applications, or in broader electronics fields? Not to my knowledge, but it would certainly be feasible.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/200574', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/34665/']}
jdg_74143
stackexchange
llm_judgeable_groundtruth_similarity
19103
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 two time series, shown in the plot below: The plot is showing the full detail of both time series, but I can easily reduce it to just the coincident observations if needed. My question is: What statistical methods can I use to assess the differences between the time series? I know this is a fairly broad and vague question, but I can't seem to find much introductory material on this anywhere. As I can see it, there are two distinct things to assess: 1. Are the values the same? 2. Are the trends the same? What sort of statistical tests would you suggest looking at to assess these questions? For question 1 I can obviously assess the means of the different datasets and look for significant differences in distributions, but is there a way of doing this that takes into account the time-series nature of the data? For question 2 - is there something like the Mann-Kendall tests that looks for the similarity between two trends? I could do the Mann-Kendall test for both datasets and compare, but I don't know if that is a valid way to do things, or whether there is a better way? I'm doing all of this in R, so if tests you suggest have a R package then please let me know. Now provide the response and nothing else.
As others have stated, you need to have a common frequency of measurement (i.e. the time between observations). With that in place I would identify a common model that would reasonably describe each series separately. This might be an ARIMA model or a multiply-trended Regression Model with possible Level Shifts or a composite model integrating both memory (ARIMA) and dummy variables. This common model could be estimated globally and separately for each of the two series and then one could construct an F test to test the hypothesis of a common set of parameters.
{}
{'log_upvote_score': 6, 'links': ['https://stats.stackexchange.com/questions/19103', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/261/']}
jdg_74144
stackexchange
llm_judgeable_groundtruth_similarity
30368
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: From my (still quite subjective) point of view, GnuPG/PGP is superior to SSL (or more specifically, PGP/MIME over S/MIME; maybe in other areas SSL is the better choice), e.g. due to the support of subkeys to separate signing and encryption certificates and the Web of Trust instead of having to blindly trust a CA - including the ability to revoke certificates without a CRL or OCSP. But in contrast to S/MIME, PGP (MIME or not) requires some additional user effort, and seamless integration (such as Enigmail in Thunderbird) in Outlook ≥ 2010 (unfortunately widely used in the business world) requires a plugin (the only usable one I found is the Outlook privacy plugin , which does currently only support plain-text PGP). But apart from this usability issue, is there a sensible reason to prefer S/MIME over PGP/MIME? Now provide the response and nothing else.
The main reason to prefer one technology over the other is usability. Regardless of the tools you use, email security will depend mostly on how well the users cooperate -- most of the confidentiality of their emails rests on their ability not to do anything stupid with their data, and to react appropriately in unusual conditions. You will get decent security only if the tools they use are available, easy to use and reliable. Therefore, it is difficult to compare S/MIME and OpenPGP in abstracto . However, we can still make some distinctions on the PKI model . S/MIME relies on X.509 , a behemoth of a standard which is meant to support a hierarchical PKI with controlled trust delegation from a limited set of trust anchors and down short paths. OpenPGP uses a Web of Trust which is decentralized. Your expression "blindly trust a CA" says a lot on your own preferences, but is quite subjective. If you look at how X.509 and OpenPGP operate, you will see that in the Web of Trust, everybody is a CA; hence, while in X.509 you put your trust into a handful of CA, in the Web of Trust you put your trust in... everybody ? That's because most people forget half of the WoT system. In a true WoT, the graph of certification (i.e. who signs the key of who) should be overconnected. When you want to validate the public key of someone (let's call him Bob), then you need to find certification paths which lead from you to Bob; such a path begins by your public key (which you know "absolutely") and each step is a signature computed over the public key of the next individual in the path. Security in the WoT model comes from the verification of many paths which all begin by you and end on Bob, but with no other individual being common to any two paths. When everybody can act as a CA, any single path is "potentially suspect": when people sign other people's keys late at night and under the auspices of heavy alcohol drinking, you cannot expect all paths to be 100% reliable. An attacker intent on forging a fake key for Bob will just have to find a few gullible or intoxicated individuals. The WoT credo is that "the crowd is right": an attacker may subvert some people, but not most of them. Thus, if you can find many valid paths which lead to Bob, then Bob's key is probably genuine, because bribing or deceiving that many people would have been "probably too hard". Bottom-line is that the Web of Trust is hard . The description above uses the fuzzy terms "few", "many", "most" and "probably". We do not know how to estimate the number of paths which must be built in order to achieve a given level of security; in fact, we do not know how to quantify a "security level". It is unclear whether WoT can work at all. OpenPGP implementations tend to use a "reliability percentage" which is a totally unsubstantiated guesswork. Of course, in practice, nobody spends time to rebuild many chains; you are already lucky if you find one chain. When I must exchange confidential data with customers , I use OpenPGP -- but not the Web of Trust. I use OpenPGP because the usual implementations have the ability to bind keys to indentity permanently: if I can make sure once that the key is genuine, then my software will remember it and things will be safe thereafter. So the customer and I exchange the key fingerprints when we meet in person, or over a phone call (which we assume to be safe from impersonations -- eavesdropping is not an issue here). Such binding is not supported by S/MIME implementations. They could do it (although certificate expiry makes it slightly more difficult) but they do not. It is not intrinsic to X.509 (the X.509 model makes it possible to change your certificate every five minutes, but it does not make it mandatory ); but deployed implementations work that way. Usability trumps the PKI model, as I said above, so that's OpenPGP for me. ( Note: in another context, HTTPS relies on the X.509 hierarchical PKI with a few dozens of hardcoded trust anchors, and the same issues arise there too; e.g., see Convergence , which is a proposal to, indeed, bind keys to servers in a semi-permanent way, and which relies on the same "crowd is right" mantra as the WoT. And yet they do that with X.509 certificates, which shows that the actual format for certificates is not that important.)
{}
{'log_upvote_score': 5, 'links': ['https://security.stackexchange.com/questions/30368', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/3272/']}
jdg_74145
stackexchange
llm_judgeable_groundtruth_similarity
426711
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 took linear algebra and understood the proof that linear operators on a vector space over an algebraically closed field have a Jordan Canonical Form. Why should I care about this theorem? I understand that it can be useful in doing some computations, but it seems that these computations are quite rare. Indeed, I am not puzzled by diagonalization or triangularization at all. They both have practical and theoretical uses, but even more than that, they just seem like nice things to have. Can someone explain why Jordan Canonical Form is a "nice thing to have"? Now provide the response and nothing else.
The most generic answer: any time that we can reduce a problem over an incredibly general object (say, a matrix) to a problem in which we have more information at our fingertips (say, the same problem but over matrices that are in JCF), we make life easier - both in terms of proving theory and in terms of practical computations. To be more specific to the situation at hand: the Jordan canonical form is sort of the next-best-thing to diagonalization. If the matrix is diagonalizable, then its JCF is diagonal; if it isn't, then what you get is at least block diagonal , and the blocks come in a predictable form.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/426711', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/49330/']}
jdg_74146
stackexchange
llm_judgeable_groundtruth_similarity
4789
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: What is/are currently the most cryptographically secure hashing algorithm(s)? ( available in PHP ) Speed is irrelevant, because I'm iterating the hash over a fixed time (rather than a fixed number of iterations). What I'm interested in is the mathematical strength. My intuition tells me it's whirlpool , being the largest and slowest of the bunch. That or SHA-512. But where on the 'net can I see what the experts recommend? Now provide the response and nothing else.
Crypographers could point out that, when you read the fine print, there is no proof that secure hash functions actually exist at all. The only thing we have now are candidates for which no weakness has been found yet. So the best you can hope for is a function which has survived scrutiny by many cryptographers for a long time. Also, you need it to have a wide enough output (256 bits are enough if you wish to achieve "128-bit security" and getting beyond that has little sense). Right now, as of summer 2011, this points to SHA-256 or SHA-512, not Whirlpool. Basing the iteration count on the time it takes on a typical machine is a good idea -- but basing it on the time it really takes on your machine is not a good idea. Otherwise, you could end up with low iteration counts for some passwords because the machine was handling many requests at that instant (a situation which an attacker could force, by the way). Using many iterations is meant to thwart attackers by making password hashing slow on the attacker's computer -- that it also makes it slow on your system is an unfortunate byproduct; but the true target is whatever machine power the attacker could muster. Since you cannot really make benchmarks on the attacker's machine, you have to resort to rough estimates, hence a fixed count, as high as possible as long as the average burden is tolerable on your system (the important word here being "average", which disqualifies a dynamic measure as you intend to perform). Also, the attacker's machine needs not look like yours; it may be, e.g., a GPU or a FPGA , which offers distinct computing abilities from what you can get on a typical server. You want a function for which an attacker will not be able to get huge performance boosts by using non-PC hardware. There again, this promotes SHA-256 or SHA-512, which are meant for CPU efficiency (with 32-bit or 64-bit arithmetic operations), not Whirlpool, which can benefit from hardware optimizations similar to those AES was designed for. Finally, iterations are just part of the job; you also need a long enough, unique enough salt. Iterations and salting can be a bit tricky to do at the same time; you are warmly encouraged to use a standard construction such as PBKDF2 (although it was meant as a key derivation function, not a password hasher, PBKDF2 turns out to be reasonably good at that too).
{}
{'log_upvote_score': 5, 'links': ['https://security.stackexchange.com/questions/4789', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/3115/']}
jdg_74147
stackexchange
llm_judgeable_groundtruth_similarity
45187785
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 newbie at react-native.What I want to do is that fit an image in device and keep the ratio of image. Simply I want to make width : 100% I searched how to make it and seems resizeMode = 'contain' is good for that. However, since I used resizeMode = 'contain' , the image keeps the position vertically centered which I don't want.I want it to be vertically top. I tried to use a plug-in such as react-native-fit-image but no luck. And I found the reason why the image is not sizing automatically .But still I have no idea how to make it. So, my question is what is the best way to deal with this situation? Do I have to manually put width, height size each images? I want : Keep image's ratio. Vertically top positioned. React native test code : https://snack.expo.io/ry3_W53rW Eventually what I want to make : https://jsfiddle.net/hadeath03/mb43awLr/ Thanks. Now provide the response and nothing else.
The image is vertically centered, because you added flex: 1 to the style property. Don't add flex: 1, because that will fill the image to its parent, which is not desired in this case. You should always add a height and width on an image in React Native. In case the image is always the same, you can use Dimensions.get('window').width to calculate the size the image should be. For example, if the ratio is always 16x9, the height is 9/16th of the width of the image. The width equals device width, so: const dimensions = Dimensions.get('window');const imageHeight = Math.round(dimensions.width * 9 / 16);const imageWidth = dimensions.width;return ( <Image style={{ height: imageHeight, width: imageWidth }} />); Note: When using an implementation like this, your image will not automatically resize when rotating your device, using split screen, etc. You will have to take care of those actions as well if you support multiple orientations... In case the ratio is not the same, dynamically change the 9 / 16 by the ratio for each different image. If you don't really bother the image is a little bit cropped, you can use cover mode with a fixed height as well: ( https://snack.expo.io/rk_NRnhHb ) <Image resizeMode={'cover'} style={{ width: '100%', height: 200 }} source={{uri: temp}}/>
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/45187785', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2805530/']}
jdg_74148
stackexchange
llm_judgeable_groundtruth_similarity
31829075
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Postgres already has fully featured user management system. Why should I duplicate this functionality and use another one on top of that? And I think this is the right place to manage users & groups as it allows fine-grained control. Am I wrong? Is there some php libraries that already have done that? I should add that the app in question is not a public web-site, but a corporate app working in the private network. Now provide the response and nothing else.
I strongly advocate that application designers make use of PostgreSQL's users and role system ... but for a number of reasons having a 1:1 mapping of app users to database users is not usually practical. PostgreSQL roles are shared across all databases (though they don't have to be granted rights on anything except one) You can't have a foreign key reference from a normal application table to a PostgreSQL user table There's no function or other interface to authenticate a user by password. You have to make a new connection to authenticate by password. This breaks connection pooling. Instead, I advise that you use a couple of roles in the database: A database owner role. This user/role owns the database and the tables within it. Scripts to change the database structure ("migrations" and so on) run as this user. A webapp role. This is the role the app connects as when establishing pooled connections. This is GRANT ed only the access the app needs when running day to day. It can't change table structure, drop tables, etc. If a table is supposed to be append-only you don't grant UPDATE rights to this role. (possibly) some maintenance roles for scripts, etc, which have limited access to just what they need for their task. You manage your application users with normal tables. Sometimes you also want additional database roles for particular categories of user. This can be handy if you're dealing with apps with different privilege levels, departments, etc. The webapp can SET ROLE to switch roles, so if "joe" connects and you know "joe" is in accounts, you "SET ROLE accounts" before running queries for joe. This is more advanced, and most people don't need it. The main time I think using PostgreSQL user management directly makes sense is when the app has quite complex access requirements and doesn't need a huge profusion of different users (thousands, rather than millions). For webapps I'd stick with normal database tables and just separate a "db admin"role from the webapp connection pool role.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/31829075', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3766061/']}
jdg_74149
stackexchange
llm_judgeable_groundtruth_similarity
14439538
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 changed the color of an AlertDialog title using this command alert.setTitle( Html.fromHtml("<font color='#FF7F27'>Set IP Address</font>")); But I want to change the color of the line that appear under the title; how can I do that ? Note: I don't want to use a custom layout Now provide the response and nothing else.
Unfortunately, this is not a particularly simple task to accomplish. In my answer here , I detail how to adjust the color of a ListSeparator by just checking out the parent style used by Android, creating a new image, and creating a new style based on the original. Unfortunately, unlike with the ListSeparator 's style, AlertDialog themes are internal, and therefore cannot be referenced as parent styles. There is no easy way to change that little blue line! Thus you need to resort to making custom dialogs. If that just isn't your cup of tea... don't give up! I was very disturbed that there was no easy way to do this so I set up a little project on github for making quickly customized holo-style dialogs (assuming that the phone supports the Holo style). You can find the project here: https://github.com/danoz73/QustomDialog It should easily enable going from boring blue to exciting orange! The project is basically an example of using a custom dialog builder, and in the example I created a custom view that seemed to cater to the IP Address example you give in your original question. With QustomDialog , in order to create a basic dialog (title, message) with a desired different color for the title or divider, you use the following code: private String HALLOWEEN_ORANGE = "#FF7F27";QustomDialogBuilder qustomDialogBuilder = new QustomDialogBuilder(v.getContext()). setTitle("Set IP Address"). setTitleColor(HALLOWEEN_ORANGE). setDividerColor(HALLOWEEN_ORANGE). setMessage("You are now entering the 10th dimension.");qustomDialogBuilder.show(); And in order to add a custom layout (say, to add the little IP address EditText ), you add setCustomView(R.layout.example_ip_address_layout, v.getContext()) to the builder with a layout that you have designed (the IP example can be found in the github). I hope this helps. Many thanks to Joseph Earl and his answer here .
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/14439538', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1327384/']}
jdg_74150
stackexchange
llm_judgeable_groundtruth_similarity
665359
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: The statement For simplicity, let's consider a finite-dimensional Hilbert space. (The question can probably be generalized, but I don't know enough about mathematical QM to properly do so.) Let $A\colon H\to H$ be some observable (self-adjoint operator) with eigenvalues $\lambda_1,\ldots,\lambda_n$ . Recall that $H$ is the direct sum of the eigenspaces: \begin{equation}\tag{1}H=\bigoplus_{i=1}^n H_i\end{equation} In other words, \begin{align}\Phi\colon H_1\times\cdots\times H_n&\to H\\(\Psi_1,\ldots,\Psi_n)&\mapsto \Psi_1+\ldots+\Psi_n\end{align} is a bijection and we can consider the projection $$P_i\colon H\to H_i$$ for each $i=1,\ldots,n$ . Born's rule says that $$p_i:=\frac{\langle P_i\Psi|\Psi\rangle}{\langle\Psi|\Psi\rangle}=\frac{\langle \Psi|P_i\Psi\rangle}{\langle\Psi|\Psi\rangle}=\frac{\langle P_i\Psi|P_i\Psi\rangle}{\langle\Psi|\Psi\rangle}\in[0,1]$$ is the probability to measure $\lambda_i$ if our system is in the state $\Psi$ . My question Would the formulation of Born's rule above typically be regarded as an axiom or as a result of some more fundamental assumptions? Now provide the response and nothing else.
The correct statement is that the probability that a measurement of an observable represented by a Hermitian operator $A$ (with non-degenerate spectrum) over a state $\vert\psi\rangle$ would yield an eigenvalue $\lambda_i$ is given by \begin{align}p_i=\frac{\langle\psi\vert\psi_i\rangle\langle\psi_i\vert\psi\rangle}{\langle\psi\vert\psi\rangle}\end{align} where $\vert\psi_i\rangle$ is the normalized eigenstate of the operator $A$ corresponding to the eigenvalue $\lambda_i$ . However, this does not require that $\vert\psi\rangle=\sum_i\vert\psi_i\rangle$ . The state vector $\vert\psi\rangle$ can be the most generic normalizable state and thus, would be represented, in general, as a generic linear combination $\vert\psi\rangle=\sum_ic_i\vert\psi_i\rangle$ where $c_i\in\mathbb{C}$ . This statement is called the Born rule. It is needed to be supplied with a closely related axiom that goes by the name of the collapse postulate or the wavepacket reduction postulate to give a "complete" picture of what happens when you perform a measurement. It says that the aforementioned measurement evolves the state $\vert\psi\rangle$ to an eigenstate $\vert\psi_i\rangle$ corresponding to the outcome $\lambda_i$ . All of this can be made a bit more general to take care of measurements of operators with degenerate spectra using the projection operators, but the basic idea is already captured here. In the case of the measurement of an operator $A$ with distinct eigenvalues $\lambda_i$ such that $A=\sum_i\lambda_i\mathbb{P}_i$ where the $\mathbb{P}_i$ s are the projection operators corresponding to the $i^\mathrm{th}$ eigensubspace, the probability of the outcome of the measurement yielding $\lambda_i$ is given by \begin{align}p_i=\frac{\langle\psi\vert\mathbb{P}_i\vert\psi\rangle}{\langle\psi\vert\psi\rangle}\end{align} The wavepacket reduction postulate now says that the aforementioned measurement evolves the state $\vert\psi\rangle$ to the state $\frac{\mathbb{P}_i\vert\psi_i\rangle}{\langle\psi\vert\mathbb{P}_i\vert\psi\rangle}$ corresponding to the measurement outcome being $\lambda_i$ . Notice that the denominator here is needed to ensure that the resultant state is normalized. In standard textbook quantum mechanics, both of these are always, as far as I know, taken to be basic axioms. One can formulate their quantum mechanics using a different mathematical formalism but they still have to provide some translation of these axioms as axioms in their framework as well -- as long they really are just another formulation of the standard textbook quantum mechanics in their physical content. Having said that, there have been attempts, starting in 1957 and continuing to this day, to derive the Born rule. There have been mainly three approaches to attempt the derivation: Measure-Theoretic/Frequentist Approaches The rather measure-theoretic and mathematical Gleason's theorem of 1957 states that in a Hilbert space with $d>3$ , the only probability measure consistent with the other axioms of quantum mechanics (linearity, etc.) is the one given by the Born rule. The 1968 proof of the Born rule by Hartle , in effect, shows that the Born rule is the quantum mechanical version of the weak law of large numbers. The 1989 proof of the Born rule by Fahri, Goldstone, and Gutman shows that the Born is the quantum mechanical version of the strong law of large numbers. Symmetry-Based Approaches The 2005 paper by Zurek derives the Born rule using an argument based on envariance which is an invariance that systems entangled with an environment exhibit. The 2015 paper by Carroll and Sebens derives the Born rule in the context of many-worlds formulation of quantum mechanics. They use the "epistemic separability principle" which is just a weird/fancy way of saying that the probability of a measurement outcome shouldn't depend on the evolution of the environment that is decoupled and unentangled from the system. Decision-Theoretic Approaches I simply mention them for the sake of completeness and to invite a more informed reader to feel free to edit the answer and fill in the details. Now, none of these attempts have been accepted, at least so far, by the community as true derivations of the Born rule. Basically, in standard quantum mechanics, there is no plausible way to do away with the wave-packet reduction axiom (which ought to accompany the Born rule for probabilities to make sense, otherwise there would simply be deterministic evolution according to the Schrodinger equation). So, even if one shows that the Born rule is the only consistent probability measure for the Hilbert spaces of quantum mechanics, it does not come in contact with the physical claims made by the standard axioms. Another approach, in particular, the papers by Carroll and Deutsch (the latter of whom has worked on decision-theoretic approaches) are in the framework of the many-words formulation. There, you can make sense of wavepacket reduction as the reduction of the relative state of a system with respect to an observer without violating underlying unitarity. However, it is conceptually difficult to derive the Born rule there. One reason is that the naive branch-counting leads to a contradiction with the Born rule. And the more sophisticated epistemic approaches have been criticized for either being circular or sloppy. You can see the critiques of the derivations of the Born rule in papers by Adrian Kent, 1997 and 2014 . I would also recommend having a look at this answer to my recent question by @ChiralAnomaly for some general comments on the derivations of the Born rule.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/665359', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/237923/']}
jdg_74151
stackexchange
llm_judgeable_groundtruth_similarity
53562417
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 would like to cast a tensor of ints to a tensor of booleans. Specifically I would like to be able to have a function which transforms tensor([0,10,0,16]) to tensor([0,1,0,1]) This is trivial in Tensorflow by just using tf.cast(x,tf.bool) . I want the cast to change all ints greater than 0 to a 1 and all ints equal to 0 to a 0. This is the equivalent of !! in most languages. Since pytorch does not seem to have a dedicated boolean type to cast to, what is the best approach here? Edit: I am looking for a vectorized solution opposed to looping through each element. Now provide the response and nothing else.
What you're looking for is to generate a boolean mask for the given integer tensor. For this, you can simply check for the condition: "whether the values in the tensor are greater than 0" using simple comparison operator ( > ) or using torch.gt() , which would then give us the desired result. # input tensorIn [76]: t Out[76]: tensor([ 0, 10, 0, 16])# generate the needed boolean maskIn [78]: t > 0 Out[78]: tensor([0, 1, 0, 1], dtype=torch.uint8) # sanity checkIn [93]: mask = t > 0 In [94]: mask.type() Out[94]: 'torch.ByteTensor' Note : In PyTorch version 1.4+, the above operation would return 'torch.BoolTensor' In [9]: t > 0 Out[9]: tensor([False, True, False, True])# alternatively, use `torch.gt()` APIIn [11]: torch.gt(t, 0)Out[11]: tensor([False, True, False, True]) If you indeed want single bits (either 0 s or 1 s), cast it using: In [14]: (t > 0).type(torch.uint8) Out[14]: tensor([0, 1, 0, 1], dtype=torch.uint8)# alternatively, use `torch.gt()` APIIn [15]: torch.gt(t, 0).int()Out[15]: tensor([0, 1, 0, 1], dtype=torch.int32) The reason for this change has been discussed in this feature-request issue: issues/4764 - Introduce torch.BoolTensor ... TL;DR : Simple one liner t.bool().int()
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/53562417', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7998652/']}
jdg_74152
stackexchange
llm_judgeable_groundtruth_similarity
9251354
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 customize a scroll bar via CSS (Cascading Style Sheets) for one div and not the whole page? Now provide the response and nothing else.
I thought it would be helpful to consolidate the latest information on scroll bars, CSS, and browser compatibility. Scroll Bar CSS Support Currently, there exists no cross-browser scroll bar CSS styling definitions. The W3C article I mention at the end has the following statement and was recently updated (10 Oct 2014): Some browsers (IE, Konqueror) support the non-standard properties 'scrollbar-shadow-color', 'scrollbar-track-color' and others. These properties are illegal: they are neither defined in any CSS specification nor are they marked as proprietary (by prefixing them with "-vendor-") Microsoft As others have mentioned, Microsoft supports scroll bar styling, but only for IE8 and above. Example: .TA { scrollbar-3dlight-color:gold; scrollbar-arrow-color:blue; scrollbar-base-color:; scrollbar-darkshadow-color:blue; scrollbar-face-color:; scrollbar-highlight-color:; scrollbar-shadow-color:} Chrome & Safari (WebKit) Similarly, WebKit now has its own version: Styling scrollbars: https://www.webkit.org/blog/363/styling-scrollbars/ Demo of all WebKit scroll bar styling From Custom scrollbars in WebKit , relevant CSS: /* pseudo elements */ ::-webkit-scrollbar { } ::-webkit-scrollbar-button { } ::-webkit-scrollbar-track { } ::-webkit-scrollbar-track-piece { } ::-webkit-scrollbar-thumb { } ::-webkit-scrollbar-corner { } ::-webkit-resizer { } /* pseudo class selectors */ :horizontal :vertical :decrement :increment :start :end :double-button :single-button :no-button :corner-present :window-inactive Firefox (Gecko) As of version 64 Firefox supports scrollbar styling through the properties scrollbar-color (partially, W3C draft ) and scrollbar-width ( W3C draft ). Some good information about the implementation can be found in this answer . Cross-browser Scroll Bar Styling JavaScript libraries and plug-ins can provide a cross-browser solution. There are many options. 20 jQuery Scrollbar plugin with examples (July 24, 2012) NiceScroll : jQuery Scrolling plugin for desktop,mobile & touch devices jQuery custom content scroller Tiny Scrollbar – A lightweight jQuery plugin etc. 30+ JavaScript/Ajax Techniques for Sliders, Scrollers and Scrollbars (May 07, 2008) 21 Useful Scrollbar CSS/JavaScript Styling Tutorials (August, 2012) 15+ Free and Premium jQuery Scrolling Plugins (August 26, 2012) The list could go on. Your best bet is to search around, research, and test the available solutions. I am sure you will be able to find something that will fit your needs. Prevent Illegal Scroll Bar Styling Just in case you want to prevent scroll bar styling that hasn't been properly prefixed with "-vendor", this article over at W3C provides some basic instructions . Basically, you'll need to add the following CSS to a user style sheet associated with your browser. These definitions will override invalid scroll bar styling on any page you visit. body, html { scrollbar-face-color: ThreeDFace !important; scrollbar-shadow-color: ThreeDDarkShadow !important; scrollbar-highlight-color: ThreeDHighlight !important; scrollbar-3dlight-color: ThreeDLightShadow !important; scrollbar-darkshadow-color: ThreeDDarkShadow !important; scrollbar-track-color: Scrollbar !important; scrollbar-arrow-color: ButtonText !important;} Duplicate or Similar Questions / Source Not Linked Above Changing the scrollbars' style CSS scrollbar style cross browser How to create a custom scrollbar on a div (Facebook style) Note: This answer contains information from various sources. If a source was used, then it is also linked in this answer.
{}
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/9251354', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/984523/']}
jdg_74153
stackexchange
llm_judgeable_groundtruth_similarity
27573365
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 a complete beginner to Typescript and am wondering if it's possible to use ES6 promises in Typescript and what I would have to do to get them to work. I'm running node 0.11.14 and am getting an error during compilation "Cannot find name 'Promise'" Now provide the response and nothing else.
The current lib.d.ts doesn't have promises in it defined so you need a extra definition file for it that is why you are getting compilation errors. You could for example use (like @elclanrs says) use the es6-promise package with the definition file from DefinitelyTyped: es6-promise definition You can then use it like this: var p = new Promise<string>((resolve, reject) => { resolve('a string'); }); edit You can use it without a definition when targeting ES6 (with the TypeScript compiler) - Note you still require the Promise to exists in the runtime ofcourse (so it won't work in old browsers :))Add/Edit the following to your tsconfig.json : "compilerOptions": { "target": "ES6"} edit 2 When TypeScript 2.0 will come out things will change a bit (though above still works) but definition files can be installed directly with npm like below: npm install --save @types/es6-promise - source edit3 Updating answer with more info for using the types. Create a package.json file with only { } as the content (if you don't have a package.json already.Call npm install --save @types/es6-promise and tsc --init . The first npm install command will change your package.json to include the es6-promise as a dependency. tsc --init will create a tsconfig.json file for you. You can now use the promise in your typescript file var x: Promise<any>; .Execute tsc -p . to compile your project. You should have no errors.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/27573365', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/764174/']}
jdg_74154
stackexchange
llm_judgeable_groundtruth_similarity
11628172
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 convert an ArrayAdapter<String> of static data into a CursorAdapter for using Suggestion Listener in SearchView ? I have constructed the ArrayAdapter<String> from static data ( allString ) ArrayAdapter<String> searchAdapter = new ArrayAdapter<String>(context, R.layout.listitem, allString); and I use it for an MultiAutoCompleteTextView which works fine in devices with API level less than 11 MultiAutoCompleteTextView findTextView.setAdapter(searchAdapter); However my target API is level is 11 and for API>10 I use an ActionBar within which I would like to have a SearchView instead. Here's what I have tried: It does show the ActionBar with the embedded SearchView but does not give any suggestions as it would in the MultiAutoCompleteTextView . @Overridepublic boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); if (android.os.Build.VERSION.SDK_INT > 10){ inflater.inflate(R.menu.menu11, menu); searchView = (SearchView) menu.findItem(R.id.MENU_SEARCH).getActionView(); int[] to = {0}; CursorAdapter cursorAdapter = new SimpleCursorAdapter(context, R.layout.listitem, null, allBusStopString, to); searchView.setSuggestionsAdapter(cursorAdapter); searchView.setOnSuggestionListener(new OnSuggestionListener() { @Override public boolean onSuggestionClick(int position) { String selectedItem = (String)cursorAdapter.getItem(position); Log.v("search view", selectedItem); return false; } @Override public boolean onSuggestionSelect(int position) { return false; } }); }else{ inflater.inflate(R.menu.menu, menu); } return true;} Now provide the response and nothing else.
That's strange SearchView.setSuggestionsAdapter accepts CursorAdapter only. You could create MatrixCursor and fill it with data from String array. I hope you have small data collection. Then pass the cursor to CursorAdapter. String[] columnNames = {"_id","text"}MatrixCursor cursor = new MatrixCursor(columnNames);String[] array = getResources().getStringArray(R.array.allStrings); //if strings are in resourcesString[] temp = new String[2];int id = 0;for(String item : array){ temp[0] = Integer.toString(id++); temp[1] = item; cursor.addRow(temp);} String[] from = {"text"}; int[] to = {R.id.name_entry};busStopCursorAdapter = new SimpleCursorAdapter(context, R.layout.listentry, cursor, from, to);
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/11628172', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1014631/']}
jdg_74155
stackexchange
llm_judgeable_groundtruth_similarity
71432
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: There is not enough gravity at the center to start nuclear fusion, but it seems that there would be plenty enough to collapse the planet. Now provide the response and nothing else.
Pulsar's answer is indeed correct, but let me expand a bit more. What happens when a gas giant shrinks? A uniform mass will have a self gravitational potential of $-\frac{3GM^2}{5R}$ . If we decrease its radius, its potential will decrease as well and the difference will be turned into thermal energy. Although gas giants and stars are not uniform mass balls, their gravitational binding energy is still proportional to $\frac{GM^2}{R}$ , Thus if the radius decreases it will release energy, which will raise the temperature in return. What happens when the temperature increases? Assuming the gas in those planets obey the ideal gas law $$PV=nRT$$ (where $R$ is not the radius but the molar gas constant $R=8.314\,\text{J K}^{−1}\text{mol}^{-1}$ ), it's obvious that when $T$ increases and $V$ decreases (due to the shrink in the previous section) $P$ must increase. Note that most real gases behave qualitatively like an ideal gas, so this is not a crazy assumption. So what is the big picture? The planet shrinks a little bit, the potential difference turns into thermal energy and its temperature rises. The rise in temperature will cause the pressure to rise and prevent the planet from shrinking further (holding the planet in hydrostatic equilibrium ). However, the planet also loses energy due to EM radiation as well, so it will continuously shrink and radiate. The process is called Kelvin–Helmholtz mechanism . For instance, Jupiter is shrinking the tiny bit of $2\,\text{cm}$ each year. Although you might think this is really nothing, the amount of heat produced is similar to the total solar radiation it receives. Addendum (Nov. 2020) As Rob Jeffries has correctly pointed out, what ultimately keeps a gas giant from collapsing indefinitely is the electron degeneracy pressure. Eventually because of high pressure the hydrogen and other elements in the deep interior of the gas giant will undergo a phase transition to a metallic phase and will not compress any further.
{}
{'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/71432', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/14320/']}
jdg_74156
stackexchange
llm_judgeable_groundtruth_similarity
7487182
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 my code: _mediaPlayer = [[MPMoviePlayerController alloc] init];_mediaPlayer.controlStyle = MPMovieControlStyleNone;_mediaPlayer.shouldAutoplay = NO;[_mediaPlayer.view setFrame: CGRectMake(5, 5, 600,400)];[playerHolder addSubview: _mediaPlayer.view];//[self prepareScreenContentToPlay];//UITapGestureRecognizer *singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleRollTap:)];singleFingerTap.numberOfTapsRequired = 1;[_mediaPlayer.view addGestureRecognizer:singleFingerTap];[singleFingerTap release]; And action method for gesture recognizer: -(void)handleRollTap:(UITapGestureRecognizer*)sender{ NSLog(@"%@", @"touch");} MPMoviePlayerController works fine. In addition I want to handle touch on MPMoviePlayerController view but handleRollTap never called. Why MPMoviePlayerController's view not works with UITapGestureRecognizer? OK. If singleFingerTap.numberOfTapsRequired = 2; then all works fine as well. But nothing for single tap.. Now provide the response and nothing else.
Actually, answer to this is simple: set yourself as UIGestureRecognizer delegate return YES for delegate methods: e.g. UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapGesture)];tapGestureRecognizer.delegate = self; and somewhere else in the code: #pragma mark - gesture delegate// this allows you to dispatch touches- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {return YES;}// this enables you to handle multiple recognizers on single view- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {return YES;}
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/7487182', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/194544/']}
jdg_74157
stackexchange
llm_judgeable_groundtruth_similarity
158986
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 very new to the entity framework, so please bear with me... How can I relate two objects from different contexts together? The example below throws the following exception: System.InvalidOperationException: The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects. void MyFunction(){ using (TCPSEntities model = new TCPSEntities()) { EmployeeRoles er = model.EmployeeRoles.First(p=>p.EmployeeId == 123); er.Roles = GetDefaultRole(); model.SaveChanges(); }}private static Roles GetDefaultRole(){ Roles r = null; using (TCPSEntities model = new TCPSEntities()) { r = model.Roles.First(p => p.RoleId == 1); } return r;} Using one context is not an option because we are using the EF in an ASP.NET application. Now provide the response and nothing else.
You will have to use the same context (you can pass the context to the getdefaultrole method) or rethink the relationships and extend the entity. EDIT: Wanted to add this was for the example provided, using asp.net will require you to fully think out your context and relationship designs. You could simply pass the context.. IE: void MyFunction(){ using (TCPSEntities model = new TCPSEntities()) { EmployeeRoles er = model.EmployeeRoles.First(p=>p.EmployeeId == 123); er.Roles = GetDefaultRole(model); model.SaveChanges(); }}private static Roles GetDefaultRole(TCPSEntities model){ Roles r = null; r = model.Roles.First(p => p.RoleId == 1); return r;}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/158986', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4050/']}
jdg_74158
stackexchange
llm_judgeable_groundtruth_similarity
35780397
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 implement a Service Worker in a test page. My end goal is an application that operates offline. The folder structure is below /myApp ... /static /mod /practice service-worker.js worker-directives.js foopage.js /templates /practice foopage.html I am registering a service worker as shown below (within service-worker.js ): navigator.serviceWorker.register('../static/mod/practice/service-worker.js').then(function(reg) { console.log('Registration succeeded. Scope is ' + reg.scope); ...} and in the console I see Registration succeeded. Scope is https://example.com/static/mod/practice/ If my page is located at https://example.com/practice/foopage , do I need to make sure that my service worker scope is https://example.com/practice/foopage ? If I try to define the scope in the register function call like navigator.serviceWorker.register('../static/mod/practice/service-worker.js', { scope: '/practice/foopage/' }).then(function(reg) { ...} I get the error Registration failed with SecurityError: Failed to register a ServiceWorker: The path of the provided scope ('/practice/foopage/') is not under the max scope allowed ('/static/mod/practice/'). Adjust the scope, move the Service Worker script, or use the Service-Worker-Allowed HTTP header to allow the scope. Question is: What exactly does scope refer to? Is it the collection of URLs that the service worker will eventually control? Do I need to move service-workers.js somewhere else? If so, where? Now provide the response and nothing else.
Service workers are basically a proxy between your web application and the internet, so it can intercept calls to the network if so desired. Scope in this instance refers to the path that the service worker will be able to intercept network calls from. The scope property can be used explicitly define the scope it will cover. However: Service workers can only intercept requests originating in the scope of the current directory that the service worker script is located in and its subdirectories. Or as MDN states : The service worker will only catch requests from clients under the service worker's scope. The max scope for a service worker is the location of the worker. As your service worker is located in /static/mod/practice/ , it's not allowed to set its scope to /practice/foopage/ . Requests to other hosts, e.g. https://stackoverflow.com/foo , can be intercepted in any case. The easiest way to ensure that your service worker can intercept all the calls it needs to, would be to place it in the root directory of your web app ( / ). You can also override the default restrictions using an http header and manually setting the scope (see Ashraf Sabry's answer).
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/35780397', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2224777/']}
jdg_74159
stackexchange
llm_judgeable_groundtruth_similarity
5814765
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: If you copy files under Windows 7, you will see the progress of the copy in a sort of progress bar begin displayed in the status or task bar button of the application. Can this be achieved using Delphi 7 ? I have some lengthy operation which would be ideally suited to show it's progress this way. sample of such a button using copy with Total Commander . Now provide the response and nothing else.
Use the ITaskbarList3 interface for that, specifically its SetProgressState and SetProgressValue methods. Use CoCreateInstance() specifying CLSID_TaskbarList and IID_ITaskbarList3 to access the interface. For example: type ITaskbarList = interface(IUnknown) ['{56FDF342-FD6D-11D0-958A-006097C9A090}'] function HrInit: HRESULT; stdcall; function AddTab(hwnd: HWND): HRESULT; stdcall; function DeleteTab(hwnd: HWND): HRESULT; stdcall; function ActivateTab(hwnd: HWND): HRESULT; stdcall; function SetActiveAlt(hwnd: HWND): HRESULT; stdcall; end; ITaskbarList2 = interface(ITaskbarList) ['{602D4995-B13A-429B-A66E-1935E44F4317}'] function MarkFullscreenWindow(hwnd: HWND; fFullscreen: BOOL): HRESULT; stdcall; end; THUMBBUTTON = record dwMask: DWORD; iId: UINT; iBitmap: UINT; hIcon: HICON; szTip: packed array[0..259] of WCHAR; dwFlags: DWORD; end; TThumbButton = THUMBBUTTON; PThumbButton = ^TThumbButton; ITaskbarList3 = interface(ITaskbarList2) ['{EA1AFB91-9E28-4B86-90E9-9E9F8A5EEFAF}'] function SetProgressValue(hwnd: HWND; ullCompleted: ULONGLONG; ullTotal: ULONGLONG): HRESULT; stdcall; function SetProgressState(hwnd: HWND; tbpFlags: Integer): HRESULT; stdcall; function RegisterTab(hwndTab: HWND; hwndMDI: HWND): HRESULT; stdcall; function UnregisterTab(hwndTab: HWND): HRESULT; stdcall; function SetTabOrder(hwndTab: HWND; hwndInsertBefore: HWND): HRESULT; stdcall; function SetTabActive(hwndTab: HWND; hwndMDI: HWND; tbatFlags: Integer): HRESULT; stdcall; function ThumbBarAddButtons(hwnd: HWND; cButtons: UINT; pButton: PThumbButton): HRESULT; stdcall; function ThumbBarUpdateButtons(hwnd: HWND; cButtons: UINT; pButton: PThumbButton): HRESULT; stdcall; function ThumbBarSetImageList(hwnd: HWND; himl: HIMAGELIST): HRESULT; stdcall; function SetOverlayIcon(hwnd: HWND; hIcon: HICON; pszDescription: LPCWSTR): HRESULT; stdcall; function SetThumbnailTooltip(hwnd: HWND; pszTip: LPCWSTR): HRESULT; stdcall; function SetThumbnailClip(hwnd: HWND; var prcClip: TRect): HRESULT; stdcall; end;const CLSID_TaskbarList: TGUID = '{56FDF344-FD6D-11d0-958A-006097C9A090}'; TBPF_NOPROGRESS = 0; TBPF_INDETERMINATE = $1; TBPF_NORMAL = $2; TBPF_ERROR = $4; TBPF_PAUSED = $8; var TBL: ITaskbarList3; I: Integer;begin CoCreateInstance(CLSID_TaskbarList, nil, CLSCTX_INPROC, ITaskbarList3, TBL); if (TBL <> nil) then TBL.SetProgressState(Application.Handle, TBPF_INDETERMINATE); try for I := 0 to 100 do begin if (TBL <> nil) then TBL.SetProgressValue(Application.Handle, I, 100); Sleep(1000); end; finally if (TBL <> nil) then TBL.SetProgressState(Application.Handle, TBPF_NOPROGRESS); end;end;
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5814765', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/231181/']}
jdg_74160
stackexchange
llm_judgeable_groundtruth_similarity
1049367
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 there a point $O$ inside a triangle $\triangle ABC$ (any triangle) such that the angle $\angle{AOB} = \angle{BOC} = \angle{AOC}$?What do we call this point? Now provide the response and nothing else.
This is not the case for every triangle, $1^\circ-1^\circ-178^\circ$ triangle, for example, is one of the counterexamples to this claim. However, if all angles are less then $120^\circ$, then the claim is true. To construct such a point; Take any side $[AB]$, find two intersections of perpendicular bisector and circle with radius $\dfrac{|AB|}{2\sqrt 3}$ centered at middle point of $[AB]$. Call this points $A'$ and $B'$. Draw two circles contains points $A'AB$ and $B'AB$. All the $120^\circ$ angles that see $[AB]$ are on these circles. If you apply these procedure to other sides and take intersection points of these circles, you can see combinations of intersection points such that three circles intersect, gave you two points. One of these points are always outside of the triangle and you can see other point could be outside or inside of the triangle. Update: Apparently; these two intersection points are named Fermat points ; point on always outside is called second Fermat point , and the other is called first Fermat point . Also, above circles which have these points on are called Vesica piscis . Here is a picture of these Fermat points and circles:
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1049367', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/159714/']}
jdg_74161
stackexchange
llm_judgeable_groundtruth_similarity
308377
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 tried everything that I know but I couldn't solve this series: $$\sum_{n=0}^{\infty} \left(\frac{\pi}{2} - \arctan(n)\right)$$ Does it diverge or converge? Now provide the response and nothing else.
Hint: $$\sum_{n=0}^{\infty} \left(\frac{\pi}{2} - \arctan(n)\right) = \dfrac{\pi}{2} + \sum_{n=1}^{\infty} \left(\arctan\left(\frac 1n\right)\right)$$ Then clearly, as $\;n \to \infty,\; \dfrac 1n \to 0$ Perhaps use the limit comparison test? Perhaps the integral test? Additional hint : To use the limit comparison test, as suggested by Mhenni in the comment below, consider $\displaystyle \sum b_n = \sum \left(\dfrac 1n\right)\,,\;\,$ and note that $$\;\lim_{n \to \infty} \frac{\arctan(1/n)}{1/n}=1,\;$$ meaning the two series either converge together or diverge together. So apply what you know about the behavior of $\displaystyle \sum_{n=1}^\infty \dfrac 1n\;$ to the task at hand.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/308377', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/62962/']}
jdg_74162
stackexchange
llm_judgeable_groundtruth_similarity
20187
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: https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-30#section-10.12 says: The client MUST implement CSRF protection [...] typically accomplished by requiring any request sent to the redirection URI endpoint to include a value that binds the request to the user-agent's authenticated state (e.g. a hash of the session cookie [...] It doesn't say much about the implementation, though. It only puts some light on how the CSRF works: A CSRF attack against the client's redirection URI allows an attacker to inject their own authorization code or access token, which can result in the client using an access token associated with the attacker's protected resources rather than the victim's (e.g. save the victim's bank account information to a protected resource controlled by the attacker) But use of the word "rather" rather makes the statement worthless. I am thinking how to implement the "state" in GAE (using Webapp2). It would be easiest starting at how a hacker could use a CSRF against OAuth2. I found only one good article about the matter: "Cross Site Request Forgery and OAuth2" . Unfortunately, while this blog post is well written, there's not much information beyond explaining the OAuth2. The examples don't work, and I don't know Spring. Still, I found one interesting recommendation there: the server connecting to an OAuth2 provider should store "state" as a random session key (e.g. "this_is_the_random_state":"this_doesn't_matter") , and not a value under a static key (e.g. "state":"random_state_string"). My question is, what's the sane implementation of the "state"? Should the randomly generated state be hashed, or can the same value be stored and sent to the OAuth2 provider? Is there a difference here if the session backend is secure cookies or a server-side storage technology (e.g. in GAE Memcache, or database)? Should state be stored as a key as suggested? Should state has validity period, or is session (if there is one) lifetime enough? Now provide the response and nothing else.
Let's walk through how this attack works. The Attack I visit some client's website and start the process of authorizing that client to access some service provider using OAuth The client asks the service provider for permission to request access on my behalf, which is granted I am redirected to the service provider's website, where I would normally enter my username/password in order to authorize access Instead, I trap/prevent this request and save its URL I somehow get you to visit that URL instead. If you are logged-in to the service provider with your own account, then your credentials will be used to issue an authorization code The authorization code is exchanged for an access token Now my account on the client is authorized to access your account on the service provider So, how do we prevent this using the state parameter? Prevention The client should create a value that is somehow based on the original user's account (a hash of the user's session key, for example). It doesn't matter what it is as long as it's unique and generated using some private information about the original user. This value is passed to the service provider in the redirect from step three above Now, I get you to visit the URL I saved (step five above) The authorization code is issued and sent back to the client in your session along with the state parameter The client generates a state value based on your session information and compares it to the state value that was sent back from the authorization request to the service provider. This value does not match the state parameter on the request, because that state value was generated based on my session information, so it is rejected. Your Questions Should the randomly generated state be hashed or can same value be stored and sent to OAuth2 provider? The point is that the attacker should not be able to generate a state value that is specific to a given user. It should be unguessable. Is there a difference here, if session back-end is secure-cookies or a server-side storage (in GAE Memcache or database)? I don't think this matters (if I understand you correctly) Should state be stored as a key as suggested? I don't know what this means. Should state has validity period, or session (if there is one) lifetime is enough? Yes, state should have an expiration. It doesn't necessarily have to be tied to the session, but it could be.
{}
{'log_upvote_score': 6, 'links': ['https://security.stackexchange.com/questions/20187', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/9134/']}
jdg_74163
stackexchange
llm_judgeable_groundtruth_similarity
14914129
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 always get undefined reference to `Graph::InsertVertex(std::string)' if I compile my project! Any hints why he cant resolve this reference?(all Files are in the netbeans project folder) // main.cpp #include <cstdlib>#include <string>#include "Graph.h"using namespace std;int main(int argc, char** argv){ Graph<string> *graph = new Graph<string>(); // <--- ERROR graph->InsertVertex("A"); return 0;} // Node.h #include <iostream>#include "Graph.h"template<class T> class Node{ friend class Graph; public: Node(T val) { this->data = val; this->vertList = NULL; this->next = NULL; } Node(const Node& orig); virtual ~Node();private: T data; Node<T> *vertList; Node<T> *next; int status;}; // Graph.h #include <iostream>#include "Node.h"template <class T> class Graph { public: Graph() { head = NULL; } void InsertVertex(T val); void InsertEdge(T v_val, T e_val); void PrintVertices(); void PrintEdges(T v_val); void DeleteEdge(T v_val, T e_val); void DeleteVertex(T val); void bfs(); private: Node<T> *head;}; // Graph.cpp #include "Graph.h"template <class T>void Graph<T>::InsertVertex(T val){ Node<T> *temp = new Node<T>(val); if(head == NULL) head = temp; else { Node<T> node = head; while(node->vertList != NULL) node = node->vertList; node->vertList = temp; } }template <class T>void Graph<T>::InsertEdge(T v_val, T e_val){ if (head != NULL) { Node<T> *k = head; Node<T> *t = head; Node<T> *temp = new Node<T> (e_val); while (t != NULL) { if (t->data == v_val) { Node<T> *s = t; while (s->next != NULL) s = s->next; s->next = temp; while (k != NULL) { if(k->data == e_val) break; k = k->vertList; } temp->vertList = k; return; } t = t->vertList; } // end while loop } else std::cout << "Add first vertices to the graph" << std::endl;}template <class T>void Graph<T>::PrintEdges(T v_val){ Node<T>* t = head; while (t != NULL) { if (t->data == v_val) { while (t->next != NULL) { std::cout << t->next->vertList->data << " "; t = t->next; } } t = t->vertList; }}template <class T>void Graph<T>::PrintVertices(){ Node<T>* t = head; while (t != NULL) { std::cout << t->data << " "; t = t->vertList; }} Now provide the response and nothing else.
Typically you want your template methods in the header, so they are compiled when needed. In case you really want to hide it in the implementation file, you have to explicitly instantiate the template in Graph.cpp like template class Graph<string>; Since you have to do that for every type T you intend to use with Graph<T> , the point of the template class is somewhat defeated and you better put everything into the header
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14914129', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/384556/']}
jdg_74164
stackexchange
llm_judgeable_groundtruth_similarity
10840084
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 you create an event when the user clicks on any part of the calendar? and then store it in the database as a new event?I know you have to use: select: function(start, end, allDay) to get the "start" and "end" times. But after I get this data how do I pass it to the database? Thanks! Now provide the response and nothing else.
You may use an ajax request to store the new event in your DB. There is a demo on the projects homepage, which can easily be adapted. Via jQuery for example like this : select: function(start, end, allDay) { var title = prompt('Event Title:'); if (title) { calendar.fullCalendar('renderEvent', { title: title, start: start, end: end, allDay: allDay }, true // make the event "stick" ); /** * ajax call to store event in DB */ jQuery.post( "event/new" // your url , { // re-use event's data title: title, start: start, end: end, allDay: allDay } ); } calendar.fullCalendar('unselect');} If you need to react on a specific click, you can also try this, but you have to grep the event end or duration by yourself. dayClick: function(date, allDay, jsEvent, view) { var title = prompt('Event Title:'); /** * again : ajax call to store event in DB */ jQuery.post( "event/new" // your url , { // re-use event's data title: title, start: date allDay: allDay } );}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/10840084', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1429187/']}
jdg_74165
stackexchange
llm_judgeable_groundtruth_similarity
31467147
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 come from a MATLAB background. When I create class definitions, I can instantiate "empty" variable names and then later assign values or objects to them. I.e. classdef myclass < handle properties var1 var2 end enda = myClass;a.var1 = someOtherClassObject; How do I do this in Python? I tried something like this: class myClass:def __init__(self): var1 var2a = myClass()a.var1 = someOtherClassObject() But that's not correct. The main purpose is to build a definition of my class, like a structure, and then later go and instantiate the variables as needed. And help would be appreciated. Now provide the response and nothing else.
You need to use self. to create variables for instances (objects) I do not think you can have an uninitialized name in python, instead why not just initialize your instance variables to None ? Example - class myClass: def __init__(self): self.var1 = None self.var2 = None You can later go and set them to whatever you want using - a = myClass()a.var1 = someOtherClassObject If you need to define class variables (that are shared across instances) , you need to define them outside the __init__() method, directly inside the class as - class myClass: var1 = None var2 = None def __init__(self): pass
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/31467147', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5125742/']}
jdg_74166
stackexchange
llm_judgeable_groundtruth_similarity
908109
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: The problem statement, all given variables and data Let $T$ be multiplication by matrix $A$: $$A= \begin{bmatrix} 1 & -1 & 3 \\ 5 & 6 & -4 \\ 7 & 4 & 2 \\ \end{bmatrix}$$ Find the range, kernel, rank and nullity of T. Attempt at a solution I can find all of these values except for A. What does the question mean when T is a multiplication by matrix A? How do I get range/kernel etc. of T.. I know how to get them for A. Thanks. Now provide the response and nothing else.
Start with integration by parts (IBP) by setting $u=\ln^3(1+x)$ and $dv=\dfrac{\ln x}{x}\ dx$ yields\begin{align}I&=-\frac32\int_0^1\frac{\ln^2(1+x)\ln^2 x}{1+x}\ dx\\&=-\frac32\int_1^2\frac{\ln^2x\ln^2 (x-1)}{x}\ dx\quad\Rightarrow\quad\color{red}{x\mapsto1+x}\\&=-\frac32\int_{\large\frac12}^1\left[\frac{\ln^2x\ln^2 (1-x)}{x}-\frac{2\ln^3x\ln(1-x)}{x}+\frac{\ln^4x}{x}\right]\ dx\quad\Rightarrow\quad\color{red}{x\mapsto\frac1x}\\&=-\frac32\int_{\large\frac12}^1\frac{\ln^2x\ln^2 (1-x)}{x}\ dx+3\int_{\large\frac12}^1\frac{\ln^3x\ln(1-x)}{x}\ dx-\left.\frac3{10}\ln^5x\right|_{\large\frac12}^1\\&=-\frac32\color{red}{\int_{\large\frac12}^1\frac{\ln^2x\ln^2 (1-x)}{x}\ dx}+3\int_{\large\frac12}^1\frac{\ln^3x\ln(1-x)}{x}\ dx-\frac3{10}\ln^52.\end{align}Applying IBP again to evaluate the red integral by setting $u=\ln^2(1-x)$ and $dv=\dfrac{\ln^2 x}{x}\ dx$ yields\begin{align}\color{red}{\int_{\large\frac12}^1\frac{\ln^2x\ln^2 (1-x)}{x}\ dx}&=\frac13\ln^52+\frac23\color{blue}{\int_{\large\frac12}^1\frac{\ln^3x\ln (1-x)}{1-x}\ dx}.\end{align} For the simplicity, let $$\color{blue}{\mathbf{H}_{m}^{(k)}(x)}=\sum_{n=1}^\infty \frac{H_{n}^{(k)}x^n}{n^m}\qquad\Rightarrow\qquad\color{blue}{\mathbf{H}(x)}=\sum_{n=1}^\infty H_{n}x^n, $$ Introduce a generating function for the generalized harmonic numbers for $|x|<1$ $$\color{blue}{\mathbf{H}^{(k)}(x)}=\sum_{n=1}^\infty H_{n}^{(k)}x^n=\frac{\operatorname{Li}_k(x)}{1-x}\qquad\Rightarrow\qquad\color{blue}{\mathbf{H}(x)}=-\frac{\ln(1-x)}{1-x}$$ and the following identity $$H_{n+1}^{(k)}-H_{n}^{(k)}=\frac1{(n+1)^k}\qquad\Rightarrow\qquad H_{n+1}-H_{n}=\frac1{n+1}$$ Let us integrating the indefinite form of the blue integral.\begin{align}\color{blue}{\int\frac{\ln^3x\ln (1-x)}{1-x}\ dx}=&-\int\sum_{n=1}^\infty H_nx^n\ln^3x\ dx\\=&-\sum_{n=1}^\infty H_n\int x^n\ln^3x\ dx\\=&-\sum_{n=1}^\infty H_n\frac{\partial^3}{\partial n^3}\left[\int x^n\ dx\right]\\=&-\sum_{n=1}^\infty H_n\frac{\partial^3}{\partial n^3}\left[\frac{x^{n+1}}{n+1}\right]\\=&-\sum_{n=1}^\infty H_n\left[\frac{x^{n+1}\ln^3x}{n+1}-\frac{3x^{n+1}\ln^2x}{(n+1)^2}+\frac{6x^{n+1}\ln x}{(n+1)^3}-\frac{6x^{n+1}}{(n+1)^4}\right]\\=&-\ln^3x\sum_{n=1}^\infty \frac{H_{n+1}x^{n+1}}{n+1}+\ln^3x\sum_{n=1}^\infty \frac{x^{n+1}}{(n+1)^2}+3\ln^2x\sum_{n=1}^\infty \frac{H_{n+1}x^{n+1}}{(n+1)^2}\\&-3\ln^2x\sum_{n=1}^\infty \frac{x^{n+1}}{(n+1)^3}-6\ln x\sum_{n=1}^\infty \frac{H_{n+1}x^{n+1}}{(n+1)^3}+6\ln x\sum_{n=1}^\infty \frac{x^{n+1}}{(n+1)^4}\\&+6\sum_{n=1}^\infty \frac{H_{n+1}x^{n+1}}{(n+1)^4}-6\sum_{n=1}^\infty \frac{x^{n+1}}{(n+1)^5}\\=&\ -\sum_{n=1}^\infty\left[\frac{H_nx^{n}\ln^3x}{n}-\frac{x^{n}\ln^3x}{n^2}-\frac{3H_nx^{n}\ln^2x}{n^2}+\frac{3x^{n}\ln^2x}{n^3}\right.\\& \left.\ +\frac{6H_nx^{n}\ln x}{n^3}-\frac{6x^{n}\ln x}{n^4}-\frac{6H_nx^{n}}{n^4}+\frac{6x^{n}}{n^5}\right]\\=&\ -\color{blue}{\mathbf{H}_{1}(x)}\ln^3x+\operatorname{Li}_2(x)\ln^3x+3\color{blue}{\mathbf{H}_{2}(x)}\ln^2x-3\operatorname{Li}_3(x)\ln^2x\\&\ -6\color{blue}{\mathbf{H}_{3}(x)}\ln x+6\operatorname{Li}_4(x)\ln x+6\color{blue}{\mathbf{H}_{4}(x)}-6\operatorname{Li}_5(x).\end{align}Therefore\begin{align}\color{blue}{\int_{\Large\frac12}^1\frac{\ln^3x\ln (1-x)}{1-x}\ dx}=&\ 6\color{blue}{\mathbf{H}_{4}(1)}-6\operatorname{Li}_5(1)-\left[\color{blue}{\mathbf{H}_{1}\left(\frac12\right)}\ln^32-\operatorname{Li}_2\left(\frac12\right)\ln^32\right.\\&\left.\ +3\color{blue}{\mathbf{H}_{2}\left(\frac12\right)}\ln^22-3\operatorname{Li}_3\left(\frac12\right)\ln^22+6\color{blue}{\mathbf{H}_{3}\left(\frac12\right)}\ln 2\right.\\&\ -6\operatorname{Li}_4(x)\ln 2+6\color{blue}{\mathbf{H}_{4}(x)}-6\operatorname{Li}_5(x)\bigg]\\=&\ 12\zeta(5)-\pi^2\zeta(3)+\frac{3}8\zeta(3)\ln^22-\frac{\pi^4}{120}\ln2-\frac{1}{4}\ln^52\\&\ -6\color{blue}{\mathbf{H}_{4}\left(\frac12\right)}+6\operatorname{Li}_4\left(\frac12\right)\ln 2+6\operatorname{Li}_5\left(\frac12\right).\end{align}Using the similar approach as calculating the blue integral, then\begin{align}\int\frac{\ln^3x\ln (1-x)}{x}\ dx&=-\int\sum_{n=1}^\infty \frac{x^{n-1}}{n}\ln^3x\ dx\\&=-\sum_{n=1}^\infty \frac{1}{n}\int x^{n-1}\ln^3x\ dx\\&=-\sum_{n=1}^\infty \frac{1}{n}\frac{\partial^3}{\partial n^3}\left[\int x^{n-1}\ dx\right]\\&=-\sum_{n=1}^\infty \frac{1}{n}\frac{\partial^3}{\partial n^3}\left[\frac{x^{n}}{n}\right]\\&=-\sum_{n=1}^\infty \frac{1}{n}\left[\frac{x^{n}\ln^3x}{n}-\frac{3x^{n}\ln^2x}{n^2}+\frac{6x^{n}\ln x}{n^3}-\frac{6x^{n}}{n^4}\right]\\&=\sum_{n=1}^\infty \left[-\frac{x^{n}\ln^3x}{n^2}+\frac{3x^{n}\ln^2x}{n^3}-\frac{6x^{n}\ln x}{n^4}+\frac{6x^{n}}{n^5}\right]\\&=6\operatorname{Li}_5(x)-6\operatorname{Li}_4(x)\ln x+3\operatorname{Li}_3(x)\ln^2x-\operatorname{Li}_2(x)\ln^3x.\end{align}Hence$$\int_{\large\frac{1}{2}}^1\frac{\ln^3x\ln (1-x)}{x}\ dx=\frac{\pi^2}{6}\ln^32-\frac{21}{8}\zeta(3)\ln^22-6\operatorname{Li}_4\left(\frac{1}{2}\right)\ln2-6\operatorname{Li}_5\left(\frac{1}{2}\right)+6\zeta(5).$$Combining altogether, we have \begin{align}I=&\ \frac{\pi^4}{120}\ln2-\frac{33}4\zeta(3)\ln^22+\frac{\pi^2}2\ln^32-\frac{11}{20}\ln^52+6\zeta(5)+\pi^2\zeta(3)\\&\ +6\color{blue}{\mathbf{H}_{4}\left(\frac12\right)}-18\operatorname{Li}_4\left(\frac12\right)\ln2-24\operatorname{Li}_5\left(\frac12\right).\end{align} Continuing my answer in: A sum containing harmonic numbers $\displaystyle\sum_{n=1}^\infty\frac{H_n}{n^3\,2^n}$ , we have\begin{align}\color{blue}{\mathbf{H}_{3}\left(x\right)}=&\frac12\zeta(3)\ln x-\frac18\ln^2x\ln^2(1-x)+\frac12\ln x\left[\color{blue}{\mathbf{H}_{2}\left(x\right)}-\operatorname{Li}_3(x)\right]\\&+\operatorname{Li}_4(x)-\frac{\pi^2}{12}\operatorname{Li}_2(x)-\frac12\operatorname{Li}_3(1-x)\ln x+\frac{\pi^4}{60}.\tag1\end{align}Dividing $(1)$ by $x$ and then integrating yields$$\small\begin{align}\color{blue}{\mathbf{H}_{4}\left(x\right)}=&\frac14\zeta(3)\ln^2 x-\frac18\int\frac{\ln^2x\ln^2(1-x)}x\ dx+\frac12\int\frac{\ln x}x\bigg[\color{blue}{\mathbf{H}_{2}\left(x\right)}-\operatorname{Li}_3(x)\bigg]\ dx\\&+\operatorname{Li}_5(x)-\frac{\pi^2}{12}\operatorname{Li}_3(x)-\frac12\int\frac{\operatorname{Li}_3(1-x)\ln x}x\ dx+\frac{\pi^4}{60}\ln x\\=&\frac14\zeta(3)\ln^2 x+\frac{\pi^4}{60}\ln x+\operatorname{Li}_5(x)-\frac{\pi^2}{12}\operatorname{Li}_3(x)-\frac18\color{red}{\int\frac{\ln^2x\ln^2(1-x)}x\ dx}\\&+\frac12\left[\color{purple}{\sum_{n=1}^\infty\frac{H_{n}}{n^2}\int x^{n-1}\ln x\ dx}-\color{green}{\int\frac{\operatorname{Li}_3(x)\ln x}x\ dx}-\color{orange}{\int\frac{\operatorname{Li}_3(1-x)\ln x}x\ dx}\right].\tag2\end{align}$$Evaluating the red integral using the same technique as the previous one yields\begin{align}\color{red}{\int\frac{\ln^2x\ln^2(1-x)}x\ dx}&=\frac13\ln^3x\ln^2(1-x)-\frac23\color{blue}{\int\frac{\ln(1-x)\ln^3 x}{1-x}\ dx}.\end{align}Evaluating the purple integral yields\begin{align}\color{purple}{\sum_{n=1}^\infty\frac{H_{n}}{n^2}\int x^{n-1}\ln x\ dx}&=\sum_{n=1}^\infty\frac{H_{n}}{n^2}\frac{\partial}{\partial n}\left[\int x^{n-1}\ dx\right]\\&=\sum_{n=1}^\infty\frac{H_{n}}{n^2}\left[\frac{x^n\ln x}{n}-\frac{x^n}{n^2}\right]\\&=\color{blue}{\mathbf{H}_{3}(x)}\ln x-\color{blue}{\mathbf{H}_{4}(x)}.\end{align}Evaluating the green integral using IBP by setting $u=\ln x$ and $dv=\dfrac{\operatorname{Li}_3(x)}{x}\ dx$ yields\begin{align}\color{green}{\int\frac{\operatorname{Li}_3(x)\ln x}x\ dx}&=\operatorname{Li}_4(x)\ln x-\int\frac{\operatorname{Li}_4(x)}x\ dx\\&=\operatorname{Li}_4(x)\ln x-\operatorname{Li}_5(x).\end{align}Evaluating the orange integral using IBP by setting $u=\operatorname{Li}_3(1-x)$ and $dv=\dfrac{\ln x}{x}\ dx$ yields\begin{align}\color{orange}{\int\frac{\operatorname{Li}_3(1-x)\ln x}x\ dx}&=\frac12\operatorname{Li}_3(1-x)\ln^2 x+\frac12\color{maroon}{\int\frac{\operatorname{Li}_2(1-x)\ln^2 x}{1-x}\ dx}.\end{align}Applying IBP again to evaluate the maroon integral by setting $u=\operatorname{Li}_2(1-x)$ and$$dv=\dfrac{\ln^2 x}{1-x}\ dx\quad\Rightarrow\quadv=2\operatorname{Li}_3(x)-2\operatorname{Li}_2(x)\ln x-\ln(1-x)\ln^2x,$$we have$$\small{\begin{align}\color{maroon}{\int\frac{\operatorname{Li}_2(1-x)\ln^2 x}{1-x}\ dx}=&\left[2\operatorname{Li}_3(x)-2\operatorname{Li}_2(x)\ln x-\ln(1-x)\ln^2x\right]\operatorname{Li}_2(1-x)\\&-2\int\frac{\operatorname{Li}_3(x)\ln x}{1-x}\ dx+2\int\frac{\operatorname{Li}_2(x)\ln x}{1-x}\ dx+\color{blue}{\int\frac{\ln(1-x)\ln^3 x}{1-x}\ dx}.\end{align}}$$ We use the generating function for the generalized harmonic numbers evaluate the above integrals involving polylogarithm. \begin{align}\int\frac{\operatorname{Li}_k(x)\ln x}{1-x}\ dx&=\sum_{n=1}^\infty H_{n}^{(k)}\int x^n\ln x\ dx\\&=\sum_{n=1}^\infty H_{n}^{(k)}\frac{\partial}{\partial n}\left[\int x^n\ dx\right]\\&=\sum_{n=1}^\infty H_{n}^{(k)}\left[\frac{x^{n+1}\ln x}{n+1}-\frac{x^{n+1}}{(n+1)^2}\right]\\&=\sum_{n=1}^\infty\left[\frac{H_{n+1}^{(k)}x^{n+1}\ln x}{n+1}-\frac{x^{n+1}\ln x}{(n+1)^{k+1}}-\frac{H_{n+1}^{(k)}x^{n+1}}{(n+1)^2}+\frac{x^{n+1}}{(n+1)^{k+2}}\right]\\&=\sum_{n=1}^\infty\left[\frac{H_{n}^{(k)}x^{n}\ln x}{n}-\frac{x^{n}\ln x}{n^{k+1}}-\frac{H_{n}^{(k)}x^{n}}{n^2}+\frac{x^{n}}{n^{k+2}}\right]\\&=\color{blue}{\mathbf{H}_{1}^{(k)}(x)}\ln x-\operatorname{Li}_{k+1}(x)\ln x-\color{blue}{\mathbf{H}_{2}^{(k)}(x)}+\operatorname{Li}_{k+2}(x).\end{align} Dividing generating function of $\color{blue}{\mathbf{H}^{(k)}(x)}$ by $x$ and then integrating yields \begin{align}\sum_{n=1}^\infty \frac{H_{n}^{(k)}x^n}{n}&=\int\frac{\operatorname{Li}_k(x)}{x(1-x)}\ dx\\\color{blue}{\mathbf{H}_{1}^{(k)}(x)}&=\int\frac{\operatorname{Li}_k(x)}{x}\ dx+\int\frac{\operatorname{Li}_k(x)}{1-x}\ dx\\&=\operatorname{Li}_{k+1}(x)+\int\frac{\operatorname{Li}_k(x)}{1-x}\ dx.\end{align} Repeating the process above yields \begin{align}\sum_{n=1}^\infty \frac{H_{n}^{(k)}x^n}{n^2}&=\int\frac{\operatorname{Li}_{k+1}(x)}{x}\ dx+\int\frac{\operatorname{Li}_k(x)}{x(1-x)}\ dx\\\color{blue}{\mathbf{H}_{2}^{(k)}(x)}&=\operatorname{Li}_{k+2}(x)+\operatorname{Li}_{k+1}(x)+\int\frac{\operatorname{Li}_k(x)}{1-x}\ dx,\end{align} where it is easy to show by using IBP that \begin{align}\int\frac{\operatorname{Li}_2(x)}{1-x}\ dx&=-\int\frac{\operatorname{Li}_2(1-x)}{x}\ dx\\&=2\operatorname{Li}_3(x)-2\operatorname{Li}_2(x)\ln(x)-\operatorname{Li}_2(1-x)\ln x-\ln (1-x)\ln^2x\end{align} and $$\int\frac{\operatorname{Li}_3(x)}{1-x}\ dx=-\int\frac{\operatorname{Li}_3(1-x)}{x}\ dx=-\frac12\operatorname{Li}_2^2(1-x)-\operatorname{Li}_3(1-x)\ln x.$$ Now, all unknown terms have been obtained. Putting altogether to $(2)$, we have$$\small{\begin{align}\color{blue}{\mathbf{H}_{4}(x)}=&\ \frac1{10}\zeta(3)\ln^2 x+\frac{\pi^4}{150}\ln x-\frac{\pi^2}{30}\operatorname{Li}_3(x)-\frac1{60}\ln^3x\ln^2(1-x)+\frac65\operatorname{Li}_5(x)\\&-\frac15\left[\operatorname{Li}_3(x)-\operatorname{Li}_2(x)\ln x-\frac12\ln(1-x)\ln^2x\right]\operatorname{Li}_2(1-x)-\frac15\operatorname{Li}_4(x)\\&-\frac35\operatorname{Li}_4(x)\ln x+\frac15\operatorname{Li}_3(x)\ln x+\frac15\operatorname{Li}_3(x)\ln^2x-\frac1{10}\operatorname{Li}_3(1-x)\ln^2 x\\&-\frac1{15}\operatorname{Li}_2(x)\ln^3x-\frac15\color{blue}{\mathbf{H}_{2}^{(3)}(x)}+\frac15\color{blue}{\mathbf{H}_{2}^{(2)}(x)}+\frac15\color{blue}{\mathbf{H}_{1}^{(3)}(x)}\ln x\\&-\frac15\color{blue}{\mathbf{H}_{1}^{(2)}(x)}\ln x+\frac25\color{blue}{\mathbf{H}_{3}(x)}\ln x-\frac15\color{blue}{\mathbf{H}_{2}(x)}\ln^2x+\frac1{15}\color{blue}{\mathbf{H}_{1}(x)}\ln^3x+C.\tag3\end{align}}$$The next step is finding the constant of integration. Setting $x=1$ to $(3)$ yields$$\small{\begin{align}\color{blue}{\mathbf{H}_{4}(1)}&=-\frac{\pi^2}{30}\operatorname{Li}_3(1)+\frac65\operatorname{Li}_5(1)-\frac15\operatorname{Li}_4(1)-\frac15\color{blue}{\mathbf{H}_{2}^{(3)}(1)}+\frac15\color{blue}{\mathbf{H}_{2}^{(2)}(1)}+C\\3\zeta(5)+\zeta(2)\zeta(3)&=-\frac{\pi^2}{30}\operatorname{Li}_3(1)+\frac{19}{30}\operatorname{Li}_5(1)+\frac{3}{5}\operatorname{Li}_3(1)+C\\C&=\frac{\pi^4}{450}+\frac{\pi^2}{5}\zeta(3)-\frac35\zeta(3)+3\zeta(5).\end{align}}$$Thus$$\small{\begin{align}\color{blue}{\mathbf{H}_{4}(x)}=&\ \frac1{10}\zeta(3)\ln^2 x+\frac{\pi^4}{150}\ln x-\frac{\pi^2}{30}\operatorname{Li}_3(x)-\frac1{60}\ln^3x\ln^2(1-x)+\frac65\operatorname{Li}_5(x)\\&-\frac15\left[\operatorname{Li}_3(x)-\operatorname{Li}_2(x)\ln x-\frac12\ln(1-x)\ln^2x\right]\operatorname{Li}_2(1-x)-\frac15\operatorname{Li}_4(x)\\&-\frac35\operatorname{Li}_4(x)\ln x+\frac15\operatorname{Li}_3(x)\ln x+\frac15\operatorname{Li}_3(x)\ln^2x-\frac1{10}\operatorname{Li}_3(1-x)\ln^2 x\\&-\frac1{15}\operatorname{Li}_2(x)\ln^3x-\frac15\color{blue}{\mathbf{H}_{2}^{(3)}(x)}+\frac15\color{blue}{\mathbf{H}_{2}^{(2)}(x)}+\frac15\color{blue}{\mathbf{H}_{1}^{(3)}(x)}\ln x\\&-\frac15\color{blue}{\mathbf{H}_{1}^{(2)}(x)}\ln x+\frac25\color{blue}{\mathbf{H}_{3}(x)}\ln x-\frac15\color{blue}{\mathbf{H}_{2}(x)}\ln^2x+\frac1{15}\color{blue}{\mathbf{H}_{1}(x)}\ln^3x\\&+\frac{\pi^4}{450}+\frac{\pi^2}{5}\zeta(3)-\frac35\zeta(3)+3\zeta(5)\tag4\end{align}}$$and setting $x=\frac12$ to $(4)$ yields\begin{align}\color{blue}{\mathbf{H}_{4}\left(\frac12\right)}=&\ \frac{\ln^52}{40}-\frac{\pi^2}{36}\ln^32+\frac{\zeta(3)}{2}\ln^22-\frac{\pi^2}{12}\zeta(3)\\&+\frac{\zeta(5)}{32}-\frac{\pi^4}{720}\ln2+\operatorname{Li}_4\left(\frac12\right)\ln2+2\operatorname{Li}_5\left(\frac12\right).\tag5\end{align} Finally, we obtain \begin{align}\int_0^1\frac{\ln^3(1+x)\ln x}x\ dx=&\ \color{blue}{\frac{\pi^2}2\zeta(3)+\frac{99}{16}\zeta(5)-\frac25\ln^52+\frac{\pi^2}3\ln^32-\frac{21}4\zeta(3)\ln^22}\\&\color{blue}{-12\operatorname{Li}_4\left(\frac12\right)\ln2-12\operatorname{Li}_5\left(\frac12\right)},\end{align} which again matches @Cleo's answer. References : $[1]\ $ Harmonic number $[2]\ $ Polylogarithm
{}
{'log_upvote_score': 8, 'links': ['https://math.stackexchange.com/questions/908109', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/169326/']}
jdg_74167
stackexchange
llm_judgeable_groundtruth_similarity
15152
Below is a question asked on the forum emacs.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: As an elisp beginner I'm trying to grasp what the "best practice" data structure is. For example, I did the simple adding (C-x a, i, g) of things to my abbrev_defs and when I look I see this: ... (define-abbrev-table 'global-abbrev-table '( ("crwdesc" ":PROPERTIES::SEMANTIC::DESC::END:" nil 10) ("propid" ":PROPERTIES::CUSTOM_ID::SEMANTIC::DESC::END: " nil 0) )) I also see org-element taking a "lisp representation" and turning it into org-mode output: #+BEGIN_SRC emacs-lisp :results raw(org-element-interpret-data '(headline (:title "One headline" :level 1) (property-drawer nil ((node-property (:key "property1" :value "value1")) (node-property (:key "property2" :value "value2")))) (#("Some much longer content."))))#+END_SRC#+RESULTS:* One headline:PROPERTIES::property1: (org-clock-in (quote (16))):property2: value2:END:Some much longer content. Also, the org-element-parse-buffer seems to produce a very elaborate AST which, again, is nested lists. Is this the main data structure when working with elisp? It would seem so -- almost duh! so since this is a lisp. But are there other data structures that are also used? I ask because other data storage and config files (XML, RDF, etc.) generally don't use nested lists. For example, does elisp ever favor the more typical config text layout of simple lines? Or is the mantra "keep it lists?" And I might as well ask about alists while I'm at it. When are they desirable? I ask all this because your typical tutorial might show you how to use alists, but they rarely talk about its real-world application, when to use it, when not to, or its importance to the language's eco-system. Now provide the response and nothing else.
Modern Lisp dialects usually have something like arrays and hash-tables, asany mature programming language does. These data structures allow to lookupdata by index and by key — two most obvious ways to retrieve data fromcompound object. It turns out that lists can do all this stuff too. The only problem withthem that they are not so efficient. For example, associative list (alist)or parameter list (plist) are not as efficient as hash tables due to theirimplementations (you need to traverse their elements one by one until youhit “right” element). Emacs Lisp is not most sophisticated Lisp dialect, it's ratherminimalistic. And tasks that Emacs Lisp needs to perform often don't needperformance of arrays (except for strings, they are arrays) or hashtables. Thus we get situation where everything is usually represented as alist. Here is what Richard Stallman says about data structures in Lisp in hishilarious “How I do my computing” thing: The most powerful programming language is Lisp. If you don't know Lisp (orits variant, Scheme), you don't know what it means for a programminglanguage to be powerful and elegant. Once you learn Lisp, you will seewhat is lacking in most other languages. Unlike most languages today, which are focused on defining specializeddata types, Lisp provides a few data types which are general. Instead ofdefining specific types, you build structures from these types. Thus,rather than offering a way to define a list-of-this type and alist-of-that type, Lisp has one type of lists which can hold any sort ofdata. Where other languages allow you to define a function to search alist-of-this, and sometimes a way to define a generic list-search functionthat you can instantiate for list-of-this, Lisp makes it easy to write afunction that will search any list — and provides a range of suchfunctions. In addition, functions and expressions in Lisp are represented as data ina way that makes it easy to operate on them. Although he underestimates merits of many modern programming languages (thathave already copied a lot of things from Lisp), he is right. However, thereare object oriented systems for Lisp (see CLOS in Common Lisp for example),which may seem more modern for some, and yes, they are definitelyuseful. Not sure if there is object system for Emacs Lisp, as I said it'squite minimalistic.
{}
{'log_upvote_score': 4, 'links': ['https://emacs.stackexchange.com/questions/15152', 'https://emacs.stackexchange.com', 'https://emacs.stackexchange.com/users/8349/']}
jdg_74168
stackexchange
llm_judgeable_groundtruth_similarity
23075397
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 installed some package via pip install something . I want to edit the source code for the package something . Where is it (on ubuntu 12.04) and how do I make it reload each time I edit the source code and run it? Currently I am editing the source code, and then running python setup.py again and again, which turns out to be quite a hassle. Now provide the response and nothing else.
You should never edit an installed package. Instead, install a forked version of package. If you need to edit the code frequently, DO NOT install the package via pip install something and edit the code in '.../site_packages/...' Instead, put the source code under a development directory, and install it with $ python setup.py develop or $ pip install -e path/to/SomePackage Or use a vcs at the first place $ pip install -e git+https://github.com/lakshmivyas/hyde.git#egg=hyde Put your changes in a version control system, and tell pip to install it explicitly. Reference: Edit mode
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/23075397', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/364914/']}
jdg_74169
stackexchange
llm_judgeable_groundtruth_similarity
2739552
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Possible Duplicate: Unexpected feature in a Python list of lists So I am relatively new to Python and I am having trouble working with 2D Lists. Here's my code: data = [[None]*5]*5data[0][0] = 'Cell A1'print data and here is the output (formatted for readability): [['Cell A1', None, None, None, None], ['Cell A1', None, None, None, None], ['Cell A1', None, None, None, None], ['Cell A1', None, None, None, None], ['Cell A1', None, None, None, None]] Why does every row get assigned the value? Now provide the response and nothing else.
This makes a list with five references to the same list: data = [[None]*5]*5 Use something like this instead which creates five separate lists: >>> data = [[None]*5 for _ in range(5)] Now it does what you expect: >>> data[0][0] = 'Cell A1'>>> print data[['Cell A1', None, None, None, None], [None, None, None, None, None], [None, None, None, None, None], [None, None, None, None, None], [None, None, None, None, None]]
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/2739552', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/329165/']}
jdg_74170
stackexchange
llm_judgeable_groundtruth_similarity
35904436
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: As you see below, I reverted a commit in local repository and commited but not pushed 2 other changes. But the remote repository still has the commit I reverted. So how can I make the remote repository exactly the local one? (I want to remove that purple branch and push 2 local commits) The repository is personal, no risk of somebody gets out of sync. Thanks in advance. Note: I am a noob at git, so it would be great if you explain your answers clearly. Now provide the response and nothing else.
The problem is within the new support library 23.2.0 , so I reverted that to 23.1.1 and it works fine. If I find a solution, or what to change, I will let you know, otherwise I'm leaving this thread open, if someone else finds a better answer. UPDATE Ok, so I decided it was time to fix this, as we need to move to new support libraries and I finally found an answer. The problem was/is that the new LayoutManager is using autoMeasure() and somehow it changed all my match_parent to wrap_content , so here is what you need to do, if you encounter a similar problem. First create LinearLayoutManager llm = new LinearLayoutManager(getActivity()); then llm.setAutoMeasureEnabled(false); and finally you set the LinearLayoutManager to your RecyclerView , but do this AFTER recyclerView.setAdapter(yourAdapter); Here is a quick example: recyclerView.setAdapter(adapter);recyclerView.setHasFixedSize(true);LinearLayoutManager llm = new LinearLayoutManager(getActivity());llm.setAutoMeasureEnabled(false);recyclerView.setLayoutManager(llm);
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/35904436', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_74171
stackexchange
llm_judgeable_groundtruth_similarity
48818110
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 Vue application.It has a header and then the main content.Nesting and structure as below TheHeader.vue -> TheLogin.vueMainContent.vue -> ShoppingCart.vue -> OrderSummary.vue I need to access an element in TheLogin.vue from OrderSummary.vue this.$refs.loginPopover.$emit('open') gives me an error "Cannot read property '$emit' of undefined" so obviously I am not able to access $refs from other components. The question is how do I get hold of refs from other components?Thanks in advance! Edit 1 - Found out $refs works with only child components.How do I access elements across components in different level? Now provide the response and nothing else.
You definitely don't want to be reaching through the hierarchy like that. You are breaking encapsulation. You want a global event bus . And here's a secret: there's one built in, called $root . Have your OrderSummary do this.$root.emit('openPopup'); and set up a listener in your TheLogin's created hook: this.$root.on('openPopup', () => this.$emit('open')); In general, you should try to avoid using refs.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/48818110', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3555262/']}
jdg_74172
stackexchange
llm_judgeable_groundtruth_similarity
275158
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Suppose I have to put $N$ points $x_1, x_2, \ldots, x_N$ on the circle $S^1$ of length 1 so as to achieve the largest minimum separation (packing radius). The optimal solution is the equally spaced arrangement $x_k = k/N \bmod 1$, which achieves $\min_{i<j}\|x_i-x_j\| = 1/N$. However, suppose I didn't know in advance the number of points $N$ I needed to put down, and I had to put the points down one by one. I am not allowed to move points that are already placed, and I want to a process that, when compared to the optimum for fixed $N$, does not do much worse asymptotically. More precisely: Problem : what is the sequence $x_i$, $i=1,2,\ldots$, that maximizes $\mu=\lim\inf_N \min_{1\le i<j\le N} \|x_i-x_j\|/(1/N)$? First example: greedy process. Put the first point at 0, the second at 1/2, and each subsequent one so as to bisect the largest empty interval. This gives $\mu=1/2$: when we add the $(2^k+1)$th point, the smallest separation is $1/2^{k+1}$. Second example: Let $x_k = k\phi \bmod 1$, where $\phi = (\sqrt{5}-1)/2\approx 0.618$ is the inverse golden ratio. This process achieves $\mu = \phi$. Conjecture : $\mu = \phi$ is optimal. I think I know how to prove that among linear sequences $x_k = k\alpha$, that $\alpha=\phi$ (or any quadratic irrational whose continued fraction expansion is eventually all ones) is optimal, and I can start to imagine how to treat polynomial sequences, but I would like to know whether it's true that no sequence can do better than $x_k = k \phi$. Motivation : the motivation for this problem is from phyllotaxis (the arrangement of leaves and other plant parts along the growth a plant), where the golden angle and Fibonacci spirals are commonly observed. Many researchers from D'arcy Thompson to Adil Mughal and Denis Weaire have proposed mechanism associated with packing problems that result in the appearance of the golden angle and Fibonacci spirals. From a mathematical perspective, the optimization problem I propose here seems to be the neatest and most succinct that has this pattern as a solution. UPDATE : Christian Remling's answer, which I have accepted, provides convincing evidence that my conjecture is in fact wrong, which is very exciting. His answer gives an alternative process, which might be able to give the real optimal $\mu$. I added an answer heuristically analyzing Christian's process and arguing that $\mu=1/\log(4)\approx 0.721$ might be the optimal asymptotic separation that can be achieved with this process. Now provide the response and nothing else.
I will show $\mu = \tfrac{1}{\log 4}$ . I first prove the upper bound $\mu \leq \tfrac{1}{\log 4}$ . Fix a positive integer $r$ . For $0 \leq k \leq r-1$ , let $N_k$ be $2^{k/r} N$ rounded to the nearest integer, where $N$ is a large parameter. Considering the $N_{r-1}$ intervals present at time $N_{r-1}$ , let $X_k$ be the number of them created between times $N_{k-1}$ and $N_k$ ; with $X_0$ the number created before time $N_0$ . Then $$X_0 \frac{\mu}{N_0} + X_1 \frac{\mu}{N_1} + \cdots + X_{r-1} \frac{\mu}{N_{r-1}} \leq 1.$$ Set $S_k=X_0+X_1+\cdots +X_k$ ; we can rewrite the above equation as $$\mu \left( S_0 \left(\frac{1}{N_0} - \frac{1}{N_1}\right) + S_1 \left(\frac{1}{N_1} - \frac{1}{N_2} \right) + \cdots + S_{r-2} \left(\frac{1}{N_{r-2}} - \frac{1}{N_{r-1}}\right) + S_{r-1} \frac{1}{N_{r-1}} \right) \leq 1.$$ Now, $S_k$ is the number of those intervals present at final time $N_{r-1}$ which were created before time $N_k$ , so we have $S_k \geq N_k - (N_{r-1} - N_k)=2 N_k - N_{r-1}$ . The coefficient $\tfrac{1}{N_k} - \tfrac{1}{N_{k+1}}$ on the left hand side is positive, so we have $$\mu \left( (2N_0-N_{r-1}) \left(\frac{1}{N_0} - \frac{1}{N_1}\right)+(2N_1-N_{r-1}) \left(\frac{1}{N_1} - \frac{1}{N_2}\right)+\cdots+(2N_{r-2}-N_{r-1}) \left(\frac{1}{N_{r-2}} - \frac{1}{N_{r-1}}\right)+\frac{N_{r-1}}{N_{r-1}} \right) \leq 1.$$ We gather terms with the same denominator to obtain $$\mu \left( \frac{2N_0-N_{r-1}}{N_0} + \frac{2 N_1 - 2 N_0}{N_1} + \cdots + \frac{2 N_{r-1} - 2 N_{r-2}}{N_{r-1}} \right) \leq 1$$ or $$\mu \left( 2r - \frac{N_{r-1}}{N_0} - \frac{2 N_0}{N_1} - \cdots - \frac{2 N_{r-2}}{N_{r-1}} \right) \leq 1.$$ Plugging in our optimized values: $$\mu \left( 2r - r 2^{(r-1)/r} \right) \leq 1$$ so $$\mu \leq \frac{1}{2r (1-2^{-1/r})}.$$ Finally, taking the limit as $r \to \infty$ gives $\mu \leq \tfrac{1}{\log 4}$ as promised. Now, for the lower bound. Again, fix a positive integer $r$ . Divide the circle into $r$ equal arcs; each arc will be subdivided into intervals. At any point in our process there will be some integer $k$ such that one arc is divided into some intervals of length $2^{-k/r}$ and some of length $2^{-(k+r)/r}$ ; the other $r-1$ arcs will contain intervals of only one length, namely $2^{-j/r}$ for $k<j<k+r$ . (Obviously, I am ignoring rounding issues.) As time ticks on, we subdivide the intervals in the first arc until they are all split in half, then move to the next arc, and so on. This achieves (again, ignoring rounding) $$\mu = 2^{-(k+r)/r} \left( \frac{2^{k/r}}{r} +\frac{2^{(k+1)/r}}{r} + \cdots \frac{2^{(k+r-1)/r}}{r} \right) = \frac{1}{2r(2^{1/r}-1)}.$$ Again, sending $r \to \infty$ achieves $\tfrac{1}{\log 4}$ . Here is a slicker, though less motivated way, to achieve the lower bound. We will number the points starting with $x_0$ at position $0$ . For $n >0$ , write $n = 2^q+r$ with $0 \leq r <2^q$ and put $x_n$ at $\log_2\left(\tfrac{2n+1}{2^{q+1}}\right)$ . So the first few points are $0$ , $\log_2(1+1/2)$ , $\log_2(1+1/4)$ , $\log_2(1+3/4)$ , $\log_2(1+1/8)$ , $\log_2(1+3/8)$ , $\log_2(1+5/8)$ , $\log_2(1+7/8)$ , ... When point $x_n$ is inserted, the smallest interval will either be the one just to the right of $x_n$ or else the furthest right interval. Approximating $\log$ by its linearization, these have lengths roughly $\tfrac{2^{q+1}}{(2n+1) \log 2} \tfrac{1}{2^{q+1}}=\tfrac{1}{(2n+1) \log 2}$ and $\tfrac{1}{2 \log 2} \tfrac{1}{2^q}=\tfrac{1}{2^{q+1} \log 2}$ respectively. Multiplying these by $n+1$ (the number of intervals) gives $\tfrac{n+1}{(2n+1) \log 2}$ and $\tfrac{n+1}{2^{q+1} \log 2}$ . The former approaches $\tfrac{1}{\log 4}$ while the latter oscillates between $\tfrac{1}{\log 2}$ and $\tfrac{1}{\log 4}$ .
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/275158', 'https://mathoverflow.net', 'https://mathoverflow.net/users/20186/']}
jdg_74173
stackexchange
llm_judgeable_groundtruth_similarity
35231
Below is a question asked on the forum cs.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: This is a question on a practice final. Problem A is polynomially reducible to problem B. Which of the following statements is correct? I. If problem A is solvable in a polynomial time then problem B is solvable in polynomial time . II. If problem A is NP-complete then problem B is NP-complete . III. If problem A is NP-hard then problem B is NP-hard a) I b) II c) III d) I and II e) I, II and III We are told that the solution is (c), but there's no explanation why on the key. I have tried to figure this out, and the only conclusion I've come to is: (I) cannot be true because if A is polynomially reducible to B, this implies B is at least as hard as A. (Not sure if this is a correct conclusion, so feedback on this would be appreciated.) This is the first time I'm learning about the notion of hardness, so I don't understand most of the technical explanations I've found. Any clarifications on why II is incorrect, and why III is correct would be appreciated. Self study I've done includes reading multiple StackExchange posts, multiple Wiki pages, and the corresponding section in the Cormen book. I just personally understand concepts better if I see different explanations. Now provide the response and nothing else.
Your intuition about "relative hardness" is correct, the underlying mathematics is why III. is true. However your justification about I. is a little off (not wrong, but the reasoning is possibly not accurate). It might help to think about reductions in these terms (everything I'll talk about here will be polynomial time, so I will leave that out just so I don't have to type it over and over); a reduction (from A to B) is just an algorithm that turns an instance of A into an instance of B, with the special property that if we know/can figure out/can use magic to find out the answer to the instance of B, we know the answer to the original instance of A. This gives us a way of solving problem A if we already know how to solve B. This is why we say things like "B is at least as hard as A", because any algorithm for B immediately gives an algorithm for A. To flip it around, if we knew B was "easy", then A must also be "easy" (for some notion of "easy"). Notice that this relationship is not symmetric - knowing how to solve A doesn't tell us anything about how to solve B (given that all we have is the single reduction). If we had more information, maybe it would, maybe it wouldn't, but from the reduction alone we get nothing in that direction. So then for I., we know we can turn an A into a B, and that we can solve an A, but this tells us nothing about B. For III., we already know that A is hard (NP-hard!), and the reduction tells us that B is at least as hard as A, so B must also be NP-hard. The formal truth behind this intuition comes from the definition of NP-hardness. Remember that A being NP-hard means every single problem in NP has a reduction to A. We also know that A reduces to B, so how does this show B is NP-hard? We can compose the reductions. For every C in NP, we can reduce every instance of it to an instance of A, then take that instance of A and use our new reduction to turn it into an instance of B (as an exercise you might want to think about why we still know this is all polynomial time etc.). So this gives us a way of turning every problem C in NP into problem B, which is the definition of NP-hardness. Coming back to II., this one again relies on definitions. NP-completeness is NP-hardness, plus the additional property that the problem is in NP. So saying problem A is NP-complete means problem A is NP-hard and A is in NP. We've just seen that the reduction to B tells us that B is NP-hard, so we have that part, but just like part I., where A being in P didn't tell us whether B was in P or not, A being in NP doesn't tell us whether B is in NP or not. It might be, but the reduction doesn't give us this information.
{}
{'log_upvote_score': 5, 'links': ['https://cs.stackexchange.com/questions/35231', 'https://cs.stackexchange.com', 'https://cs.stackexchange.com/users/25716/']}
jdg_74174
stackexchange
llm_judgeable_groundtruth_similarity
56402093
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 with an initializer that does some monkey patching on app start by including some app concerns into a third party lib. Basically: # config/initializers/my_initializer.rbclass SomeExternalLib include MyConcern1 include MyConcern2end This works fine in Rails 5.2.3, but I got the following deprecation message when upgrading to Rails 6: DEPRECATION WARNING: Initialization autoloaded the constants MyConcern1, and MyConcern2. Being able to do this is deprecated. Autoloading during initialization is going to be an error condition in future versions of Rails. Reloading does not reboot the application, and therefore code executed during initialization does not run again. So, if you reload ApplicationHelper, for example, the expected changes won't be reflected in that stale Module object. These autoloaded constants have been unloaded. Please, check the "Autoloading and Reloading Constants" guide for solutions. (called from at /Users/myuser/code/myapp/config/environment.rb:7) My concerns are in app/controllers/concerns/. After some investigation, I figured out that that path wasn't being autoloaded, but I can't figure out how to make Zeitwerk—Rails 6's new autoloader—load this dynamically. I tried following the pattern for STI autoloading described here , but no luck. Any idea how to address this deprecation warning? Now provide the response and nothing else.
As described by @Glyoko's answer, using require on dependencies prevents autoloading in initializers. However, doing so leads to problems during reloading as @Puhlze mentioned in his comment. I stumbled across an alternate approach that utilizes Rails.configuration.to_prepare in this post . An example would be: # config/initializers/my_initializer.rbRails.configuration.to_prepare do class SomeExternalLib include MyConcern1 include MyConcern2 endend Note that this runs before every request in development but only once before eager loading in production. Edit: it appears to also work with reloading.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/56402093', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4067720/']}
jdg_74175
stackexchange
llm_judgeable_groundtruth_similarity
356475
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: The question is motivated by my failed comment to this one . Let $M$ and $N$ be path connected locally compact, locally contractible metric spaces (you may assume that they are manifolds). Let $\varphi_{n}:M\to N$ be null-homotopic and convergent to $\varphi:M\to N$ in the compact open topology. Does it follow that $\varphi$ is null-homotopic? Note that homotopy between maps is a path in $C(M,N)$ (for nice $M$ , $N$ ), and so what my question asks is whether the path component of a constant map is closed in $C(M,N)$ . I am waaay out of my depth here, but perhaps there is a continuous or positive lower semi-continuous functional on $C(M,N)$ akin to the topological degree such that null-homotopic maps would be the zero-set of that functional? Now provide the response and nothing else.
I'll provide a general theorem (then one has to apply it to specific circumstances). There is a micro-dictionary/Notation at the bottom of this note. B-assumption :   Space $\ N\times N\times[0;1]\ $ is normal. Every metric space $\ N\ $ satisfies B-assumption . Notation Let $\ \mathcal W_N\ $ be the set of all closedneighborhoods of diagonal $\ \Delta_N\ :=\ \{(y\ y):\ y\in N\}\ $ in $\ N\times N.$ Family $\ \mathcal W_N\ $ is a basis of all neighborhoods of the diagonal $\ \Delta_N.$ A-assumption :   Space $\ N\ $ is an ANR, meaning thatfor every normal space $\ X\ $ and closed subset $\ A\ $ of $\ X,\ $ and for every continuous function $\ f:A\to N\ $ there existsa neighborhood $\ U\ $ of $\ A\ $ and continuous $\ F:U\to N\ $ suchthat $\ F|A=f.$ Thus, $\ N^2\ $ is an ANR too. Definition :   Sequence $\ f_n:M\to N\ $ is d-convergent to $\ f:M\to N\ \Leftarrow:\Rightarrow $ $$ \forall_{V\in\mathcal W_N}\exists_{m\in\Bbb N} \forall_{n\ge m}\quad (f_n\triangle f)(M)\, \subseteq V $$ Only continuous functions are meant: THEOREM Let sequence $\ f_n:M\to N\ $ be d-convergentto $\ f:M\to N.\ $ Then there exists $\ m\in\Bbb N\ $ such that $\ f_n\ $ and $\ f\ $ are homotopic for every $\ n\ge m.$ PROOF Diagonal $\ \Delta_N\ $ is an ANR because it ishomeomorphic to $\ N.\ $ Also, $\ \Delta_N\ $ is closed in $\ N^2\ $ since $\ N\ $ is Hausdorff.  Thus, there exists $\ U\in\mathcal W_N\ $ and a retraction $\ \rho:U\to\Delta_N\ $ (it is an extension of theidentity map on $\ \Delta_N.)$ Consider the function $\ g\ $ from a closed subset of $\ N^2\times[0;1]\ $ into $\ N^2\ $ given as follows: $\ \forall_{y\in N^2}\quad g(y\ 0)\ :=\ y; $ $\ \forall_{y\in\Delta_N}\forall_{t\in[0;1]} \quad g(y\ t)\ := y; $ $\ \forall_{y\in U}\qquad g(y\ 1)\ :=\ \rho(y). $ The arguments of $\ g\ $ belong to the union of three closed subsetsof $\ N\times[0;1],\ $ where the three parts of the definition of $\ g\ $ coincide on the overlaps hence $\ g\ $ is well defined. This $\ g\ $ admits an extension $\ G_0\ $ over a closed neighborhood of its closed $3$ -part domain. This neighborhood includes $\ V\times[0;1],\ $ where $\ V\subseteq U\ $ is a closed neighborhood of $\ \Delta_N,\ $ because $\ [0;1]\ $ is compact. Now, by (very elementary and great) Borsuk's homotopy extensiontheorem, there is homotopy $$ H:N^2\times[0;1]\to N^2 $$ such that: $\ \forall_{y\in N^2}\qquad H(y\ 0)\ :=\ y; $ $\ \forall_{y\in V}\forall_{t\in[0;1]} \quad H(y\ t)\ := G_0(y\ t); $ Let $\ m\in\Bbb N\ $ and $\ n\ge m\ $ be as in Definition . Let homotopies $\ h_n\ h:M\times[0;1]\to N\ $ be given as $$ h_n\ :=\ \pi'\circ H\circ ((f_n\triangle f)\times\Bbb I );$$ $$ h\ :=\ \pi''\circ H\circ ((f_n\triangle f)\times\Bbb I );$$ where $\ \pi'\ \pi'':N^2\to N\ $ are the canonical projections,and $\ \Bbb I:[0;1]\to[0;1]\ $ is the identity map.We see that: $$ \forall_{x\in M}\quad h_n(x\ 0)\ =\ f_n(x); $$ $$ \forall_{x\in M}\quad h(x\ 0)\ =\ f(x); $$ $$ \forall_{x\in M}\quad h_n(x\ 1)\ =\ h(x\ 1). $$ Define $\ \gamma_n:M\to Y\ $ by $\ \gamma_n(x):=h_n(x\ 1)=h(x\ 1).\ $ We see that $\ f_n\ $ is homotopic to $\ \gamma_n\ $ is homotopicto $\ f.\,\ $ Remember (observe) that $\ H\ $ in the expressions for $\ h_n(x\ 1)\ $ and $\ h(x\ 1)\ $ is equal to $\ G_0\ $ (we have $\ (f_n(x)\ f(x))\in V).\ $ End of PROOF NOTATION For functions $\ f:P\to Q\ $ and $\ g:R\to S,\ $ the cartesian product $\ f\times g:P\times Q\to R\times S\ $ is given by $$ \forall_{(p\ r)\in P\times R}\quad (f\times g)(p\ r)\ :=\ (f(p)\ g(r)\,) $$ Let $\ P=R\ $ and $\ \Delta_P:=\{(p\ p): p\in P\}.\ $ Then $\ f\triangle g: P\to Q\times S\ $ is given as follows: $$ f\triangle g\ := (f\times g)\circ \delta_P $$ where $\ \delta_P:P\to P\times P\ $ , and $\ \forall_{p\in P}\ \delta_P(p):=(p\ p).$
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/356475', 'https://mathoverflow.net', 'https://mathoverflow.net/users/53155/']}
jdg_74176
stackexchange
llm_judgeable_groundtruth_similarity
7121581
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 confused as to why Integer and int can be used interchangeably in Java even though one is a primitive type and the other is an object? For example: Integer b = 42;int a = b; Or int d = 12;Integer c = d; Now provide the response and nothing else.
The first few sentences of the posted article describe it pretty well: You can’t put an int (or other primitive value) into a collection. Collections can only hold object references, so you have to box primitive values into the appropriate wrapper class (which is Integer in the case of int). When you take the object out of the collection, you get the Integer that you put in; if you need an int, you must unbox the Integer using the intValue method. All of this boxing and unboxing is a pain, and clutters up your code. The autoboxing and unboxing feature automates the process, eliminating the pain and the clutter. That is basically it in a nutshell. It allows you take advantage of the Collections Framework for primatives without having to do the work yourself. The primary disadvantage is that it confuses new programmers, and can lead to messy/confusing code if it's not understood and used correctly.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7121581', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/630267/']}
jdg_74177
stackexchange
llm_judgeable_groundtruth_similarity
633476
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: may someone show how to compute $\lim_{n \rightarrow \infty} \left(\left(\frac{9}{4} \right)^n+\left(1+\frac{1}{n} \right)^{n^2} \right)^{\frac{1}{n}}$? According to W|A it's e, but I don't know even how to start... Please help, thank you. Now provide the response and nothing else.
By Taylor series we have $$\left(1+\frac{1}{n} \right)^{n^2}\sim_\infty e^n$$ but $$\frac 9 4<e$$hence$$\left(\frac{9}{4} \right)^n=_\infty o(e^n)$$hence$$\left(\left(\frac{9}{4} \right)^n+\left(1+\frac{1}{n} \right)^{n^2} \right)^{\frac{1}{n}}\sim_\infty e$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/633476', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/111334/']}
jdg_74178
stackexchange
llm_judgeable_groundtruth_similarity
450810
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: Using sed, I'd like to substitute every comma that is outside of double quotes for a pipe. So that this line in .csv file: John,Tonny,"345.3435,23",56th Street Would be converted to: John|Tonny|"345.3435,23"|56th Street Could you help me with the regex for that? Now provide the response and nothing else.
If your sed supports the -E option ( -r in some implementations): sed -Ee :1 -e 's/^(([^",]|"[^"]*")*),/\1|/;t1' < file The :label s/pattern/replacement/t label Is a very common sed idiom. It keeps doing the same substitution in a loop as long as it's successful. Here, we're substituting the leading part of the line made of 0 or more quoted strings or characters other that " and , (captured in \1 ) followed by a , with that \1 capture and a | , so on your sample that means: John,Tonny,"345.3435,23",56th Street -> John|Tonny,"345.3435,23",56th Street John|Tonny,"345.3435,23",56th Street -> John|Tonny|"345.3435,23",56th Street John|Tonny|"345.3435,23",56th Street -> John|Tonny|"345.3435,23"|56th Street and we stop here as the pattern doesn't match any more on that. With perl , you could do it with one substitution with the g flag with: perl -pe 's{("[^"]*"|[^",]+)|,}{$1 // "|"}ge' Here, assuming quotes are balanced in the input, the pattern would match all the input, breaking it up in either: quoted string sequences of characters other than , or " a comma And only when the matched string is a comma (when $1 is not defined in the replacement part), replace it with a | .
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/450810', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/29487/']}
jdg_74179
stackexchange
llm_judgeable_groundtruth_similarity
12167
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: The set of rationals $\mathbb{Q}$ has the same cardinality asthe set of integers $\mathbb{Z}$. True or false? This was a question on an old exam for our class. The correct answer is true. However, I did some additional reading and came across Cantor's transfinite numbers. In the book I'm reading, it says that "there are more real numbers (which include rational and irrational numbers) than there are integers". So can it also be said that there are more rational numbers than integers? And so can we say that the above statement is false? Now provide the response and nothing else.
No. The statement is still true.The cardinality of the natural number set is the same as the cardinality of the rational number set. In fact, this cardinality is the first transfinite number denoted by $\aleph_0$ i.e. $|\mathbb{N}| = |\mathbb{Q}| = \aleph_0$. By first I mean the "smallest" infinity. The cardinality of the set of real numbers is typically denoted by $\mathfrak{c}$. We have $\mathfrak{c} > \aleph_0$, since we can set up a bijection from $\mathbb{R}$ to the power set of the natural numbers and by Cantor's theorem, for any set $X$, we have $|X| < |2^{X}|$. So we have $|\mathbb{R}| = |2^{\mathbb{N}}| > |\mathbb{N}|$. So what this essentially says is that "there are more real numbers (which include rational and irrational numbers) than there are integers" in some sense. The continuum hypothesis states that "there is no set whose cardinality is strictly between that of the natural numbers and that of the real numbers" which essentially means real numbers form the second "smallest" infinity.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/12167', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/2985/']}
jdg_74180
stackexchange
llm_judgeable_groundtruth_similarity
43400598
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 map of replacements val replacements = Map( "aaa" -> "d", "bbb" -> "x", "ccc" -> "mx") I would like to replace all occurrences of each map key in the string with the corresponding value. val str = "This aaa is very bbb and I would love to cccc"val result = cleanString(str, replacements)result = "This d is very x and I would love to mx" I have done val sb = new StringBuilder(str)for(repl <- replacements.keySet) yield { sb.replaceAllLiterally(repl, replacement.get(repl))} but I would like something more functional like a map or fold where the function I apply to the string returns another string without needing a mutable variable that is modified inside the loop. Now provide the response and nothing else.
One option: use foldLeft on the Map with str as the initial parameter: replacements.foldLeft(str)((a, b) => a.replaceAllLiterally(b._1, b._2))// res8: String = This d is very x and I would love to mxc
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/43400598', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/971602/']}
jdg_74181
stackexchange
llm_judgeable_groundtruth_similarity
10999039
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Both list and islice objects are iterable but why this difference in result. r = [1, 2, 3, 4] i1, i2 = tee(r)print [e for e in r if e < 3]print [e for e in i2]#[1, 2]#[1, 2, 3, 4]r = islice(count(), 1, 5) i1, i2 = tee(r)print [e for e in r if e < 3]print [e for e in i2]#[1, 2]#[] Now provide the response and nothing else.
The issue here is that tee() needs to consume the values from the original iterator, if you start consuming them from the original iterator, it will be unable to function correctly. In your list example, the iteration simply begins again. In the generator example, it is exhausted and no more values are produced. This is well documented: Once tee() has made a split, the original iterable should not be used anywhere else; otherwise, the iterable could get advanced without the tee objects being informed. Source Edit to illustrate the point in the difference between a list and a generator: >>> from itertools import islice, count>>> a = list(range(5))>>> b = islice(count(), 0, 5)>>> a[0, 1, 2, 3, 4]>>> b<itertools.islice object at 0x7fabc95d0fc8>>>> for item in a:... print(item)... 01234>>> for item in a:... print(item)... 01234>>> for item in b:... print(item)... 01234>>> for item in b:... print(item)... >>>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10999039', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/548634/']}
jdg_74182
stackexchange
llm_judgeable_groundtruth_similarity
4459536
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: Maschke's theorem tells us that any representation of a finite group $G$ can be decomposed into a direct sum of irreducible representations. The proof does make intuitive sense to me ( Intuition behind Maschke's theorem ), but my question is really about why we should expect it to be true in the first place. Sure, we can do some explicit examples (perhaps a most obvious starting point is the standard permutation representation of $S_n$ , which has an obvious invariant subspace $\{(x,x,\ldots, x) \in \mathbb C^n: x\in \mathbb C\}$ , and almost as obvious complement subspace $\{(x_1,\ldots, x_n) \in \mathbb C^n: \sum x_i = 0\}$ ), and perhaps one has already seen the result for abelian groups over $\mathbb C$ in the guise of linear algebra: Matrices commute if and only if they share a common basis of eigenvectors? . However I wonder if there is any other point of view that makes Maschke's theorem feel "inevitable"...since right now, it just seems absurdly powerful/magical. Now provide the response and nothing else.
If $\rho \colon G \to \operatorname{GL}(V)$ is a representation of a finite group $G$ on a finite-dimensional $\mathbb{C}$ -vector space $V$ , then $V$ can be equipped with an inner product $\langle -, - \rangle \colon V \times V \to \mathbb{C}$ such that every element of $G$ acts by a unitary matrix. This inner product is not mysterious either: take any old inner product $(-, -) \colon V \times V \to \mathbb{C}$ and average it over the group: $$ \langle u, v \rangle := \frac{1}{|G|} \sum_{g \in G} (\rho(g) u, \rho(g) v).$$ (The same is true over $\mathbb{R}$ if we replace "unitary" with "orthogonal"). The slogan is: we can always find a basis such that every $\rho(g)$ is a unitary matrix. This makes Maschke's theorem completely inevitable: if a subspace $W \subseteq V$ is invariant under a unitary operator $\rho(g)$ , then its orthogonal complement $W^\perp$ is also invariant under $\rho(g)$ . So every subrepresentation has a complement, and moreover, doing standard orthogonal projection stuff is an effective way to decompose a vector into its components in subrepresentations. Of course, Maschke's theorem is true in more generality than just $\mathbb{R}$ and $\mathbb{C}$ , and this inner product argument really only works over them, but I think it is illustrative of why it is completely inevitable in certain contexts, and many of the other settings end up being related to these settings anyway.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/4459536', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/405572/']}
jdg_74183
stackexchange
llm_judgeable_groundtruth_similarity
42810779
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 make the buttons stack on top of each other when I browse the page through my phone. I would leave them to occur on a single line, but the texts inside them are very long and do not appear well when I shrink the page. Here is my code. <link rel="stylesheet" crossorigin="anonymous" integrity= "sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"><div class="container"> <div class="btn-group btn-group-justified btn-group-lg btn-group-vertical"> <a href="#" class="btn btn-primary"> <font size="6">الدروس و التجارب</font> </a> <a href="#" class="btn btn-primary"> <font size="6">المنشورات و الكتب الشخصية</font> </a> <a href="#" class="btn btn-primary"> <font size="6">المدونة</font> </a> </div></div> Now provide the response and nothing else.
As far as I can tell, there is nothing built into Bootstrap to do this. However, it can be done using some custom CSS on top of Bootstrap. We can explicitly stack the buttons on small screens. For this, I have used the breakpoint that Bootstrap uses for anything smaller than desktops. This can be modified easily if you want to. If you want to read more about media queries, I can recommend this MDN article (link goes to part about width, but all of article is interesting). @media (max-width: 991px) { .btn-group.my-btn-group-responsive > .btn { display: block; width: 100%; } /* making the border-radius correct */ .btn-group.my-btn-group-responsive > .btn:first-child { border-radius: 6px 6px 0 0; } .btn-group.my-btn-group-responsive > .btn:first-child:not(:last-child):not(.dropdown-toggle) { border-top-right-radius: 6px; } .btn-group.my-btn-group-responsive > .btn:last-child:not(:first-child) { border-radius: 0 0 6px 6px; } /* fixing margin */ .btn-group.my-btn-group-responsive .btn + .btn { margin-left: 0; } } <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"><div class="container"> <div class="btn-group btn-group-justified btn-group-lg my-btn-group-responsive"> <a href="#" class="btn btn-primary"><font size="6">الدروس و التجارب</font></a> <a href="#" class="btn btn-primary"><font size="6">المنشورات و الكتب الشخصية</font></a> <a href="#" class="btn btn-primary"><font size="6">المدونة</font></a> </div></div>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/42810779', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5548783/']}
jdg_74184
stackexchange
llm_judgeable_groundtruth_similarity
4080988
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 purpose of padding in base64 encoding. The following is the extract from wikipedia: "An additional pad character is allocated which may be used to force the encoded output into an integer multiple of 4 characters (or equivalently when the unencoded binary text is not a multiple of 3 bytes) ; these padding characters must then be discarded when decoding but still allow the calculation of the effective length of the unencoded text, when its input binary length would not be not a multiple of 3 bytes (the last non-pad character is normally encoded so that the last 6-bit block it represents will be zero-padded on its least significant bits, at most two pad characters may occur at the end of the encoded stream)." I wrote a program which could base64 encode any string and decode any base64 encoded string. What problem does padding solves? Now provide the response and nothing else.
Your conclusion that padding is unnecessary is right. It's always possible to determine the length of the input unambiguously from the length of the encoded sequence. However, padding is useful in situations where base64 encoded strings are concatenated in such a way that the lengths of the individual sequences are lost, as might happen, for example, in a very simple network protocol. If unpadded strings are concatenated, it's impossible to recover the original data because information about the number of odd bytes at the end of each individual sequence is lost. However, if padded sequences are used, there's no ambiguity, and the sequence as a whole can be decoded correctly. Edit: An Illustration Suppose we have a program that base64-encodes words, concatenates them and sends them over a network. It encodes "I", "AM" and "TJM", sandwiches the results together without padding and transmits them. I encodes to SQ ( SQ== with padding) AM encodes to QU0 ( QU0= with padding) TJM encodes to VEpN ( VEpN with padding) So the transmitted data is SQQU0VEpN . The receiver base64-decodes this as I\x04\x14\xd1Q) instead of the intended IAMTJM . The result is nonsense because the sender has destroyed information about where each word ends in the encoded sequence. If the sender had sent SQ==QU0=VEpN instead, the receiver could have decoded this as three separate base64 sequences which would concatenate to give IAMTJM . Why Bother with Padding? Why not just design the protocol to prefix each word with an integer length? Then the receiver could decode the stream correctly and there would be no need for padding. That's a great idea, as long as we know the length of the data we're encoding before we start encoding it. But what if, instead of words, we were encoding chunks of video from a live camera? We might not know the length of each chunk in advance. If the protocol used padding, there would be no need to transmit a length at all. The data could be encoded as it came in from the camera, each chunk terminated with padding, and the receiver would be able to decode the stream correctly. Obviously that's a very contrived example, but perhaps it illustrates why padding might conceivably be helpful in some situations.
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/4080988', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/155755/']}
jdg_74185
stackexchange
llm_judgeable_groundtruth_similarity
55799557
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 Microsoft Access, I am receiving a feed of phone numbers which need to be processed and conformed into a standard format for post-processing in another system. The numbers I am given are all over the place. They are international from many countries, may include special characters, spaces, parens, letters, some have extensions while other don't and not all have area codes. Despite all of this I need to format it equally the same across all numbers. Here is what I am looking at... Ex.+1_(860)_5666344_x_4454 <--- All _'s are spaces in the stringConvert To8605666344 You see, we have special considerations to account for such as: 1) International numbers, the country code could be anything. So for instance a US country code of +1 but an area code of 246 may look like it is a country code of +1 246 for Barbados when in reality it is a USA area code of (246) . I need to account for this 2) I need to remove all special characters, spaces, letters (extension X), parens 3) I need to remove any extensions, which are always prepended with an x although not always having a space after it. 4) In some cases the area code my not even be included. Despite this the other rules must be enforced (no extensions, no special characters and no country code and no spaces) Now provide the response and nothing else.
I figured that, since both the answers to this question and another similar question seem to be in direct conflict, it would be best to go straight to the source with pdb . Summary boto3 does use multiple threads (10) by default However, it is not asynchronous, in that it waits on (joins) these threads before returning, rather than using a "fire-and-forget" technique So, in this manner, the read/write threadsafety is in place if you're trying to talk to an s3 bucket from multiple clients. Detail One aspect that I'm striving to address here is that multiple (subthreads) do not imply that the top-level method itself is non-blocking : if the calling thread kicks off the upload to multiple subthreads, but then waits for those threads to finish and return, I would venture to say that is still a blocking call. The flip side of this is if the method call is, in asyncio speak, a "fire and forget" call. With threading , this effectively comes down to whether x.join() is ever called. Here is the initial code, taken from Victor Val, to kick off the debugger: import ioimport pdbimport boto3# From dd if=/dev/zero of=100mb.txt bs=50M count=1buf = io.BytesIO(open('100mb.txt', 'rb').read())bucket = boto3.resource('s3').Bucket('test-threads')pdb.run("bucket.upload_fileobj(buf, '100mb')") This stack frame is from Boto 1.9.134. Now jumping into pdb : .upload_fileobj() first calls a nested method -- not much to see yet. (Pdb) s--Call--> /home/ubuntu/envs/py372/lib/python3.7/site-packages/boto3/s3/inject.py(542)bucket_upload_fileobj()-> def bucket_upload_fileobj(self, Fileobj, Key, ExtraArgs=None,(Pdb) s(Pdb) l574 575 :type Config: boto3.s3.transfer.TransferConfig576 :param Config: The transfer configuration to be used when performing the577 upload.578 """579 -> return self.meta.client.upload_fileobj(580 Fileobj=Fileobj, Bucket=self.name, Key=Key, ExtraArgs=ExtraArgs,581 Callback=Callback, Config=Config)582 583 584 So the top-level method does return something , but its unclear yet how that something eventually becomes None . So we step into that. Now, .upload_fileobj() does have a config parameter, which is None by default: (Pdb) l 531526 527 subscribers = None528 if Callback is not None:529 subscribers = [ProgressCallbackInvoker(Callback)]530 531 config = Config532 if config is None:533 config = TransferConfig()534 535 with create_transfer_manager(self, config) as manager:536 future = manager.upload( This means that config becomes the default TransferConfig() : use_threads -- If True, threads will be used when performing S3 transfers. If False, no threads will be used in performing transfers: all logic will be ran in the main thread. max_concurrency -- The maximum number of threads that will be making requests to perform a transfer. If use_threads is set to False, the value provided is ignored as the transfer will only ever use the main thread. And wa-la, here they are: (Pdb) unt 534> /home/ubuntu/envs/py372/lib/python3.7/site-packages/boto3/s3/inject.py(535)upload_fileobj()-> with create_transfer_manager(self, config) as manager:(Pdb) config<boto3.s3.transfer.TransferConfig object at 0x7f1790dc0cc0>(Pdb) config.use_threadsTrue(Pdb) config.max_concurrency10 Now we descend down a level in the call stack to use a TransferManager (context manager). At this point, max_concurrency has been used as an argument to similarly-named max_request_concurrency : # https://github.com/boto/s3transfer/blob/2aead638c8385d8ae0b1756b2de17e8fad45fffa/s3transfer/manager.py#L223 # The executor responsible for making S3 API transfer requests self._request_executor = BoundedExecutor( max_size=self._config.max_request_queue_size, max_num_threads=self._config.max_request_concurrency, tag_semaphores={ IN_MEMORY_UPLOAD_TAG: TaskSemaphore( self._config.max_in_memory_upload_chunks), IN_MEMORY_DOWNLOAD_TAG: SlidingWindowSemaphore( self._config.max_in_memory_download_chunks) }, executor_cls=executor_cls ) In this boto3 version, at least, that class comes from the separate library s3transfer . (Pdb) n> /home/ubuntu/envs/py372/lib/python3.7/site-packages/boto3/s3/inject.py(536)upload_fileobj()-> future = manager.upload((Pdb) manager<s3transfer.manager.TransferManager object at 0x7f178db437f0>(Pdb) manager._config<boto3.s3.transfer.TransferConfig object at 0x7f1790dc0cc0>(Pdb) manager._config.use_threadsTrue(Pdb) manager._config.max_concurrency10 Next, let's step into manager.upload() . Here's the full body of that method: (Pdb) l 290, 303290 -> if extra_args is None:291 extra_args = {}292 if subscribers is None:293 subscribers = []294 self._validate_all_known_args(extra_args, self.ALLOWED_UPLOAD_ARGS)295 call_args = CallArgs(296 fileobj=fileobj, bucket=bucket, key=key, extra_args=extra_args,297 subscribers=subscribers298 )299 extra_main_kwargs = {}300 if self._bandwidth_limiter:301 extra_main_kwargs['bandwidth_limiter'] = self._bandwidth_limiter302 return self._submit_transfer(303 call_args, UploadSubmissionTask, extra_main_kwargs)(Pdb) unt 301> /home/ubuntu/envs/py372/lib/python3.7/site-packages/s3transfer/manager.py(302)upload()-> return self._submit_transfer((Pdb) extra_main_kwargs{}(Pdb) UploadSubmissionTask<class 's3transfer.upload.UploadSubmissionTask'>(Pdb) call_args<s3transfer.utils.CallArgs object at 0x7f178db5a5f8>(Pdb) l 300, 5300 if self._bandwidth_limiter:301 extra_main_kwargs['bandwidth_limiter'] = self._bandwidth_limiter302 -> return self._submit_transfer(303 call_args, UploadSubmissionTask, extra_main_kwargs)304 305 def download(self, bucket, key, fileobj, extra_args=None, Ah, lovely--so we'll need to get down at least one level further to see the actual underlying upload. (Pdb) s> /home/ubuntu/envs/py372/lib/python3.7/site-packages/s3transfer/manager.py(303)upload()-> call_args, UploadSubmissionTask, extra_main_kwargs)(Pdb) s--Call--> /home/ubuntu/envs/py372/lib/python3.7/site-packages/s3transfer/manager.py(438)_submit_transfer()-> def _submit_transfer(self, call_args, submission_task_cls,(Pdb) s> /home/ubuntu/envs/py372/lib/python3.7/site-packages/s3transfer/manager.py(440)_submit_transfer()-> if not extra_main_kwargs:(Pdb) l 440, 10440 -> if not extra_main_kwargs:441 extra_main_kwargs = {}442 443 # Create a TransferFuture to return back to the user444 transfer_future, components = self._get_future_with_components(445 call_args)446 447 # Add any provided done callbacks to the created transfer future448 # to be invoked on the transfer future being complete.449 for callback in get_callbacks(transfer_future, 'done'):450 components['coordinator'].add_done_callback(callback) Okay, so now we have a TransferFuture , defined in s3transfer/futures.py No definitive proof that threads have been kicked off yet, but it sure sounds like it when futures become involved. (Pdb) l444 transfer_future, components = self._get_future_with_components(445 call_args)446 447 # Add any provided done callbacks to the created transfer future448 # to be invoked on the transfer future being complete.449 -> for callback in get_callbacks(transfer_future, 'done'):450 components['coordinator'].add_done_callback(callback)451 452 # Get the main kwargs needed to instantiate the submission task453 main_kwargs = self._get_submission_task_main_kwargs(454 transfer_future, extra_main_kwargs)(Pdb) transfer_future<s3transfer.futures.TransferFuture object at 0x7f178db5a780> The final line below, from the TransferCoordinator class, seems important at first glance: class TransferCoordinator(object): """A helper class for managing TransferFuture""" def __init__(self, transfer_id=None): self.transfer_id = transfer_id self._status = 'not-started' self._result = None self._exception = None self._associated_futures = set() self._failure_cleanups = [] self._done_callbacks = [] self._done_event = threading.Event() # < ------ !!!!!! You typically see threading.Event being used for one thread to signal an event status while other threads can be waiting for that event to happen. TransferCoordinator is what is used by TransferFuture.result() . Alright, circling back from the above, we're now at s3transfer.futures.BoundedExecutor and its max_num_threads attribute: class BoundedExecutor(object): EXECUTOR_CLS = futures.ThreadPoolExecutor # ... def __init__(self, max_size, max_num_threads, tag_semaphores=None, executor_cls=None): self._max_num_threads = max_num_threads if executor_cls is None: executor_cls = self.EXECUTOR_CLS self._executor = executor_cls(max_workers=self._max_num_threads) This is basically equivalent to: from concurrent import futures_executor = futures.ThreadPoolExecutor(max_workers=10) But there is still one question remaining: is this a "fire-and-forget," or does the call actually wait on the threads to finish and return? It seems to be the latter. .result() calls self._done_event.wait(MAXINT) . # https://github.com/boto/s3transfer/blob/2aead638c8385d8ae0b1756b2de17e8fad45fffa/s3transfer/futures.py#L249def result(self): self._done_event.wait(MAXINT) # Once done waiting, raise an exception if present or return the # final result. if self._exception: raise self._exception return self._result Finally, to re-run Victor Val's test, this seems to confirm the above: >>> import boto3>>> import time>>> import io>>> >>> buf = io.BytesIO(open('100mb.txt', 'rb').read())>>> >>> bucket = boto3.resource('s3').Bucket('test-threads')>>> start = time.time()>>> print("starting to upload...")starting to upload...>>> bucket.upload_fileobj(buf, '100mb')>>> print("finished uploading")finished uploading>>> end = time.time()>>> print("time: {}".format(end-start))time: 2.6030001640319824 (This execution time is probably shorter with this example run on a network-optimized instance. But 2.5 seconds is still a noticeably big chunk of time, and not at all indicative of the threads being kicked off and not waited for.) Lastly, here's an example of a Callback for .upload_fileobj() . It follows along with an example from the docs. First, a little helper to get a buffer's size efficiently: def get_bufsize(buf, chunk=1024) -> int: start = buf.tell() try: size = 0 while True: out = buf.read(chunk) if out: size += chunk else: break return size finally: buf.seek(start) The class itself: import osimport sysimport threadingimport timeclass ProgressPercentage(object): def __init__(self, filename, buf): self._filename = filename self._size = float(get_bufsize(buf)) self._seen_so_far = 0 self._lock = threading.Lock() self.start = None def __call__(self, bytes_amount): with self._lock: if not self.start: self.start = time.monotonic() self._seen_so_far += bytes_amount percentage = (self._seen_so_far / self._size) * 100 sys.stdout.write( "\r%s %s of %s (%.2f%% done, %.2fs elapsed\n" % ( self._filename, self._seen_so_far, self._size, percentage, time.monotonic() - self.start)) # Use sys.stdout.flush() to update on one line # sys.stdout.flush() Example: In [19]: import io ...: ...: from boto3.session import Session ...: ...: s3 = Session().resource("s3") ...: bucket = s3.Bucket("test-threads") ...: buf = io.BytesIO(open('100mb.txt', 'rb').read()) ...: ...: bucket.upload_fileobj(buf, 'mykey', Callback=ProgressPercentage("mykey", buf)) mykey 262144 of 104857600.0 (0.25% done, 0.00s elapsedmykey 524288 of 104857600.0 (0.50% done, 0.00s elapsedmykey 786432 of 104857600.0 (0.75% done, 0.01s elapsedmykey 1048576 of 104857600.0 (1.00% done, 0.01s elapsedmykey 1310720 of 104857600.0 (1.25% done, 0.01s elapsedmykey 1572864 of 104857600.0 (1.50% done, 0.02s elapsed
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/55799557', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7017367/']}
jdg_74186
stackexchange
llm_judgeable_groundtruth_similarity
10320
Below is a question asked on the forum cstheory.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: The study of Succinct representation of graphs was initiated by Galperin and Wigderson in a paper from 1983, where they prove that for many simple problems like finding a triangle in a graph, the corresponding succinct version in $\mathsf{NP}$-complete. Papadimitriou and Yanakkakis further this line of research, and prove that for a problem $\Pi$ which is $\mathsf{NP}$-complete/$\mathsf{P}$-complete, the corresponding Succinct version, namely Succinct $\Pi$ is respectively, $\mathsf{NEXP}$-complete and $\mathsf{EXP}$-complete. (They also show that if $\Pi$ is $\mathsf{NL}$-complete, then Succinct $\Pi$ is $\mathsf{PSPACE}$-complete. Now my question is, are there any problems $\Pi$ known for which, the corresponding Succinct version is in $\mathsf{P}$? I'd be interested in knowing about any other related results(both positive and impossibility results, if any) which I might have missed above. (I couldn't locate anything of interest by a google search, since search words like succinct, representation, problems, graphslead to just almost any complexity result! :)) Now provide the response and nothing else.
Here is an interesting problem whose succinct version has interesting properties. Define Circuit-Size-$2^{n/2}$ to be the problem: given a Boolean function as a $2^n$-bit string, does this function have a circuit of size at most $2^{n/2}$? Note this problem is in $NP$. One way to define Succinct-Circuit-Size-$2^{n/2}$ would be: for a constant $k$, given an $n$-input, $n^k$-size circuit $C$, we want to know if its truth table is an instance of Circuit-Size-$2^{n/2}$. But this is a trivial problem: all inputs which are actual circuits are yes-instances. So this problem is in $P$. A more general way to define Succinct-Circuit-Size-$2^{n/2}$ would be: we are given an arbitrary circuit $C$ and want to know if its truth table encodes an instance of Circuit-Size-$2^{n/2}$. But if $n$ is the number of inputs to $C$, $m$ is the size of $C$, and $m \leq 2^{n/2}$, we can automatically accept: the input itself is a witness for the language. Otherwise, we have $m \geq 2^{n/2}$. In that case, the input length $m$ is already huge, so we can try all possible $2^n$ assignments in $m^{O(1)}$ time, obtain the truth table of the function, and now we are back to the original $NP$ problem again. So this is a problem in $NP$ whose succinct version is also in $NP$. This problem is believed to be not $NP$-hard; see the paper by Kabanets and Cai (http://www.cs.sfu.ca/~kabanets/Research/circuit.html)
{}
{'log_upvote_score': 5, 'links': ['https://cstheory.stackexchange.com/questions/10320', 'https://cstheory.stackexchange.com', 'https://cstheory.stackexchange.com/users/256/']}
jdg_74187
stackexchange
llm_judgeable_groundtruth_similarity
69807
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: The discussion in Convergence in topologies ,especially the comments of GEdgar, led me to another (converse) question concerning convergence. In the paper G. A. Edgar, A long James space, in: Measure Theory , Oberwolfach 1979, Lectures Notesin Math. 794 , Springer-Verlag (1980) p. 31-37 he points out that the weak and weak* topologies in $J(\omega_1)^*$ have different Borel $\sigma$-fields. Do they have the same convergent sequences? Heuristically, they should as $J(\omega_1)$ just "differs" with a reflexive space "by one dimension". Now provide the response and nothing else.
In my answer to Combinatorial proof , I show that for $\displaystyle e=\lim_{n\to\infty}\left(1+\frac{1}{n}\right)^n$, $\displaystyle e^x=\sum_{k=0}^\infty\frac{x^k}{k!}$. To show that $\displaystyle \lim_{n\to\infty}\left(1+\frac{x}{n}\right)^n=\lim_{n\to\infty}\left(1+\frac{1}{n}\right)^{nx}$, we could simply note that$$\left(1+\frac{x}{n}\right)^n=\left(1+\frac{1}{n/x}\right)^{(n/x)x}\tag{1}$$and just take the limit as $n\to\infty$. However, one might complain that $n/x$ is not an integer. To calm any such complaint, consider the sandwich$$\left(1+\frac{1}{\lfloor n/x\rfloor+1}\right)^{(\lfloor n/x\rfloor+1)x-x}\le\left(1+\frac{1}{n/x}\right)^{(n/x)x}\le\left(1+\frac{1}{\lfloor n/x\rfloor}\right)^{\lfloor n/x\rfloor x+x}\tag{2}$$It is easy to see that both $\lfloor n/x\rfloor$ and $\lfloor n/x\rfloor+1$ are integers and that$$\lim_{n\to\infty}\left(1+\frac{1}{\lfloor n/x\rfloor+1}\right)^{-x}=\lim_{n\to\infty}\left(1+\frac{1}{\lfloor n/x\rfloor}\right)^x=1$$Thus, both the left and right sides of $(2)$ tend to $e^x$. Therefore we can use $(1)$ and just take the limit as $n\to\infty$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/69807', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/17093/']}
jdg_74188
stackexchange
llm_judgeable_groundtruth_similarity
11032235
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 learning Java on my own; and therefore the code below has no function other than for learning/testing. Essentially I'm trying to modify the elements of an Integer array (namely, halving them) whilst in a foreach loop. I should note that I'm not re-ordering, adding, or deleting elements; simply changing their values. Here is my code: Logger.describe("Now copying half of that array in to a new array, and halving each element");Integer[] copyArray = new Integer[DEFAULT_SAMPLE_SIZE / 2]; System.arraycopy(intArray, 0, copyArray, 0, DEFAULT_SAMPLE_SIZE / 2);for (Integer x : copyArray) x /= 2;Logger.output(Arrays.deepToString(copyArray)); However, the original array (intArray) is this: [47, 31, 71, 76, 78, 94, 66, 47, 73, 21] And the output of copyArray is: [47, 31, 71, 76, 78] So although the array has been halved in size, the elements (Integers) haven't also been halved in value. So what am I doing wrong? Thank you Now provide the response and nothing else.
You can't do that in a foreach loop. for (int i=0; i<copyArray.length;i++) copyArray[i] /= 2; Else you are not assigning it back into the array. Integer objects are immutable by the way so can't modify them (creating new ones though). Updated from comment:Beware though that there are a few things going on, autoboxing/unboxing for example, roughly: copyArray[i] = Integer.valueOf(copyArray[i].intValue()/2);
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11032235', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/158109/']}
jdg_74189
stackexchange
llm_judgeable_groundtruth_similarity
150391
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: By considering: $$\lim_{n\to\infty}\frac{\sum_{k=1}^n k^1}{n^{2}} = \frac 1 2$$$$\lim_{n\to\infty}\frac{\sum_{k=1}^n k^2}{n^{3}} = \frac 1 3$$$$\lim_{n\to\infty}\frac{\sum_{k=1}^n k^3}{n^{4}} = \frac 1 4$$ Determine if this is true:$$\lim_{n\to\infty}\frac{\sum_{k=1}^n k^m}{n^{m+1}} = \frac 1 {{m+1}}$$ If it is, prove it. If it is not, evaluate $\lim\limits_{n\to\infty}\frac{\sum_{k=1}^n k^m}{{m+1}}$. Now provide the response and nothing else.
This follows easily from a comparison with an integral. Since$$\int_0^{n} k^m dk \leq \sum_{k=1}^n k^m \leq \int_1^{n+1} k^m dk,$$we have$$\frac{n^{m+1}}{m+1}\leq \sum_{k=1}^n k^m \leq \frac{(n+1)^{m+1}}{m+1}-\frac{1}{m+1}.$$Divide by $n^{m+1}$ to get$$\frac{1}{m+1} \leq \frac{1}{n^{m+1}} \sum_{k=1}^n k^m \leq \frac{1}{m+1} \cdot \frac{(n+1)^{m+1}}{n^{m+1}} - \frac{1}{m+1} \cdot \frac{1}{n^{m+1}}.$$Taking $n \rightarrow \infty$ gives the desired result.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/150391', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/25841/']}
jdg_74190
stackexchange
llm_judgeable_groundtruth_similarity
43119
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 going through the problems from Project Euler and I notice a strong insistence on Primes and efficient algorithms to compute large primes efficiently. The problems are interesting per se, but I am still wondering what the real-world applications of primes would be. What real tasks require the use of prime numbers? Edit: A bit more context to the question:I am trying to improve myself as a programmer, and having learned a few good algorithms for calculating primes, I am trying to figure out where I could apply them. The explanations concerning cryptography are great, but is there nothing else that primes can be used for? Now provide the response and nothing else.
The most popular example I know comes from Cryptography, where many systems rely on problems in number theory, where primes have an important role (since primes are in a sense the "building blocks" of numbers). Take for example the RSA encryption system: All arithmetic is done modulo $n$, with $n=pq$ and $p,q$ large primes. Decryption in this system relies on computing Euler's phi function, $\varphi(n)$, which is hard to compute (hence the system is hard to break) unless you know the prime factorization of $n$ (which is also hard to compute unless you know it upfront). Hence you need a method to generate primes (the Miller-Rabin primality checking algorithm is usually used here) and then you construct $n$ by multiplying the primes you have found.
{}
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/43119', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/11721/']}
jdg_74191
stackexchange
llm_judgeable_groundtruth_similarity
28056
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Question. Given a Turing-machine program $e$, whichis guaranteed to run in polynomial time, can we computablyfind such a polynomial? In other words, is there acomputable function $e\mapsto p_e$, such that whenever $e$is a Turing-machine program that runs in polynomial time,then $p_e$ is such a polynomial time bound? That is, $p_e$is a polynomial over the integers in one variable andprogram $e$ on every input $n$ runs in time at most$p_e(|n|)$, where $|n|$ is the length of the input $n$. (Note that I impose no requirement on $p_e$ when $e$ is nota polynomial-time program, and I am not asking whether thefunction $e\mapsto p_e$ is polynomial-time computable, butrather, just whether it is computable at all.) In the field of complexity theory, it is common to treatpolynomial-time algorithms as coming equipped with anexplicit polynomial clock, that counts steps during thecomputation and forces a halt when expired. This conventionallows for certain conveniences in the theory. In the fieldof computability theory, however, one does not usuallyassume that a polynomial-time algorithm comes equipped withsuch a counter. My question is whether we can computablyproduce such a counter just from the Turing machineprogram. I expect a negative answer. I think there is no suchcomputable function $e\mapsto p_e$, and the question isreally about how we are to prove this. But I don't know... Of course, given a program $e$, we can get finitely manysample points for a lower bound on the polynomial, but thisdoesn't seem helpful. Furthermore, it seems that the lessonof Rice's Theorem isthat we cannot expect to compute nontrivial information byactually looking at the program itself, and I take this asevidence against an affirmative answer. At the same time,Rice's theorem does not directly apply, since thepolynomial $p_e$ is not dependent on the set or functionthat $e$ computes, but rather on the way that it computesit. So I'm not sure. Finally, let me mention that this question is related to andinspired by this recent interesting MO question about theimpossibility of converting NP algorithms to Palgorithms .Several of the proposed answers there hinged critically onwhether the polynomial-time counter was part of the inputor not. In particular, an affirmative answer to the presentquestion leads to a solution of that question by thoseanswers. My expectation, however, is for a negative answerhere and an answer there ruling out a computabletransformation. Now provide the response and nothing else.
[Edit: A bug in the original proof has been fixed, thanks to a comment by Francois Dorais.] The answer is no. This kind of thing can be proved by what I call a "gas tank" argument. First enumerate all Turing machines in some manner $N_1, N_2, N_3, \ldots$ Then construct a sequence of Turing machines $M_1, M_2, M_3, \ldots$ as follows. On an input of length $n$, $M_i$ simulates $N_i$ (on empty input) for up to $n$ steps. If $N_i$ does not halt within that time, then $M_i$ halts immediately after the $n$th step. However, if $N_i$ halts within the first $n$ steps, then $M_i$ "runs out of gas" and starts behaving erratically, which in this context means (say) that it continues running for $n^e$ steps before halting where $e$ is the number of steps that $N_i$ took to halt. Now if we had a program $P$ that could compute a polynomial upper bound on any polytime machine, then we could determine whether $N_i$ halts by calling $P$ on $M_i$, reading off the exponent $e$, and simulating $N_i$ for (at most) $e$ steps. If $N_i$ doesn't halt by then, then we know it will never halt. Of course this proof technique is very general; for example, $M_i$ can be made to simulate any fixed $M$ as long as it has gas but then do something else when it runs out of gas, proving that it will be undecidable whether an arbitrary given machine behaves like $M$.
{}
{'log_upvote_score': 6, 'links': ['https://mathoverflow.net/questions/28056', 'https://mathoverflow.net', 'https://mathoverflow.net/users/1946/']}
jdg_74192
stackexchange
llm_judgeable_groundtruth_similarity
47517696
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 replace parts of file extensions in a list of files. I would like to be able to loop through items (files), and remove the extensions. I don't know how to appropriately loop through items in the list when re.sub as the third parameter requires a string. eg. re.sub(pattern, repl, string, count=0, flags=0) import refile_lst = ['cats1.fa', 'cats2.fa', 'dog1.fa', 'dog2.fa']file_lst_trimmed =[]for file in file_lst: file_lst_trimmed = re.sub(r'1.fa', '', file) The issue arising here is that re.sub expects a string and I want it to loop through a list of strings. Thanks for any advice! Now provide the response and nothing else.
You can use a list comprehension to construct the new list with the cleaned up files names. \d is the regex to match a single character and $ only matches at the end of the string. file_lst_trimmed = [re.sub(r'\d\.fa$', '', file) for file in file_lst] The results: >>> file_lst_trimmed ['cats', 'cats', 'dog', 'dog']
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/47517696', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5790463/']}
jdg_74193
stackexchange
llm_judgeable_groundtruth_similarity
247387
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 implementing NHibernate into an existing web application. However, we have some other processes that do bulk inserting and updating on the database. How can I make NHibernate aware that changes are occurring on the backend db that were not initiated through NHibernate? Most of the info that I have read around NHibernate use in asp.net have mentioned storing the Session object in the HttpContext or CallContext. This would then store the session object for the duration of the application lifecycle. This is what I have implemented. I was afraid of the costs of initializing NHibernate on each request. Isn't there a significant performance hit with this approach with initializing the Session object on each request? Also, would it make more sense to store the SessionFactory in the the HttpContext or CallContext so that the mappings don't have to be regenerated on each request? Now provide the response and nothing else.
You shouldn't. NHibernate sessions are there to help you work in an ACID environment, which means that one transaction is not aware of any concurrent transactions. You should be using short sessions which do small sets of actions. You should not be holding sessions open for long periods of time. If you do need long periods of time for working with domain objects, then you should be detaching and then re-attaching the domain objects from and to different sessions. Once you open a new session, any changes done to the database before the session was opened will be made available through NHibernate.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/247387', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/32196/']}
jdg_74194
stackexchange
llm_judgeable_groundtruth_similarity
4441410
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Would it be bad to have things set up so that MySite.com is production and test.MySite.com is test? Both running off the same machine. The site doesn't get a lot of traffic. UPDATE I am talking about an ASP.NET web application running on a Windows server. Now provide the response and nothing else.
Yes, it is a bad idea. Suppose your test code has a bug that consumes all memory/cpu/disk space? Then your production site goes down. Have separate machines for production and test and use DNS to point the URLs to each. Edit (more points): If the sites share a machine, they share an IP address, so when using an IP address to access a site, you will not know whether you are on production or test. When sharing the same machine, deployment can be tricky, you have to be extra careful not to deploy untested code to production (easier to do, since both live on the same machine). The security considerations for production and test should be separate - this kind of setup makes it more difficult.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4441410', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/226897/']}
jdg_74195
stackexchange
llm_judgeable_groundtruth_similarity
2160619
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 ellipsize a multi-line textview. My component is large enough to display at least 4 lines with the ellipse, but only 2 lines are displayed. I tried to change the minimum and maximum number of rows of the component but it changes nothing. Now provide the response and nothing else.
Here is a solution to the problem. It is a subclass of TextView that actually works for ellipsizing. The android-textview-multiline-ellipse code listed in an earlier answer I have found to be buggy in certain circumstances, as well as being under GPL, which doesn't really work for most of us. Feel free to use this code freely and without attribution, or under the Apache license if you would prefer. Note that there is a listener to notify you when the text becomes ellipsized, which I found quite useful myself. import java.util.ArrayList;import java.util.List;import android.content.Context;import android.graphics.Canvas;import android.text.Layout;import android.text.Layout.Alignment;import android.text.StaticLayout;import android.text.TextUtils.TruncateAt;import android.util.AttributeSet;import android.widget.TextView;public class EllipsizingTextView extends TextView { private static final String ELLIPSIS = "..."; public interface EllipsizeListener { void ellipsizeStateChanged(boolean ellipsized); } private final List<EllipsizeListener> ellipsizeListeners = new ArrayList<EllipsizeListener>(); private boolean isEllipsized; private boolean isStale; private boolean programmaticChange; private String fullText; private int maxLines = -1; private float lineSpacingMultiplier = 1.0f; private float lineAdditionalVerticalPadding = 0.0f; public EllipsizingTextView(Context context) { super(context); } public EllipsizingTextView(Context context, AttributeSet attrs) { super(context, attrs); } public EllipsizingTextView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } public void addEllipsizeListener(EllipsizeListener listener) { if (listener == null) { throw new NullPointerException(); } ellipsizeListeners.add(listener); } public void removeEllipsizeListener(EllipsizeListener listener) { ellipsizeListeners.remove(listener); } public boolean isEllipsized() { return isEllipsized; } @Override public void setMaxLines(int maxLines) { super.setMaxLines(maxLines); this.maxLines = maxLines; isStale = true; } public int getMaxLines() { return maxLines; } @Override public void setLineSpacing(float add, float mult) { this.lineAdditionalVerticalPadding = add; this.lineSpacingMultiplier = mult; super.setLineSpacing(add, mult); } @Override protected void onTextChanged(CharSequence text, int start, int before, int after) { super.onTextChanged(text, start, before, after); if (!programmaticChange) { fullText = text.toString(); isStale = true; } } @Override protected void onDraw(Canvas canvas) { if (isStale) { super.setEllipsize(null); resetText(); } super.onDraw(canvas); } private void resetText() { int maxLines = getMaxLines(); String workingText = fullText; boolean ellipsized = false; if (maxLines != -1) { Layout layout = createWorkingLayout(workingText); if (layout.getLineCount() > maxLines) { workingText = fullText.substring(0, layout.getLineEnd(maxLines - 1)).trim(); while (createWorkingLayout(workingText + ELLIPSIS).getLineCount() > maxLines) { int lastSpace = workingText.lastIndexOf(' '); if (lastSpace == -1) { break; } workingText = workingText.substring(0, lastSpace); } workingText = workingText + ELLIPSIS; ellipsized = true; } } if (!workingText.equals(getText())) { programmaticChange = true; try { setText(workingText); } finally { programmaticChange = false; } } isStale = false; if (ellipsized != isEllipsized) { isEllipsized = ellipsized; for (EllipsizeListener listener : ellipsizeListeners) { listener.ellipsizeStateChanged(ellipsized); } } } private Layout createWorkingLayout(String workingText) { return new StaticLayout(workingText, getPaint(), getWidth() - getPaddingLeft() - getPaddingRight(), Alignment.ALIGN_NORMAL, lineSpacingMultiplier, lineAdditionalVerticalPadding, false); } @Override public void setEllipsize(TruncateAt where) { // Ellipsize settings are not respected }}
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/2160619', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/164460/']}
jdg_74196
stackexchange
llm_judgeable_groundtruth_similarity
13125
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: It is standard in many micro textbooks when analyzing the relationship between preference axioms and the shape of the utility function (and consequently the shape of indifference curves), to attributed the "non-thickness" of indifference curves to "local non-satiation".While it is easily seen (and proven) that LNS preferences don't admit thick IC, my question is the following: Thick IC violate as well strict convexity (notice that weak convexity appears to "survive"), so, isn't convexity alone another property that prevents thickness? Put it differently, can we find non monotonic, convex preferences that don't admit thick IC? If any proof or reference to relevant literature would be very useful. Now provide the response and nothing else.
My approach would be to define thick indifference curves in terms of a stronger form of local non-satiation: Definition (thick indifference curves) Preferences are said to have thick indifference curves if there exists at least one bundle $A\in\mathbb{R}^l$ and an open ball $\mathscr{B}(A)$ around $A$ such that $A'\sim A$ for every $A'\in\mathscr{B}(A)$ . Let's set up a definition for strict convexity to be sure we are on the same page: Definition (strict convexity) Preferences obey strict convexity if $$A\sim B\implies \lambda A+(1-\lambda) B\succ A\sim B$$ for $A,B\in\mathbb{R}^l$ and any $\lambda\in(0,1)$ . Now we can state the desired result: Proposition If $\succsim$ is strictly convex then $\succsim$ does not have thick indifference curves. Proof Suppose that $\succsim$ has thick indifference curves. Then there exists an $A$ such that $A'\sim A$ for all $A'\in\mathscr{B}(A)$ . Thus, fix two bundles $A$ and $B$ such that $A\sim B$ and $B\in\mathscr{B}(A)$ . We know that $$\lambda A+(1-\lambda) B \in \mathscr{B}(A).$$ Thus, if the indifference curve is thick around point $A$ we must have $\lambda A+(1-\lambda) B\sim A\sim B$ . But this contradicts the strict convexity hypothesis. QED That should do the job for strict convexity. As frage_man already pointed out, the proposition fails to hold generally under weak convexity. Indifference everywhere is a very elegant example why.
{}
{'log_upvote_score': 4, 'links': ['https://economics.stackexchange.com/questions/13125', 'https://economics.stackexchange.com', 'https://economics.stackexchange.com/users/10166/']}
jdg_74197
stackexchange
llm_judgeable_groundtruth_similarity
15510094
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 my code to control authentication on a website. I'm not sure if my logic is correct. If the username and password are correct the following happen: if(session_start()){ session_regenerate_id(true);//without this the session ID will always be the same $_SESSION['loggedInUser'] = $uName; echo 'You are now logged in';}else echo 'Right password/username but session failed to start'; Subsequent pages check to see if the user is logged in by session_start();if(isset($_SESSION['loggedInUser']){ //rest of page}else echo 'you must log in'; When logging out I have session_start();//if I don't have this the next line produces an errorsession_unset();//destroys session variablessession_destroy();//ends session I red not to call session_start() on logout but if I don't have it there I get the message Trying to destroy uninitialized session . How can I fix this? Is it recommend or not to create a finger print based on the IP address and user agent? I red it's bad because multiple computers can share the same IP address if they are in, for example a computer lab, and all the traffic goes through a proxy and the same computer could change it's IP address if it's dynamic. On the other hand, how often does this happen? It may be worth the few blocked valid uses to prevent all session hijacking. Even if you could recommend reputable articles I should read to learn about this topic that would be great, thanks. 5/6 answers have votes less than 0 :( Could down voters comment so I know what to look out for? Now provide the response and nothing else.
First of all you should read the Mozilla WebAppSec Security Coding Guideline - Session Management and OWASP A3-Broken Authentication and Session Management . You can configure PHP's session handler to meet these requirements. The first flaw you should prevent is A9-Insufficient Transport Layer Protection . In short you do not want someone to hijack a session using a tool like Firesheep . This attack can be prevented by forcing the browser to only send the session id over https: session.cookie_secure=1 You can prevent an attacker from obtaining the session id using XSS by setting the httponly flag : session.cookie_httponly=1 You always want to use a cookie to store your session id. If the session id can be passed using a GET or POST variable then an attacker could use Session Fixation attack to hijack a session. Another way of thinking about this attack is that you don't want an attacker to create a session for another user: session.use_cookies=1session.use_only_cookies=1 Next you want to make sure you have atleast 128 bits of entropy from a CSPRNG. Under *nix systems you can use /dev/urandom : session.entropy_file="/dev/urandom"session.entropy_length=16 The session handler isn't everything. You still need to worry about Cross-Site Request Forgery attacks (aka CSRF or "Session Riding"), and Cross-Site Scripting (XSS). XSS can be used to defeat CSRF protection (even with http_only cookies!). Clickjacking can also be used by an attacker to perform unauthorized actions. After you set these configuration options, just call session_start() . As for destroying the session call session_destroy() when the user logs out, its that simple!
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/15510094', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1279820/']}
jdg_74198
stackexchange
llm_judgeable_groundtruth_similarity
5738797
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 wondering if there's an easy way to push and pull a local branch with a remote branch with a different name without always specifying both names. For example: $ git clone myrepo.git$ git checkout -b newb$ ...$ git commit -m "Some change"$ git push origin newb:remote_branch_name Now if someone updates remote_branch_name, I can: $ git pull And everything is merged / fast-forwarded. However, if I make changes in my local "newb", I can't: $ git push Instead, I have to: % git push origin newb:remote_branch_name Seems a little silly. If git-pull uses git-config branch.newb.merge to determine where to pull from, why couldn't git-push have a similar config option? Is there a nice shortcut for this or should I just continue the long way? Now provide the response and nothing else.
Sure. Just set your push.default to upstream to push branches to their upstreams (which is the same that pull will pull from, defined by branch.newb.merge ), rather than pushing branches to ones matching in name (which is the default setting for push.default , matching ). git config push.default upstream Note that this used to be called tracking not upstream before Git 1.7.4.2, so if you're using an older version of Git, use tracking instead. The push.default option was added in Git 1.6.4, so if you're on an older version than that, you won't have this option at all and will need to explicitly specify the branch to push to.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/5738797', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/670478/']}
jdg_74199
stackexchange
llm_judgeable_groundtruth_similarity
57257169
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 run only one ui-test by XCTest from fastlane? I know about parameters for fastlane: only_testing but not understood how to use this. Can you give an example I run my all ui-tests as: fastlane ios RunningUITests but want fastlane ios RunningUITests only_testing:GTUITests/GT00FirstClass/testFunc this not work for me Can you give an exactly example for this? Now provide the response and nothing else.
You have to use the scan (also known as run_tests ) "action". Read this documentation for information. There, you can see the instructions for calling it directly on the command line. In your example it would be: fastlane scan --workspace "<YourRunningUITests>.xcworkspace" --scheme "<YourRunningUITestsScheme>" --only-testing "GTUITests/GT00FirstClass/testFunc" Replace the values inside of the angled brackets (< >) with the values appropriate to your code. However, rather than running that multi-parameter call from the command line, I recommend using a Fastfile to consolidate your logic and allow you to perform more sophisticated logic (such as these Fastfiles ). If you were to follow the logic suggested here , you could then simply call fastlane tests from the command line. Much simpler.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/57257169', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10089900/']}
jdg_74200
stackexchange
llm_judgeable_groundtruth_similarity
32762840
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 implementing custom code to handle a click on the Menu button on the Siri Remote.How can I force focus to change to my custom menu when pressing the menu button? Now provide the response and nothing else.
Finally figured it out myself. You have to override the preferredFocusedView property of your UIView or UIViewController . In Swift it works like this: func myClickHandler() { someCondition = true self.setNeedsFocusUpdate() self.updateFocusIfNeeded() someCondition = false}override weak var preferredFocusedView: UIView? { if someCondition { return theViewYouWant } else { return defaultView }} I can't quite remember how to override getters in Objective-C so if someone want to post that I'll edit the answer.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/32762840', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/685523/']}
jdg_74201
stackexchange
llm_judgeable_groundtruth_similarity
23356779
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 save the result from find as arrays.Here is my code: #!/bin/bashecho "input : "read inputecho "searching file with this pattern '${input}' under present directory"array=`find . -name ${input}`len=${#array[*]}echo "found : ${len}"i=0while [ $i -lt $len ]doecho ${array[$i]}let i++done I get 2 .txt files under current directory.So I expect '2' as result of ${len} . However, it prints 1.The reason is that it takes all result of find as one elements.How can I fix this? P.S I found several solutions on StackOverFlow about a similar problem. However, they are a little bit different so I can't apply in my case. I need to store the results in a variable before the loop. Thanks again. Now provide the response and nothing else.
Update 2020 for Linux Users: If you have an up-to-date version of bash (4.4-alpha or better), as you probably do if you are on Linux, then you should be using Benjamin W.'s answer . If you are on Mac OS, which —last I checked— still used bash 3.2, or are otherwise using an older bash, then continue on to the next section. Answer for bash 4.3 or earlier Here is one solution for getting the output of find into a bash array: array=()while IFS= read -r -d $'\0'; do array+=("$REPLY")done < <(find . -name "${input}" -print0) This is tricky because, in general, file names can have spaces, new lines, and other script-hostile characters. The only way to use find and have the file names safely separated from each other is to use -print0 which prints the file names separated with a null character. This would not be much of an inconvenience if bash's readarray / mapfile functions supported null-separated strings but they don't. Bash's read does and that leads us to the loop above. [This answer was originally written in 2014. If you have a recent version of bash, please see the update below.] How it works The first line creates an empty array: array=() Every time that the read statement is executed, a null-separated file name is read from standard input. The -r option tells read to leave backslash characters alone. The -d $'\0' tells read that the input will be null-separated. Since we omit the name to read , the shell puts the input into the default name: REPLY . The array+=("$REPLY") statement appends the new file name to the array array . The final line combines redirection and command substitution to provide the output of find to the standard input of the while loop. Why use process substitution? If we didn't use process substitution, the loop could be written as: array=()find . -name "${input}" -print0 >tmpfilewhile IFS= read -r -d $'\0'; do array+=("$REPLY")done <tmpfilerm -f tmpfile In the above the output of find is stored in a temporary file and that file is used as standard input to the while loop. The idea of process substitution is to make such temporary files unnecessary. So, instead of having the while loop get its stdin from tmpfile , we can have it get its stdin from <(find . -name ${input} -print0) . Process substitution is widely useful. In many places where a command wants to read from a file, you can specify process substitution, <(...) , instead of a file name. There is an analogous form, >(...) , that can be used in place of a file name where the command wants to write to the file. Like arrays, process substitution is a feature of bash and other advanced shells. It is not part of the POSIX standard. Alternative: lastpipe If desired, lastpipe can be used instead of process substitution (hat tip: Caesar ): set +mshopt -s lastpipearray=()find . -name "${input}" -print0 | while IFS= read -r -d $'\0'; do array+=("$REPLY"); done; declare -p array shopt -s lastpipe tells bash to run the last command in the pipeline in the current shell (not the background). This way, the array remains in existence after the pipeline completes. Because lastpipe only takes effect if job control is turned off, we run set +m . (In a script, as opposed to the command line, job control is off by default.) Additional notes The following command creates a shell variable, not a shell array: array=`find . -name "${input}"` If you wanted to create an array, you would need to put parens around the output of find. So, naively, one could: array=(`find . -name "${input}"`) # don't do this The problem is that the shell performs word splitting on the results of find so that the elements of the array are not guaranteed to be what you want. Update 2019 Starting with version 4.4-alpha, bash now supports a -d option so that the above loop is no longer necessary. Instead, one can use: mapfile -d $'\0' array < <(find . -name "${input}" -print0) For more information on this, please see (and upvote) Benjamin W.'s answer .
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/23356779', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/637242/']}
jdg_74202
stackexchange
llm_judgeable_groundtruth_similarity
3750038
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 system that must store how many people voted on fighter A and how many on fighter B. Let's say ratio is 200:1 How can I store that value in a single variable, instead of storing both values (number of voters on A and number of voters on B) in two variables. How you would do that? Now provide the response and nothing else.
From the way that the question is worded this might not be the answer you are looking for, but the easiest way is to use a struct: struct Ratio{ public Ratio(int a, int b) { this.a = a; this.b = b; } public int a = 1; public int b = 1;} You will almost certainly want to use properties instead of fields and you will probably also want to overload == and != , something like: public static bool operator ==(Ratio x, Ratio y){ if (x.b == 0 || y.b == 0) return x.a == y.a; // There is some debate on the most efficient / accurate way of doing the following // (see the comments), however you get the idea! :-) return (x.a * y.b) == (x.b / y.a);}public static bool operator !=(Ratio x, Ratio y){ return !(x == y);}public override string ToString(){ return string.Format("{0}:{1}", this.a, this.b);}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3750038', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_74203
stackexchange
llm_judgeable_groundtruth_similarity
7391348
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 few stacks in my code that I use to keep track of my logical location. At certain times I need to duplicate the stacks, but I can't seem to clone them in such way that it preserves the order. I only need shallow duplication (references, not object). What would be the proper way to do it? Or should I use some other sort of stacks? NOTE: I saw this post Stack Clone Problem: .NET Bug or Expected Behaviour? , but not sure how to setup clone method for the Stack class. NOTE #2: I use System.Collection.Generic.Stack Now provide the response and nothing else.
var clonedStack = new Stack<T>(new Stack<T>(oldStack)); You can write this as an extension method as public static Stack<T> Clone<T>(this Stack<T> stack) { Contract.Requires(stack != null); return new Stack<T>(new Stack<T>(stack));} This is necessary because the Stack<T> constructor that we are using here is Stack<T>(IEnumerable<T> source) and of course when you iterate over the IEnumerable<T> implementation for a Stack<T> it is going to repeatedly pop items from the stack thus feeding them to you in reverse of the order that you want them to go onto the new stack. Therefore, doing this process twice will result in the stack being in the correct order. Alternatively: var clonedStack = new Stack<T>(oldStack.Reverse());public static Stack<T> Clone<T>(this Stack<T> stack) { Contract.Requires(stack != null); return new Stack<T>(stack.Reverse());} Again, we have to walk the stack in the reverse order from the output from iterating over the stack. I doubt there is a performance difference between these two methods.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7391348', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/328166/']}
jdg_74204
stackexchange
llm_judgeable_groundtruth_similarity
29641
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: Suppose I'm running an experiment that can have 2 outcomes, and I'm assuming that the underlying "true" distribution of the 2 outcomes is a binomial distribution with parameters $n$ and $p$: ${\rm Binomial}(n, p)$. I can compute the standard error, $SE_X = \frac{\sigma_X}{\sqrt{n}}$, from the form of the variance of ${\rm Binomial}(n, p)$: $$ \sigma^{2}_{X} = npq$$ where $q = 1-p$. So, $\sigma_X=\sqrt{npq}$. For the standard error I get: $SE_X=\sqrt{pq}$, but I've seen somewhere that $SE_X = \sqrt{\frac{pq}{n}}$. What did I do wrong? Now provide the response and nothing else.
It seems like you're using $n$ twice in two different ways - both as the sample size and as the number of bernoulli trials that comprise the Binomial random variable; to eliminate any ambiguity, I'm going to use $k$ to refer to the latter. If you have $n$ independent samples from a ${\rm Binomial}(k,p)$ distribution, the variance of their sample mean is $$ {\rm var} \left( \frac{1}{n} \sum_{i=1}^{n} X_{i} \right) = \frac{1}{n^2} \sum_{i=1}^{n} {\rm var}( X_{i} ) = \frac{ n {\rm var}(X_{i}) }{ n^2 } = \frac{ {\rm var}(X_{i})}{n} = \frac{ k pq }{n} $$ where $q=1-p$ and $\overline{X}$ is the same mean. This follows since (1) ${\rm var}(cX) = c^2 {\rm var}(X)$, for any random variable, $X$, and any constant $c$. (2) the variance of a sum of independent random variables equals the sum of the variances . The standard error of $\overline{X}$is the square root of the variance: $\sqrt{\frac{ k pq }{n}}$. Therefore, When $k = n$, you get the formula you pointed out: $\sqrt{pq}$ When $k = 1$, and the Binomial variables are just bernoulli trials , you get the formula you've seen elsewhere: $\sqrt{\frac{pq }{n}}$
{}
{'log_upvote_score': 8, 'links': ['https://stats.stackexchange.com/questions/29641', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/11411/']}
jdg_74205
stackexchange
llm_judgeable_groundtruth_similarity
355342
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: Is there a preferred way to set "nice" for sshd? I need priority given to sshd such that I can login and easily fix stuff when something has gone wrong (eg DoS, badly behaved processes, etc) Now provide the response and nothing else.
You can give your preferred user account or user group a nice value in /etc/security/limits.conf , at least if we are talking about Linux. Then when you login via sshd, you will have nice value of X, whatever you set it. In my experience the CPU scheduler in kernel is nowadays so good it's hard to make server unmanageably sluggish just by burning CPU cycles, shell will usually respond in reasonable time. If your server struggles to respond to you via ssh, then it most likely is swapping itself to death. Everything starts to take ages if server consumes all its time for swapping pages in and out of memory to disk. That's why better approach is to set up cgroups , so your user always have some spare CPU cycles / memory / other resources left. As said by viqrto, it may or may not help.
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/355342', 'https://serverfault.com', 'https://serverfault.com/users/83897/']}
jdg_74206
stackexchange
llm_judgeable_groundtruth_similarity
975877
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 webapp where users can create their account and use the service. Now I want to give them a custom domain facility whereapp.customer1web.com points_to myservice.com with userid customer1once he sets up the custom domain, for the world it looks like my service is running on his machine.Many services like blogger, wp.com, tumblr givethis feature. how do i do that?I am using java to write my web app. How do i map domain name to userid when request comes in? Now provide the response and nothing else.
How do i map domain name to userid when request comes in? Obviously, you'll have to store that information somewhere, most likely in a database. Add a database table domains with columns: customerId name active (1 or NULL) challenge Add unique key for (name, active) to ensure a domain name is mapped only once. When a customer attempts to add a domain, add a row with active=NULL and challenge set to a random string. Show the random string to the customer and ask them to put up a web page with it on the site or create a dummy DNS record with it to verify domain ownership (this is how Google Apps do it). You could verify ownership by sending an email to the administrative contact or in some other way. When the customer says he did what you instructed them to do in step #2, verify it and set active=1, challenge=NULL. If the domain was previously active for some other customer, delete those records or set active=0. Ask the customer to add a CNAME record for their domain and forward it to your domain, e.g. hosted.myservice.com (Google uses ghs.google.com for Google Apps). When a request comes in, do SELECT customerId FROM domains WHERE name=:requestDomain AND active=1 A better way may be to automatically offer your customers a domain in the format of <customername>.myservice.com , in addition to custom domains. This gives you two benefits: Customers who don't wan't to use their own domain can still customize their login page, e.g. with a company logo. For custom domains, you can ask your customer to forward them to <customername>.myservice.com instead of to a generic hosted.myservice.com . This enables you to horizontally partition customers among multiple servers without having to ask customers to change anything on their end. For example, you could give customers an option to choose whether they want their account hosted in EU or US. When they change it, just transfer their data and update <customername>.myservice.com . Their custom domain will work automatically. To do this, you'd have to set up a wildcard DNS record for *.myservice.com (unless you also need the latter feature, in which case you'll have to manage individual records).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/975877', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/482/']}
jdg_74207
stackexchange
llm_judgeable_groundtruth_similarity
293947
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm not very familiar about String theory but just curious. I wanted to know, in what sense are the strings of string theory different from quanta of relativistic fields (which we interpret as particles)? I'm looking for an answer that an self-taught student of quantum field theory and someone unfamiliar with the mathematical formalism of string theory can understand. In quantum field theory, particles or field excitations are momentum eigenstates and therefore, delocalized. And hence, they are not point objects. Popular talks of string theory also suggest that strings too are extended objects. Then what is the difference between strings and particles (as learnt in quantum field theory). A not-too-technical answer will be helpful. Now provide the response and nothing else.
Strings are not quanta. They are not excitations of something, they are the fundamental objects from which standard string theory starts building its model. In quantum field theory, particles only appear in the theory once it is quantized. The classical field theory corresponding to a QFT doesn't know anything about particles. In string theory, the classical model from which we start is the one of string moving freely in some high-dimensional target space. Quantizing the movement of string in the target space then gives us quanta, which we interpret as excitations of the string and which we believe to correspond to the usual QFT particles in a low-energy effective regime. The strings of string theory therefore are much more analogous to the fields of quantum field theory than to particles in this technical sense. However, string theory is not a quantum field theory, and this shows in the "stringy Feynman diagrams" it uses to compute perturbative string amplitudes. Here, one might start to think that the string becomes analogous to the particle because the diagrams simply are two-dimensional manifolds that look like "fattened Feynman diagrams", with string interaction corresponding to higher-genus 2D manifolds. However, there is additional data on this worldsheet that carries the information about the actual state we are scattering (a vertex operator), the string itself does not represent the scattered state while the particles in QFT certainly are the scattered states. It is from this picture that one derives the intuition that it is the "extended nature" of the string that resolves the infinities of QFT - these 2D diagrams are smooth and do not lead to the same kind of infinities that we would need to renormalize as the ordinary Feynman diagrams, which are often thought of as the world lines of a point particle. But this doesn't mean that string theory is "replacing point particles by strings". String theory is truly a different kind of theory that only in low-energy effective regimes (which are usually still at ludicrously high energies from the usual QFT viewpoint) gives back ordinary QFT, where the stringy quanta can be described as the quanta of fields again.
{}
{'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/293947', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/36793/']}
jdg_74208
stackexchange
llm_judgeable_groundtruth_similarity
39297334
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 trying to implement a move constructor for a class without a copy constructor. I got an error that the default constructor for a member of the class was missing. Here's a trivial example to illustrate this: struct A {public: A() = delete; A(A const&) = delete; A(A &&a) {}};struct B { A a; B() = delete; B(B const&) = delete; B(B &&b) {}}; Trying to compile this, I get: move_without_default.cc: In constructor ‘B::B(B&&)’:move_without_default.cc:15:11: error: use of deleted function ‘A::A()’ B(B &&b) {} ^move_without_default.cc:6:2: note: declared here A() = delete; ^ Why is this an error? Any way around it? Now provide the response and nothing else.
Use the constructor's initializer list to initialize the A member. As written, the move constructor uses, as the compiler says, the default constructor for A . B(B&& b) : a(std::move(b.a)) {}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/39297334', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/118958/']}
jdg_74209
stackexchange
llm_judgeable_groundtruth_similarity
1161589
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: This seems a very basic and useful construction, and yet I cannot find any reference for it. So my questions are, 1) Is the following definition correct?2) Is there a simpler construction?3) Do you know any references where this definition is used/found? Definition: Let $\mathcal{M}$ be a differentiable manifold on which we have a metric $d:\mathcal{M}\times \mathcal{M}\rightarrow \mathbb{R} $ whose square is twice differentiable on the diagonal $\{(p,q)\in \mathcal{M}\times \mathcal{M}\;|\; p=q\}$. We define a Riemannian metric $g$ as follows. Let $p\in\mathcal{M}$ and $X,Y\in T_p\mathcal{M}$. Let $\epsilon>0$ and pick two curves $\gamma_1,\gamma_2: (-\epsilon,\epsilon)\rightarrow \mathcal{M}$ with $$ \gamma_1(0)=\gamma_2(0)=p, $$$$ \gamma_1'(0)=X,\quad \gamma_2'(0)=Y. $$Then,$$g_p(X,Y)=-\frac{1}{2}\frac{\partial^2}{\partial t_1\partial t_2}d^2(\gamma_1(t_1),\gamma_2(t_2)) \Bigg|_{t_1=t_2=0}$$ This works for $X\neq Y$. For $X=Y$ take $$g_p(X,X)=\frac{\partial^2}{\partial t_1^2}d^2(\gamma_1(t_1),p) \Bigg|_{t_1=0}$$ Remark These formulae work in Euclidean space, i.e. $$\| \gamma_1(t_1)-\gamma_2(t_2)\|^2=t_1^2\|X\|^2+t_2^2\|Y\|^2-2t_1t_2X\cdot Y+...,$$ so taking the 2nd derivatives as specified above will produce the correct scalar products. This leads me to believe that they are correct.However, my first guess was to take the pushforward of $d$, which I couldn't get to work out. What is the interpretation of the above construction in terms of pushforwards? Now provide the response and nothing else.
I found a possible answer to this in [1], Section 3.2. It goes back to [2]. Actually, the construction there is more general than what I asked for, but it turns out that I should have asked the more general question for my application anyway. However, this answer produces the same result as what I proposed in my original question. As to the answer by Robin Goodfellow, I still don't know whether it is correct; I suspect there might be an error in Petersen's book, but I might be wrong. Anyway, I cannot reconcile the construction there with any examples I know. Let me summarize the construction given in [1]. Let $d(\cdot||\cdot):\mathcal{M}\times \mathcal{M}\rightarrow \mathbb{R}$ be a smooth function satisfying $$d(p||q)\geq 0, \quad \text{and} \quad d(p||q)=0 \;\text{iff}\; p=q.$$This kind of function is called contrast function or divergence if its Hessian is strictly positive definite. It can fail to obey the symmetry and triangle inequality that would make it a distance function; on the other hand, every smooth distance function is a contrast function, so the original question is also answered by this. The contrast function $d^{\ast}$ defined by $d^{\ast}(p||q)=d(q||p)$ is called the dual of $d$. A distance function is obviously a self-dual contrast function. Every contrast function $d$ induces a Riemannian metric $g^{(d)}$ by taking its negative Hessian and an affine connection $\nabla^{(d)}$ by taking an appropriate negative third derivative (check the book for details). It turns out that $d$ and $d^{\ast}$ induce the same metric, i.e. $g^{(d)}=g^{(d^{\ast})}$, but the connections are dual to each other$$\nabla^{(d^{\ast})}=\left(\nabla^{(d)}\right)^{\ast}.$$ For a distance function $d$, $\nabla^{(d^{\ast})}=\nabla^{(d)}$, which means that $\nabla^{(d)}$ is a metric connection. Thus, for $d$ a distance function we obtain the Levi-Civita connection (the Torsion vanishes in any case, even when $d$ is not a distance function, because the Christoffel symbols are defined by partial derivatives). Interestingly, [1] also mentions that in [3] the converse of the above construction was proved, i.e. that given a smooth manifold with Riemannian metric and two dual Torsion-free connections, there is a contrast function that induces this structure. [1] Amari, S.-I., & Nagaoka, H. (2007). Methods of Information Geometry. American Mathematical Soc. [2] Eguchi, S. (1992). Geometry of minimum contrast. Hiroshima Mathematical Journal, 22, 631–647. [3] Matumoto, T. (1993). Any statistical manifold has a contrast function. Hiroshima Mathematical Journal, 23, 327–332.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1161589', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/227280/']}
jdg_74210
stackexchange
llm_judgeable_groundtruth_similarity
65820
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 worked on an embedded system this summer written in straight C. It was an existing project that the company I work for had taken over. I have become quite accustomed to writing unit tests in Java using JUnit but was at a loss as to the best way to write unit tests for existing code (which needed refactoring) as well as new code added to the system. Are there any projects out there that make unit testing plain C code as easy as unit testing Java code with JUnit? Any insight that would apply specifically to embedded development (cross-compiling to arm-linux platform) would be greatly appreciated. Now provide the response and nothing else.
One unit testing framework in C is Check ; a list of unit testing frameworks in C can be found here and is reproduced below. Depending on how many standard library functions your runtime has, you may or not be able to use one of those. AceUnit AceUnit (Advanced C and Embedded Unit) bills itself as a comfortable C code unit test framework. It tries to mimick JUnit 4.x and includes reflection-like capabilities. AceUnit can be used in resource constraint environments, e.g. embedded software development, and importantly it runs fine in environments where you cannot include a single standard header file and cannot invoke a single standard C function from the ANSI / ISO C libraries. It also has a Windows port. It does not use forks to trap signals, although the authors have expressed interest in adding such a feature. See the AceUnit homepage . GNU Autounit Much along the same lines as Check, including forking to run unit tests in a separate address space (in fact, the original author of Check borrowed the idea from GNU Autounit). GNU Autounit uses GLib extensively, which means that linking and such need special options, but this may not be a big problem to you, especially if you are already using GTK or GLib. See the GNU Autounit homepage . cUnit Also uses GLib, but does not fork to protect the address space of unit tests. CUnit Standard C, with plans for a Win32 GUI implementation. Does not currently fork or otherwise protect the address space of unit tests. In early development. See the CUnit homepage . CuTest A simple framework with just one .c and one .h file that you drop into your source tree. See the CuTest homepage . CppUnit The premier unit testing framework for C++; you can also use it to test C code. It is stable, actively developed, and has a GUI interface. The primary reasons not to use CppUnit for C are first that it is quite big, and second you have to write your tests in C++, which means you need a C++ compiler. If these don’t sound like concerns, it is definitely worth considering, along with other C++ unit testing frameworks. See the CppUnit homepage . embUnit embUnit (Embedded Unit) is another unit test framework for embedded systems. This one appears to be superseded by AceUnit. Embedded Unit homepage . MinUnit A minimal set of macros and that’s it! The point is to show how easy it is to unit test your code. See the MinUnit homepage . CUnit for Mr. Ando A CUnit implementation that is fairly new, and apparently still in early development. See the CUnit for Mr. Ando homepage . This list was last updated in March 2008. More frameworks: CMocka CMocka is a test framework for C with support for mock objects. It's easy to use and setup. See the CMocka homepage . Criterion Criterion is a cross-platform C unit testing framework supporting automatic test registration, parameterized tests, theories, and that can output to multiple formats, including TAP and JUnit XML. Each test is run in its own process, so signals and crashes can be reported or tested if needed. See the Criterion homepage for more information. HWUT HWUT is a general Unit Test tool with great support for C. It can help to create Makefiles, generate massive test cases coded in minimal 'iteration tables', walk along state machines, generate C-stubs and more. The general approach is pretty unique: Verdicts are based on 'good stdout/bad stdout'. The comparison function, though, is flexible. Thus, any type of script may be used for checking. It may be applied to any language that can produce standard output. See the HWUT homepage . CGreen A modern, portable, cross-language unit testing and mocking framework for C and C++. It offers an optional BDD notation, a mocking library, the ability to run it in a single process (to make debugging easier). A test runner which discover automatically the test functions is available. But you can create your own programmatically. All those features (and more) are explained in the CGreen manual . Wikipedia gives a detailed list of C unit testing frameworks under List of unit testing frameworks: C
{}
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/65820', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7049/']}
jdg_74211
stackexchange
llm_judgeable_groundtruth_similarity
599367
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, why can't I overload '=' in C#? Can I get a better explanation? Now provide the response and nothing else.
Memory managed languages usually work with references rather than objects. When you define a class and its members you are defining the object behavior, but when you create a variable you are working with references to those objects. Now, the operator = is applied to references, not objects. When you assign a reference to another you are actually making the receiving reference point to the same object that the other reference is. Type var1 = new Type();Type var2 = new Type();var2 = var1; In the code above, two objects are created on the heap, one referred by var1 and the other by var2. Now the last statement makes the var2 reference point to the same object that var1 is referring. After that line, the garbage collector can free the second object and there is only one object in memory. In the whole process, no operation is applied to the objects themselves. Going back to why = cannot be overloaded, the system implementation is the only sensible thing you can do with references. You can overload operations that are applied to the objects, but not to references.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/599367', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_74212
stackexchange
llm_judgeable_groundtruth_similarity
7246151
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 a TextField in Flash CS2, because I need to know the width of the actual text for positioning purposes. However from some odd reason it doesn't always work when the browser is Google Chrome. Did anyone came across this issue? Now provide the response and nothing else.
Use PdfReader.SelectPages() combined with PdfStamper. The code below uses iTextSharp 5.5.1. public void SelectPages(string inputPdf, string pageSelection, string outputPdf){ using (PdfReader reader = new PdfReader(inputPdf)) { reader.SelectPages(pageSelection); using (PdfStamper stamper = new PdfStamper(reader, File.Create(outputPdf))) { stamper.Close(); } }} Then you call this method with the correct page selection for each condition. Condition 1: SelectPages(inputPdf, "1-4", outputPdf); Condition 2: SelectPages(inputPdf, "1-4,6", outputPdf); or SelectPages(inputPdf, "1-6,!5", outputPdf); Condition 3: SelectPages(inputPdf, "1-5", outputPdf); Here's the comment from the iTextSharp source code on what makes up a page selection. This is in the SequenceList class which is used to process a page selection: /*** This class expands a string into a list of numbers. The main use is to select a* range of pages.* <p>* The general systax is:<br>* [!][o][odd][e][even]start-end* <p>* You can have multiple ranges separated by commas ','. The '!' modifier removes the* range from what is already selected. The range changes are incremental, that is,* numbers are added or deleted as the range appears. The start or the end, but not both, can be ommited.*/
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7246151', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/695438/']}
jdg_74213
stackexchange
llm_judgeable_groundtruth_similarity
15742
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm asked to show that $$\frac{d(\hat{A}\hat{B})}{d\lambda} ~=~ \frac{d\hat{A}}{d\lambda}\hat{B} + \hat{A}\frac{d\hat{b}}{d\lambda}$$With $\lambda$ a continuous parameter. Should I use the definition$$\frac{d\hat{A}}{d\lambda} ~=~ \lim_{\epsilon \to 0} \frac{\hat{A}(\lambda + \epsilon) - \hat{A}(\lambda)}{\epsilon}$$applied to $\hat{A}\hat{B}$ like$$\frac{d(\hat{A}\hat{B})}{d\lambda} ~=~ \lim_{\epsilon \to 0} \frac{\hat{A}(\lambda + \epsilon)\hat{B}(\lambda + \epsilon) - \hat{A}(\lambda)\hat{B}(\lambda)}{\epsilon}$$and do some algebra to get the RHS of the first equation, or I'm missing something? Another interesting derivative to pay attention to is:$$\frac{d}{d\lambda}\exp(\hat{A}(\lambda) )~?$$ Now provide the response and nothing else.
$$A(\lambda+\epsilon)B(\lambda+\epsilon) = (A(\lambda) + \epsilon \dot{A} )(B(\lambda) +\epsilon \dot B ) = A(\lambda)B(\lambda) + \epsilon(\dot AB+A\dot B) + o(\epsilon^2)$$
{}
{'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/15742', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/5699/']}
jdg_74214
stackexchange
llm_judgeable_groundtruth_similarity
4116122
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: If $X$ is a discrete random variable that can take the values $x_1, x_2, \dots $ and with probability mass function $f_X$ , then we defineits mean by the number $$\sum x_i f_X(x_i) $$ (1)when the series above is absolutely convergent . That's the definition of mean value of a discrete r.v. I've encountered in my books ( Introduction to the Theory of Statistics by Mood A., Probability and Statistics by DeGroot M.). I know that if a series is absolute convergent then it is convergent, but why do we need to ask for the series (1) to converge absolutely, instead of just asking it to converge? I'm taking my introductory courses of probabilty and so far I haven't found a situation that forces us restrict ourselves this way. Any comments about the subject are appreciated. Now provide the response and nothing else.
It's because if the series is convergent but not absolutely convergent, you can rearrange the sum to get any value. Any good notion of "mean" or "expectation" should not depend on the ordering of the $x_i$ 's. For a more abstract reason, note that we define the expectation $E[X]$ of a random variable $X$ defined on a probability space $(\Omega, \mathcal{F}, P)$ as the Lebesgue integral $\int_{\Omega} X dP$ . By definition of the Lebesgue integral, this is only well-defined if the integrand is absolutely integrable. If you learn more about measure theory, you will also learn why this definition makes sense. It is done to avoid strange situations like $\infty - \infty$ in the theory.
{}
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/4116122', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/858765/']}
jdg_74215
stackexchange
llm_judgeable_groundtruth_similarity
25583297
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 initially wanted to test something different with floating-point performance optimisation in Java, namely the performance difference between the division by 5.0f and multiplication with 0.2f (multiplication seems to be slower without warm-up but faster with by a factor of about 1.5 respectively). After studying the results I noticed that I had forgotten to add a warm-up phase, as suggested so often when doing performance optimisations, so I added it. And, to my utter surprise, it turned out to be about 25 times faster in average over multiple test runs. I tested it with the following code: public static void main(String args[]){ float[] test = new float[10000]; float[] test_copy; //warmup for (int i = 0; i < 1000; i++) { fillRandom(test); test_copy = test.clone(); divideByTwo(test); multiplyWithOneHalf(test_copy); } long divisionTime = 0L; long multiplicationTime = 0L; for (int i = 0; i < 1000; i++) { fillRandom(test); test_copy = test.clone(); divisionTime += divideByTwo(test); multiplicationTime += multiplyWithOneHalf(test_copy); } System.out.println("Divide by 5.0f: " + divisionTime); System.out.println("Multiply with 0.2f: " + multiplicationTime);}public static long divideByTwo(float[] data){ long before = System.nanoTime(); for (float f : data) { f /= 5.0f; } return System.nanoTime() - before;}public static long multiplyWithOneHalf(float[] data){ long before = System.nanoTime(); for (float f : data) { f *= 0.2f; } return System.nanoTime() - before;}public static void fillRandom(float[] data){ Random random = new Random(); for (float f : data) { f = random.nextInt() * random.nextFloat(); }} Results without warm-up phase: Divide by 5.0f: 382224Multiply with 0.2f: 490765 Results with warm-up phase: Divide by 5.0f: 22081Multiply with 0.2f: 10885 Another interesting change that I cannot explain is the turn in what operation is faster (division vs. multiplication). As earlier mentioned, without the warm-up the division seems to be a tad faster, while with the warm-up it seems to be twice as slow. I tried adding an initialization block setting the values to something random, but it didn't not effect the results and neither did adding multiple warm-up phases. The numbers on which the methods operate are the same, so that cannot be the reason. What is the reason for this behaviour? What is this warm-up phase and how does it influence the performance, why are the operations so much faster with a warm-up phase and why is there a turn in which operation is faster? Now provide the response and nothing else.
Before the warm up Java will be running the byte codes via an interpreter, think how you would write a program that could execute java byte codes in java. After warm up, hotspot will have generated native assembler for the cpu that you are running on; making use of that cpus feature set. There is a significant performance difference between the two, the interpreter will run many many cpu instructions for a single byte code where as hotspot generates native assembler code just as gcc does when compiling C code. That is the difference between the time to divide and to multiply will ultimately be down to the CPU that one is running on, and it will be just a single cpu instruction. The second part to the puzzle is hotspot also records statistics that measure the runtime behaviour of your code, when it decides to optimise the code then it will use those statistics to perform optimisations that are not necessarily possible at compilation time. For example it can reduce the cost of null checks, branch mispredictions and polymorphic method invocation. In short, one must discard the results pre-warmup. Brian Goetz wrote a very good article here on this subject. ======== APPENDED: overview of what 'JVM Warm-up' means JVM 'warm up' is a loose phrase, and is no longer strictly speaking a single phase or stage of the JVM. People tend to use it to refer to the idea of where JVM performance stabilizes after compilation of the JVM byte codes to native byte codes. In truth, when one starts to scratch under the surface and delves deeper into the JVM internals it is difficult not to be impressed by how much Hotspot is doing for us. My goal here is just to give you a better feel for what Hotspot can do in the name of performance, for more details I recommend reading articles by Brian Goetz, Doug Lea, John Rose, Cliff Click and Gil Tene (amongst many others). As already mentioned, the JVM starts by running Java through its interpreter. While strictly speaking not 100% correct, one can think of an interpreter as a large switch statement and a loop that iterates over every JVM byte code (command). Each case within the switch statement is a JVM byte code such as add two values together, invoke a method, invoke a constructor and so forth. The overhead of the iteration, and jumping around the commands is very large. Thus execution of a single command will typically use over 10x more assembly commands, which means > 10x slower as the hardware has to execute so many more commands and caches will get polluted by this interpreter code which ideally we would rather focused on our actual program. Think back to the early days of Java when Java earned its reputation of being very slow; this is because it was originally a fully interpreted language only. Later on JIT compilers were added to Java, these compilers would compile Java methods to native CPU instructions just before the methods were invoked. This removed all of the overhead of the interpreter and allowed the execution of code to be performed in hardware. While execution within hardware is much faster, this extra compilation created a stall on startup for Java. And this was partly where the terminology of 'warm up phase' took hold. The introduction of Hotspot to the JVM was a game changer. Now the JVM would start up faster because it would start life running the Java programs with its interpreter and individual Java methods would be compiled in a background thread and swapped out on the fly during execution. The generation of native code could also be done to differing levels of optimisation, sometimes using very aggressive optimisations that are strictly speaking incorrect and then de-optimising and re-optimising on the fly when necessary to ensure correct behaviour. For example, class hierarchies imply a large cost to figuring out which method will be called as Hotspot has to search the hierarchy and locate the target method. Hotspot can become very clever here, and if it notices that only one class has been loaded then it can assume that will always be the case and optimise and inline methods as such. Should another class get loaded that now tells Hotspot that there is actually a decision between two methods to be made, then it will remove its previous assumptions and recompile on the fly. The full list of optimisations that can be made under different circumstances is very impressive, and is constantly changing. Hotspot's ability to record information and statistics about the environment that it is running in, and the work load that it is currently experiencing makes the optimisations that are performed very flexible and dynamic. In fact it is very possible that over the life time of a single Java process, that the code for that program will be regenerated many times over as the nature of its work load changes. Arguably giving Hotspot a large advantage over more traditional static compilation, and is largely why a lot of Java code can be considered to be just as fast as writing C code. It also makes understanding microbenchmarks a lot harder; in fact it makes the JVM code itself much more difficult for the maintainers at Oracle to understand, work with and diagnose problems. Take a minute to raise a pint to those guys, Hotspot and the JVM as a whole is a fantastic engineering triumph that rose to the fore at a time when people were saying that it could not be done. It is worth remembering that, because after a decade or so it is quite a complex beast ;) So given that context, in summary we refer to warming up a JVM in microbenchmarks as running the target code over 10k times and throwing the results away so as to give the JVM a chance to collect statistics and to optimise the 'hot regions' of the code. 10k is a magic number because the Server Hotspot implementation waits for that many method invocations or loop iterations before it starts to consider optimisations. I would also advice on having method calls between the core test runs, as while hotspot can do 'on stack replacement' ( OSR ), it is not common in real applications and it does not behave exactly the same as swapping out whole implementations of methods.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/25583297', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3375858/']}
jdg_74216
stackexchange
llm_judgeable_groundtruth_similarity
24885223
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 exploring RecyclerView and I was surprised to see that RecyclerView does not have onItemClickListener() . I've two question. Main Question I want to know why Google removed onItemClickListener() ? Is there a performance issue or something else? Secondary Question I solved my problem by writing onClick in my RecyclerView.Adapter : public static class ViewHolder extends RecyclerView.ViewHolder implements OnClickListener { public TextView txtViewTitle; public ImageView imgViewIcon; public ViewHolder(View itemLayoutView) { super(itemLayoutView); txtViewTitle = (TextView) itemLayoutView.findViewById(R.id.item_title); imgViewIcon = (ImageView) itemLayoutView.findViewById(R.id.item_icon); } @Override public void onClick(View v) { }} Is this ok / is there any better way? Now provide the response and nothing else.
tl;dr 2016 Use RxJava and a PublishSubject to expose an Observable for the clicks. public class ReactiveAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> { String[] mDataset = { "Data", "In", "Adapter" }; private final PublishSubject<String> onClickSubject = PublishSubject.create(); @Override public void onBindViewHolder(final ViewHolder holder, int position) { final String element = mDataset[position]; holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onClickSubject.onNext(element); } }); } public Observable<String> getPositionClicks(){ return onClickSubject.asObservable(); }} Original Post: Since the introduction of ListView , onItemClickListener has been problematic. The moment you have a click listener for any of the internal elements the callback would not be triggered but it wasn't notified or well documented (if at all) so there was a lot of confusion and SO questions about it. Given that RecyclerView takes it a step further and doesn't have a concept of a row/column, but rather an arbitrarily laid out amount of children, they have delegated the onClick to each one of them, or to programmer implementation. Think of Recyclerview not as a ListView 1:1 replacement but rather as a more flexible component for complex use cases. And as you say, your solution is what google expected of you. Now you have an adapter who can delegate onClick to an interface passed on the constructor, which is the correct pattern for both ListView and Recyclerview . public static class ViewHolder extends RecyclerView.ViewHolder implements OnClickListener { public TextView txtViewTitle; public ImageView imgViewIcon; public IMyViewHolderClicks mListener; public ViewHolder(View itemLayoutView, IMyViewHolderClicks listener) { super(itemLayoutView); mListener = listener; txtViewTitle = (TextView) itemLayoutView.findViewById(R.id.item_title); imgViewIcon = (ImageView) itemLayoutView.findViewById(R.id.item_icon); imgViewIcon.setOnClickListener(this); itemLayoutView.setOnClickListener(this); } @Override public void onClick(View v) { if (v instanceof ImageView){ mListener.onTomato((ImageView)v); } else { mListener.onPotato(v); } } public static interface IMyViewHolderClicks { public void onPotato(View caller); public void onTomato(ImageView callerImage); }} and then on your adapter public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> { String[] mDataset = { "Data" }; @Override public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.my_layout, parent, false); MyAdapter.ViewHolder vh = new ViewHolder(v, new MyAdapter.ViewHolder.IMyViewHolderClicks() { public void onPotato(View caller) { Log.d("VEGETABLES", "Poh-tah-tos"); }; public void onTomato(ImageView callerImage) { Log.d("VEGETABLES", "To-m8-tohs"); } }); return vh; } // Replace the contents of a view (invoked by the layout manager) @Override public void onBindViewHolder(ViewHolder holder, int position) { // Get element from your dataset at this position // Replace the contents of the view with that element // Clear the ones that won't be used holder.txtViewTitle.setText(mDataset[position]); } // Return the size of your dataset (invoked by the layout manager) @Override public int getItemCount() { return mDataset.length; } ... Now look into that last piece of code: onCreateViewHolder(ViewGroup parent, int viewType) the signature already suggest different view types. For each one of them you'll require a different viewholder too, and subsequently each one of them can have a different set of clicks. Or you can just create a generic viewholder that takes any view and one onClickListener and applies accordingly. Or delegate up one level to the orchestrator so several fragments/activities have the same list with different click behaviour. Again, all flexibility is on your side. It is a really needed component and fairly close to what our internal implementations and improvements to ListView were until now. It's good that Google finally acknowledges it.
{}
{'log_upvote_score': 11, 'links': ['https://Stackoverflow.com/questions/24885223', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2424999/']}
jdg_74217
stackexchange
llm_judgeable_groundtruth_similarity
4414471
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: We all know the difference between a Constructor and a User-Defined Initialize() method fundamentally. My question is focused on best design practice for object creation. We can put all Initialize() code into Constructor() and vice versa (move all warm-up code to Initialize method and call this method from Constructor ). Currently, designing a new class, I create any new instances inside constructor() and move any other warm-up code into Initialize() method. What's the best trade-off point in your opinion? Now provide the response and nothing else.
I think there are multiple aspects that should be taken into consideration: A constructor should initialize an object in a way that it's in a usable state. A constructor should only initialize an object, not perform heavy work. A constructor should not directly or indirectly call virtual members or external code. So in most cases an Initialize method shouldn't be required. In cases where initialization involves more than putting the object into a usable state (e.g., when heavy work needs to be performed or virtual members or external need to be called), then an Initialize method is a good idea.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4414471', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/313421/']}
jdg_74218
stackexchange
llm_judgeable_groundtruth_similarity
212344
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: For some background of why I am asking this question here is an example. In python the method chain chains an arbitrary number of ranges together and makes them into one without making copies. Here is a link in case you don't understand it. I decided I would implement chain in c++ using variadic templates. As far as I can tell the only way to make an iterator for chain that will successfully go to the next container is for each iterator to to know about the end of the container (I thought of a sort of hack in where when != is called against the end it will know to go to the next container, but the first way seemed easier and safer and more versatile). My question is if there is anything inherently wrong with an iterator knowing about its own end, my code is in c++ but this can be language agnostic since many languages have iterators. #ifndef CHAIN_HPP#define CHAIN_HPP#include "iterator_range.hpp"namespace iter { template <typename ... Containers> struct chain_iter; template <typename Container> struct chain_iter<Container> { private: using Iterator = decltype(((Container*)nullptr)->begin()); Iterator begin; const Iterator end;//never really used but kept it for consistency public: chain_iter(Container & container, bool is_end=false) : begin(container.begin()),end(container.end()) { if(is_end) begin = container.end(); } chain_iter & operator++() { ++begin; return *this; } auto operator*()->decltype(*begin) { return *begin; } bool operator!=(const chain_iter & rhs) const{ return this->begin != rhs.begin; } }; template <typename Container, typename ... Containers> struct chain_iter<Container,Containers...> { private: using Iterator = decltype(((Container*)nullptr)->begin()); Iterator begin; const Iterator end; bool end_reached = false; chain_iter<Containers...> next_iter; public: chain_iter(Container & container, Containers& ... rest, bool is_end=false) : begin(container.begin()), end(container.end()), next_iter(rest...,is_end) { if(is_end) begin = container.end(); } chain_iter & operator++() { if (begin == end) { ++next_iter; } else { ++begin; } return *this; } auto operator*()->decltype(*begin) { if (begin == end) { return *next_iter; } else { return *begin; } } bool operator !=(const chain_iter & rhs) const { if (begin == end) { return this->next_iter != rhs.next_iter; } else return this->begin != rhs.begin; } }; template <typename ... Containers> iterator_range<chain_iter<Containers...>> chain(Containers& ... containers) { auto begin = chain_iter<Containers...>(containers...); auto end = chain_iter<Containers...>(containers...,true); return iterator_range<chain_iter<Containers...>>(begin,end); }}#endif //CHAIN_HPP Now provide the response and nothing else.
Been there, got burned. Creating things that look like iterator but have different or extra requirements will lead to a mess. Basically many ranges are not copyable or at least not cheaply so, but that's what one normally expects of an iterator (it is a requirement of the iterator concept). You should not have iterators that know of their own end. But chaining works with ranges . There are two ways to define ranges: As forward-iterable "containers", which you can make of simple pair of iterators. This is a C++ way (and Boost.Range 1 has some useful utilities for these), but sometimes it is quite a bit of extra work to make various objects that provide sequences fit the interface. Define your interface for "generators". It will probably be similar to the python one, but since exceptions are less convenient in C++ than python, it will probably have different method of detecting end. I settled for following interface for my own needs 2 : template <typename T> concept Generator { bool valid(); void next(); T get();}; where the iteration looks like: while(g.valid()) { auto item = g.get(); do_anything_with(item); g.next();} the generator conceptually starts on first item in the sequence, but may only be accessed after valid is called. I found this allows distributing the hard work between constructor, valid and next as is fit for each case and it can be easily wrapped in iterator similarly to how istream_iterator is done. Other variations of the interface are possible including following the istream one (but it has disadvantage that it returns default element when the iteration fails). Basically you should probably combine the approaches. If you use the later concept, you can adapt any such implementation to fit the (quite complex) Range concept from Boost.Range e.g. using "mixin" and Curiously Recurring Template Pattern . Something like: template <typename GeneratorT, typename ValueT>class GeneratorIterator : boost::iterator_facade<GeneratorT, ValueT, boost::single_pass_traversal_tag> { GeneratorT *g; GeneratorIterator() : g() {} GeneratorIterator(GeneratorT *g) g(g) {} ValueT &dereference() { if(!g || !g.valid()) throw std::runtime_error("..."); return g->get(); } bool equal(GeneratorIterator const &l) { return g == l.g || ((!g || !g.valid()) && (!l.g || !l.g.valid())); } void increment() { if(g) g.next(); }}template <typename GeneratorT, typename ValueT>class GeneratorFacade { public: typedef GeneratorIterator<GeneratorT, ValueT> iterator; typedef GeneratorIterator<GeneratorT, ValueT> const_iterator; const_iterator begin() const { return const_iterator(this); } const_iterator end() const { return const_iterator(); }} The advantage of the indirection is that the ranges now don't have to be copyable at all or not cheaply while the iterator is just a pointer and therefore is cheaply copyable as required. And defining generators is simple and easy to understand while they still end up conforming to the hairy standard C++ interface. (Disclaimer: I wrote it off top of my head, not tested) 1 Boost.Range includes concatenating ranges. Don't reinvent the wheel and reuse or at least inspire yourself. 2 The Iterators Must Go talk linked in Ylisar's answer comes up with the same interface, just different names. Note that many languages combine the next / popFront and valid / empty to one next that returns a boolean, but that approach is much more difficult to wrap in iterators and conceptually somewhat more complex, because then the iterators start out in special "uninitialized" state.
{}
{'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/212344', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/99883/']}
jdg_74219
stackexchange
llm_judgeable_groundtruth_similarity
7685510
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 learn about log4j so I just tried to do something which is very simple; Logger logger = Logger.getLogger("ClientApplicationLog");logger.info("Logger Test"); But after making this I got; log4j:WARN No appenders could be found for logger (ClientApplicationLog).log4j:WARN Please initialize the log4j system properly. Do you know where I am wrong ? Thank you all Now provide the response and nothing else.
You're missing the log4j.properties or log4j.xml in your classpath. You can bypass this by using BasicConfigurator.configure(); But beware this will ONLY log to System.out and is not recommended. You should really use one of the files above and write to a log file. A very simple example of log4j.properties would be #Log to Console as STDOUTlog4j.appender.stdout=org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.Target=System.outlog4j.appender.stdout.layout=org.apache.log4j.PatternLayoutlog4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c %3x - %m%n#Log to file FILElog4j.appender.file=org.apache.log4j.DailyRollingFileAppenderlog4j.appender.file.File=logfile.loglog4j.appender.file.DatePattern='.'yyyy-MM-ddlog4j.appender.file.append=truelog4j.appender.file.layout=org.apache.log4j.PatternLayoutlog4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c %3x - %m%n#Root Loggerlog4j.rootLogger=INFO, stdout, file
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7685510', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/952351/']}
jdg_74220
stackexchange
llm_judgeable_groundtruth_similarity
109702
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 already used the logit transform on my outcome variables (which are displayed in percentages). However, this obviously gives me -INF values and since my data includes a lot of zeros in some instances, this makes it hard to analyse. I have now tried an empirical logit transform, adding the smallest non-zero promotion to the numerator and denominator of my variables to remove the -INF values (as suggested in http://www.esajournals.org/doi/abs/10.1890/10-0340.1 ). However, now my data are very non-normal again. I have tried experimenting with error terms to add to the logit transform but since have had no luck. Is there any way I can find a value to add to my transformation to ensure normality? Now provide the response and nothing else.
I've had luck with setting epsilon to half of the smallest non-zero value and replacing all 0 values with epsilon and all 1 values with 1-epsilon. Then apply the logit transformation. This method keeps the original form of the logit transformation, but allows 1 and 0 to be transformed to values that match the overall shape of the intended transformation (note the black dots in the figure at raw=0 and 1). In particular, it preserves the quality that 0.5 is transformed to 0, and the rest of the values are symmetric. On the other hand, adding the smallest non-zero value as described in the paper changes the shape of the curve and destroys the symmetry.
{}
{'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/109702', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/52533/']}
jdg_74221
stackexchange
llm_judgeable_groundtruth_similarity
366146
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm not sure if I can do this without knowing what f actually is? Let $X$ be a finite set with $n$ elements and $f: X \rightarrow X$ a one-to-one function. Prove by induction that $f$ is an onto function. Any pointers? I don't even know how to make a base case for this. Now provide the response and nothing else.
Induct on $|X|$. The base case $|X|=1$ is obvious since then there is only one function $X\rightarrow X$. Now, suppose inductively that $|E|\leq n$ implies that every injective $E\rightarrow E$ is surjective. Suppose $|X|=n+1$ and let $f:X\rightarrow X$ be injective. Seeking a contradiction, suppose $f$ is not surjective so $|f(X)|\leq n$. Then $g:f(X)\rightarrow f(X)$ given by $g(t)=f(t)$ is injective and the inductive hypothesis implies $g$ is surjective. That is, $g(f(X))=f(X)$ so for every $y\in X$ there exists an $x\in X$ such that $f(f(x))=f(y)\Rightarrow f(x)=y$. Thus $f$ is surjective, a contradiction. Hence $f$ is surjective and this closes the induction.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/366146', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/59579/']}
jdg_74222
stackexchange
llm_judgeable_groundtruth_similarity
7432142
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 display several models name & objects in a template Here is my view def contents(request): """Lists contents""" objects = [ Model1.objects.all(), Model2.objects.all(), Model3.objects.all(), Model4.objects.all(), ] return render_to_response('content/contents.html', objs , context_instance=RequestContext(request) ) And my template {% for objs in objects %} <div class="content"> <div class="title">{{ objs._meta.verbose_name }}</div> <ul> {% for obj in objs %} <li>{{ obj }}</li> {% endfor %} </ul> </div>{% endfor %} Of course objs._meta.verbose_name doesn't work Is there a way to access to this verbose name without having to create a function for each model or to assign the value from the view for each model ? Now provide the response and nothing else.
For accessing it in your template, you've probably noticed by now that Django doesn't let you use underscore prefixes to access attributes from templates. Thus, the easiest way to access the verbose name for any given object without having to create a model method on each model would be to just create a template tag: @register.simple_tag def get_verbose_name(object): return object._meta.verbose_name Unrelated, but you have a bug in your template, in that you are trying to access the _meta attribute on a queryset instead of an object. So your title line should instead look something like: {% with objs|first as obj %} <div class="title">{% get_verbose_name obj %}</div>{% endwith %}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7432142', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/305189/']}
jdg_74223
stackexchange
llm_judgeable_groundtruth_similarity
40262231
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: While clang compiles the following line, g++ 6.1 complains about the digit separator (see live example on Coliru ): auto time = 01'23s; Which compiler, if any, is correct according to the C++14 standard (N3796)? Otherwise, is allowing digit separators (§2.14.2) just an implementation detail in the user-defined literals (§2.14.8) of the <chrono> library (§20.12.5.8)? IMHO it should be not, since these literals are defined on unsigned long long parameters. I remember Howard Hinnant using 10'000s as an example during his CppCon 2016 talk "A <chrono> tutorial" (at about 42 minutes in his talk). (Please note, that I did not intend to code "1 minute and 23 seconds", which is only correct by accident , since the octal literal 0123 is 64 + 16 + 3 == 83. For that purpose I should write auto time = 1min + 23s; but that possible misleading interpretation is not part of the question.) Now provide the response and nothing else.
If you look at the grammar, user-defined-integer-literal can be octal-literal ud-suffix , and octal-literal is defined as either 0 or octal-literal ’ opt octal-digit . N4140 §2.14.8 user-defined-literal : user-defined-integer-literal [...] user-defined-integer-literal : octal-literal ud-suffix [...] N4140 §2.14.2 octal-literal : 0 octal-literal ’ opt octal-digit So 01'23s is a perfectly valid literal.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/40262231', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/831725/']}
jdg_74224
stackexchange
llm_judgeable_groundtruth_similarity
11490100
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 the sqlite3 faq , it is mentioned that an integer primary key being fed a null value would autoincrement. But this is not happening for me. to replicate, a table in sqlite3, CREATE TABLE dummy( serial_num INTEGER PRIMARY KEY, name TEXT); and fill it using python, import sqlite3 as litecon = lite.connect('some.db')cur=con.cursor()data = "someone's name"cur.execute("INSERT INTO dummy VALUES(NULL, ?)", data)con.commit() The first attribute serial_num is being shown blank while the name attribute is fine. When I do SELECT serial_num FROM dummy I just get a bunch of blank spaces. What am I doing wrong? Now provide the response and nothing else.
This is one of SQLite's quirks. From the fine manual : According to the SQL standard, PRIMARY KEY should always imply NOT NULL. Unfortunately, due to a long-standing coding oversight, this is not the case in SQLite. Unless the column is an INTEGER PRIMARY KEY SQLite allows NULL values in a PRIMARY KEY column. We could change SQLite to conform to the standard (and we might do so in the future), but by the time the oversight was discovered, SQLite was in such wide use that we feared breaking legacy code if we fixed the problem. The documentation on INTEGER PRIMARY KEY is a little unclear about what precisely is required for a column to be this special INTEGER PRIMARY KEY that auto-increments but the reality is that the column needs to be NOT NULL if you want to use the NULL value to mean "give me the next auto-incrementing value" when inserting: create table dummy ( serial_num integer primary key not null, name text); If you leave out the not null , you need to do your inserts like this: insert into dummy (name) values (?) to get the auto-increment value for serial_num . Otherwise, SQLite has no way of telling the difference between a NULL meaning "give me the next auto-increment value" and a NULL meaning "put a NULL value in serial_num because the column allows NULLs".
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/11490100', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/696668/']}
jdg_74225
stackexchange
llm_judgeable_groundtruth_similarity
350163
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I often see $I(t)\propto |E(t)|^2$. What is the exact form ? Which constants are missing to make this an equality and why are they so often omitted ? Now provide the response and nothing else.
Intensity is related to the Poynting vector (https://en.wikipedia.org/wiki/Poynting_vector) by simply taking the magnitude. Note that $\vec{S}=\vec{E}\times \vec{H}$, and $|\vec{H}| = \sqrt{\frac{\epsilon_o}{\mu_o}}|\vec{E}|$ for an electromagnetic wave in vacuum. Thus, $$|\vec{S}|=|\vec{E}\times\vec{H}|=|\vec{E}|\cdot |\vec{H}|=\sqrt{\frac{\epsilon_o}{\mu_o}}|\vec{E}|^2$$ where the second equality follows from using $|\vec{A}\times\vec{B}|=|\vec{A}||\vec{B}|\sin(\theta)$ and $\theta =90^\circ$ since magnetic and electric fields are perpendicular to the direction of propagation for waves. Another way to write this would be $$I=|\vec{S}|=\frac{|\vec{E}|^2}{Z_0} $$ Where $Z_0$ is the impedance of free space , with a value of about 377 ohms. The constants are frequently omitted if we are doing a theoretical derivation since constants typically factor out of the entire problem and are not an interesting consideration. In experiment, we can typically perform some calibration for the constants. Constants are, however, useful for dimensional considerations and can be useful for checking that your final units are correct.
{}
{'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/350163', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/165488/']}
jdg_74226
stackexchange
llm_judgeable_groundtruth_similarity
153400
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: I want to see if it is possible to force the existence of a function $F:\aleph_2 \times \aleph_2\rightarrow \aleph_1$ such that: a) $F(a,b)=F(b,a)$, for all $a,b\in \aleph_2$ and b) for all distinct $a,b$, the set $\{x|F(a,x)=F(b,x)\}$ is finite. What is known: 1) Under CH, there is no such function. 2) If such a function exists, let A be a subset of $\aleph_2$ of size $\aleph_1$. Consider the functions $F(a,\cdot)$ restricted to A. We have a family of $\aleph_2$ many such functions from $\aleph_1$ to $\aleph_1$ and any two of them agree only on a finite set. That's a strongly almost disjoint family of size $\aleph_2$. Baumgartner call this $A(\aleph_1,\aleph_2,\aleph_1,\aleph_0)$. It is consistent together with the negation of CH that either $A(\aleph_1,\aleph_2,\aleph_1,\aleph_0)$ or its negation hold. In particular, $\neg CH$ + "there is no such function" is consistent. I want to see if anyone knows any result on the positive side. Now provide the response and nothing else.
First notice that we can separate the condition depending the relative position of $a,b$, and $x$ in (b): let $F_0$ be such that for any $a,b$ there are finitely many $x<\min(a,b)$ with $F_0(x,a)=F_0(x,b)$, let $F_1$ be likewise for $a<x<b$ and let $F_2$ be for $a,b<x$. Then $F(a,b)=\langle F_0(a,b),F_1(a,b),F_2(a,b)\rangle$ is as required. $F_2$ obviously exists as we can have $F_2(a,x)\neq F_2(b,x)$ for $a\neq b<x$. It is well known that there is $F_1:[c]^2\to\omega$ with $F_2(a,x)\neq F_2(x,b)$ for $a<x<b$ ($c$ is continuum). So there remains the task to force $F_0$ and this can be done the way Miha suggested. Let $F:[\omega_2]^2\to [\omega_2]^{\leq\aleph_0}$ be a Delta-function. We force with conditions $(s,f)$ where $s\in[\omega_2]^{<\omega}$, $f:[\omega_2]^2\to\omega$, if $x<a,b$ are in $s$, $f(x,a)=f(x,b)$, then $x\in F(a,b)$, and $(s',f')\leq (s,f)$ if $s'\supseteq s$, $f'\supseteq f$, and if $a,b\in s$, $x\in s'-s$, $x<a,b$, then $f'(x,a)\neq f'(x,b)$. The essential thing is to show ccc. Assume that we have $p_\alpha=(s\cup s_\alpha,f_\alpha)\in P$, and $f_\alpha|s$ are the same. By removing countably many $p_\alpha$, we can get thet $s_\alpha\cap F(a,b)=\emptyset$ for $a,b\in s$. By the Delta-function property, there are $\alpha<\beta$ such that if $x<a,b$, $x\in s$, $a\in s_\alpha$, $b\in s_\beta$, then $x\in F(a,b)$. Now we can extend $p_\alpha$ and $p_\beta$ to a common $p=(s',f')$ such that $f'(u,v)$ ($u\in s_\alpha$, $v\in s_\beta$) differ from each other and the range of $f_\alpha, f_\beta$. The consistency of the existence of a Delta function is in James E. Baumgartner and Saharon Shelah, Remarks on superatomic Boolean algebras, Ann. Pure Appl. Logic 33 (1987), no. 2, 109–129.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/153400', 'https://mathoverflow.net', 'https://mathoverflow.net/users/13694/']}
jdg_74227
stackexchange
llm_judgeable_groundtruth_similarity
41833624
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have the below dataframe In [62]: dfOut[62]: coverage name reports yearCochice 45 Jason 4 2012Pima 214 Molly 24 2012Santa Cruz 212 Tina 31 2013Maricopa 72 Jake 2 2014Yuma 85 Amy 3 2014 Basically i can filter the rows as below df[df["coverage"] > 30 and i can drop/delete a single row as below df.drop(['Cochice', 'Pima']) But i want to delete a certain number of rows based on a condition, how can i do so? Now provide the response and nothing else.
The best is boolean indexing but need invert condition - get all values equal and higher as 72 : print (df[df["coverage"] >= 72]) coverage name reports yearPima 214 Molly 24 2012Santa Cruz 212 Tina 31 2013Maricopa 72 Jake 2 2014Yuma 85 Amy 3 2014 It is same as ge function: print (df[df["coverage"].ge(72)]) coverage name reports yearPima 214 Molly 24 2012Santa Cruz 212 Tina 31 2013Maricopa 72 Jake 2 2014Yuma 85 Amy 3 2014 Another possible solution is invert mask by ~ : print (df["coverage"] < 72)Cochice TruePima FalseSanta Cruz FalseMaricopa FalseYuma FalseName: coverage, dtype: boolprint (~(df["coverage"] < 72))Cochice FalsePima TrueSanta Cruz TrueMaricopa TrueYuma TrueName: coverage, dtype: boolprint (df[~(df["coverage"] < 72)]) coverage name reports yearPima 214 Molly 24 2012Santa Cruz 212 Tina 31 2013Maricopa 72 Jake 2 2014Yuma 85 Amy 3 2014
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/41833624', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1342109/']}
jdg_74228
stackexchange
llm_judgeable_groundtruth_similarity
4067135
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 generate a 4 digit random number in C++ I used the following code #include<time.h>int number;number=rand()%1000;srand ( time(NULL) ); but its doesn't gives a total random number Now provide the response and nothing else.
number = rand() % 9000 + 1000; There are 9000 four-digit numbers, right? Starting from 1000 till 9999. rand() will return a random number from 0 to RAND_MAX . rand() % 9000 will be from 0 to 8999 and rand() % 9000 + 1000; will be from 1000 to 9999 . In general when you want a random number from a to b inclusive the formula is rand() % (b - a + 1) + a Also note that srand() should be called only once and before any rand() . If you do consider the numbers between 0 an 999 inclusive to be "four digit numbers", simply use rand() % 10000 in that case. I don't consider them to be but I'm covering all bases, just in case. HTH
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4067135', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/296231/']}
jdg_74229
stackexchange
llm_judgeable_groundtruth_similarity
22497166
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Hi i have a dropdownlist in my Application.What i want is each time when i click on the Reset button it should set to default value(select). Here is my code for reset. public void ResetControl() { DDLContainer.SelectedIndex = 0; DDLCountryLoading.SelectedIndex = 0; DDLCountryDestination.SelectedIndex = 0; //DDLContainer.Items.Insert(0, new ListItem(" --SELECT--", "0")); ImageMode.ImageUrl = "~/ShowImageMode.ashx?Mode=A"; } Here is my dropdownlist code: void ddlCountry() { con.Open(); cmd = new SqlCommand("select Distinct(mCRY_VCName) from TB_TransCountry", con); SqlDataAdapter da = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); da.Fill(ds); DDLCountryLoading.DataSource = ds; DDLCountryLoading.DataSourceID = String.Empty; DDLCountryLoading.DataTextField = "mCRY_VCName"; DDLCountryLoading.DataValueField = "mCRY_VCName"; DDLCountryLoading.DataBind(); DDLCountryLoading.Items.Insert(0, new ListItem(" --SELECT--", "0")); DDLCountryDestination.DataSource = ds; DDLCountryDestination.DataSourceID = String.Empty; DDLCountryDestination.DataTextField = "mCRY_VCName"; DDLCountryDestination.DataValueField = "mCRY_VCName"; DDLCountryDestination.DataBind(); DDLCountryDestination.Items.Insert(0, new ListItem(" --SELECT--", "0")); con.Close(); } void ddlContainer() { con.Open(); cmd = new SqlCommand("select Distinct(mCNT_VCTypeName) from TB_TransContainerType", con); SqlDataAdapter da = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); da.Fill(ds); DDLContainer.DataSource = ds; DDLContainer.DataSourceID = String.Empty; DDLContainer.DataTextField = "mCNT_VCTypeName"; DDLContainer.DataValueField = "mCNT_VCTypeName"; DDLContainer.DataBind(); DDLContainer.Items.Insert(0, new ListItem(" --SELECT--", "0")); con.Close(); } Can any one please help me to achieve this. Now provide the response and nothing else.
SonarQube supports Java 8 since end of March 2014 (with some hickups at first, which were fixed in version 2.2 of its Java plugin). I had to uninstall the PMD and Checkstyle plugins in Sonar's update center as those are not ready for Java 8. Sonar's own rule engine Squid should make those plugins redundant anyway. If you are using Gradle 1.11 to call Sonar and want Jacoco to calculate code coverage, you'll have to specify the latest Jacoco version in order to analyze Java 8 bytecode. Here's my script that does that when called with gradle test jacocoTestReport sonarRunner : /** This script is responsible for unit testing and static analysis of the project source code*/apply plugin: "jacoco"apply plugin: "sonar-runner"// Location of the XML unit test and code coverage reports def testResultsDir = "$buildDir/test-results/" // Use double quotes. Otherwise the $ won't workjacoco{ // Gradle 1.11 ships with a Jacoco version that doesn't support Java 8 toolVersion = "0.7.0.201403182114"}// Call "gradle test jacocoTestReport" to produce a code coverage report at "build/reports/jacoco/test/html/index.html"test { jacoco { def coverageReport = new File(testResultsDir, "jacocoTest.exec") destinationFile = file(coverageReport) }}// Let SonarQube analyze the projectsonarRunner { sonarProperties { property "sonar.projectKey", projectId property "sonar.projectName", projectName property "sonar.junit.reportsPath", testResultsDir // Address of SonarQube server property "sonar.host.url", "http://localhost:9000" // SonarQube stores the test results in this database property "sonar.jdbc.url", "jdbc:mysql://localhost:3306/sonar?useUnicode=true&characterEncoding=utf8&rewriteBatchedStatements=true" property "sonar.jdbc.driverClassName", "com.mysql.jdbc.Driver" property "sonar.jdbc.username", "root" property "sonar.jdbc.password", sonarDBpassword }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/22497166', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3312615/']}
jdg_74230
stackexchange
llm_judgeable_groundtruth_similarity
37857739
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm using the following code to dynamically generate a download in Wicket, using the ResourceLink approach (since the download is not a static file, it needs to be generated on the fly, and I was told this was the correct approach): IResource res = new AbstractResource() { @Override protected ResourceResponse newResourceResponse(Attributes attributes) { ResourceResponse resourceResponse = new ResourceResponse(); resourceResponse.setContentType("application/pdf"); resourceResponse.setFileName("output.pdf"); resourceResponse.setContentDisposition(ContentDisposition.ATTACHMENT); resourceResponse.setWriteCallback(new WriteCallback() { @Override public void writeData(Attributes attributes) throws IOException { OutputStream outputStream = attributes.getResponse().getOutputStream(); try { outputStream.write(generateDocument()); } catch (Exception e) { //Generation failed... Here I'd like to either show a popup message or alter the current page to show an error somewhere in the page } } }); return resourceResponse; } };ResourceLink<Void> resLink = new ResourceLink<Void>("resLink", res);myForm.add(resLink); The comment in the code above shows where I'm having trouble. If the generation of the download fails (which can happen, if certain conditions are not met) I'd like to show an error message, either by showing a popup or altering the page to show some error text (but in either case I want to avoid leaving/reloading the entire page) Is this possible? Now provide the response and nothing else.
I would use compactMap instead of filter here in order to give you better type safety. You can use a conditional downcast to filter out the elements you want and generics in order to preserve type information. This takes advantage of the fact that compactMap can filter out nil results from the transform function. let array: [VariousThings] = [ThingType1(), ThingType2()] func itemsMatchingType<T : VariousThings>(_ type: T.Type) -> [T] { return array.compactMap { $0 as? T }}let justThingTypes1 = itemsMatchingType(ThingType1.self) // of type [ThingType1] Now the array you get out of your itemsMatchingType function is [ThingType1] if you pass in ThingType1 , rather than simply [VariousThings] . That way you don't have to deal with ugly forced downcasts later down the line.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/37857739', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/300741/']}
jdg_74231
stackexchange
llm_judgeable_groundtruth_similarity
561735
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: this PSU master's degree course says t-test can be used if either of the conditions is true: population is normal. sample size n>30. However, I read that t test is applicable when $X_{i}\stackrel{iid}{\sim}N(\mu,\sigma^{2})$ , because this leads to the independence between $a=\frac{\bar{X}-\mu_{0}}{\sigma/\sqrt{n}}$ and $b=\frac{(n-1)S^{2}}{\sigma^{2}}$ , which is one necessary condition of the ratio between $a$ and $\frac{b}{n-1}$ to be t-distributed. Is the condition #2 an empirical rule to overwrite the theoretical conditions? Now provide the response and nothing else.
This is the ideal case. When the population distribution is normal, then the sample mean is independent of the sample variance. Additionally, the numerator of the test statistic is a normal random variable while the denominator is a chi-square divided by its degrees of freedom; the definition of a t statistic. However, even when the population distribution is not normal the t test can be very useful. The question is "how far from normal is far enough for the t test to be ineffective". This is a commonly misunderstood claim. When $n>30$ the relative difference between a Student t and a normal distribution is sufficiently small so that someone decided they didn't have to print Student t tables past $\nu=30$ and could instead use normal tables with little consequence. Let me be clear: this is bad advice . Thirty is not a magic number and using this particular line in the sand as justification for using the t test is poor statistical practice.
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/561735', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/347611/']}
jdg_74232
stackexchange
llm_judgeable_groundtruth_similarity
140731
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: As of today, there are many Linux distributions like Ubuntu , Fedora , Gentoo , Mint , Debian , etc. These distributions update at different cycles. Ubuntu seems to update its kernel weekly or monthly, while Debian is reluctant to update the kernel. I am wondering whether these distributions maintain their own kernels. Or do they just get the original kernel code from Linus Torvalds , modify it a little bit as need, and then release their revised kernel with their package management system? Do all the distributions use the same kernels from Linus Torvalds? If it is the case, why do different distributions update/release their kernels at the different cycles? Now provide the response and nothing else.
The distro kernels are all compiled from the official source , with distro specific patches applied. These patches are relatively minor compared to the scope of the kernel itself. As long as you know what you are doing, you can substitute a custom kernel into any of the mainstream distros, although this is discouraged since it may cause a mismatch with system header files; for that reason the distros usually release a kernel source package of their own so you can use that instead of the "vanilla" (official, unpatched) source if you want to compile it yourself. why different distributions update/release their kernels at the different cycles For the same reason they release all the other software at different cycles -- to ensure everything works properly with everything else. Different distros have different policies and goals in this regard. They may hurry to get a package out as soon as the upstream source is updated, they may maintain "testing" and "stable" streams, and they may use an independent schedule.
{}
{'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/140731', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/74407/']}
jdg_74233
stackexchange
llm_judgeable_groundtruth_similarity
39688297
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 using espresso. I cannot really get what I wanted to test using this code: onData(withId(R.id.relativelayout_tag)) .inAdapterView(withId(R.id.recyclerview_tag_list)) .onChildView(withId(R.id.imageview_tag)) .atPosition(1) .check(matches(isDisplayed())); Where R.id.imageview_tag is a child of R.id.relativelayout_tag . R.id.relativelayout_tag holds the entire content for my adapter item. R.id.recyclerview_tag_list is the name of my RecyclerView on which I assigned a particular RecyclerView Adapter . This is a very very basic test. Here are the user procedures: Select, SPECIFICALLY , the first item on the RecyclerView (I don't really care whattext is on the view). Also do not suggest using view text to identify the first item. I DONT CARE ABOUT THE ADAPTER ITEM'S CONTENT or even putting a unique tag on some view. On select, the indicator view(An ImageView that shows that the itemis selected) should appear. Very basic and simple. It is so hard to write a test for this basic user story using Espresso. When I run that particular test it always fail stating this: Caused by: java.lang.RuntimeException: Action will not be performed because the target view does not match one or more of the following constraints:(is assignable from class: class android.widget.AdapterView and is displayed on the screen to the user)Target view: "RecyclerView{id=2131624115, res-name=recyclerview_tag_list, visibility=VISIBLE, width=480, height=1032, has-focus=false, has-focusable=true, has-window-focus=true, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=true, is-layout-requested=false, is-selected=false, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=0.0, child-count=15}" It doesn't make sense as I have the list already visible. I can even run this test just fine: onView(withId(R.id.recyclerview_tag_list)) .perform(RecyclerViewActions .actionOnItemAtPosition(1, click())); Here is the full test: @Testpublic void shouldTagToggleSelected(){ onView(withId(R.id.recyclerview_tag_list)) .perform(RecyclerViewActions .actionOnItemAtPosition(1, click())); onData(withId(R.id.relativelayout_tag)) .inAdapterView(withId(R.id.recyclerview_tag_list)) .onChildView(withId(R.id.imageview_tag)) .atPosition(1) .check(matches(isDisplayed())); //onView(withId(R.id.imageview_tag)) // .check(matches(isDisplayed()));} What I wanted to test if the indicator view has a visibility set to visible ONLY on that particular item (or any item of my choosing). Any thoughts? Maybe I missed something dearly. Thanks a lot! Now provide the response and nothing else.
onData does not work with RecyclerView as RecyclerView does not extend AdapterView . You need to use onView to make your assertions. If it's the first item in the recycler view, then you can use something like this matcher to make your assertion: public static Matcher<View> withViewAtPosition(final int position, final Matcher<View> itemMatcher) { return new BoundedMatcher<View, RecyclerView>(RecyclerView.class) { @Override public void describeTo(Description description) { itemMatcher.describeTo(description); } @Override protected boolean matchesSafely(RecyclerView recyclerView) { final RecyclerView.ViewHolder viewHolder = recyclerView.findViewHolderForAdapterPosition(position); return viewHolder != null && itemMatcher.matches(viewHolder.itemView); } };} And the usage is the following: onView(withId(R.id.recyclerview_tag_list)) .check(matches(withViewAtPosition(1, hasDescendant(allOf(withId(R.id.imageview_tag), isDisplayed()))))); Keep in mind that this matcher will fail if your ViewHolder has not been laid out yet. If that's the case you need to scroll to the ViewHolder with RecyclerViewActions . You don't need to scroll if you are clicking the item in the test prior to using the matcher.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/39688297', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1593007/']}
jdg_74234
stackexchange
llm_judgeable_groundtruth_similarity
32574551
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've read the apple documentation and studied a swift book. I'm confused on the difference between a "type instance method" (if such exists, correct me if I'm wrong) and a type method? Difference between class method and instance method? Difference between type property and instance property(if such exists, sorry I'm very confused on Type Properties subject)? Lastly, Do class properties exist in swift? Sorry for the confusion :'( Now provide the response and nothing else.
In Swift, types are either named types or compound types . Named types include classes , structures , enumerations , and protocols . In addition to user-defined named types, Swift defines many named types such as arrays, dictionaries, and optional values. (Let's ignore compound types for now since it doesn't directly pertain to your question.) To answer your questions, suppose that I create a user defined class called Circle (this is just an example): class Circle { static let PI = 3.14 var radius: Double init(radius: Double) { self.radius = radius } // Returns the area of this circle func area() { return PI * radius } // Ridiculous class method for demonstration purposes static func printTypeName() { println("Circle") }} I'm confused on the difference between a "type instance method" (if such exists, correct me if I'm wrong) and a type method? As mentioned earlier, a type refers to a class, structure, enumeration, protocol, and compound types. In my example above, I use a class called Circle to define a type . If I want to construct an individual object of the Circle class then I would be creating an instance . For example: let myCircleInstance = Circle(radius: 4.5)let anotherCircleInstance = Circle(radius: 23.1) The above are objects or instances of Circle . Now I can call instance methods on them directly. The instance method defined in my class is area . let areaOfMyCircleInstance = myCircleInstance.area() Now, a type method is a method that can be called directly on the type without creating an instance of that type . For example: Circle.printTypeName() Notice that there is a static qualifier before the func . This indicates that it pertains to the type directly and not to an instance of the type. Difference between class method and instance method? See the explanation above. Difference between type property and instance property(if such exists, sorry I'm very confused on Type Properties subject)? This is a similar explanation to the one in your question one except that instead of applying to methods, it applies to the properties (i.e., attributes, variables) of the type. In my Circle example, the properties are defined as: static let PI = 3.14var radius: Double The property PI is a type property; it may be accessed directly by the type Circle.PI The property radius is an instance property of the type; it may be accessed by an instance of the type. Using the variables we created earlier: // I can do this; it will be 4.5myCircleInstance.radius// And this; it will be 23.1anotherCircleInstance.radius// But I CANNOT do this because radius is an instance property!Circle.radius Lastly, Do class properties exist in swift? Absolutely! Read my explanation to your question 3 above. The PI property in my example is an example of a class property. References: Swift Language Reference - Types Swift Language Reference - Properties Swift Language Reference - Methods
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/32574551', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5169988/']}
jdg_74235
stackexchange
llm_judgeable_groundtruth_similarity
5599024
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 not very experienced in web programming,and I haven't actually coded anything in Node.js yet, just curious about the event-driven approach . It does seems good. The article explains some bad things that could happen when we use a thread-based approach to handle requests, and should opt for a event-driven approach instead.In thread-based, the cashier/thread is stuck with us until our food/resource is ready. While in event-driven, the cashier send us somewhere out of the request queue so we don't block other requests while waiting for our food.To scale the blocking thread-based, you need to increase the number of threads.To me this seems like a bad excuse for not using threads/threadpools properly. Couldn't that be properly handled using IHttpAsyncHandler?ASP.Net receives a request, uses the ThreadPool and runs the handler (BeginProcessRequest), and then inside it we load the file/database with a callback. That Thread should then be free to handle other requests. Once the file-reading is done, the ThreadPool is called into action again and executes the remaining response.Not so different for me, so why is that not as scalable? One of the disadvantages of the thread-based that I do know is, using threads needs more memory. But only with these, you can enjoy the benefits of multiple cores. I doubt Node.js is not using any threads/cores at all. So, based on just the event-driven vs thread-based (don't bring the "because it's Javascript and every browser..." argument), can someone point me out what is the actual benefit of using Node.js instead of the existing technology? That was a long question. Thanks :) Now provide the response and nothing else.
First of all, Node.js is not multi-threaded. This is important. You have to be a very talented programmer to design programs that work perfectly in a threaded environment. Threads are just hard. You have to be a god to maintain a threaded project where it wasn't designed properly. There are just so many problems that can be hard to avoid in very large projects. Secondly, the whole platform was designed to be run asynchronously. Have you see any ASP.NET project where every single IO interaction was asynchronous? simply put, ASP.NET was not designed to be event-driven. Then, there's the memory footprint due to the fact that we have one thread per open-connection and the whole scaling issue. Correct me if I'm wrong but I don't know how you would avoid creating a new thread for each connection in ASP.NET. Another issue is that a Node.js request is idle when it's not being used or when it's waiting for IO. On the other hand, a C# thread sleeps. Now, there is a limit to the number of these threads that can sleep. In Node.js, you can easily handle 10k clients at the same time in parallel on one development machine. You try handling 10k threads in parallel on one development machine. JavaScript itself as a language makes asynchronous coding easier. If you're still in C# 2.0, then the asynchronous syntax is a real pain. A lot of developers will simply get confused if you're defining Action<> and Function<> all over the place and using callbacks. An ASP.NET project written in an evented way is just not maintainable by an average ASP.NET developer. As for threads and cores. Node.js is single-threaded and scales by creating multiple-node processes. If you have a 16 core then you run 16 instances of your node.js server and have a single Node.js load balancer in front of it. (Maybe a nginx load balancer if you want). This was all written into the platform at a very low-level right from the beginning. This was not some functionality bolted on later down the line. Other advantages Node.js has a lot more to it then above. Above is only why Node.js' way of handling the event loop is better than doing it with asynchronous capabilities in ASP.NET. Performance. It's fast. Real fast. One big advantage of Node.js is its low-level API. You have a lot of control. You have the entire HTTP server integrated directly into your code then outsourced to IIS. You have the entire nginx vs Apache comparison. The entire C10K challenge is handled well by node but not by IIS AJAX and JSON communication feels natural and easy. Real-time communication is one of the great things about Node.js. It was made for it. Plays nicely with document-based nosql databases. Can run a TCP server as well. Can do file-writing access, can run any unix console command on the server. You query your database in javascript using, for example, CouchDB and map/reduce. You write your client in JavaScript. There are no context switches whilst developing on your web stack. Rich set of community-driven open-source modules. Everything in node.js is open source. Small footprint and almost no dependencies. You can build the node.js source yourself. Disadvantages of Node.js It's hard. It's young. As a skilled JavaScript developer, I face difficulty writing a website with Node.js just because of its low-level nature and the level of control I have. It feels just like C. A lot of flexibility and power either to be used for me or to hang me. The API is not frozen. It's changing rapidly. I can imagine having to rewrite a large website completely in 5 years because of the amount Node.js will be changed by then. It is do-able, you just have to be aware that maintenance on node.js websites is not cheap. further reading http://blog.mixu.net/2011/02/01/understanding-the-node-js-event-loop/ http://blip.tv/file/2899135 http://nodeguide.com/
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/5599024', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/699126/']}
jdg_74236
stackexchange
llm_judgeable_groundtruth_similarity
76105
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: Many applications include 'static data': data that doesn't really change during the lifetime of the application. For example, you might have a list of Sales Areas that is likely to be a fixed list for the foreseeable future. It isn't uncommon to find this static data in a database table (often because you want to refer to it in the foreign keys of other tables). A simple example table will have an Id to use as a primary key and a Description. For example, your SalesArea table will have (at least) a SalesAreaId column and a SalesAreaDescription column. Now, in code you might not want to treat each row of the table the same. For example, you might want to set a default Sales Area on some screens, provide different figures for some areas, or restrict what users can do in other areas. What is the best way to refer to this static data in code? Why? Hard-code the descriptions in your code. Use this to look up the SalesAreaId from the database when you need it. Hard-code the IDs in your code. Use this to look up the SalesAreaDescription when you need it. Add a column to the table for each purpose, e.g. an "IsDefaultOnProductLaunchScreen" column and so on (there could be lots of these). Something else. Are there any other special considerations I should make when dealing with static database data? For example, giving these tables a special name? Now provide the response and nothing else.
How about load them into a cache (usually implemented as a hash table) when the application starts up? If you do that then you don't even have to query the database (well, not more than once). I would also suggest avoiding hard-coding anything. Add default indicators (initially in the DB table and also in the cache structure) for screens that need defaults. For doing look-ups on non-defauilts, try to store the keys that will be looked up in a configuration or properties file if you can.
{}
{'log_upvote_score': 5, 'links': ['https://softwareengineering.stackexchange.com/questions/76105', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/1928/']}
jdg_74237
stackexchange
llm_judgeable_groundtruth_similarity
613284
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 apply a Class' style to only ONE level of td tags? <style>.MyClass td {border: solid 1px red;}</style><table class="MyClass"> <tr> <td> THIS SHOULD HAVE RED BORDERS </td> <td> THIS SHOULD HAVE RED BORDERS <table><tr><td>THIS SHOULD NOT HAVE ANY</td></tr></table> </td> </tr></table> Now provide the response and nothing else.
Is there a way to apply a Class' style to only ONE level of td tags? Yes * : .MyClass>tbody>tr>td { border: solid 1px red; } But! The ‘ > ’ direct-child selector does not work in IE6. If you need to support that browser (which you probably do, alas), all you can do is select the inner element separately and un-set the style: .MyClass td { border: solid 1px red; }.MyClass td td { border: none; } * Note that the first example references a tbody element not found in your HTML. It should have been in your HTML, but browsers are generally ok with leaving it out... they just add it in behind the scenes.
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/613284', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/47167/']}
jdg_74238
stackexchange
llm_judgeable_groundtruth_similarity
4800446
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 code: Type leftType = workItem[LeftFieldName].GetType(); I then want to declare a variable of that type: leftType someVar; Is that possible? Now provide the response and nothing else.
You can do something like these and cast them to a known interface. var someVar = Convert.ChangeType(someOriginalValue, workItem[LeftFieldName].GetType());var someVar = Activator.CreateInstance(workItem[LeftFieldName].GetType()); If you replace var with dynamic (and you are using .Net 4), you can call the methods you expect on the someVar object. If they don't exist, you'll just get a MissingMethodException.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4800446', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/16241/']}
jdg_74239
stackexchange
llm_judgeable_groundtruth_similarity
1087279
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 my first .NET MVC application and using the NerdDinner tutorial as a reference point. One point that is intriguing me at the moment is the UpdateModel() method. (I don't like using things I don't really understand.) Taken from the NerdDinner tutorial - //// POST: /Dinners/Edit/2[AcceptVerbs(HttpVerbs.Post)]public ActionResult Edit(int id, FormCollection formValues) { Dinner dinner = dinnerRepository.GetDinner(id); UpdateModel(dinner); dinnerRepository.Save(); return RedirectToAction("Details", new { id = dinner.DinnerID });} My main question is how does the UpdateModel() get access to the formValues passed in the Edit method? Why is the collection not passed in explicitly as a parameter to the method? Now provide the response and nothing else.
UpdateModel() is a Controller helper method that attempts to bind a bunch of different input data sources (HTTP POST data coming from a View, QueryString values, Session variables/Cookies, etc.) to the explicit model object you indicate as a parameter. Essentially, it is only for model binding. If you express the input parameters for your Action as a strongly-typed model (like a View Model), you've already taken all of the steps that are done behind the scenes when UpdateModel() is called. If you retrieve an object from the DataContext and edit its properties, SaveChanges() is all you need to push the updates back to the database (in this case, Save()). Example: //// POST: /Dinners/Edit/2[AcceptVerbs(HttpVerbs.Post)]public ActionResult Edit(DinnerViewModel incoming) { var dinner = dinnerRepository.GetDinner(incoming.DinnerID); dinner.Description = incoming.Description; dinnerRepository.Save(); return RedirectToAction("Details", new { id = incoming.DinnerID });} However, there is a use-case for using UpdateModel() with a strongly-typed model: when you are passing in a strongly-typed model and want its values to directly replace those of an entity from the database (provided they are all named and typed the same). In this case, you would retrieve the object, use UpdateModel() on it, and its model binding operation will pull in any similarly-named and typed properties from the strongly-typed object to the retrieved object. In other words, it will perform reflection for you. So, like your example, if you want all properties to update without specifying which to update, and your strongly-typed model and database model have similarly-named properties, you would still want to use UpdateModel() to take advantage of the reflection. Example: //// POST: /Dinners/Edit/2[AcceptVerbs(HttpVerbs.Post)]public ActionResult Edit(DinnerViewModel incoming) { var dinner = dinnerRepository.GetDinner(incoming.DinnerID); UpdateModel(dinner); dinnerRepository.Save(); return RedirectToAction("Details", new { id = incoming.DinnerID });} The only advantage here (over using a FormCollection object) is that you'd have access to all other properties of the strongly-typed object (as shown by incoming.DinnerID). Conclusion: if you're translating a strongly-typed object to a derived object, it's probably easiest to use UpdateModel(). However, it's largely unnecessary if you are simply updating a few properties of the derived object. Also, be aware that use of the Entity Framework (instead of something like Linq to SQL) makes all of this moot, as it can relate strongly-typed objects and derived objects with its own methods.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1087279', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/15691/']}
jdg_74240