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
1141848
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 the following regex to match a URL: $search = "/([\S]+\.(MUSEUM|TRAVEL|AERO|ARPA|ASIA|COOP|INFO|NAME|BIZ|CAT|COM|INT|JOBS|NET|ORG|PRO|TEL|AC|AD|AE|AF|AG|AI|AL|AM|AN|AO|AQ|AR|AS|AT|AU|au|AW|AX|AZ|BA|BB|BD|BE|BF|BG|BH|BI|BJ|BL|BM|BN|BO|BR|BS|BT|BV|BW|BY|BZ|CA|CC|CD|CF|CG|CH|CI|CK|CL|CM|CN|CO|CR|CU|CV|CX|CY|CZ|DE|DJ|DK|DM|DO|DZ|EC|EDU|EE|EG|EH|ER|ES|ET|EU|FI|FJ|FK|FM|FO|FR|GA|GB|GD|GE|GF|GG|GH|GI|GL|GM|GN|GOV|GP|GQ|GR|GS|GT|GU|GW|GY|HK|HM|HN|HR|HT|HU|ID|IE|IL|IM|IN|IO|IQ|IR|IS|IT|JE|JM|JO|JP|KE|KG|KH|KI|KM|KN|KP|KR|KW|KY|KZ|LA|LB|LC|LI|LK|LR|LS|LT|LU|LV|LY|MA|MC|MD|ME|MF|MG|MH|MIL|MK|ML|MM|MN|MO|MOBI|MP|MQ|MR|MS|MT|MU|MV|MW|MX|MY|MZ|NA|NC|NE|NF|NG|NI|NL|NO|NP|NR|NU|NZ|OM|PA|PE|PF|PG|PH|PK|PL|PM|PN|PR|PS|PT|PW|PY|QA|RE|RO|RS|RU|RW|SA|SB|SC|SD|SE|SG|SH|SI|SJ|SK|SL|SM|SN|SO|SR|ST|SU|SV|SY|SZ|TC|TD|TF|TG|TH|TJ|TK|TL|TM|TN|TO|R|H|TP|TR|TT|TV|TW|TZ|UA|UG|UK|UM|US|UY|UZ|VA|VC|VE|VG|VI|VN|VU|WF|WS|YE|YT|YU|ZA|ZM|ZW)([\S]*))/i"; But its a bit screwed up because it also matches "abc.php" which I dont want. and something like abc...test. I want it to match abc.com though. and www.abc.com as well as http://abc.com . It just needs a slight tweak at the end but I am not sure what. (there should be a slash after the any domain name which it is not checking for right now and it is only checking \S) thank you for your time. Now provide the response and nothing else.
$search = "#^((?# the scheme: )(?:https?://)(?# second level domains and beyond: )(?:[\S]+\.)+((?# top level domains: )MUSEUM|TRAVEL|AERO|ARPA|ASIA|EDU|GOV|MIL|MOBI|(?# )COOP|INFO|NAME|BIZ|CAT|COM|INT|JOBS|NET|ORG|PRO|TEL|(?# )A[CDEFGILMNOQRSTUWXZ]|B[ABDEFGHIJLMNORSTVWYZ]|(?# )C[ACDFGHIKLMNORUVXYZ]|D[EJKMOZ]|(?# )E[CEGHRSTU]|F[IJKMOR]|G[ABDEFGHILMNPQRSTUWY]|(?# )H[KMNRTU]|I[DELMNOQRST]|J[EMOP]|(?# )K[EGHIMNPRWYZ]|L[ABCIKRSTUVY]|M[ACDEFGHKLMNOPQRSTUVWXYZ]|(?# )N[ACEFGILOPRUZ]|OM|P[AEFGHKLMNRSTWY]|QA|R[EOSUW]|(?# )S[ABCDEGHIJKLMNORTUVYZ]|T[CDFGHJKLMNOPRTVWZ]|(?# )U[AGKMSYZ]|V[ACEGINU]|W[FS]|Y[ETU]|Z[AMW])(?# the path, can be there or not: )(/[a-z0-9\._/~%\-\+&\#\?!=\(\)@]*)?)$#i"; Just cleaned up a bit. This will match only HTTP(s) addresses, and, as long as you copied all top level domains correctly from IANA, only those standardized (it will not match http://localhost ) and with the http:// declared. Finally you should end with the path part, that will always start with a /, if it is there. However, I'd suggest to follow Cerebrus: If you're not sure about this, learn regexps in a more gentle way and use proven patterns for complicated tasks. Cheers, By the way: Your regexp will also match something.r and something.h (between |TO| and |TR| in your example). I left them out in my version, as I guess it was a typo. On re-reading the question: Change )(?:https?://)(?# to )(?:https?://)?(?# (there is a ? extra) to match 'URLs' without the scheme.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1141848', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/426996/']}
jdg_84941
stackexchange
llm_judgeable_groundtruth_similarity
17736215
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 making an application and I want to make it installable on the user's desktops using chrome URL shortcut. Therefore, is there a universal path to the chrome.exe that can launch my app on all Windows versions ( XP, Seven and vista ) Now provide the response and nothing else.
Chrome installs by default to the User's AppData Local folder: XP:C:\Documents and Settings\UserName\Local Settings\Application Data\Google\ChromeVista:C:\Users\UserName\AppDataLocal\Google\ChromeWindows 7:C:\Program Files (x86)\Google\ApplicationWin 7/8/10/11, (either):- C:\Program Files (x86)\Google\Chrome\Application- C:\Program Files\Google\Chrome\Application Best bet is to use some OS detection code, then use an environment variable to detect the User's AppData folder (i.e. %LOCALAPPDATA% ) or the ProgramFiles folder, and then append the difference in OS's to the end of the variable.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17736215', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2061456/']}
jdg_84942
stackexchange
llm_judgeable_groundtruth_similarity
43343231
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 use enhanced REP MOVSB (ERMSB) to get a high bandwidth for a custom memcpy . ERMSB was introduced with the Ivy Bridge microarchitecture. See the section "Enhanced REP MOVSB and STOSB operation (ERMSB)" in the Intel optimization manual if you don't know what ERMSB is. The only way I know to do this directly is with inline assembly. I got the following function from https://groups.google.com/forum/#!topic/gnu.gcc.help/-Bmlm_EG_fE static inline void *__movsb(void *d, const void *s, size_t n) { asm volatile ("rep movsb" : "=D" (d), "=S" (s), "=c" (n) : "0" (d), "1" (s), "2" (n) : "memory"); return d;} When I use this however, the bandwidth is much less than with memcpy . __movsb gets 15 GB/s and memcpy get 26 GB/s with my i7-6700HQ (Skylake) system, Ubuntu 16.10, DDR4@2400 MHz dual channel 32 GB, GCC 6.2. Why is the bandwidth so much lower with REP MOVSB ? What can I do to improve it? Here is the code I used to test this. //gcc -O3 -march=native -fopenmp foo.c#include <stdlib.h>#include <string.h>#include <stdio.h>#include <stddef.h>#include <omp.h>#include <x86intrin.h>static inline void *__movsb(void *d, const void *s, size_t n) { asm volatile ("rep movsb" : "=D" (d), "=S" (s), "=c" (n) : "0" (d), "1" (s), "2" (n) : "memory"); return d;}int main(void) { int n = 1<<30; //char *a = malloc(n), *b = malloc(n); char *a = _mm_malloc(n,4096), *b = _mm_malloc(n,4096); memset(a,2,n), memset(b,1,n); __movsb(b,a,n); printf("%d\n", memcmp(b,a,n)); double dtime; dtime = -omp_get_wtime(); for(int i=0; i<10; i++) __movsb(b,a,n); dtime += omp_get_wtime(); printf("dtime %f, %.2f GB/s\n", dtime, 2.0*10*1E-9*n/dtime); dtime = -omp_get_wtime(); for(int i=0; i<10; i++) memcpy(b,a,n); dtime += omp_get_wtime(); printf("dtime %f, %.2f GB/s\n", dtime, 2.0*10*1E-9*n/dtime); } The reason I am interested in rep movsb is based off these comments Note that on Ivybridge and Haswell, with buffers to large to fit in MLC you can beat movntdqa using rep movsb; movntdqa incurs a RFO into LLC, rep movsb does not...rep movsb is significantly faster than movntdqa when streaming to memory on Ivybridge and Haswell (but be aware that pre-Ivybridge it is slow!) What's missing/sub-optimal in this memcpy implementation? Here are my results on the same system from tinymembnech . C copy backwards : 7910.6 MB/s (1.4%) C copy backwards (32 byte blocks) : 7696.6 MB/s (0.9%) C copy backwards (64 byte blocks) : 7679.5 MB/s (0.7%) C copy : 8811.0 MB/s (1.2%) C copy prefetched (32 bytes step) : 9328.4 MB/s (0.5%) C copy prefetched (64 bytes step) : 9355.1 MB/s (0.6%) C 2-pass copy : 6474.3 MB/s (1.3%) C 2-pass copy prefetched (32 bytes step) : 7072.9 MB/s (1.2%) C 2-pass copy prefetched (64 bytes step) : 7065.2 MB/s (0.8%) C fill : 14426.0 MB/s (1.5%) C fill (shuffle within 16 byte blocks) : 14198.0 MB/s (1.1%) C fill (shuffle within 32 byte blocks) : 14422.0 MB/s (1.7%) C fill (shuffle within 64 byte blocks) : 14178.3 MB/s (1.0%) --- standard memcpy : 12784.4 MB/s (1.9%) standard memset : 30630.3 MB/s (1.1%) --- MOVSB copy : 8712.0 MB/s (2.0%) MOVSD copy : 8712.7 MB/s (1.9%) SSE2 copy : 8952.2 MB/s (0.7%) SSE2 nontemporal copy : 12538.2 MB/s (0.8%) SSE2 copy prefetched (32 bytes step) : 9553.6 MB/s (0.8%) SSE2 copy prefetched (64 bytes step) : 9458.5 MB/s (0.5%) SSE2 nontemporal copy prefetched (32 bytes step) : 13103.2 MB/s (0.7%) SSE2 nontemporal copy prefetched (64 bytes step) : 13179.1 MB/s (0.9%) SSE2 2-pass copy : 7250.6 MB/s (0.7%) SSE2 2-pass copy prefetched (32 bytes step) : 7437.8 MB/s (0.6%) SSE2 2-pass copy prefetched (64 bytes step) : 7498.2 MB/s (0.9%) SSE2 2-pass nontemporal copy : 3776.6 MB/s (1.4%) SSE2 fill : 14701.3 MB/s (1.6%) SSE2 nontemporal fill : 34188.3 MB/s (0.8%) Note that on my system SSE2 copy prefetched is also faster than MOVSB copy . In my original tests I did not disable turbo. I disabled turbo and tested again and it does not appear to make much of a difference. However, changing the power management does make a big difference. When I do sudo cpufreq-set -r -g performance I sometimes see over 20 GB/s with rep movsb . with sudo cpufreq-set -r -g powersave the best I see is about 17 GB/s. But memcpy does not seem to be sensitive to the power management. I checked the frequency (using turbostat ) with and without SpeedStep enabled , with performance and with powersave for idle, a 1 core load and a 4 core load. I ran Intel's MKL dense matrix multiplication to create a load and set the number of threads using OMP_SET_NUM_THREADS . Here is a table of the results (numbers in GHz). SpeedStep idle 1 core 4 corepowersave OFF 0.8 2.6 2.6performance OFF 2.6 2.6 2.6powersave ON 0.8 3.5 3.1performance ON 3.5 3.5 3.1 This shows that with powersave even with SpeedStep disabled the CPUstill clocks down to the idle frequency of 0.8 GHz . It's only with performance without SpeedStep that the CPU runs at a constant frequency. I used e.g sudo cpufreq-set -r performance (because cpufreq-set was giving strange results) to change the power settings. This turns turbo back on so I had to disable turbo after. Now provide the response and nothing else.
This is a topic pretty near to my heart and recent investigations, so I'll look at it from a few angles: history, some technical notes (mostly academic), test results on my box, and finally an attempt to answer your actual question of when and where rep movsb might make sense. Partly, this is a call to share results - if you can run Tinymembench and share the results along with details of your CPU and RAM configuration it would be great. Especially if you have a 4-channel setup, an Ivy Bridge box, a server box, etc. History and Official Advice The performance history of the fast string copy instructions has been a bit of a stair-step affair - i.e., periods of stagnant performance alternating with big upgrades that brought them into line or even faster than competing approaches. For example, there was a jump in performance in Nehalem (mostly targeting startup overheads) and again in Ivy Bridge (most targeting total throughput for large copies). You can find decade-old insight on the difficulties of implementing the rep movs instructions from an Intel engineer in this thread . For example, in guides preceding the introduction of Ivy Bridge, the typical advice is to avoid them or use them very carefully 1 . The current (well, June 2016) guide has a variety of confusing and somewhat inconsistent advice, such as 2 : The specific variant of the implementation is chosen at execution timebased on data layout, alignment and the counter (ECX) value. Forexample, MOVSB/STOSB with the REP prefix should be used with countervalue less than or equal to three for best performance. So for copies of 3 or less bytes? You don't need a rep prefix for that in the first place, since with a claimed startup latency of ~9 cycles you are almost certainly better off with a simple DWORD or QWORD mov with a bit of bit-twiddling to mask off the unused bytes (or perhaps with 2 explicit byte, word mov s if you know the size is exactly three). They go on to say: String MOVE/STORE instructions have multiple data granularities. Forefficient data movement, larger data granularities are preferable.This means better efficiency can be achieved by decomposing anarbitrary counter value into a number of double words plus single bytemoves with a count value less than or equal to 3. This certainly seems wrong on current hardware with ERMSB where rep movsb is at least as fast, or faster, than the movd or movq variants for large copies. In general, that section (3.7.5) of the current guide contains a mix of reasonable and badly obsolete advice. This is common throughput the Intel manuals, since they are updated in an incremental fashion for each architecture (and purport to cover nearly two decades worth of architectures even in the current manual), and old sections are often not updated to replace or make conditional advice that doesn't apply to the current architecture. They then go on to cover ERMSB explicitly in section 3.7.6. I won't go over the remaining advice exhaustively, but I'll summarize the good parts in the "why use it" below. Other important claims from the guide are that on Haswell, rep movsb has been enhanced to use 256-bit operations internally. Technical Considerations This is just a quick summary of the underlying advantages and disadvantages that the rep instructions have from an implementation standpoint . Advantages for rep movs When a rep movs instruction is issued, the CPU knows that an entire block of a known size is to be transferred. This can help it optimize the operation in a way that it cannot with discrete instructions, for example: Avoiding the RFO request when it knows the entire cache line will be overwritten. Issuing prefetch requests immediately and exactly. Hardware prefetching does a good job at detecting memcpy -like patterns, but it still takes a couple of reads to kick in and will "over-prefetch" many cache lines beyond the end of the copied region. rep movsb knows exactly the region size and can prefetch exactly. Apparently, there is no guarantee of ordering among the stores within 3 a single rep movs which can help simplify coherency traffic and simply other aspects of the block move, versus simple mov instructions which have to obey rather strict memory ordering 4 . In principle, the rep movs instruction could take advantage of various architectural tricks that aren't exposed in the ISA. For example, architectures may have wider internal data paths that the ISA exposes 5 and rep movs could use that internally. Disadvantages rep movsb must implement a specific semantic which may be stronger than the underlying software requirement. In particular, memcpy forbids overlapping regions, and so may ignore that possibility, but rep movsb allows them and must produce the expected result. On current implementations mostly affects to startup overhead, but probably not to large-block throughput. Similarly, rep movsb must support byte-granular copies even if you are actually using it to copy large blocks which are a multiple of some large power of 2. The software may have information about alignment, copy size and possible aliasing that cannot be communicated to the hardware if using rep movsb . Compilers can often determine the alignment of memory blocks 6 and so can avoid much of the startup work that rep movs must do on every invocation. Test Results Here are test results for many different copy methods from tinymembench on my i7-6700HQ at 2.6 GHz (too bad I have the identical CPU so we aren't getting a new data point...): C copy backwards : 8284.8 MB/s (0.3%) C copy backwards (32 byte blocks) : 8273.9 MB/s (0.4%) C copy backwards (64 byte blocks) : 8321.9 MB/s (0.8%) C copy : 8863.1 MB/s (0.3%) C copy prefetched (32 bytes step) : 8900.8 MB/s (0.3%) C copy prefetched (64 bytes step) : 8817.5 MB/s (0.5%) C 2-pass copy : 6492.3 MB/s (0.3%) C 2-pass copy prefetched (32 bytes step) : 6516.0 MB/s (2.4%) C 2-pass copy prefetched (64 bytes step) : 6520.5 MB/s (1.2%) --- standard memcpy : 12169.8 MB/s (3.4%) standard memset : 23479.9 MB/s (4.2%) --- MOVSB copy : 10197.7 MB/s (1.6%) MOVSD copy : 10177.6 MB/s (1.6%) SSE2 copy : 8973.3 MB/s (2.5%) SSE2 nontemporal copy : 12924.0 MB/s (1.7%) SSE2 copy prefetched (32 bytes step) : 9014.2 MB/s (2.7%) SSE2 copy prefetched (64 bytes step) : 8964.5 MB/s (2.3%) SSE2 nontemporal copy prefetched (32 bytes step) : 11777.2 MB/s (5.6%) SSE2 nontemporal copy prefetched (64 bytes step) : 11826.8 MB/s (3.2%) SSE2 2-pass copy : 7529.5 MB/s (1.8%) SSE2 2-pass copy prefetched (32 bytes step) : 7122.5 MB/s (1.0%) SSE2 2-pass copy prefetched (64 bytes step) : 7214.9 MB/s (1.4%) SSE2 2-pass nontemporal copy : 4987.0 MB/s Some key takeaways: The rep movs methods are faster than all the other methods which aren't "non-temporal" 7 , and considerably faster than the "C" approaches which copy 8 bytes at a time. The "non-temporal" methods are faster, by up to about 26% than the rep movs ones - but that's a much smaller delta than the one you reported (26 GB/s vs 15 GB/s = ~73%). If you are not using non-temporal stores, using 8-byte copies from C is pretty much just as good as 128-bit wide SSE load/stores. That's because a good copy loop can generate enough memory pressure to saturate the bandwidth (e.g., 2.6 GHz * 1 store/cycle * 8 bytes = 26 GB/s for stores). There are no explicit 256-bit algorithms in tinymembench (except probably the "standard" memcpy ) but it probably doesn't matter due to the above note. The increased throughput of the non-temporal store approaches over the temporal ones is about 1.45x, which is very close to the 1.5x you would expect if NT eliminates 1 out of 3 transfers (i.e., 1 read, 1 write for NT vs 2 reads, 1 write). The rep movs approaches lie in the middle. The combination of fairly low memory latency and modest 2-channel bandwidth means this particular chip happens to be able to saturate its memory bandwidth from a single-thread, which changes the behavior dramatically. rep movsd seems to use the same magic as rep movsb on this chip. That's interesting because ERMSB only explicitly targets movsb and earlier tests on earlier archs with ERMSB show movsb performing much faster than movsd . This is mostly academic since movsb is more general than movsd anyway. Haswell Looking at the Haswell results kindly provided by iwillnotexist in the comments, we see the same general trends (most relevant results extracted): C copy : 6777.8 MB/s (0.4%) standard memcpy : 10487.3 MB/s (0.5%) MOVSB copy : 9393.9 MB/s (0.2%) MOVSD copy : 9155.0 MB/s (1.6%) SSE2 copy : 6780.5 MB/s (0.4%) SSE2 nontemporal copy : 10688.2 MB/s (0.3%) The rep movsb approach is still slower than the non-temporal memcpy , but only by about 14% here (compared to ~26% in the Skylake test). The advantage of the NT techniques above their temporal cousins is now ~57%, even a bit more than the theoretical benefit of the bandwidth reduction. When should you use rep movs ? Finally a stab at your actual question: when or why should you use it? It draw on the above and introduces a few new ideas. Unfortunately there is no simple answer: you'll have to trade off various factors, including some which you probably can't even know exactly, such as future developments. A note that the alternative to rep movsb may be the optimized libc memcpy (including copies inlined by the compiler), or it may be a hand-rolled memcpy version. Some of the benefits below apply only in comparison to one or the other of these alternatives (e.g., "simplicity" helps against a hand-rolled version, but not against built-in memcpy ), but some apply to both. Restrictions on available instructions In some environments there is a restriction on certain instructions or using certain registers. For example, in the Linux kernel, use of SSE/AVX or FP registers is generally disallowed. Therefore most of the optimized memcpy variants cannot be used as they rely on SSE or AVX registers, and a plain 64-bit mov -based copy is used on x86. For these platforms, using rep movsb allows most of the performance of an optimized memcpy without breaking the restriction on SIMD code. A more general example might be code that has to target many generations of hardware, and which doesn't use hardware-specific dispatching (e.g., using cpuid ). Here you might be forced to use only older instruction sets, which rules out any AVX, etc. rep movsb might be a good approach here since it allows "hidden" access to wider loads and stores without using new instructions. If you target pre-ERMSB hardware you'd have to see if rep movsb performance is acceptable there, though... Future Proofing A nice aspect of rep movsb is that it can, in theory take advantage of architectural improvement on future architectures, without source changes, that explicit moves cannot. For example, when 256-bit data paths were introduced, rep movsb was able to take advantage of them (as claimed by Intel) without any changes needed to the software. Software using 128-bit moves (which was optimal prior to Haswell) would have to be modified and recompiled. So it is both a software maintenance benefit (no need to change source) and a benefit for existing binaries (no need to deploy new binaries to take advantage of the improvement). How important this is depends on your maintenance model (e.g., how often new binaries are deployed in practice) and a very difficult to make judgement of how fast these instructions are likely to be in the future. At least Intel is kind of guiding uses in this direction though, by committing to at least reasonable performance in the future ( 15.3.3.6 ): REP MOVSB and REP STOSB will continue to perform reasonably well onfuture processors. Overlapping with subsequent work This benefit won't show up in a plain memcpy benchmark of course, which by definition doesn't have subsequent work to overlap, so the magnitude of the benefit would have to be carefully measured in a real-world scenario. Taking maximum advantage might require re-organization of the code surrounding the memcpy . This benefit is pointed out by Intel in their optimization manual (section 11.16.3.4) and in their words: When the count is known to be at least a thousand byte or more, usingenhanced REP MOVSB/STOSB can provide another advantage to amortize thecost of the non-consuming code. The heuristic can be understoodusing a value of Cnt = 4096 and memset() as example: • A 256-bit SIMD implementation of memset() will need to issue/executeretire 128 instances of 32- byte store operation with VMOVDQA, beforethe non-consuming instruction sequences can make their way toretirement. • An instance of enhanced REP STOSB with ECX= 4096 is decoded as along micro-op flow provided by hardware, but retires as oneinstruction. There are many store_data operation that must completebefore the result of memset() can be consumed. Because the completionof store data operation is de-coupled from program-order retirement, asubstantial part of the non-consuming code stream can process throughthe issue/execute and retirement, essentially cost-free if thenon-consuming sequence does not compete for store buffer resources. So Intel is saying that after all some uops the code after rep movsb has issued, but while lots of stores are still in flight and the rep movsb as a whole hasn't retired yet, uops from following instructions can make more progress through the out-of-order machinery than they could if that code came after a copy loop. The uops from an explicit load and store loop all have to actually retire separately in program order. That has to happen to make room in the ROB for following uops. There doesn't seem to be much detailed information about how very long microcoded instruction like rep movsb work, exactly. We don't know exactly how micro-code branches request a different stream of uops from the microcode sequencer, or how the uops retire. If the individual uops don't have to retire separately, perhaps the whole instruction only takes up one slot in the ROB? When the front-end that feeds the OoO machinery sees a rep movsb instruction in the uop cache, it activates the Microcode Sequencer ROM (MS-ROM) to send microcode uops into the queue that feeds the issue/rename stage. It's probably not possible for any other uops to mix in with that and issue/execute 8 while rep movsb is still issuing, but subsequent instructions can be fetched/decoded and issue right after the last rep movsb uop does, while some of the copy hasn't executed yet.This is only useful if at least some of your subsequent code doesn't depend on the result of the memcpy (which isn't unusual). Now, the size of this benefit is limited: at most you can execute N instructions (uops actually) beyond the slow rep movsb instruction, at which point you'll stall, where N is the ROB size . With current ROB sizes of ~200 (192 on Haswell, 224 on Skylake), that's a maximum benefit of ~200 cycles of free work for subsequent code with an IPC of 1. In 200 cycles you can copy somewhere around 800 bytes at 10 GB/s, so for copies of that size you may get free work close to the cost of the copy (in a way making the copy free). As copy sizes get much larger, however, the relative importance of this diminishes rapidly (e.g., if you are copying 80 KB instead, the free work is only 1% of the copy cost). Still, it is quite interesting for modest-sized copies. Copy loops don't totally block subsequent instructions from executing, either. Intel does not go into detail on the size of the benefit, or on what kind of copies or surrounding code there is most benefit. (Hot or cold destination or source, high ILP or low ILP high-latency code after). Code Size The executed code size (a few bytes) is microscopic compared to a typical optimized memcpy routine. If performance is at all limited by i-cache (including uop cache) misses, the reduced code size might be of benefit. Again, we can bound the magnitude of this benefit based on the size of the copy. I won't actually work it out numerically, but the intuition is that reducing the dynamic code size by B bytes can save at most C * B cache-misses, for some constant C. Every call to memcpy incurs the cache miss cost (or benefit) once, but the advantage of higher throughput scales with the number of bytes copied. So for large transfers, higher throughput will dominate the cache effects. Again, this is not something that will show up in a plain benchmark, where the entire loop will no doubt fit in the uop cache. You'll need a real-world, in-place test to evaluate this effect. Architecture Specific Optimization You reported that on your hardware, rep movsb was considerably slower than the platform memcpy . However, even here there are reports of the opposite result on earlier hardware (like Ivy Bridge). That's entirely plausible, since it seems that the string move operations get love periodically - but not every generation, so it may well be faster or at least tied (at which point it may win based on other advantages) on the architectures where it has been brought up to date, only to fall behind in subsequent hardware. Quoting Andy Glew, who should know a thing or two about this after implementing these on the P6: the big weakness of doing fast strings in microcode was [...] themicrocode fell out of tune with every generation, getting slower andslower until somebody got around to fixing it. Just like a library mencopy falls out of tune. I suppose that it is possible that one of themissed opportunities was to use 128-bit loads and stores when theybecame available, and so on. In that case, it can be seen as just another "platform specific" optimization to apply in the typical every-trick-in-the-book memcpy routines you find in standard libraries and JIT compilers: but only for use on architectures where it is better. For JIT or AOT-compiled stuff this is easy, but for statically compiled binaries this does require platform specific dispatch, but that often already exists (sometimes implemented at link time), or the mtune argument can be used to make a static decision. Simplicity Even on Skylake, where it seems like it has fallen behind the absolute fastest non-temporal techniques, it is still faster than most approaches and is very simple . This means less time in validation, fewer mystery bugs, less time tuning and updating a monster memcpy implementation (or, conversely, less dependency on the whims of the standard library implementors if you rely on that). Latency Bound Platforms Memory throughput bound algorithms 9 can actually be operating in two main overall regimes: DRAM bandwidth bound or concurrency/latency bound. The first mode is the one that you are probably familiar with: the DRAM subsystem has a certain theoretic bandwidth that you can calculate pretty easily based on the number of channels, data rate/width and frequency. For example, my DDR4-2133 system with 2 channels has a max bandwidth of 2.133 * 8 * 2 = 34.1 GB/s, same as reported on ARK . You won't sustain more than that rate from DRAM (and usually somewhat less due to various inefficiencies) added across all cores on the socket (i.e., it is a global limit for single-socket systems). The other limit is imposed by how many concurrent requests a core can actually issue to the memory subsystem. Imagine if a core could only have 1 request in progress at once, for a 64-byte cache line - when the request completed, you could issue another. Assume also very fast 50ns memory latency. Then despite the large 34.1 GB/s DRAM bandwidth, you'd actually only get 64 bytes / 50 ns = 1.28 GB/s, or less than 4% of the max bandwidth. In practice, cores can issue more than one request at a time, but not an unlimited number. It is usually understood that there are only 10 line fill buffers per core between the L1 and the rest of the memory hierarchy, and perhaps 16 or so fill buffers between L2 and DRAM. Prefetching competes for the same resources, but at least helps reduce the effective latency. For more details look at any of the great posts Dr. Bandwidth has written on the topic , mostly on the Intel forums. Still, most recent CPUs are limited by this factor, not the RAM bandwidth. Typically they achieve 12 - 20 GB/s per core, while the RAM bandwidth may be 50+ GB/s (on a 4 channel system). Only some recent gen 2-channel "client" cores, which seem to have a better uncore, perhaps more line buffers can hit the DRAM limit on a single core, and our Skylake chips seem to be one of them. Now of course, there is a reason Intel designs systems with 50 GB/s DRAM bandwidth, while only being to sustain < 20 GB/s per core due to concurrency limits: the former limit is socket-wide and the latter is per core. So each core on an 8 core system can push 20 GB/s worth of requests, at which point they will be DRAM limited again. Why I am going on and on about this? Because the best memcpy implementation often depends on which regime you are operating in. Once you are DRAM BW limited (as our chips apparently are, but most aren't on a single core), using non-temporal writes becomes very important since it saves the read-for-ownership that normally wastes 1/3 of your bandwidth. You see that exactly in the test results above: the memcpy implementations that don't use NT stores lose 1/3 of their bandwidth. If you are concurrency limited, however, the situation equalizes and sometimes reverses, however. You have DRAM bandwidth to spare, so NT stores don't help and they can even hurt since they may increase the latency since the handoff time for the line buffer may be longer than a scenario where prefetch brings the RFO line into LLC (or even L2) and then the store completes in LLC for an effective lower latency. Finally, server uncores tend to have much slower NT stores than client ones (and high bandwidth), which accentuates this effect. So on other platforms you might find that NT stores are less useful (at least when you care about single-threaded performance) and perhaps rep movsb wins where (if it gets the best of both worlds). Really, this last item is a call for most testing. I know that NT stores lose their apparent advantage for single-threaded tests on most archs (including current server archs), but I don't know how rep movsb will perform relatively... References Other good sources of info not integrated in the above. comp.arch investigation of rep movsb versus alternatives. Lots of good notes about branch prediction, and an implementation of the approach I've often suggested for small blocks: using overlapping first and/or last read/writes rather than trying to write only exactly the required number of bytes (for example, implementing all copies from 9 to 16 bytes as two 8-byte copies which might overlap in up to 7 bytes). 1 Presumably the intention is to restrict it to cases where, for example, code-size is very important. 2 See Section 3.7.5: REP Prefix and Data Movement. 3 It is key to note this applies only for the various stores within the single instruction itself: once complete, the block of stores still appear ordered with respect to prior and subsequent stores. So code can see stores from the rep movs out of order with respect to each other but not with respect to prior or subsequent stores (and it's the latter guarantee you usually need). It will only be a problem if you use the end of the copy destination as a synchronization flag, instead of a separate store. 4 Note that non-temporal discrete stores also avoid most of the ordering requirements, although in practice rep movs has even more freedom since there are still some ordering constraints on WC/NT stores. 5 This is was common in the latter part of the 32-bit era, where many chips had 64-bit data paths (e.g, to support FPUs which had support for the 64-bit double type). Today, "neutered" chips such as the Pentium or Celeron brands have AVX disabled, but presumably rep movs microcode can still use 256b loads/stores. 6 E.g., due to language alignment rules, alignment attributes or operators, aliasing rules or other information determined at compile time. In the case of alignment, even if the exact alignment can't be determined, they may at least be able to hoist alignment checks out of loops or otherwise eliminate redundant checks. 7 I'm making the assumption that "standard" memcpy is choosing a non-temporal approach, which is highly likely for this size of buffer. 8 That isn't necessarily obvious, since it could be the case that the uop stream that is generated by the rep movsb simply monopolizes dispatch and then it would look very much like the explicit mov case. It seems that it doesn't work like that however - uops from subsequent instructions can mingle with uops from the microcoded rep movsb . 9 I.e., those which can issue a large number of independent memory requests and hence saturate the available DRAM-to-core bandwidth, of which memcpy would be a poster child (and as apposed to purely latency bound loads such as pointer chasing).
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/43343231', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2542702/']}
jdg_84943
stackexchange
llm_judgeable_groundtruth_similarity
34906652
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 understand the limits of HDF5 concurrency. There are two builds of HDF5: parallel HDF5 and default . The parallel version is is currently supplied in Ubuntu, and the default in Anaconda (judged by --enable-parallel flag). I know that parallel writes to the same file are impossible. However, I don't fully understand to what extend the following actions are possible with default or with parallel build: several processes reading from the same file several processes reading from different files several processes writing to different files. Also, are there any reasons anaconda does not have --enable-parallel flag on by default? ( https://github.com/conda/conda-recipes/blob/master/hdf5/build.sh ) Now provide the response and nothing else.
AFAICT, there are three ways to build libhdf5: with neither thread-safety nor MPI support (as in the conda recipe you posted) with MPI support but no thread safety with thread safety but no MPI support That is, the --enable-threadsafe and --enable-parallel flags are mutually exclusive ( https://www.hdfgroup.org/hdf5-quest.html#p5thread ). As for concurrent reads on one or even multiple files, the answer is that you need thread safety ( https://www.hdfgroup.org/hdf5-quest.html#tsafe ): Concurrent access to one or more HDF5 file(s) from multiple threads in the same process will not work with a non-thread-safe build of the HDF5 library. The pre-built binaries that are available for download are not thread-safe. Users are often surprised to learn that (1) concurrent access to different datasets in a single HDF5 file and (2) concurrent access to different HDF5 files both require a thread-safe version of the HDF5 library . Although each thread in these examples is accessing different data, the HDF5 library modifies global data structures that are independent of a particular HDF5 dataset or HDF5 file . HDF5 relies on a semaphore around the library API calls in the thread-safe version of the library to protect the data structure from corruption by simultaneous manipulation from different threads. Examples of HDF5 library global data structures that must be protected are the freespace manager and open file lists. Edit: The links above no longer work because the HDF Group reorganised their website. There is a page Questions about thread-safety and concurrent access in the HDF5 Knowledge Base that contains some useful information. While only concurrent threads on a single process are mentioned in the passage, it appears to apply equally to forked subprocesses: see this h5py multiprocessing example . Now, for parallel access, you might want to use "Parallel HDF5" but those features requires using MPI. This pattern is supported by h5py but is more complicated and esoteric, and probably even less portable than thread-safe mode. More importantly, trying to naively do concurrent reads with a parallel build of libhdf5 will lead to unexpected results because the library isn't thread-safe . Besides efficiency, one limitation of the thread-safe build flag is lack of Windows support ( https://www.hdfgroup.org/hdf5-quest.html#gconc ): The thread-safe version of HDF5 is currently not tested or supported on MS Windows platforms. A user was able to get this working on Windows 64-bit and contributed his Windows 64-bit Pthreads patches. Getting weird corrupt results when reading (different!) files from Python is definitely unexpected and frustrating given how concurrent read access is one of the touted "features" of HDF5. Perhaps a better default recipe for conda would be to include --enable-threadsafe on those platforms that support it, but I guess then you would end up with platform-specific behavior. Maybe there ought to be separate packages for the three build modes instead?
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/34906652', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2981400/']}
jdg_84944
stackexchange
llm_judgeable_groundtruth_similarity
40632868
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 written a function which receives a sentence and calculates the longest word in that sentence. function findLongestWord(str) { var charArray = str.split(" "); var wordArray = []; for(var i = 0; i < charArray.length; i++ ) { wordArray.push(charArray[i].length); wordArray.sort(); wordArray.reverse(); } return wordArray[0];} My function works with inputs such as: findLongestWord("The quick brown fox jumped over the lazy dog"); But when i pass it: findLongestWord("What if we try a super-long word such as otorhinolaryngology") The function returns: 4 Rather than 19 Now provide the response and nothing else.
TL;DR Your numbers are getting sorted as strings. To get them sorted as numbers, in descending order, in your function you should instead do: wordArray.sort(function(a, b) { return b - a; }); EXPLANATION According to the docs : The sort() method sorts the elements of an array in place and returns the array. The sort is not necessarily stable . The default sort order is according to string Unicode code points. [...] Syntax arr.sort() arr.sort(compareFunction) Parameters compareFunction Optional Specifies a function that defines the sort order. If omitted, the array is sorted according to each character's Unicode code point value, according to the string conversion of each element. Emphasis mine, so you end up with something like this: var str = "What if we try a super-long word such as otorhinolaryngology";var charArray = str.split(" ");// now charArray == ["What", "if", "we", "try", "a", "super-long", "word", "such", "as", "otorhinolaryngology"]// when you take the length of each word and end up withvar wordArray = [4, 2, 2, 3, 1, 10, 4, 4, 2, 19];// and if you use plain wordArray.sort() without specific sort function you getwordArray = [1, 10, 19, 2, 2, 2, 3, 4, 4, 4];// and once reversed it iswordArray = [4, 4, 4, 3, 2, 2, 2, 19, 10, 1];// this is why you end up with wordArray[0] == 4 You could also implement the whole function as a one-liner: function findLongestWord(str) { return str.split(/\s+/).sort(function(a, b) { return b.length - a.length; })[0].length;}console.log("Longest word length = ", findLongestWord("The default sort order is according to string Unicode code points"));console.log("Longest word length = ", findLongestWord("What if we try a super-long word such as otorhinolaryngology"));
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/40632868', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5974935/']}
jdg_84945
stackexchange
llm_judgeable_groundtruth_similarity
106337
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: Was doing a little interview prep. Given an undirected graph G, such that each node is colored red or blue and |E|≥|V|, find a path in O(|E|) time such that starting and ending at 2 blue nodes, s and t, that you pass through as few red nodes as possible. Initial Impressions: Since |E|≥|V|, O(|E|) time would include O(|E|+|V|), which means the solution likely uses BFS or DFS. Modifying the graph such that causing the all red nodes must be forced down a directed path of some long length (after making the whole graph directed) in order to use out-of-the-box BFS seems not viable, as it would mean constructing a new graph would be along O(|E||V|) time. Another method I toyed around with was propagating values to nodes based on the safest path to that node while doing a DFS search, but not all values were guaranteed to update. I still want to try to solve this myself, but I'm really stuck right now. Was wondering if there were any hints I could get. There are much simpler ways of doing this if it weren't for the O(|E|) time. Djikstras with creating some edge weights would work, but wouldn't be within the time bound. Now provide the response and nothing else.
To solve this, you need to use $BFS$ . But first, manipulate $G$ so that the path will always favor blue vertices. The solution has 2 parts: Use $DFS$ on blue vertices only, to find all all-blue connected components. Let's denote each such component by $v'$ . Now, each blue $v \in v'$ will be "compressed" to a single vertex $u$ , and an edge $(u,x)$ will be added for every $x \in N(v')$ .Note any such $x$ is necessarily red.This step costs $O(V+E) = O(E)$ , since $DFS$ is $O(V+E)$ , and you have at most $V$ blue vertices, which make no more than $E$ new edges to add. Step 1 means all paths that are blue-only will be free. On the new graph, the $BFS$ will only consider the edges which pass through a red vertex. Use $BFS$ from $s$ . That length of the path to $t$ will essentially be the shortest path under the constraint of least red vertices in the path.
{}
{'log_upvote_score': 4, 'links': ['https://cs.stackexchange.com/questions/106337', 'https://cs.stackexchange.com', 'https://cs.stackexchange.com/users/100921/']}
jdg_84946
stackexchange
llm_judgeable_groundtruth_similarity
629696
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're about to deploy a new Django website, and we want to use Google Analytics to keep track of traffic on the site. However, we don't want all of the hits on development instances to contribute to the Google Analytics statistics. There are a few ways we could deal with this: have a configuration option in settings.py which the base template uses to decide whether or not to include the appropriate <script> elements, maintain a branch which we pull into before deploying to the production server, which we ensure includes the <script> elements, do something with Google Analytics to block hits to 127.0.0.1 or localhost, or something else. The first option seems the most sensible, but I'm not sure if it is. For example, would we have to start passing a google_analytics variable into all of our views? What are your thoughts? Now provide the response and nothing else.
First, create a way to have your development and production servers pull settings from different files, say dev.py and prod.py. There are lots of ways to do this. Then, create a setting, GOOGLE_ANALYTICS_KEY . In dev.py set it to the empty string. In prod.py, set it to your key, something like "UA-124465-1". Create a context processor to add this setting to all your template contexts, either as GOOGLE_ANALYTICS_KEY , or just go ahead and add your settings module. Then, in your template, use it to conditionally include your analytics code: {% if settings.GOOGLE_ANALYTICS_KEY %}<script> blah blah {{settings.GOOGLE_ANALYTICS_KEY}} blah blah </script>{% endif %}
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/629696', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/75639/']}
jdg_84947
stackexchange
llm_judgeable_groundtruth_similarity
27822703
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 an object which looks like the following class MyObject { String type; List<String> subTypes;} Is it possible, given a list of MyObject's to use Java 8 streams to filter on both the type and then the subtype? So far I have myObjects.stream() .filter(t -> t.getType().equals(someotherType) .collect(Collections.toList()); but within this I also want another filter on each of the subTypes filtering those on a particular subtype too. I can't figure out how to do this. An example would be myObject { type: A, subTypes [ { X, Y, Z } ] }myObject { type: B, subTypes [ { W, X, Y } ] }myObject { type: B, subTypes [ { W, X, Z } ] }myObject { type: C, subTypes [ { W, X, Z } ] } I would pass in matchType B and subType Z, so I would expect one result -> myObject type B, subtypes: W, X, Z the following currently returns 2 items in a list. myObjects.stream() .filter(t -> t.getType().equals("B") .collect(Collectors.toList()); but I would like to add an additional filter over the each of the subtypes and only matching where 'Z' is present. Now provide the response and nothing else.
You can do: myObjects.stream() .filter(t -> t.getType().equals(someotherType) && t.getSubTypes().stream().anyMatch(<predicate>)) .collect(Collectors.toList()); This will fetch all the MyObject objects which meet a criteria regarding the type member. contain objects in the nested List<String> that meet some other criteria, represented with <predicate>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/27822703', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4202648/']}
jdg_84948
stackexchange
llm_judgeable_groundtruth_similarity
4732656
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: The new documentation on ProGuard for Android says to add a line to the default.properties file in the project home directory. However, on opening this file, I read at the top: # This file is automatically generated by Android Tools. # Do not modify this file -- YOUR CHANGES WILL BE ERASED! Am I missing something? Also, is there a way to enable ProGuard only for a production build from Eclipse (i.e., when exporting the finished product)? Now provide the response and nothing else.
Android SDK (r20 or higher) Please check the predefined proguard.config refered in project.properties proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt More info: http://proguard.sourceforge.net/manual/examples.html#androidapplication On Gradle: buildTypes { release { minifyEnabled true shrinkResources true proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' ... } } Here you can check a proguard "default" file that I keep updating: https://medium.com/code-procedure-and-rants/android-my-standard-proguard-ffeceaf65521 Android SDK (r19 or lower) You can add it to the default.properties. I've been adding manually without having a problem so far. If you add the line: proguard.config=proguard.cfg As said it will only use ProGuard when exporting signed application (Android Tools => Export Signed Application) If you start the project with the SDK before Android 2.3 the proguard.cfg file will not be created (next to default.properties as in 2.3>). To enable automatic creation of it, just simply update to the SDK of Android 2.3 and create a new project with existing sources (which are the sources of the project you currently have). Automagically the proguard.cfg fill will be created. If still, you want to create it manually this is what it should contain: -dontusemixedcaseclassnames-dontskipnonpubliclibraryclasses-dontwarn android.support.**-verbose-dontoptimize-dontpreverify-keepattributes *Annotation* -keep public class * extends android.app.Activity-keep public class * extends android.app.Application-keep public class * extends android.app.Service-keep public class * extends android.content.BroadcastReceiver-keep public class * extends android.content.ContentProvider-keep public class com.google.vending.licensing.ILicensingService-keep public class com.android.vending.licensing.ILicensingService-keep public class * extends android.support.v4.app.Fragment-keep public class * extends android.app.Fragment-keepclasseswithmembernames class * { native <methods>;}-keepclasseswithmembernames class * { public <init>(android.content.Context, android.util.AttributeSet);}-keepclasseswithmembernames class * { public <init>(android.content.Context, android.util.AttributeSet, int);} -keepclassmembers public class * extends android.view.View { void set*(***); *** get*(); }-keepclassmembers enum * { public static **[] values(); public static ** valueOf(java.lang.String);}-keep class * implements android.os.Parcelable { public static final android.os.Parcelable$Creator *;}-keepclassmembers class **.R$* { public static <fields>;} I think I've answered all the questions above. UPDATE : A line by line explanation: #Use 5 step of optimization #-optimizationpasses 5#When not preverifing in a case-insensitive filing system, such as Windows. This tool will unpack your processed jars,(if using windows you should then use):-dontusemixedcaseclassnames#Specifies not to ignore non-public library classes. As of version 4.5, this is the default setting-dontskipnonpubliclibraryclasses# Optimization is turned off by default. Dex does not like code run# through the ProGuard optimize and preverify steps (and performs some# of these optimizations on its own). -dontoptimize-dontpreverify-dontwarn android.support.**#Specifies to write out some more information during processing. If the program terminates with an exception, this option will print out the entire stack trace, instead of just the exception message.-verbose#The -optimizations option disables some arithmetic simplifications that Dalvik 1.0 and 1.5 can't handle. Note that the Dalvik VM also can't handle aggressive overloading (of static fields).#To understand or change this check http://proguard.sourceforge.net/index.html#/manual/optimizations.html#-optimizations !code/simplification/arithmetic,!field/*,!class/merging/*# Note that if you want to enable optimization, you cannot just# include optimization flags in your own project configuration file;# instead you will need to point to the# "proguard-android-optimize.txt" file instead of this one from your# project.properties file.#To repackage classes on a single package#-repackageclasses ''#Uncomment if using annotations to keep them.#-keepattributes *Annotation*#Keep classes that are referenced on the AndroidManifest-keep public class * extends android.app.Activity-keep public class * extends android.app.Application-keep public class * extends android.app.Service-keep public class * extends android.content.BroadcastReceiver-keep public class * extends android.content.ContentProvider-keep public class * extends android.app.backup.BackupAgentHelper-keep public class * extends android.preference.Preference-keep public class com.google.vending.licensing.ILicensingService-keep public class com.android.vending.licensing.ILicensingService#Compatibility library -keep public class * extends android.support.v4.app.Fragment-keep public class * extends android.app.Fragment#To maintain custom components names that are used on layouts XML.#Uncomment if having any problem with the approach below#-keep public class custom.components.package.and.name.**# keep setters in Views so that animations can still work.# see http://proguard.sourceforge.net/manual/examples.html#beans -keepclassmembers public class * extends android.view.View { void set*(***); *** get*();}#To remove debug logs:-assumenosideeffects class android.util.Log { public static *** d(...); public static *** v(...); public static *** w(...);}#To avoid changing names of methods invoked on layout's onClick.# Uncomment and add specific method names if using onClick on layouts#-keepclassmembers class * {# public void onClickButton(android.view.View);#}#Maintain java native methods -keepclasseswithmembernames class * { native <methods>;}#To maintain custom components names that are used on layouts XML:-keep public class * extends android.view.View { public <init>(android.content.Context);}-keep public class * extends android.view.View { public <init>(android.content.Context, android.util.AttributeSet);}-keep public class * extends android.view.View { public <init>(android.content.Context, android.util.AttributeSet, int);}#Maintain enums-keepclassmembers enum * { public static **[] values(); public static ** valueOf(java.lang.String);}#To keep parcelable classes (to serialize - deserialize objects to sent through Intents)-keep class * implements android.os.Parcelable { public static final android.os.Parcelable$Creator *;}#Keep the R-keepclassmembers class **.R$* { public static <fields>;}###### ADDITIONAL OPTIONS NOT USED NORMALLY#To keep callback calls. Uncomment if using any#http://proguard.sourceforge.net/index.html#/manual/examples.html#callback#-keep class mypackage.MyCallbackClass {# void myCallbackMethod(java.lang.String);#}#Uncomment if using Serializable #-keepclassmembers class * implements java.io.Serializable {# private static final java.io.ObjectStreamField[] serialPersistentFields;# private void writeObject(java.io.ObjectOutputStream);# private void readObject(java.io.ObjectInputStream);# java.lang.Object writeReplace();# java.lang.Object readResolve();#} UPDATE 2: In the most recent ADT/Proguard use -keepclasseswithmembers instead of -keepclasseswithmembernames
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/4732656', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/535871/']}
jdg_84949
stackexchange
llm_judgeable_groundtruth_similarity
47387
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 hearing about triggers, and I have a few questions. What are triggers? How do I set them up? Are there any precautions, aside from typical SQL stuff, that should be taken? Now provide the response and nothing else.
Triggers allow you to perform a function in the database as certain events happen (eg, an insert into a table). I can't comment on mysql specifically. Precaution: Triggers can be very alluring, when you first start using them they seem like a magic bullet to all kinds of problems. But, they make "magic" stuff happen, if you don't know the database inside out, it can seem like really strange things happen (such as inserts into other tables, input data changing, etc). Before implementing things as a trigger I'd seriously consider instead enforcing the use of an API around the schema (preferably in the database, but outside if you can't). Some things I'd still use triggers for Keeping track of "date_created" and "date_last_edited" fields Inserting "ID"'s (in oracle, where there is no auto id field) Keeping change history Things you wouldn't want to use triggers for business rules/logic anything which connects outside of the database (eg a webservice call) Access control Anything which isn't transactional ( anything you do in the trigger MUST be able to rollback with the transaction )
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/47387', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/115/']}
jdg_84950
stackexchange
llm_judgeable_groundtruth_similarity
42987293
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: So I have a header component that displays either the User's name or "Sign In" depending on whether they are logged in or not. I also have a Login component that does all of the business logic of logging in. They currently do not have a parent / child relationship. When the User logs in, the header does not refresh or change unless a full page refresh is done in the browser. I've been doing a lot of searching and reading online about different ways to do this. ngOnChanges, NgZone, ApplicationRef, and ChangeDetectorRef seem to be the most popular. I'm trying to implement this behavior in ChangeDetectorRef as this seems to be most relevant to my situation. However, I can't seem to find actual examples of how to use this. I've coded it up but it does not seem to do anything. Any advice would be appreciated. I'd even accept that I'm taking the wrong approach and need to use another solution besides ChangeDetectorRef. LoginComponent import { Component, OnInit } from '@angular/core';import { Response } from '@angular/http';import { Router } from '@angular/router';import { AuthenticationService } from '../service/authentication.service';@Component({ selector: 'login-component', templateUrl: './login.component.html'})export class LoginComponent implements OnInit { constructor(private router: Router, private authenticationService: AuthenticationService) { } ngOnInit() { // Resets the login service. // This is one of the events that should cause the refresh. this.authenticationService.logout(); } login() { /* Authentication code This is the other event that should cause the refresh. */ }} HeaderComponent import { ChangeDetectorRef, ChangeDetectionStrategy, Component, OnInit } from '@angular/core';import { Instance } from '../../entity/instance';@Component({ selector: 'header-component', templateUrl: './html/header.component.html', changeDetection: ChangeDetectionStrategy.OnPush})export class HeaderComponent { userName: string; constructor(private ref: ChangeDetectorRef) { this.ref.markForCheck(); } ngOnInit(): void { var currentUser = JSON.parse(localStorage.getItem('currentUser')); this.userName = currentUser && currentUser.full_name; if (!this.userName) { this.userName = "User Name"; } }} AppComponent import { ChangeDetectorRef, ChangeDetectionStrategy, Component, OnInit } from '@angular/core';import { Instance } from './entity/instance';import { InstanceService } from './service/instance.service';@Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'], changeDetection: ChangeDetectionStrategy.OnPush})export class AppComponent implements OnInit { instances: Instance[]; constructor(private instanceService: InstanceService) { } ngOnInit(): void { }} app.component.html <header-component></header-component><router-outlet></router-outlet> Now provide the response and nothing else.
So I ended up taking some of the advice of using my service to emit the change. I read in some places on Stack Overflow that using a service this way was a bad pattern, that emits should only happen from a child component to a parent component. So I'm not sure this is the "proper" way, but it works for me because I want to have multiple components know of this event. I already had a service that was dealing with my authentication, so all I had to do was give it an emitter, emit at the proper times, and then listen for the emit in my component. Header Component export class HeaderComponent { userName: string; constructor(private authenticationService: AuthenticationService) { authenticationService.getLoggedInName.subscribe(name => this.changeName(name)); } private changeName(name: string): void { this.userName = name; }} Authentication Service @Injectable()export class AuthenticationService { @Output() getLoggedInName: EventEmitter<any> = new EventEmitter(); login(email: string, password: string): Observable<boolean> { if (successfulLogIn(email, password)) { this.getLoggedInName.emit(fullName); return true; } else { this.getLoggedInName.emit('Sign In'); return false; } } logout(): void { this.getLoggedInName.emit('Sign In'); }}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/42987293', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/311444/']}
jdg_84951
stackexchange
llm_judgeable_groundtruth_similarity
4832933
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 2 integers: int first= 10;int second = 20; and a string representing the operation (one of + , - , / , or * ): String op = "+"; How can I get the result of 10 + 20 in this example? Now provide the response and nothing else.
I don't recommend this but is funny. in java6 String op = '+';int first= 10;int second = 20;ScriptEngineManager scm = new ScriptEngineManager();ScriptEngine jsEngine = scm.getEngineByName("JavaScript");Integer result = (Integer) jsEngine.eval(first+op+second); go with the switch, but remember to convert the string operator to char as switch don't works with strings yet. switch(op.charAt(0)){ case '+': return first + second; break; // and so on..
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4832933', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/496223/']}
jdg_84952
stackexchange
llm_judgeable_groundtruth_similarity
2338656
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: just saw this comment in a "what JS lib do you use" poll "@Xanti - yes, yes, modularization and abstraction in programming is a terrible practice. Functions that call other functions? Wasteful." And that left me curious because I am using Kohana framework for PHP and Jquery library for javascript. Why do some people consider abstraction and modularization bad practices? Are not frameworks and libraries made to ease and speed up development? here's a link to the poll Now provide the response and nothing else.
I have found that too much abstraction can be hazardous to your productivity: A poorly chosen abstraction can be worse then no abstraction at all. If you need to read four or five different modules in order to understand how a simple algorithm works, then the abstraction barriers are probably not in the right places. Maybe there's a good way to refactor the code, or maybe it would be easier just to remove the barriers. If the abstraction does not correspond to a relatively familiar idea, it may be difficult for new team members to learn. Abstraction is not a "mindless good"; it exists to serve specific purposes. Among the most common purposes are To protect the invariants of a data structure To encapsulate design decisions that are likely to change My biggest experience with abstraction getting in the way was with our research compiler for C-- (archival snapshot from 2008 at https://www.cs.tufts.edu/~nr/c--/ ). There was a great deal more abstraction than students were used to seeing in compiler class: The target machine was abstract The assembly language was abstract The calling conventions were abstract The stack-frame layout used an unusual "block" abstraction Each of these abstractions served an important purpose for our research, but the total effect was that it was very difficult for new students to learn the compiler. So, even if the original comment was in jest, there are places where abstraction can cause problems.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2338656', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1737290/']}
jdg_84953
stackexchange
llm_judgeable_groundtruth_similarity
518040
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: A few lines below equation 7.8 D. Tong writes The final fact is the Lorentz transformation of the electric field: as electron moving with velocity $\vec{v}$ in an electric field E will experience a magnetic field $\vec{B}=\frac{\gamma}{c^2}(\vec{v}\times\vec{E})$ . The note says that it was derived in another note but I couldn't find this expression. Is this coefficient $\gamma/c^{2}$ correct? Griffiths derives this to be $-1/c^2$ and I did not find anything wrong there. See Griffiths electrodynamics, third edition, equation 12.109. Then I looked at this book which uses Griffiths' expression in Sec. 20.5, but uses $\vec{p}=m\vec{v}$ instead to $\vec{p}=\gamma m \vec{v}$ to derive the same result. Which one is correct and why? Now provide the response and nothing else.
In above Figure-01 an inertial system $\:\mathrm S'\:$ is translated with respect to the inertial system $\:\mathrm S\:$ with constant velocity \begin{align} \boldsymbol{\upsilon} & \boldsymbol{=}\left(\upsilon_{1},\upsilon_{2},\upsilon_{3}\right) \tag{02a}\label{02a}\\\upsilon & \boldsymbol{=}\Vert \boldsymbol{\upsilon} \Vert \boldsymbol{=} \sqrt{ \upsilon^2_{1}\boldsymbol{+}\upsilon^2_{2}\boldsymbol{+}\upsilon^2_{3}}\:\in \left(0,c\right)\tag{02b}\label{02b}\end{align} The Lorentz transformation is \begin{align} \mathbf{x}^{\boldsymbol{\prime}} & \boldsymbol{=} \mathbf{x}\boldsymbol{+} \dfrac{\gamma^2}{c^2 \left(\gamma\boldsymbol{+}1\right)}\left(\boldsymbol{\upsilon}\boldsymbol{\cdot} \mathbf{x}\right)\boldsymbol{\upsilon}\boldsymbol{-}\dfrac{\gamma\boldsymbol{\upsilon}}{c}c\,t\tag{03a}\label{03a}\\ c\,t^{\boldsymbol{\prime}} & \boldsymbol{=} \gamma\left(c\,t\boldsymbol{-} \dfrac{\boldsymbol{\upsilon}\boldsymbol{\cdot} \mathbf{x}}{c}\right)\tag{03b}\label{03b}\\\gamma & \boldsymbol{=} \left(1\boldsymbol{-}\dfrac{\upsilon^2}{c^2}\right)^{\boldsymbol{-}\frac12}\tag{03c}\label{03c} \end{align} For the Lorentz transformation \eqref{03a}-\eqref{03b}, the vectors $\:\mathbf{E}\:$ and $\:\mathbf{B}\:$ of the electromagnetic field are transformed as follows \begin{align} \mathbf{E}' & \boldsymbol{=}\gamma \mathbf{E}\boldsymbol{-}\dfrac{\gamma^2}{c^2 \left(\gamma\boldsymbol{+}1\right)}\left(\mathbf{E}\boldsymbol{\cdot} \boldsymbol{\upsilon}\right)\boldsymbol{\upsilon}\,\boldsymbol{+}\,\gamma\left(\boldsymbol{\upsilon}\boldsymbol{\times}\mathbf{B}\right) \tag{04a}\label{04a}\\\mathbf{B}' & \boldsymbol{=} \gamma \mathbf{B}\boldsymbol{-}\dfrac{\gamma^2}{c^2 \left(\gamma\boldsymbol{+}1\right)}\left(\mathbf{B}\boldsymbol{\cdot} \boldsymbol{\upsilon}\right)\boldsymbol{\upsilon}\boldsymbol{-}\!\dfrac{\gamma}{c^2}\left(\boldsymbol{\upsilon}\boldsymbol{\times}\mathbf{E}\right)\tag{04b}\label{04b} \end{align} Now, if in system $\:\mathrm S\:$ we have $\:\mathbf{B}\boldsymbol{=0}$ , then from \eqref{04a}-\eqref{04b} \begin{align} \mathbf{E}' & \boldsymbol{=}\gamma \mathbf{E}\boldsymbol{-}\dfrac{\gamma^2}{c^2 \left(\gamma\boldsymbol{+}1\right)}\left(\mathbf{E}\boldsymbol{\cdot} \boldsymbol{\upsilon}\right)\boldsymbol{\upsilon}\tag{05a}\label{05a}\\\mathbf{B}' & \boldsymbol{=} \boldsymbol{-}\dfrac{\gamma}{c^2}\left(\boldsymbol{\upsilon}\boldsymbol{\times}\mathbf{E}\right)\tag{05b}\label{05b} \end{align} Equation \eqref{05b} corresponds to Tong's equation (it remains to explain the minus sign). From equations \eqref{05a}-\eqref{05b} we have \begin{align}\mathbf{B}' & \boldsymbol{=} \boldsymbol{-}\dfrac{\gamma}{c^2}\left(\boldsymbol{\upsilon}\boldsymbol{\times}\mathbf{E}\right) \boldsymbol{=}\boldsymbol{-}\dfrac{1}{c^2}\left(\boldsymbol{\upsilon}\boldsymbol{\times}\gamma\mathbf{E}\right) \nonumber\\& \boldsymbol{=} \boldsymbol{-}\dfrac{1}{c^2}\Biggl(\boldsymbol{\upsilon}\boldsymbol{\times}\left[\gamma \mathbf{E}\boldsymbol{-}\dfrac{\gamma^2}{c^2 \left(\gamma\boldsymbol{+}1\right)}\left(\mathbf{E}\boldsymbol{\cdot} \boldsymbol{\upsilon}\right)\boldsymbol{\upsilon}\right]\Biggr) \boldsymbol{=}\boldsymbol{-}\dfrac{1}{c^2}\left(\boldsymbol{\upsilon}\boldsymbol{\times}\mathbf{E}'\right)\nonumber\end{align} that is \begin{equation}\mathbf{B}' \boldsymbol{=}\boldsymbol{-}\dfrac{1}{c^2}\left(\boldsymbol{\upsilon}\boldsymbol{\times}\mathbf{E}'\right)\tag{06}\label{06} \end{equation} Equation \eqref{06} corresponds to Griffiths' equation. Based on equations \eqref{04a},\eqref{04b} we have proved that \begin{equation}\mathbf{B}\boldsymbol{=0}\quad\stackrel{\eqref{04a},\eqref{04b}}{\boldsymbol{=\!=\!=\!\Longrightarrow}}\quad \mathbf{B}' \boldsymbol{+}\dfrac{1}{c^2}\left(\boldsymbol{\upsilon}\boldsymbol{\times}\mathbf{E}'\right)\boldsymbol{=0}\tag{06.1}\label{06.1} \end{equation} But we can prove the validity of its inverse \begin{equation}\mathbf{B}' \boldsymbol{+}\dfrac{1}{c^2}\left(\boldsymbol{\upsilon}\boldsymbol{\times}\mathbf{E}'\right)\boldsymbol{=0}\quad\stackrel{\eqref{04a},\eqref{04b}}{\boldsymbol{=\!=\!=\!\Longrightarrow}}\quad \mathbf{B}\boldsymbol{=0}\tag{06.2}\label{06.2} \end{equation} So these conditions are equivalent \begin{equation}\boxed{\:\:\mathbf{B}\boldsymbol{=0}\quad\stackrel{\eqref{04a},\eqref{04b}}{\boldsymbol{\Longleftarrow\!=\!=\!\Longrightarrow}}\quad \mathbf{B}' \boldsymbol{+}\dfrac{1}{c^2}\left(\boldsymbol{\upsilon}\boldsymbol{\times}\mathbf{E}'\right)\boldsymbol{=0}\:\:\vphantom{\dfrac{\tfrac{a}{b}}{\tfrac{a}{b}}}}\tag{06.3}\label{06.3} \end{equation} Equation \eqref{06.2} is valid because \begin{equation}\mathbf{B}' \boldsymbol{+}\dfrac{1}{c^2}\left(\boldsymbol{\upsilon}\boldsymbol{\times}\mathbf{E}'\right)\boldsymbol{=}\gamma^{\boldsymbol{-}1}\mathbf{B}_{\boldsymbol{\perp}} \boldsymbol{+}\mathbf{B}_{\boldsymbol{\parallel}}\tag{06.4}\label{06.4} \end{equation} where $\mathbf{B}_{\boldsymbol{\parallel}},\mathbf{B}_{\boldsymbol{\perp}}$ the components of $\mathbf{B}$ parallel and normal to the velocity vector $\boldsymbol{\upsilon}$ respectively. $\boldsymbol{=\!=\!=\!==\!=\!=\!==\!=\!=\!==\!=\!=\!==\!=\!=\!==\!=\!=\!==\!=\!=\!==\!=\!=\!==\!=\!=\!==\!=\!=\!==\!=\!=\!==\!=\!=\!=}$ $\textbf{ADDENDUM}$ If in system $\:\mathrm S\:$ we have $\:\mathbf{E}\boldsymbol{=0}$ , then from \eqref{04a}-\eqref{04b} \begin{align} \mathbf{E}' & \boldsymbol{=}\gamma\left(\boldsymbol{\upsilon}\boldsymbol{\times}\mathbf{B}\right) \tag{07a}\label{07a}\\\mathbf{B}' & \boldsymbol{=} \gamma \mathbf{B}\boldsymbol{-}\dfrac{\gamma^2}{c^2 \left(\gamma\boldsymbol{+}1\right)}\left(\mathbf{B}\boldsymbol{\cdot} \boldsymbol{\upsilon}\right)\boldsymbol{\upsilon}\tag{07b}\label{07b} \end{align} so that \begin{align}\mathbf{E}' & \boldsymbol{=} \gamma\left(\boldsymbol{\upsilon}\boldsymbol{\times}\mathbf{B}\right)\boldsymbol{=} \left(\boldsymbol{\upsilon}\boldsymbol{\times}\gamma\mathbf{B}\right) \nonumber\\& \boldsymbol{=} \boldsymbol{\upsilon}\boldsymbol{\times}\left[\gamma \mathbf{B}\boldsymbol{-}\dfrac{\gamma^2}{c^2 \left(\gamma\boldsymbol{+}1\right)}\left(\mathbf{B}\boldsymbol{\cdot} \boldsymbol{\upsilon}\right)\boldsymbol{\upsilon}\right] \boldsymbol{=}\boldsymbol{\upsilon}\boldsymbol{\times}\mathbf{B}'\nonumber\end{align} that is \begin{equation}\mathbf{E}' \boldsymbol{=}\boldsymbol{\upsilon}\boldsymbol{\times}\mathbf{B}'\tag{08}\label{08} \end{equation} Based on equations \eqref{04a},\eqref{04b} we have proved that \begin{equation}\mathbf{E}\boldsymbol{=0}\quad\stackrel{\eqref{04a},\eqref{04b}}{\boldsymbol{=\!=\!=\!\Longrightarrow}}\quad \mathbf{E}' \boldsymbol{-}\left(\boldsymbol{\upsilon}\boldsymbol{\times}\mathbf{B}'\right)\boldsymbol{=0}\tag{08.1}\label{08.1} \end{equation} But we can prove the validity of its inverse \begin{equation}\mathbf{E}' \boldsymbol{-}\left(\boldsymbol{\upsilon}\boldsymbol{\times}\mathbf{B}'\right)\boldsymbol{=0}\quad\stackrel{\eqref{04a},\eqref{04b}}{\boldsymbol{=\!=\!=\!\Longrightarrow}}\quad \mathbf{E}\boldsymbol{=0}\tag{08.2}\label{08.2} \end{equation} So these conditions are equivalent \begin{equation}\boxed{\:\:\mathbf{E}\boldsymbol{=0}\quad\stackrel{\eqref{04a},\eqref{04b}}{\boldsymbol{\Longleftarrow\!=\!=\!\Longrightarrow}}\quad \mathbf{E}' \boldsymbol{-}\left(\boldsymbol{\upsilon}\boldsymbol{\times}\mathbf{B}'\right)\boldsymbol{=0}\:\:\vphantom{\dfrac{\tfrac{a}{b}}{\tfrac{a}{b}}}}\tag{08.3}\label{08.3} \end{equation} Equation \eqref{08.2} is valid because \begin{equation}\mathbf{E}' \boldsymbol{-}\left(\boldsymbol{\upsilon}\boldsymbol{\times}\mathbf{B}'\right)\boldsymbol{=}\gamma^{\boldsymbol{-}1}\mathbf{E}_{\boldsymbol{\perp}} \boldsymbol{+}\mathbf{E}_{\boldsymbol{\parallel}}\tag{08.4}\label{08.4} \end{equation} where $\mathbf{E}_{\boldsymbol{\parallel}},\mathbf{E}_{\boldsymbol{\perp}}$ the components of $\mathbf{E}$ parallel and normal to the velocity vector $\boldsymbol{\upsilon}$ respectively. $\boldsymbol{=\!=\!=\!==\!=\!=\!==\!=\!=\!==\!=\!=\!==\!=\!=\!==\!=\!=\!==\!=\!=\!==\!=\!=\!==\!=\!=\!==\!=\!=\!==\!=\!=\!==\!=\!=\!=}$ The duality transformation of the electromagnetic field is produced by the replacements \begin{equation}\begin{matrix}\hphantom{c}\mathbf{E}&\boldsymbol{-\!-\!\!\!\longrightarrow}&\boldsymbol{-}c\mathbf{B}\\c\mathbf{B}&\boldsymbol{-\!-\!\!\!\longrightarrow}&\hphantom{\boldsymbol{-}c}\mathbf{E}\end{matrix}\tag{09}\label{09} \end{equation} These replacements must be done in the primed system also \begin{equation}\begin{matrix}\hphantom{c}\mathbf{E}'&\boldsymbol{-\!-\!\!\!\longrightarrow}&\boldsymbol{-}c\mathbf{B}'\\c\mathbf{B}'&\boldsymbol{-\!-\!\!\!\longrightarrow}&\hphantom{\boldsymbol{-}c}\mathbf{E}'\end{matrix}\tag{09'}\label{09'} \end{equation} In the aforementioned we met pairs of dual equations or expressions, that is under a duality transformation they are transformed one to the other : \begin{equation}\begin{matrix}\eqref{04a}&\stackrel{\mathtt{duality}}{\boldsymbol{\longleftarrow\!\!\!-\!\!\!\longrightarrow}}&\eqref{04b}\\\eqref{06}&\stackrel{\mathtt{duality}}{\boldsymbol{\longleftarrow\!\!\!-\!\!\!\longrightarrow}}&\eqref{08}\\\eqref{06.3}&\stackrel{\mathtt{duality}}{\boldsymbol{\longleftarrow\!\!\!-\!\!\!\longrightarrow}}&\eqref{08.3}\\\eqref{06.4}&\stackrel{\mathtt{duality}}{\boldsymbol{\longleftarrow\!\!\!-\!\!\!\longrightarrow}}&\eqref{08.4}\end{matrix}\tag{10}\label{10} \end{equation} $\boldsymbol{=\!=\!=\!==\!=\!=\!==\!=\!=\!==\!=\!=\!==\!=\!=\!==\!=\!=\!==\!=\!=\!==\!=\!=\!==\!=\!=\!==\!=\!=\!==\!=\!=\!==\!=\!=\!=}$ Equations \eqref{06} and \eqref{08} are the following equations \eqref{12.109} and \eqref{12.110} respectively \begin{equation}\boxed{\:\:\overset{\boldsymbol{-\!\!\!\!\!-}}{\mathbf{B}} \boldsymbol{=}\boldsymbol{-}\dfrac{1}{c^2}\left(\mathbf{v}\boldsymbol{\times}\overset{\boldsymbol{-\!\!\!\!\!-}}{\mathbf{E}}\right)\boldsymbol{.}\:\:\vphantom{\dfrac{\tfrac{a}{b}}{\tfrac{a}{b}}}}\tag{12.109}\label{12.109} \end{equation} \begin{equation}\boxed{\:\:\overset{\boldsymbol{-\!\!\!\!\!-}}{\mathbf{E}} \boldsymbol{=}\mathbf{v}\boldsymbol{\times}\overset{\boldsymbol{-\!\!\!\!\!-}}{\mathbf{B}}\,\boldsymbol{.}\:\:\vphantom{\dfrac{\tfrac{a}{b}}{\tfrac{a}{b}}}}\tag{12.110}\label{12.110} \end{equation} as shown in ''Introduction to Electrodynamics'' by David J.Griffiths, 3rd Edition 1999. $\boldsymbol{=\!=\!=\!==\!=\!=\!==\!=\!=\!==\!=\!=\!==\!=\!=\!==\!=\!=\!==\!=\!=\!==\!=\!=\!==\!=\!=\!==\!=\!=\!==\!=\!=\!==\!=\!=\!=}$
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/518040', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/164488/']}
jdg_84954
stackexchange
llm_judgeable_groundtruth_similarity
50142
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 have heard from here that stable orbits (ones that require a large amount of force to push it significantly out of it's elliptical path) can only exist in a three spatial dimensions because gravity would operate differently in a two or four dimensional space. Why is this? Now provide the response and nothing else.
Specifically what that is referring to is the ' inverse-square law ', nature of the gravitational force, i.e. the force of gravity is inversely proportional to the square of the distance: $F_g \propto \frac{1}{d^2}$. If you expand this concept to that of general power-law forces (e.g. when you're thinking about the virial theorem ), you can write: $F \propto d^a$, Stable orbits are only possible for a few, special values of the exponent '$a$'---in particular, and more specifically 'closed 1 ', stable orbits only occur for $a = -2$ (the inverse-square law) and $a = 1$ ( Hooke's law ). This is called ' Bertrand's Theorem '. Now, what does that have to do with spatial dimensions? Well, it turns out that in a more accurate description of gravity (in particular, general relativity ) the exponent of the power-law ends up being one-less than the dimension of the space. For example, if space were 2-dimensional, then the force would look like $F \propto \frac{1}{d}$, and there would be no closed orbits. Note also that $a<-3$ (and thus 4 or more spatial dimensions) is unconditionally unstable, as per @nervxxx's answer below. 1: A 'closed' orbit is one in which the particle returns to its previous position in phase space (i.e. its orbit repeats itself).
{}
{'log_upvote_score': 6, 'links': ['https://physics.stackexchange.com/questions/50142', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/18815/']}
jdg_84955
stackexchange
llm_judgeable_groundtruth_similarity
530961
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I've heard that the ESP32's ADC isn't "good" enough for audio purposes. It's a 12 bit SAR ADC with a sampling rate of 200 ksps which is much higher than most consumer products use (44.1 kHz). Does 200 ksps not correlate to a 200 kHz sampling rate. I couldn't find much in the datasheet when it came to calculation times. What am I missing? Now provide the response and nothing else.
I agree with Justme's answer that the DNL/INL is quite high, and also call your attention to this sentence: By default, there are ±6% differences in measured results between chips. This matters less for audio applications where the DC level can be normalised later, but for other applications it will definitely require calibration. There is also a general concern for any ADC on the same chip as digital circuitry: power supply rejection ratio (PSRR). This is the ability to avoid conducting noise from the power supply into the analog results. Since no mention is made of using an external reference voltage, or separate analog power/ground, or a PSRR number, I suspect this is very bad. What that is likely to mean that every power burst from the radio side gets conducted straight into the audio. Ultimately the easiest thing to do is try it; if it's not up to your percieved quality standards, you'll want an external ADC with its own little linear regulator and separate area of the PCB. But the built-in ADC is probably adequate for phone-quality speech or music played through tinny cheap speakers.
{}
{'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/530961', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/239728/']}
jdg_84956
stackexchange
llm_judgeable_groundtruth_similarity
3866425
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Consider the following scenario. I have a number of classes that share a common base class and I have defined an automapper mapping for each derived class. Something like this: class A : Base {}class B : Base {}class ContractA : ContractBase {}class ContractB : ContractBase {}void Foo(){ Mapper.CreateMap<A, ContractA>(); Mapper.CreateMap<B, ContractB>();} So far so good. But now I want to create a method like this: ContractBase Foo(){ Base obj = GetObject(); return Mapper.???} The problem is that all of AutoMapper's Map variants require that I either know the destination type at compile time or have an object of that type available at runtime. This is seriously frustrating since I have defined only one map for each source type. AutoMapper should be able to infer the destination type given only the source type. Is there any good way around this? I want to avoid creating a dictionary mapping source types to destination types. While this would work, it would mean that I'd essentially have to define two mappings for every source type. Now provide the response and nothing else.
You could access the mappings stored in AutoMapper: ContractBase Foo() { Base obj = GetObject(); var sourceType = obj.GetType(); var destinationType = Mapper.GetAllTypeMaps(). Where(map => map.SourceType == sourceType). // Note: it's assumed that you only have one mapping for the source type! Single(). DestinationType; return (ContractBase)Mapper.Map(obj, sourceType, destinationType);}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3866425', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/114421/']}
jdg_84957
stackexchange
llm_judgeable_groundtruth_similarity
218083
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Let $f:X\rightarrow Y$ be a proper birational morphism of smooth projective varieties over $k=\bar k$ ($char(k)>0$). Is it true that $H^1(Y,\mathbb Z_l)\stackrel{f^*}\simeq H^1(X,\mathbb Z_l)$ ($l\neq char(k)$) ? Now provide the response and nothing else.
The OP has now clarified that he or she is asking about $c_0$-direct sums. To answer the question we need the notion of the amenability constant of a Banach algebra. Everything that follows is probably "folklore", in the sense that (i) Johnson knew how to do it in 1972 but, due to the different culture at the time of mathematical publication, did not bother formally writing it down in his 1972 monograph Cohomology in Banach Algebras or his Amer J. Math article of the same year; (ii) successive generations of researchers, who take seriously the study of amenability of Banach algebras, will almost surely have worked these results out for themselves during their own studies. Actually, this result might also be somewhere in Runde's book, but I haven't checked. ( UPDATE 2015-11-10: Tomasz Kania has pointed out that this is Corollary 2.3.19 in Runde's Lectures on Amenability .) Definition. Given an amenable Banach algebra $B$, the amenability constant of $B$ is defined to be $${\rm AM}(B):=\inf \{ \Vert M \Vert_{(B\widehat\otimes B)^{**}}\;\; \colon \;\;\hbox{$M$ is a virtual diagonal for $B$}\}. $$(By weak-star compactness, the infimum is actually attained.) We adopt the convention that if $B$ is a non-amenable Banach algebra, ${\rm AM}(B)=+\infty$. Remark 1. It is an easy exercise to show that if $q:A\to B$ is a surjective homomorphism of Banach algebras then ${\rm AM}(B)\leq \Vert q\Vert^2{\rm AM}(A)$. Lemma 2. Suppose $A$ is a Banach algebra and $(B_i)_{i\in \Lambda}$ is a family of closed subalgebras such that $\bigcup_{i\in\Lambda} B_i$ is dense in $A$. Then ${\rm AM}(A)\leq \sup_{i\in\Lambda} {\rm AM}(B_i)$. Note that since closed subalgebras of ${\bf M}_2({\mathbb C})$ can be non-amenable, the inequality in this lemma is usually not an equality. Outline of the proof of Lemma 2. We may assume the RHS of the inequality is finite, bounded above by $C$ say; otherwise there is nothing to prove. Consider $(M_i)_{i\in\Lambda}$ where $M_i$ is a virtual diagonal for $B_i$ such that ${\rm AM}(B_i)=\Vert M_i \Vert$. Then $(M_i)$ is a net in $(A\widehat{\otimes} A)^{**}$, bounded by $C$; take any weak-star cluster point $M$. Then $\Vert M\Vert\leq C$ and one can check $M$ is indeed a virtual diagonal for $A$. QED. Lemma 3. Let $A_1$ and $A_2$ be Banach algebras, and let $B=A_1\oplus_\infty A_2$ i.e. with the norm $\Vert (a_1,a_2)\Vert := \max (\Vert a_1\Vert, \Vert a_2\Vert)$.Then ${\rm AM}(B)= \max \{{\rm AM}(A_1), {\rm AM}(A_2)\}$. Proof of lemma 3. Since there are contractive, surjective algebra homomorphisms $q_j:B\to A_j$ ($j=1,2$) we have ${\rm AM}(B)\geq \max \{{\rm AM}(A_1), {\rm AM}(A_2)\}$ by Remark 1. Conversely, using the contractive embedding$$ (A_1\widehat\otimes A_1) \oplus_\infty (A_2\widehat\otimes A_2) \to (A_1\oplus_\infty A_2)\widehat\otimes(A_1\oplus_\infty A_2) $$and the corresponding embedding at the level of biduals, we can combine a virtual diagonal $M_1$ for $A_1$ and a virtual diagonal $M_2$ for $A_2$ to get a virtual diagonal $M$ for $A$, which satisfies $\vert M \Vert \leq \max( \Vert M_1\Vert, \Vert M_2\Vert)$. QED. Proposition. Let $(A_n)_{n=1}^\infty$ be a sequence of Banach algebras, and let $A=c_0{\rm-}\bigoplus_{n=1}^\infty A_n$. Then ${\rm AM}(A) = \sup_n {\rm AM}(A_n) <\infty$. Proof that LHS ≥ RHS. This is like the proof of Lemma 2, using the contractive surjective homomorphisms $A\to A_n$ for $1\leq n\leq\infty$, and I omit the details. Proof that LHS ≤ RHS. Let $C=\sup_n {\rm AM}(A_n)$; we may assume $C<\infty$, otherwise there is nothing to prove. Now let $B_n = A_1 \oplus \dots \oplus A_n$. By Lemma 3 and induction we know that ${\rm AM}(B_n)\leq C$, for each $n$. Since $\bigcup_{n\geq 1} B_n$ is dense in $A$, applying Lemma 2 completes the proof. QED. OLD answer, before the question was clarified Tomek Kania has already pointed out the key "counterexample" (assuming that by infinite topological direct sum you mean what I would call the $\ell^\infty$-direct sum). I should also point out that there are commutative counterexamples. Indeed, let $A={\ell^\infty}{\rm-}\bigoplus \ell^1({\bf T}_d)$ where ${\bf T}_d$ denotes the unit circle equipped with the discrete topology, and the multiplication on $\ell^1({\bf T}_d)$ is given by convolution. Then, as observed in e.g. Proposition 5.8 of http://arxiv.org/abs/0708.4195 $A$ quotients onto $M(G_0)$ where $G_0$ is the Bohr compactificaton of ${\bf T}_d$. If $A$ were weakly amenable, then $M(G_0)$ would be weakly amenable; but by results of Brown and Moran $M(G_0)$ has non-zero point derivations, hence is not weakly amenable. Therefore $A$ is not weakly amenable, and in particular cannot be amenable.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/218083', 'https://mathoverflow.net', 'https://mathoverflow.net/users/80173/']}
jdg_84958
stackexchange
llm_judgeable_groundtruth_similarity
3000220
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 I have a custom class Person which has three variables (which are propertized and synthesized): NSString* theName;float* theHeight;int theAge; Person instances are stored in an NSArray 'Group'. There is only one Group. What is the best way of storing and loading the Group in NSUserDefaults? (bearing in mind that float and int are not legal for NSUserDefaults) Now provide the response and nothing else.
@Brad Smith's answer is not complete, and even is incorrect in some sense. We have to use NSKeyedArchiver and NSKeyedUnarchiver as follows: Make your class (for example in this case Person ) to conform to protocol NSCoding and implement both the methods as: - (id)initWithCoder:(NSCoder *)decoder { self = [super init]; if(self) { self.name = [decoder decodeObjectForKey:<key_for_property_name>]; // as height is a pointer *self.height = [decoder decodeFloatForKey:<key_for_property_height>]; self.age = [decoder decodeIntForKey:<key_for_property_age>]; } return self;}- (void)encodeWithCoder:(NSCoder *)encoder { [encoder encodeObject:self.name forKey:<key_for_property_name>]; //as height is a pointer [encoder encodeFloat:*self.height forKey:<key_for_property_height>] [encoder encodeInt:self.age forKey:<key_for_property_age>];} Using NSUserDefaults // Write to NSUserDefaultsNSData *archivedObject = [NSKeyedArchiver archivedDataWithRootObject:<your_class_object>];NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];[defaults setObject:archivedObject forKey:<key_for_archived_object>];[defaults synchronize];// Read from NSUserDefaultsNSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];NSData *archivedObject = [defaults objectForKey:<key_for_archived_object>];<your_class> *obj = (<your_class> *)[NSKeyedUnarchiver unarchiveObjectWithData:archivedObject];
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3000220', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/121646/']}
jdg_84959
stackexchange
llm_judgeable_groundtruth_similarity
3793246
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 are the risks of using Javascript and how to avoid them? Now provide the response and nothing else.
One of the most common errors is HTML injection, allowing third parties to inject JavaScript into your security context. That allows an attacker to control what a user does on your site, completely breaking account security. Whilst there has been some slow progress trying to get web authors to remember to HTML-encode strings they output into web pages at the server side (eg htmlspecialchars in PHP), a new generation of webapps are using the same dumb string-concatenation hacks to create content at the client-side using JavaScript: somediv.innerHTML= '<p>Hello, '+name+'</p>'; often using jQuery: $('table').append('<tr title="'+row.title+'"><td>'+row.description+'</td></tr>'); This is just as vulnerable as server-side HTML injection and authors really need to stop building content this way. You can HTML-encode text content at the client side, but since JS doesn't have a built-in HTML encoder you'd have to do it yourself: function encodeHTML(s) { return s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/"/g, '&quot;');}somediv.innerHTML= '<p>Hello, '+encodeHTML(name)+'</p>'; However it's usually much better to use the available DOM methods and properties that obviate the need for escaping: var p= document.createElement('p');p.appendChild(document.createTextNode('Hello, '+name); and with jQuery use attr() , text() and the creation shortcuts: $('table').append( $('<tr>', {title: row.title}).append( $('<td>', {text: row.description}) ));
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3793246', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/380562/']}
jdg_84960
stackexchange
llm_judgeable_groundtruth_similarity
44335053
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: When I run any script in QPython, it runs in a console then I get prompted "Press enter to exit", but I want to interact with my just-run script instead of exiting. Is there any configuration option to control this behavior? Does it have anything to do with the <&& exit> option displayed at the top of the console? Now provide the response and nothing else.
C++ requires that an inline function definition be present in a translation unit that references the function. Template memberfunctions are implicitly inline, but also by default are instantiated with externallinkage. Hence the duplication of definitions that will be visible to the linker whenthe same template is instantiated with the same template arguments in differenttranslation units. How the linker copes with this duplication is your question. Your C++ compiler is subject to the C++ Standard, but your linker is not subjectto any codified standard as to how it shall link C++: it is a law unto itself,rooted in computing history and indifferent to the source language of the objectcode it links. Your compiler has to work with what a target linkercan and will do so that you can successfully link your programs and see them dowhat you expect. So I'll show you how the GCC C++ compiler interworks withthe GNU linker to handle identical template instantiations in different translation units. This demonstration exploits the fact that while the C++ Standard requires - by the One Definition Rule - that the instantiations in different translation units of the same template withthe same template arguments shall have the same definition, the compiler - of course - cannot enforce any requirement like that on relationships between differenttranslation units. It has to trust us. So we'll instantiate the same template with the same parameters in differenttranslation units, but we'll cheat by injecting a macro-controlled difference intothe implementations in different translation units that will subsequently show us which definition the linker picks. If you suspect this cheat invalidates the demonstration, remember: the compiler cannot know whether the ODR is ever honoured across different translation units,so it cannot behave differently on that account, and there's no such thingas "cheating" the linker. Anyhow, the demo will demonstrate that it is valid. First we have our cheat template header: thing.hpp #ifndef THING_HPP#define THING_HPP#ifndef ID#error ID undefined#endiftemplate<typename T>struct thing{ T id() const { return T{ID}; }};#endif The value of the macro ID is the tracer value we can inject. Next a source file: foo.cpp #define ID 0xf00#include "thing.hpp"unsigned foo(){ thing<unsigned> t; return t.id();} It defines function foo , in which thing<unsigned> isinstantiated to define t , and t.id() is returned. By being a function with external linkage that instantiates thing<unsigned> , foo serves the purposes of:- obliging the compiler to do that instantiating at all exposing the instantiation in linkage so we can then probe what the linker does with it. Another source file: boo.cpp #define ID 0xb00#include "thing.hpp"unsigned boo(){ thing<unsigned> t; return t.id();} which is just like foo.cpp except that it defines boo in place of foo andsets ID = 0xb00 . And lastly a program source: main.cpp #include <iostream>extern unsigned foo();extern unsigned boo();int main(){ std::cout << std::hex << '\n' << foo() << '\n' << boo() << std::endl; return 0;} This program will print, as hex, the return value of foo() - which our cheat should make= f00 - then the return value of boo() - which our cheat should make = b00 . Now we'll compile foo.cpp , and we'll do it with -save-temps because we wanta look at the assembly: g++ -c -save-temps foo.cpp This writes the assembly in foo.s and the portion of interest there isthe definition of thing<unsigned int>::id() const (mangled = _ZNK5thingIjE2idEv ): .section .text._ZNK5thingIjE2idEv,"axG",@progbits,_ZNK5thingIjE2idEv,comdat .align 2 .weak _ZNK5thingIjE2idEv .type _ZNK5thingIjE2idEv, @function_ZNK5thingIjE2idEv:.LFB2: .cfi_startproc pushq %rbp .cfi_def_cfa_offset 16 .cfi_offset 6, -16 movq %rsp, %rbp .cfi_def_cfa_register 6 movq %rdi, -8(%rbp) movl $3840, %eax popq %rbp .cfi_def_cfa 7, 8 ret .cfi_endproc Three of the directives at the top are significant: .section .text._ZNK5thingIjE2idEv,"axG",@progbits,_ZNK5thingIjE2idEv,comdat This one puts the function definition in a linkage section of its own called .text._ZNK5thingIjE2idEv that will be output, if it's needed, merged into the .text (i.e. code) section of program in which the object file is linked. A linkage section like that, i.e. .text.<function_name> is called a function-section .It's a code section that contains only the definition of function <function_name> . The directive: .weak _ZNK5thingIjE2idEv is crucial. It classifies thing<unsigned int>::id() const as a weak symbol.The GNU linker recognises strong symbols and weak symbols. For a strong symbol, thelinker will accept only one definition in the linkage. If there are more, it will give a multiple-definition error. But for a weak symbol, it will tolerate any number of definitions,and pick one. If a weakly defined symbol also has (just one) strong definition in the linkage then thestrong definition will be picked. If a symbol has multiple weak definitions and no strong definition,then the linker can pick any one of the weak definitions, arbitrarily. The directive: .type _ZNK5thingIjE2idEv, @function classifies thing<unsigned int>::id() as referring to a function - not data. Then in the body of the definition, the code is assembled at the addresslabelled by the weak global symbol _ZNK5thingIjE2idEv , the same one locallylabelled .LFB2 . The code returns 3840 ( = 0xf00). Next we'll compile boo.cpp the same way: g++ -c -save-temps boo.cpp and look again at how thing<unsigned int>::id() is defined in boo.s .section .text._ZNK5thingIjE2idEv,"axG",@progbits,_ZNK5thingIjE2idEv,comdat .align 2 .weak _ZNK5thingIjE2idEv .type _ZNK5thingIjE2idEv, @function_ZNK5thingIjE2idEv:.LFB2: .cfi_startproc pushq %rbp .cfi_def_cfa_offset 16 .cfi_offset 6, -16 movq %rsp, %rbp .cfi_def_cfa_register 6 movq %rdi, -8(%rbp) movl $2816, %eax popq %rbp .cfi_def_cfa 7, 8 ret .cfi_endproc It's identical, except for our cheat: this definition returns 2816 ( = 0xb00). While we're here, let's note something that might or might not go without saying:Once we're in assembly (or object code), classes have evaporated . Here,we're down to: - data code symbols, which can label data or label code. So nothing here specifically represents the instantiation of thing<T> for T = unsigned . All that's left of thing<unsigned> in this instance isthe definition of _ZNK5thingIjE2idEv a.k.a thing<unsigned int>::id() const . So now we know what the compiler does about instantiating thing<unsigned> in a given translation unit. If it is obliged to instantiate a thing<unsigned> member function, then it assembles the definition of the instantiated memberfunction at a weakly global symbol that identifies the member function, and itputs this definition into its own function-section. Now let's see what the linker does. First we'll compile the main source file. g++ -c main.cpp Then link all the object files, requesting a diagnostic trace on _ZNK5thingIjE2idEv ,and a linkage map file: g++ -o prog main.o foo.o boo.o -Wl,--trace-symbol='_ZNK5thingIjE2idEv',-M=prog.mapfoo.o: definition of _ZNK5thingIjE2idEvboo.o: reference to _ZNK5thingIjE2idEv So the linker tells us that the program gets the definition of _ZNK5thingIjE2idEv from foo.o and calls it in boo.o . Running the program shows it's telling the truth: ./progf00f00 Both foo() and boo() are returning the value of thing<unsigned>().id() as instantiated in foo.cpp . What has become of the other definition of thing<unsigned int>::id() const in boo.o ? The map file shows us: prog.map ...Discarded input sections ... ... .text._ZNK5thingIjE2idEv 0x0000000000000000 0xf boo.o ... ... The linker chucked away the function-section in boo.o thatcontained the other definition. Let's now link prog again, but this time with foo.o and boo.o in thereverse order: $ g++ -o prog main.o boo.o foo.o -Wl,--trace-symbol='_ZNK5thingIjE2idEv',-M=prog.mapboo.o: definition of _ZNK5thingIjE2idEvfoo.o: reference to _ZNK5thingIjE2idEv This time, the program gets the definition of _ZNK5thingIjE2idEv from boo.o andcalls it in foo.o . The program confirms that: $ ./progb00b00 And the map file shows: ...Discarded input sections ... ... .text._ZNK5thingIjE2idEv 0x0000000000000000 0xf foo.o ... ... that the linker chucked away the function-section .text._ZNK5thingIjE2idEv from foo.o . That completes the picture. The compiler emits, in each translation unit, a weak definition ofeach instantiated template member in its own function section. The linkerthen just picks the first of those weak definitions that it encountersin the linkage sequence when it needs to resolve a reference to the weaksymbol. Because each of the weak symbols addresses a definition, anyone one of them - in particular, the first one - can be used to resolve all referencesto the symbol in the linkage, and the rest of the weak definitions areexpendable. The surplus weak definitions must be ignored, becausethe linker can only link one definition of a given symbol. And the surplusweak definitions can be discarded by the linker, with no collateraldamage to the program, because the compiler placed each one in a linkage section all by itself. By picking the first weak definition it sees, the linker is effectivelypicking at random, because the order in which object files are linked is arbitrary.But this is fine, as long as we obey the ODR accross multiple translation units ,because it we do, then all of the weak definitions are indeed identical. The usual practice of #include -ing a class template everywhere from a header file (and not macro-injecting any local edits when we do so) is a fairly robust way of obeying the rule.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/44335053', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8072435/']}
jdg_84961
stackexchange
llm_judgeable_groundtruth_similarity
1468328
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've encountered this weird question: Show that the derivative of the area of a circle with respect to its radius is equal to its circumference. Show that this relationship holds between the area and circumference of a square, too. Explain what you mean by the radius of a square. I don't have any trouble with the first part, $A=\pi r^2$, $A'= 2\pi r$ and $c = 2\pi r$.Now for the square, my speculation was that the "radius" is half of the diagonal ($\frac{r\sqrt 2}{2}$) but it's derivative is not equal to the perimeter (or "circumference"). Something that makes sense in terms of the numbers is $A$ equal the whole diagonal ($r \sqrt 2)^2$. But I don't know if it means anything on a geometry basis. What are your thoughts on this? Thanks! Now provide the response and nothing else.
Let the "radius" of a square be the perpendicular distance from the centre to a side, or equivalently the radius of the inscribed circle, or equivalently half the side. Then the area of a square of radius $r$ is $4r^2$, and the perimeter is $8r$. Note that the perimeter is the derivative of the area with respect to $r$. Remark: Let the "radius" $r$ of a regular $n$-gon be the radius of the inscribed circle. Join the centre $O$ to two adjacent vertices $A$ and $B$. Let $2\theta=\angle AOB$. Then the side $AB$ is equal to $2r\cot\theta$, so the perimeter is $(2n\cot\theta)r$. The area of the polygon turns out to be $(n\cot\theta) r^2$. Thus again, if we measure the "size" of the polygon using $r$, the perimeter is the derivative of area! If we think of the polygon as made up of "shells" then the fact this should happen becomes geometrically clear.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1468328', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/268950/']}
jdg_84962
stackexchange
llm_judgeable_groundtruth_similarity
13960209
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I've tried multiple ways. I know the dictionary is NULL, as the console also prints out when I break there. Yet when I put it in an if( ) it doesn't trigger. ([myDict count] == 0) //results in crash(myDict == NULL)[myDict isEqual:[NSNull null]] Now provide the response and nothing else.
It looks like you have a dangling or wild pointer. You can consider Objective-C objects as pointers to structs. You can then of course compare them with NULL , or with other pointers. So: ( myDict == NULL ) and ( myDict == [ NSNull null ] ) are both valid. The first one will check if the pointer is NULL . NULL is usually defined as a void * with a value of 0. Note that, for Objective-C objects, we usually use nil . nil is also defined as a void * with a value of 0, so it equals NULL . It's just here to denote a NULL pointer to an object, rather than a standard pointer. The second one compares the address of myDict with the singleton instance of the NSNull class. So you are here comparing two pointers values. So to quickly resume: NULL == nil == Nil == 0 And as [ NSNull null ] is a valid instance: NULL != [ NSNull null ] Now about this: ( [ myDict count ] == 0 ) It may crash if you have a wild pointer: NSDictionary * myDict;[ myDict count ]; Unless using ARC, it will surely crash, because the myDict variable has not been initialised, and may actually point to anything. It may also crash if you have a dangling pointer: NSDictionary * myDict;myDict = [ [ NSDictionary alloc ] init ];[ myDict release ];[ myDict count ]; Then you'll try to send a message to a deallocated object. Sending a message to nil / NULL is always valid in Objective-C. So it depends if you want to check if a dictionary is nil , or if it doesn't have values (as a valid dictionary instance may be empty). In the first case, compare with nil . Otherwise, checks if count is 0, and ensure you're instance is still valid. Maybe you just forgot a retain somewhere.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/13960209', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/879555/']}
jdg_84963
stackexchange
llm_judgeable_groundtruth_similarity
13796595
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 working on JavaFX application, in my scenario is to show a password prompt created in JavaFX which takes password with two option OK and Cancel . I have returned the password entered by user. My class of showing password dialog is - public static String showPasswordDialog(String title, String message, Stage parentStage, double w, double h) { try { Stage stage = new Stage(); PasswordDialogController controller = (PasswordDialogController) Utility.replaceScene("Password.fxml", stage); passwordDialogController.init(stage, message, "/images/password.png"); if (parentStage != null) { stage.initOwner(parentStage); } stage.initModality(Modality.WINDOW_MODAL); stage.initStyle(StageStyle.UTILITY); stage.setResizable(false); stage.setWidth(w); stage.setHeight(h); stage.showAndWait(); return controller.getPassword(); } catch (Exception ex) { return null; } My code where to show password prompt is below, actually this prompt will be shown over other UI, so I need to inclose this inside Platform.runlater() , otherwise it throws Not on FX application thread . I need this password prompt to be shown until I get correct one. How can I get value of password if I inclosed showing password inside runlater. Is there any other better way? final String sPassword = null; do { Platform.runLater(new Runnable() { @Override public void run() { sPassword = JavaFXDialog.showPasswordDialog(sTaskName + "Password", "Enter the password:", parentStage, 400.0, 160.0); } }); if (sPassword == null) { System.out.println("Entering password cancelled."); throw new Exception("Cancel"); } } while (sPassword.equalsIgnoreCase("")); Now provide the response and nothing else.
I'd recommend wrapping the code within a FutureTask object. FutureTask is a construct useful (among other things) for executing a portion of code on one thread (usually a worker, in your case the event queue) and safely retrieving it on another. FutureTask#get will block until FutureTask#run has been invoked, therefore your password prompt could look like this: final FutureTask query = new FutureTask(new Callable() { @Override public Object call() throws Exception { return queryPassword(); }});Platform.runLater(query);System.out.println(query.get()); As FutureTask implements Runnable, you can pass it directly to Platform#runLater(...) . queryPassword() will be inokved on the event queue, and the subsequent call to get block until that method completes. Of course, you will want to invoke this code in a loop until the password actually matches.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/13796595', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1053182/']}
jdg_84964
stackexchange
llm_judgeable_groundtruth_similarity
7455147
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 I have to find a string name "Akito" and it lies in the table foo then following is the normal procedure, select * from foo where `name = 'Akito'` I tried to check two variations of it, Worked fine select * from foo where name = 'Akito ' Did not Worked Fine select * from foo where name = ' Akito' Can anyone please explain why did the 2nd one did not work? Thanks in advance Now provide the response and nothing else.
CHAR types fill the string to the length of the field with null bytes (while VARCHAR add delimiters to indicate the end of the string - thus ignoring extra data at the end ( I mean empty bytes )), and therefore comparisons that have spaces at the end will ignore those. Leading spaces are relevant as their alter the string itself. See Christopher's answer. EDIT: some further elaboration required See some practical tests below. VARCHAR types do add spaces to the string, whilst CHAR fields, even though they fill the string up to its size with spaces, ignore them during comparisons. See specifically the second line with the LENGTH function query: mysql> create table test (a VARCHAR(10), b CHAR(10));Query OK, 0 rows affected (0.17 sec)mysql> insert into test values ('a', 'a'), ('a ', 'a '), (' a', ' a');Query OK, 3 rows affected (0.00 sec)Records: 3 Duplicates: 0 Warnings: 0mysql> select a, LENGTH(a), b, LENGTH(b) FROM test;+------+-----------+------+-----------+| a | LENGTH(a) | b | LENGTH(b) |+------+-----------+------+-----------+| a | 1 | a | 1 | | a | 2 | a | 1 | | a | 2 | a | 2 | +------+-----------+------+-----------+3 rows in set (0.00 sec) where MySQL states the CHAR field, with the value of 'a ' as it was inserted, has only 1 character in length. Furthermore, if we concatenate a little data: mysql> select CONCAT(a, '.'), CONCAT(b, '.') FROM test;+----------------+----------------+| CONCAT(a, '.') | CONCAT(b, '.') |+----------------+----------------+| a. | a. | | a . | a. | | a. | a. | +----------------+----------------+3 rows in set (0.00 sec)mysql> select CONCAT(a, b), CONCAT(b, a) FROM test;+--------------+--------------+| CONCAT(a, b) | CONCAT(b, a) |+--------------+--------------+| aa | aa | | a a | aa | | a a | a a | +--------------+--------------+3 rows in set (0.00 sec) you can see that, since VARCHAR does store where the string ends, the space remains on concatenations - which does not hold true for CHAR types. Now, keeping in mind the previous LENGTH example, where line two has different lengths for its fields a and b, we test: mysql> SELECT * FROM test WHERE a=b;+------+------+| a | b |+------+------+| a | a | | a | a | | a | a | +------+------+3 rows in set (0.00 sec) Therefore, we can sum up stating that the CHAR datatype ignores and trims extra space at the end of its string, while VARCHAR does not - except during comparisons : mysql> select a from test where a = 'a ';+------+| a |+------+| a | | a | +------+2 rows in set (0.00 sec)mysql> select a from test where a = 'a';+------+| a |+------+| a | | a | +------+2 rows in set (0.00 sec)mysql> select a from test where a = ' a';+------+| a |+------+| a | +------+1 row in set (0.00 sec) So, is the same true for the CHAR type? mysql> select a from test where b = 'a ';+------+| a |+------+| a | | a | +------+2 rows in set (0.00 sec)mysql> select a from test where b = 'a';+------+| a |+------+| a | | a | +------+2 rows in set (0.00 sec)mysql> select a from test where b = ' a';+------+| a |+------+| a | +------+1 row in set (0.00 sec) Which displays that the CHAR and VARCHAR types have different storage methods, but follow the same rules for sheer string comparison . Trailing spaces are ignored; while leading spaces modify the string itself.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7455147', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_84965
stackexchange
llm_judgeable_groundtruth_similarity
42496917
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: In my Ubuntu VM, I kept getting SQLSTATE[HY000] [1045] Access denied for user 'username'@'localhost' (using password: YES) update I have configured my database like this in my .env file DB_HOST=45.55.88.57DB_DATABASE=b-prodDB_USERNAME=rootDB_PASSWORD=*********UNIX_SOCKET=/var/run/mysqld/mysqld.sock It works perfectly. But when I use DB_HOST=45.55.88.57DB_DATABASE=b-prodDB_USERNAME=b <----------------------------------------------DB_PASSWORD=*********UNIX_SOCKET=/var/run/mysqld/mysqld.sock I didn't work. What else I should look into to prevent this ? I have a feeling that I have the wrong password. How do I test my database password ? DB_PASSWORD=********* ? This is all user I have mysql> SELECT User,Host FROM mysql.user;+------------------+-------------+| User | Host |+------------------+-------------+| root | % || root | 127.0.0.1 || root | 45.55.88.57 || root | ::1 || root | b || b | localhost || debian-sys-maint | localhost || root | localhost |+------------------+-------------+8 rows in set (0.00 sec) Now provide the response and nothing else.
The solution: Sometimes when you change your .env, the configs don't refresh without clear cache or restarting the server. The error message are: SQLSTATE[HY000] [1045] Access denied for user 'forge'@'localhost' (using password: YES) The database are trying to get the information from the "cached" .env configuration, you should try: php artisan config:clear if not solve, restart your server. [Edit] Another NON RECOMMENDED option: Go to your config\database.php remove the .env configuration And set your own credentials 'mysql' => [ 'host' => '45.55.88.77', 'database' => 'prod', 'username' => 'forge', 'password' => '*********', ],
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/42496917', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4480164/']}
jdg_84966
stackexchange
llm_judgeable_groundtruth_similarity
9200951
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 my thread to shut down more gracefully so I am trying to implement a simple signalling mechanism. I don't think I want a fully event-driven thread so I have a worker with a method to graceully stop it using a critical section Monitor (equivalent to a C# lock I believe): DrawingThread.h class DrawingThread { bool stopRequested; Runtime::Monitor CSMonitor; CPInfo *pPInfo; //More..} DrawingThread.cpp void DrawingThread::Run() { if (!stopRequested) //Time consuming call#1 if (!stopRequested) { CSMonitor.Enter(); pPInfo = new CPInfo(/**/); //Not time consuming but pPInfo must either be null or constructed. CSMonitor.Exit(); } if (!stopRequested) { pPInfo->foobar(/**/);//Time consuming and can be signalled } if (!stopRequested) { //One more optional but time consuming call. }}void DrawingThread::RequestStop() { CSMonitor.Enter(); stopRequested = true; if (pPInfo) pPInfo->RequestStop(); CSMonitor.Exit();} I understand (at least in Windows) Monitor / lock s are the least expensive thread synchronization primitive but I am keen to avoid overuse. Should I be wrapping each read of this boolean flag? It is initialized to false and only set once to true when stop is requested (if it is requested before the task completes). My tutors advised to protect even bool 's because read/writing may not be atomic. I think this one shot flag is the exception that proves the rule? Now provide the response and nothing else.
It is never OK to read something possibly modified in a different thread without synchronization. What level of synchronization is needed depends on what you are actually reading. For primitive types, you should have a look at atomic reads, e.g. in the form of std::atomic<bool> . The reason synchronization is always needed is that the processors will have the data possibly shared in a cache line. It has no reason to update this value to a value possibly changed in a different thread if there is no synchronization. Worse, yet, if there is no synchronization it may write the wrong value if something stored close to the value is changed and synchronized.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/9200951', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/866333/']}
jdg_84967
stackexchange
llm_judgeable_groundtruth_similarity
15220861
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 read and write pi as 3,141592 instead of 3.141592 , as using the comma is common in many European countries. How can I accomplish this with iostream s? In other words cout << 3.141592; should print 3,141592 to standard output. Now provide the response and nothing else.
You should use basic_ios::imbue to set the preferred locale. Take a look here: http://www.cplusplus.com/reference/ios/ios_base/imbue/ Locales allow you to use the preferred way by the user, so if a computer in Italy uses comma to separate decimal digits, in the US the dot is still used. Using locales is a Good Practice. But if you want to explicitly force the use of the comma, take a look here: http://www.cplusplus.com/reference/locale/numpunct/decimal_point/ Here a small example I just made with g++ which enforces the char ',' (passing the separator as template argument is just for fun, not really necessary) #include <iostream>#include <locale>template <class charT, charT sep>class punct_facet: public std::numpunct<charT> {protected: charT do_decimal_point() const { return sep; }};int main(int argc, char **argv) { std::cout.imbue(std::locale(std::cout.getloc(), new punct_facet<char, ','>)); std::cout << "My age is " << 3.1415 << " lightyears.\n";} Note that using cout.getloc() I'm overriding just a single facet in the currently set locale, that is, in the current locale settings of cout, I'm changing only how the punctuation is done. do_decimal_point is a virtual function of std::numpunct that you can redefine to provide your custom separator. This virtual function will be used by numpunct::decimal_point when printing your number.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15220861', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1335865/']}
jdg_84968
stackexchange
llm_judgeable_groundtruth_similarity
60392949
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 NextJS with typescript, mongo Atlas, mongoose, node and express. I am getting the following error when I run node pages/server:I have uploaded my package.json file and have added babel as well import express from 'express'; ^^^^^^ SyntaxError: Cannot use import statement outside a module at wrapSafe (internal/modules/cjs/loader.js:1072:16) at Module._compile (internal/modules/cjs/loader.js:1122:27) at Object.Module._extensions..js (internal/modules/cjs/loader.js:1178:10) at Module.load (internal/modules/cjs/loader.js:1002:32) at Function.Module._load (internal/modules/cjs/loader.js:901:14) at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12) at internal/main/run_main_module.js:18:47 This is my server.js code: import express from 'express';import { connect, connection } from 'mongoose';import morgan from 'morgan';import path from 'path';const app = express();const PORT = process.env.PORT || 8080;//Success import routes from './routes/api.tsx';const MONGODB_URI = 'xxx';// const routes=require('./routes/api')connect(MONGODB_URI ||'mongodb://localhost/success', { useNewUrlParser: true, useUnifiedTopology: true});connection.on('connected', () => { console.log('Mongoose is connected');});const newBlogPost = new BlogPost(data); //instance of the modelapp.use(morgan('tiny'));app.use('/',routes)app.listen(PORT, console.log(`Server is starting at ${PORT}`)); package.json file { "name": "la-sheild", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "dev": "next", "build": "next build", "start": "babel-node server.js" }, "keywords": [], "author": "", "license": "ISC", "dependencies": { "@types/express": "^4.17.2", "@types/mongoose": "^5.7.1", "axios": "^0.19.2", "concurrently": "^5.1.0", "express": "^4.17.1", "mongoose": "^5.9.1", "morgan": "^1.9.1", "next": "^9.2.2", "node": "^13.8.0", "react": "^16.12.0", "react-dom": "^16.12.0" }, "devDependencies": { "@babel/core": "^7.8.4", "@babel/preset-env": "^7.8.4", "@babel/register": "^7.8.3", "@types/node": "^13.7.4", "@types/react": "^16.9.21", "babel-cli": "^6.26.0", "typescript": "^3.7.5" }, "proxy": "http://localhost:8080"} Now provide the response and nothing else.
Since Node v12, you can use either the .mjs extension or set "type": "module" in your package.json . And you need to run node with the - -experimental-modules flag. node --experimental-modules server.mjs You can check the SO link Or you can create .babelrc file in the root of your project.Add following (and any other babel presets you need, can be added in this file): { "presets": ["env"]} Install babel-preset-env using npm install babel-preset-envnpm install babel-cli -g# ORyarn add babel-preset-envyarn global add babel-cli Now, go to the folder where your server.js file exists and run using: babel-node fileName.js Or you can run using npm start by adding following code to your package.json file: "scripts": { "start": "babel-node server.js"} There is a tutorial link for Set Up Next.js with a Custom Express Server + Typescript on a medium that will be very helpful for you.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/60392949', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12540328/']}
jdg_84969
stackexchange
llm_judgeable_groundtruth_similarity
1309535
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 understand that it marks the end of a set of varargs, but why can't it be implemented in such a way that doesn't require the nil? Now provide the response and nothing else.
It all has to do with the C calling ABI. Consider these methods: - (id)initWithFormat:(NSString *)format, ...;+ (id)arrayWithObjects:(id)firstObj, ...;+ (id)dictionaryWithObjectsAndKeys:(id)firstObject, ...; The ... tells the compiler that a variable number of arguments of any type may be present. There is no way for the compiler to know what those types are required to be (the real definitions have markers that help with that). Now, consider the three methods. All three have vastly different requirements for what might be present in the variable argument list. An array must be a bunch of objects followed by a nil. The dictionary requires a bunch of pairs of objects followed by a nil. Finally, the string method requires a bunch of arguments that match the types in the format string. All of these behaviors are directly tied to the method being invoked and, if the author of an API decided to go for "hard to use", the behavior of decoding the variable arguments could be modified at runtime, just to make life difficult. Bottom line: The C ABI doesn't have a syntax that allows for specifying that a method or function takes a variable number of arguments with any kind of set of constraints on the arguments or their termination. Objective-C could change the rules just for method declarations & invocations, but that wouldn't help with C functions or C++, both of which Objective-C must remain compatible with.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1309535', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/41984/']}
jdg_84970
stackexchange
llm_judgeable_groundtruth_similarity
75948
Below is a question asked on the forum datascience.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am interested in using Google Colab for data modeling. How do I install conda, create an environment and run python in a notebook? I did some searching and found some helpful hints, but had several issues with this. I can only get a partially functional environment so far. I get stuck in running another cell in the same environment. Seems that switching cells resets the environment back to default. Now provide the response and nothing else.
Found a way to get Miniconda working in Google colab. For now, use source activate, not conda activate in the 2nd cell. Still working out the bugs with using conda to activate. Full Notebook demo here: https://donaldsrepo.github.io/Notebooks/GoogleColabCondaCreateEnv.html github with demo notebook: https://github.com/donaldsrepo/SampleNotebooks/blob/master/CondaCreateEnv/GoogleColabCondaCreateEnv.ipynb Google uses Python 3.6.9 by default. I created an environment using Python 3.6.10. Steps to follow: Install miniconda Create a new environment Run some python code to test the environment is being used Some sample code: # try to get the bare minimum to get a new conda env workingconda_path = ''try: conda_path = !which condafinally: print('')if (len(conda_path) == 0): print('installing miniconda') !wget https://repo.continuum.io/miniconda/Miniconda3-4.5.4-Linux-x86_64.sh && bash Miniconda3-4.5.4-Linux-x86_64.sh -bfp /usr/local !conda update conda -y -q !source /usr/local/etc/profile.d/conda.sh !conda init !conda install -n root _license -y -qelse: print('found miniconda')conda_envs = !conda env listres = [i for i in conda_envs if 'test36' in i]if (len(res) == 0): print('not found test36 env', len(res)) !conda create -y -q --name test36 python=3.6else: print('found test36 env', len(res)) Next cell: %%bashsource activate test36pythonimport sys# maybe only need this the first time we run this notebooksys.path.append('/usr/local/lib/python3.6/site-packages')print("Python version")print(sys.version) Output: Python version3.6.10 |Anaconda, Inc.| (default, May 8 2020, 02:54:21) [GCC 7.3.0] Note that version 3.6.10 is the one installed in my personal conda environment. You can also see your new environment here: A few things to point out: If you open a new notebook, your new environment does not exist. Seems to be stored in a transient location, similar to docker.
{}
{'log_upvote_score': 4, 'links': ['https://datascience.stackexchange.com/questions/75948', 'https://datascience.stackexchange.com', 'https://datascience.stackexchange.com/users/91826/']}
jdg_84971
stackexchange
llm_judgeable_groundtruth_similarity
51021
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to set up Brillouin zone and representing the lines that are formed by the intersection of two planes is part of my step.I have tried the sample sections from the graphics guide book, but I got some wrong output.Here is the code that I copied from the guidebook: (* to save memory *) $HistoryLength = 0; The function latticePointListSC generates all lattice points that we want to take into account. It returns all lattice points inside a sphere of radius d around the origin. latticePointListSC[d_] := With[{n = Ceiling[d]}, Select[ DeleteCases[ Flatten[Table[{i, j, k}, {i, -n, n}, {j, -n, n}, {k, -n, n}], 2], (* without origin *){0, 0, 0}], #. # <= d^2&]]maxDist = 4;Length[latticePoints = latticePointListSC[maxDist]]Show[Graphics3D[Cuboid[# + 0.1 {1, 1, 1},# - 0.1 {1, 1, 1}]& /@ latticePoints], Axes -> True]; Next, we construct the perpendicular planes in the middle of the lines origin–latticePoint. We denote a plane in the form Plane[onePointOfThePlane, listOfTwoOrthogonalDirections] . The function toPlane generates a plane (head Plane) of the bisector plane formed by the point latticePoint. toPlane[p:latticePoint_] := Plane[latticePoint/2, Which[(* lattice point is on a coordinate axis *) p[1] == 0 && p[2] == 0, {{1, 0, 0}, {0, 1, 0}}, p[1] == 0 && p[3] == 0, {{1, 0, 0}, {0, 0, 1}}, p[2] == 0 && p[3] == 0, {{0, 1, 0}, {0, 0, 1}}, (* lattice point is on a coordinate plane *) p[1] != 0 && p[2] != 0, {#, Cross[#, p]}&[{p[2], -p[1], 0}], p[1] != 0 && p[3] != 0, {#, Cross[#, p]}&[{p[3], 0, -p[1]}], p[2] != 0 && [P3] != 0, {#, Cross[#, p]}&[{0, p[3], -p[2]}], (* lattice point is in generic position *) True, {#, Cross[#, p]}&[{p[2], -p[1], 0}]]] We are now adding some planes that guarantee that polygons are divided along the symmetry planes. A “symmetry unit” (forbrevity, just called unit in the following) is given by the following domain x>=0, y>= 0, z>= 0, z >= x, x >=y. This is 1/48 of thewhole space. The list symmetrySlicingPlanes contains the planes that bound the unit. symmetrySlicingPlanes = Plane[{0, 0, 0}, #]& /@ {{{1, 0, 0}, {0, 1, 0}}, {{1, 0, 0}, {0, 0, 1}},{{0, 1, 0}, {0, 0, 1}}, {{0, 0, 1}, {-1, 1, 0}}, {{0, 0, 1}, {1, 1, 0}}, {{1, 0, 0}, {0, -1, 1}}, {{1, 0, 0}, {0, 1, 1}}, {{0, 1, 0}, {-1, 0, 1}},{{0, 1, 0}, {1, 0, 1}}}; Here are the symmetrySlicingPlanes. The red, slightly sticking out polygons mark one symmetry unit. We will in thefollowing concentrate on this unit and only later in the visualization part generate all other 47 units by reflection and rotation. With[{ε = 0.05}, Show[ Graphics3D[{ (* make polygons *) Polygon[{#[1] - #[2, 1] - #[2, 2], #[1] + #[2, 1] - #[2, 2], #[1] + #[2, 1] + #[2, 2], #[1] - #[2, 1] + #[2, 2]}]& /@ symmetrySlicingPlanes, {SurfaceColor[Hue[0]], (* lift a bit up *) Map[# + {ε, ε, 2ε}&, (* boundary of the unit cone *) {Polygon[{{0, 0, 0}, {0, 0, 1}, {1, 0, 1}}], Polygon[{{0, 0, 0}, {0, 0, 1}, {1, 1, 1}}], Polygon[{{0, 0, 0}, {1, 0, 1}, {1, 1, 1}}]}, {-2}]}}], Boxed->False]]planes = Join[toPlane /@ latticePoints, symmetrySlicingPlanes];Take[planes, 4] Next, we construct representations of the lines that are formed by the intersection of two planes. The presentation of the lineswill be in the form Line[onePointOfTheLine, lineDirection]. We use here a two-argument version of Line, in distinctionto the built-in Line, which takes one argument. The function lineOnPlane[plane1, plane2] calculates the intersectionline which is located on plane1 , induced by its intersection with the plane plane2 . (* three equations cannot be solved for four variables *)Off[Solve::"svars"];lineOnPlane[Plane[p_, {dir1_, dir2_}], Plane[q_, {d1_, d2_}]] := Module[{eqs, sol, line, var, aux, P1, P2}, If[ (* are the planes parallel? *) Length[DeleteCases[RowReduce[{dir1, dir2, d1, d2}], {0, 0, 0}, {1}]] == 2, {}, (* calculate direction of the intersecting line *) eqs = Thread[p + s dir1 + t dir2 == q + u d1 + v d2]; sol = Solve[eqs, {s, t, u, v}]; aux = p + s dir1 + t dir2 /. sol[[1]]; (* two points on the line *) {P1, P2} = {aux /. {u -> 0, v -> 0}, aux /. {u -> 1, v -> 1}};Line[P1, P2 - P1]]]lineOnPlane[planes[[1]], planes[[5]]] I should have gotten Line[{-2, 1, -1}, {0, -20, 10}] but i got Line[{-2, s, -(1/2) - s/2}, {0, 0, 0}] instead The lines after this all got messed up beacuse of the wrong out[16] Could anyone please help? Is there a better way I could do compute the lines that are formed by the intersection of two planes? Now provide the response and nothing else.
From a first look, late at night. In the third panel of code, aren't all of the terms really parts of a list p, and should therefore be written as p[[1]], p[[2]], etc., rather than p[1], p[2], etc. The paired single square brackets would surround the argument(s) of a function, e.g. Sin[x] or Sqrt[x]; paired double square brackets designate an element of a list. There is also a typo: what appears as [p3] is almost certainly intended to be p[[3]]. In the fifth panel of code, below the comment (*make polygons*), shouldn't all of the terms be double square brackets , such as #[[1]], #[[2]], etc. rather than #[1], #[2]? When mapping the Polygon onto symmetrySlicingPlanes you are extracting parts from each of the elements of the symmetrySlicingPlanes list, not making function evaluations with paired single square brackets. Once I changed a lot of [ ] cases to [[ ]] cases and corrected a typo, I got the following for the Graphics3D. Is this what you expect? [I got the same final result as you got for lineOnPlane[planes[[1]], planes[[5]]], but I think printing some intermediate results leading up to that answer, such as eqs = {-2==-(3/2)-u-6 v, s==-(1/2)+3 u-2 v, t==-1+10 v} sol = {{t->-(1/2)-s/2, u->1/5+(3 s)/10, v->1/20-s/20}} aux = {-2,s,-(1/2)-s/2} Line[{-2, s, -(1/2) - s/2}, {0, 0, 0}] should provide clues as to what is wrong and how this needs to be fixed. Too late at night now. P.S. The printing did supply some clues, and I think the code below now gives the answer you desire, but you really need to check this yourself. I'm not familiar enough with this particular type of calculation. latticePointListSC[d_] := With[{n = Ceiling[d]}, Select[ DeleteCases[ Flatten[ Table[{i, j, k}, {i, -n, n}, {j, -n, n}, {k, -n, n}], 2], (*without origin*){0, 0, 0}], #.# <= d^2 &]]maxDist = 4;Length[latticePoints = latticePointListSC[maxDist]](* 256 *)g3d1 = Show[ Graphics3D[ Cuboid[# + 0.1 {1, 1, 1}, # - 0.1 {1, 1, 1}] & /@ latticePoints ], Axes -> True];Raster[Image[g3d1, ImageSize -> 4*72]] (*No way to include this graphic in answer.*)(*Notice the many double square brackets that are in this toPlane function now*)(*when compared with the original.*)toPlane[p : latticePoint_] := Plane[latticePoint/2, Which[ (*lattice point is on a coordinate axis*) p[[1]] == 0 && p[[2]] == 0, {{1, 0, 0}, {0, 1, 0}}, p[[1]] == 0 && p[[3]] == 0, {{1, 0, 0}, {0, 0, 1}}, p[[2]] == 0 && p[[3]] == 0, {{0, 1, 0}, {0, 0, 1}}, (*lattice point is on a coordinate plane*) (*WATCH OUT--IN THE NEXT THREE CONDITIONALS*) (*I ADDED A THIRD && CONDITION THAT WAS NOT IN THE ORIGINAL*) (*I COULD BE WRONG--I"M NO EXPERT ON THIS*) p[[1]] != 0 && p[[2]] != 0 && p[[3]] == 0, {#, Cross[#, p]} &[{p[[2]], -p[[1]], 0}], p[[1]] != 0 && p[[3]] != 0 && p[[2]] == 0, {#, Cross[#, p]} &[{p[[3]], 0, -p[[1]]}], p[[2]] != 0 && p[[3]] != 0 && p[[1]] == 0, {#, Cross[#, p]} &[{0, p[[3]], -p[[2]]}], (*lattice point is in generic position*) True, {#, Cross[#, p]} &[{p[[2]], -p[[1]], 0}]]]symmetrySlicingPlanes =Plane[{0, 0, 0}, #] & /@{{{1, 0, 0}, {0, 1, 0}}, {{1, 0, 0}, {0, 0, 1}}, {{0, 1, 0}, {0, 0,1}},{{0, 0, 1}, {-1, 1, 0}}, {{0, 0, 1}, {1, 1, 0}}, {{1, 0, 0}, {0, -1, 1}},{{1, 0, 0}, {0, 1, 1}}, {{0, 1, 0}, {-1, 0, 1}}, {{0, 1, 0}, {1, 0, 1}}};g3d2 = With[{\[CurlyEpsilon] = 0.05}, Show[ Graphics3D[ {(*make polygons*) Polygon[{#[[1]] - #[[2, 1]] - #[[2, 2]], #[[1]] + #[[2, 1]] - #[[ 2, 2]], #[[1]] + #[[2, 1]] + #[[2, 2]], #[[1]] - #[[2, 1]] + #[[2, 2]]}] & /@ symmetrySlicingPlanes, { SurfaceColor[Hue[0]],(*lift a bit up*) Map[# + {\[CurlyEpsilon], \[CurlyEpsilon], 2 \[CurlyEpsilon]} &, (*boundary of the unit cone*) {Polygon[{{0, 0, 0}, {0, 0, 1}, {1, 0, 1}}], Polygon[{{0, 0, 0}, {0, 0, 1}, {1, 1, 1}}], Polygon[{{0, 0, 0}, {1, 0, 1}, {1, 1, 1}}]}, {-2}] } }], Boxed -> False]]Raster[Image[g3d2, ImageSize -> 4*72]](* This made the 2D image I uploaded earlier *)planes = Join[toPlane /@ latticePoints, symmetrySlicingPlanes];Take[planes, 4];Off[Solve::"svars"];lineOnPlane[Plane[p_, {dir1_, dir2_}], Plane[q_, {d1_, d2_}]] := Module[ {eqs, sol, line, var, aux, P1, P2}, If[ (*are the planes parallel?*) Length[ DeleteCases[RowReduce[{dir1, dir2, d1, d2}], {0, 0, 0}, {1}] ] == 2, {}, (*calculate direction of the intersecting line*) eqs = Thread[p + s dir1 + t dir2 == q + u d1 + v d2]; Print["eqs = ", eqs]; (*BIG CHANGE IN SOLVE ON NEXT LINE!*) (*Now solving for {s,t,u}, NOT {s, t, u, v}, as in original*) sol = Solve[eqs, {s, t, u}]; Print["sol = ", sol]; aux = ((p + s dir1 + t dir2) /. sol[[1]]); Print["aux = ", aux]; (*two points on the line*) {P1, P2} = {aux /. {u -> 0, v -> 0}, aux /. {u -> 1, v -> 1}}; Line[P1, P2 - P1] ]] lineOnPlane[planes[[1]], planes[[5]]](* Prints: eqs = {-2==-(3/2)-u-6 v, s==-(1/2)+3 u-2 v, t==-1+10 v} *)(* Prints: sol = {{s->1-20 v, t->-1+10 v, u->1/2 (1-12 v)}} *)(* Prints: aux = {-2,1-20 v,-1+10 v} *)(* Line[{-2, 1, -1}, {0, -20, 10}] *) I cannot promise that these changes are correct--you must check them. You should remove the three Print[] functions; I used them for the diagnostic work I was doing, but they are not necessary. New errors have probably been introduced in the course of all of the copy and paste work necessary to move my Mathematica notebook code to this answer window. This is not an efficient way to answer a question with so much intricate code. Would have been better to e-mail you my .nb, but I think this site is not intended for exchanging .nb files. I hope this helps you somewhat though.
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/51021', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/15990/']}
jdg_84972
stackexchange
llm_judgeable_groundtruth_similarity
1137839
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Ok a pretty simple question.. in c++ it seems to work but in objective-c i seem to struggle with it :S .. If you want to compare two arrays it should be something like this right for ( int i = 0; i < [appdelegate.nicearray count]; i++ ) { if ( appdelegate.nicearray[i] == appdelegate.exercarray[i] ) { NSLog(@"the same elements in this selection"); }} what's the problem exactly ? Now provide the response and nothing else.
These are Cocoa array objects (instances of NSArray), not C arrays or C++ vectors, and remember that Objective-C does not have operator overloading. The only things you can do with an object are pass it around, store it in variables, and send messages to it. So the array-subscript operator is wrong with Objective-C objects. I don't think it's even linguistically valid to dereference a pointer to an Objective-C object, so this code should be giving you a compiler error. I may be misremembering, though. If it does make it to runtime, that code will crash sooner or later, since you're accessing memory beyond the ends of the array objects. (EDIT from the year 2013: Objective-C now supports subscripting of objects. This ultimately translates into the appropriate objectAtIndex: or replaceObjectAtIndex:withObject: message. So, the code in the question would actually work now, although it's still not the proper way to simply walk an array, much less to compare two arrays.) The proper way to retrieve an object from an NSArray object by its index is not to use the array-subscript operator, but to send the array object the objectAtIndex: message: [myArray objectAtIndex:i] The proper way to iterate on the elements of an array object, assuming you don't really need the index for something else (such as replacing objects in a mutable array), is to loop on it directly (this is called “fast enumeration”): for (MyObject *myObject in myArray) { …} NSArray also responds to objectEnumerator and reverseObjectEnumerator , which return a similarly-iterable object. Of the two, reverseObjectEnumerator is the more useful in new code, since you can just iterate on the array directly to iterate forward. Both of them were most useful before fast enumeration existed; that code looked like this: NSEnumerator *myArrayEnum = [myArray objectEnumerator];MyObject *myObject;while ((myObject = [myArrayEnum nextObject])) { …} (Yes, that's an assignment in the condition. Deliberately, hence the extra () . We coded boldly back then, didn't we?) For what you're doing, though, you more likely want to send one of the arrays an isEqualToArray: message, as Williham Totland suggested: BOOL theyAreEqual = [myFirstArray isEqualToArray:mySecondArray]; This will make sure both arrays have the same length, then walk them both in lock-step, sending isEqual: to each pair of objects. It'll return YES if every isEqual: message returned YES ; NO otherwise. The arrays may contain different objects, but as long as each pair is equal, the arrays themselves are equal. That assumes you want object equality. Two separate objects are equal if one of them responds with YES when you send it an isEqual: message and pass the other object. If you meant to compare the identities of the objects, then you do need to do the lock-step loop yourself and use == : BOOL arraysContainTheSameObjects = YES;NSEnumerator *otherEnum = [otherArray objectEnumerator];for (MyObject *myObject in myArray) { if (myObject != [otherEnum nextObject]) { //We have found a pair of two different objects. arraysContainTheSameObjects = NO; break; }} But that's unlikely. Most of the time, I have wanted to test the objects' equality, not identities, so isEqualToArray: is what I wanted.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1137839', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_84973
stackexchange
llm_judgeable_groundtruth_similarity
13102116
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Yesterday I installed Windows 8 and am now trying to understand why I am getting an "Access Denied" message when accessing localstorage. The page is being served on the same PC with the browser (http://localhost). My feeling is that one of the security settings in IE 10 is wrong, but I haven't figured out which one. The line of JavaScript code triggering the error is: if(window.localStorage.getItem('phone') == null) The code works fine in the latest version of Chrome. Now provide the response and nothing else.
Our users were having issues with web sites using the LocalStorage feature (including Twitter) on Windows 8 with IE 10. When accessing one of these sites with the F12 Developer Tools open, a SCRIPT5: Access is denied message appeared on the console. After working with Microsoft support, we identified the cause. It turned out to be a problem with the settings on the C:\Users\username\Appdata\LocalLow folder in their user profile. Each folder on your computer has an integrity setting. More information about the purpose of this setting is here: http://msdn.microsoft.com/en-us/library/bb625964.aspx The integrity setting on the AppData\LocalLow folder (and its subfolders) in each user's profile is supposed to be set to "Low" (hence the name). In our case, the integrity level was not set correctly on this folder. To rectify the problem, run the following command in a command prompt window: icacls %userprofile%\Appdata\LocalLow /t /setintegritylevel (OI)(CI)L (If there is more than one user account on the computer and the other users are having the same issue, the command needs to be run under each affected user's account.) As for how this setting got changed in the first place? In our case, it was caused by a problem in the customized Windows 8 image we deployed to our workstations. For others that are having the issue, my research has revealed that the use of a "system cleaner" utility may be to blame.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/13102116', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1221748/']}
jdg_84974
stackexchange
llm_judgeable_groundtruth_similarity
3721861
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: Given $\min \{a^Tx\mid x^TQx+2b^Tx+c\leq0\}$ and $Q_{n\times n}\succ0,b\in\mathbb{R}^n,c\in\mathbb{R},a\in\mathbb{R}^n\backslash\{0\}$ find conditions for $Q,b,c$ for which the problem is feasible find conditions for $Q,b,c$ for which KKT conditions are suffices find conditions for $Q,b,c$ for which KKT conditions are necessary I thought maybe to look at $2b^Tx+c\leq0$ because $Q$ is positive but couldn't get more conditions from this inequality Now provide the response and nothing else.
Let's check feasibility, the problem is infeasible only if, $$\g(x) = x^TQx + 2b^Tx + c>0 \ \forall x$$ You can easily check $g(x) = x^TQx + 2b^Tx +c$ is convex. Let $x^*$ be the minima. For the problem to be feasible we need $g(x^*) \leq 0$ . $$\\nabla g(x^*)=2Qx +2b=0 \implies x^*=-Q^{-1}b$$ Setting $g(x^*)\leq0$ , we get, $$\c-b^TQ^{-1}b \leq 0$$ Hence, we have this upper-bound on $c$ for the problem to be feasible. Note that we have assumed $Q$ to be a symmetric matrix. In case if its not, you can always replace $Q$ by $\frac{1}{2}(Q^T+Q)$ . This won't change anything. Since, both the objective and constraints are convex. KKT conditions suffice. But are they necessary? Can you figure it out? Hint1: Are there points which violates the regularity conditions? Hint2: Do we need $g(x^*) < 0$ for KKT?
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3721861', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/628914/']}
jdg_84975
stackexchange
llm_judgeable_groundtruth_similarity
2205159
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 this the correct use of Blockquote , q and cite ? <p><blockquote>Type HTML in the textarea above, <q>and it will magically appear</q> in the frame below.</blockquote><cite><a href="http://stackoverflow.com">refrence url</a></p> Is use of Blockquote , q semantically correct? or both are presentational element , so should not be used? Now provide the response and nothing else.
Yes. They are not presentational elements — blockquote represents a block quotation, q represents an inline quotation, and cite represents a reference to a name, work, standard, URL, etc. You do have some validation errors that are fairly common with blockquote. A blockquote element cannot be inside a paragraph, and in HTML4 actually needs to contain paragraphs. The nesting of the p and blockquote elements in your fragment needs to be reversed. The blockquote element (also the q element) can optionally have a cite attribute to specify a URI where the quote came from. HTML5 says user agents should make that link available to the user, and HTML4 doesn't say anything at all. I would include the URI both in the cite attribute and as an inline link, since browsers don't handle it. Here's how I would write that fragment, with those revisions in mind: <blockquote cite="http://stackoverflow.com"> <p>Type HTML in the textarea above, <q>and it will magically appear</q> in the frame below.</p></blockquote><p> <cite><a href="http://stackoverflow.com">reference url</a></cite></p> Validate this fragment
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/2205159', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/84201/']}
jdg_84976
stackexchange
llm_judgeable_groundtruth_similarity
14296173
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'm debugging an https page with httpFox, looking for insecure content. There's only one insecure request on the entire page, but I can't tell what it is for? httpFox is flagging this request...it's the only "http" request on the page (the rest are "https" ): 00:00:57.444 0.378 970 113575 GET 200 text/html (NS_IMAGELIB_ERROR_NO_DECODER) http://[thebaseURL]/ where the "thebaseURL" is the just the root domain without anything after it (no subpath or file request) Is there something in the response header that would be the problem? when I click on the line above, I see the response header includes to "set-coookie" for two cookies...would setting a cookie without the secure flag being set cause the problem? Now provide the response and nothing else.
To understand you correctly, you still want to run the test modules, but your don't want to deploy/release them. The maven-deploy-plugin to the rescue! To artifact will still be built, but not deployed. <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-deploy-plugin</artifactId> <version>2.7</version> <configuration> <skip>true</skip> </configuration> </plugin> However, the jenkins release plugin will still release all artifacts. Instead of using the jenkins release plugin, think about releasing with the maven-release-plugin , which is easy to do: mvn release:preparemvn release:perform Since the default goals are deploy and site , all should be ok. Just make sure you have a scm tag in your root pom: <scm> <connection>scm:svn|git:https://...</connection> <developerConnection>scm:svn|git:https://...</developerConnection></scm> and that your versioning tool command (git, svn, ...) is available on the PATH.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/14296173', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1367131/']}
jdg_84977
stackexchange
llm_judgeable_groundtruth_similarity
18355889
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: http://jsfiddle.net/tfwqD/1/ As with the above fiddle. I can expand the div when clicked and setInterval will collapse the div after 3000ms, however attempting to click on the button again will not re-expand the div. Here's the JS code (full JSfiddle is above): function growDiv(div) {growDiv = document.getElementById(div);if (growDiv.clientHeight) { growDiv.style.height = 0;} else { var wrapper = document.querySelector('.measuringWrapper'); growDiv.style.height = wrapper.clientHeight + "px";}setInterval(function(){growDiv.style.height = 0},3000);} Now provide the response and nothing else.
If you need to set one font for all TextViews in android application you can use this solution. It will override ALL TextView's typefaces, includes action bar and other standard components, but EditText's password font won't be overriden. MyApp.java public class MyApp extends Application { @Override public void onCreate() { TypefaceUtil.overrideFont(getApplicationContext(), "SERIF", "fonts/Roboto-Regular.ttf"); } } TypefaceUtil.java public class TypefaceUtil { /** * Using reflection to override default typeface * NOTICE: DO NOT FORGET TO SET TYPEFACE FOR APP THEME AS DEFAULT TYPEFACE WHICH WILL BE OVERRIDDEN * @param context to work with assets * @param defaultFontNameToOverride for example "monospace" * @param customFontFileNameInAssets file name of the font from assets */ public static void overrideFont(Context context, String defaultFontNameToOverride, String customFontFileNameInAssets) { try { final Typeface customFontTypeface = Typeface.createFromAsset(context.getAssets(), customFontFileNameInAssets); final Field defaultFontTypefaceField = Typeface.class.getDeclaredField(defaultFontNameToOverride); defaultFontTypefaceField.setAccessible(true); defaultFontTypefaceField.set(null, customFontTypeface); } catch (Exception e) { Log.e("TypefaceUtil","Can not set custom font " + customFontFileNameInAssets + " instead of " + defaultFontNameToOverride); } }} themes.xml <?xml version="1.0" encoding="utf-8"?> <resources> <style name="MyAppTheme" parent="@android:style/Theme.Holo.Light"> <!-- you should set typeface which you want to override with TypefaceUtil --> <item name="android:typeface">serif</item> </style> </resources> Update for Android 5.0 or greater As i have investigated and tested on device running api 5.0 or greater this solution is working fine because i am using the single style.xml file and not making other style.xml in values-21 folder AlthoughSome users asking me that this solution not working with android 5.0 device (they may be using values-21 style.xml i guess) So that is because Under API 21, most of the text styles include fontFamily setting, like <item name="fontFamily">@string/font_family_body_1_material</item> Which applys the default Roboto Regular font: <string name="font_family_body_1_material">sans-serif</string> So the best solution is If Any one having problem not working for 5.0+. Don't override typeface in your values-v21 styles. Just override font in values/style.xml and you will good to go :)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18355889', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2483703/']}
jdg_84978
stackexchange
llm_judgeable_groundtruth_similarity
2529446
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 currently assisting a basic course where the students have to write some proofs. Most of them use terminology like "Let $x$ be a random integer", instead of "Let $x$ be an arbitrary integer" or plainly "Let $x$ be an integer". Am I doing the right thing in correcting them? My point of view is that a random integer is an integer chosen by some kind of random distribution. In that interpretation, there's some truth in saying that "Let $x$ be a random integer, then $x$ is not equal to 25", since the probability might be zero for that to happen, and in that sense the randomly chosen integer is not going to be 25. Meanwhile the sentence "Let $x$ be an integer, then $x$ is not equal to 25" is blatantly false, since we can take $x=25$ deterministically (but definitely not randomly). Now provide the response and nothing else.
I originally wrote a more ambivalent response, but thinking about it further I've changed my mind. It's clear that the phrase "let $x$ be a random integer" is mathematically . . . bad. What is at question is whether: it is misleading to the student, it is worth correcting, and as a bonus, whether it is worth penalizing when repeated. I think the answer to (3) is no (unless one is in a class dealing with probability), and the answer to (2) is yes, since if nothing else explaining why the phrase is wrong lets you preemptively address some of the usual confusions around quantifiers (e.g. we're allowed to pick a number that happens to be a counterexample "out of a hat"). I think the answer to (1) (and here's where I've changed my mind) is "yes" - or rather, it is "yes" enough that we should treat it as "yes." I think this is a case where poor use of language early on could set the student up for more confusion down the road, even if they are not being confused by the phrase at the moment . (And this is generally an argument for helping students with language use in mathematics.) That said, I still think the answer to (3) is no (again, unless the class is dealing with probability).
{}
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/2529446', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/139618/']}
jdg_84979
stackexchange
llm_judgeable_groundtruth_similarity
48981070
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 currently studying c array and is confused about what can and can't be used to represent the size of the array during initialisation. Am I right to assume #define SIZE 5 and const int SIZE = 5; are fundamentally different to one another? They have their difference and one particular example that confuses me is #define SIZE 5int arr[SIZE] = {11, 22, 33, 44, 55}; is valid syntax, but const int SIZE = 5;int arr[SIZE] = {11, 22, 33, 44, 55}; is not valid syntax. Though interestingly, const int SIZE = 5;int arr[SIZE]; is valid syntax. What's the logic behind whether a particular syntax is valid or invalid? Now provide the response and nothing else.
Am I right to assume #define SIZE 5 and const int SIZE = 5; are fundamentally different to one another? Yes, you are right. #define is simply a textual replacement . Basically, the C preprocessor is going a "find and replace" for you during the compilation process (processing stage). Whereas, const qualified object means "the thing stored at this location can't changed" - roughly equivalent to saying it's "read-only". #define SIZE 5 int arr[SIZE] = {11, 22, 33, 44, 55}; is valid syntax. This is exactly equivalent to writing: int arr[5] = {11, 22, 33, 44, 55}; yourself. The compiler simply does the replacement job for you when you use define . const int SIZE = 5; int arr[SIZE] = {11, 22, 33, 44, 55}; is not valid syntax. It's invalid but the reason could be more than one. If arr has static storage duration (i.e., the object arr is alive throughout the program execution) then it's invalid. Because C requires that the size of an array object with static storage duration to be a constant expression : If the size is an integer constant expression and the element type has a known constant size, the array type is not a variable length array type; otherwise, the array type is a variable length array type. So, the following program is not valid: const int SIZE = 5;int arr[SIZE] = {11, 22, 33, 44, 55};int main(void){} because SIZE doesn't qualify as a "constant expression" in C. Note that this is totally valid in C++ where SIZE qualifies as a constant expression (the two languages differ here). Another reason is C standard doesn't allow initializing variable-length arrays. If you have the definition inside a function such as: The type of the entity to be initialized shall be an array of unknown size or a complete object type that is not a variable length array type. So if you don't have the initializer then it becomes valid: int main(void){ const int SIZE = 5; int arr[SIZE]; /* This is OK */} Similarly, you can do without the const as well: int main(void){ int SIZE = 5; int arr[SIZE]; /* Thi is OK too. */} In both of the above snippets, arr is simply a variable-length array . Though interestingly, const int SIZE = 5; int arr[SIZE]; is valid syntax. It's valid only if it's inside a function (as above) - it's a VLA. But if you make it have static storage duration such as: const int SIZE = 5;int arr[SIZE]; /* arr has static storage duration just as all objects defined at file scope */int main(void){} it's invalid because as noted above, SIZE is not a "constant expression" in C. Similarly, int main(void){ const int SIZE = 5; static int arr[SIZE]; /* arr has static storage duration */} is invalid for the same reason, despite arr being inside a function, because arr has static storage duration . However, if you have: enum {SIZE = 5};int arr[SIZE] = {11, 22, 33, 44, 55}; int arr2[SIZE]; /* Valid without initializer too. */int main(){} it's valid. Why? Because enum constants qualify as "constant expressions" in C.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/48981070', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5581182/']}
jdg_84980
stackexchange
llm_judgeable_groundtruth_similarity
1490896
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 fixed-sized array where the size of the array is always in factor of 3. my @array = ('foo', 'bar', 'qux', 'foo1', 'bar', 'qux2', 3, 4, 5); How can I cluster the member of array such that we can getan array of array group by 3: $VAR = [ ['foo','bar','qux'], ['foo1','bar','qux2'], [3, 4, 5] ]; Now provide the response and nothing else.
my @VAR;push @VAR, [ splice @array, 0, 3 ] while @array; or you could use natatime from List::MoreUtils use List::MoreUtils qw(natatime);my @VAR;{ my $iter = natatime 3, @array; while( my @tmp = $iter->() ){ push @VAR, \@tmp; }}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1490896', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/67405/']}
jdg_84981
stackexchange
llm_judgeable_groundtruth_similarity
6758364
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 Apache POI(XSSF API) for reading xlsx file.when i tried to read file.i got the following error: org.apache.poi.POIXMLException: org.apache.poi.openxml4j.exceptions.InvalidFormatException: Package should contain a content type part [M1.13] Code: public class ReadXLSX{private String filepath;private XSSFWorkbook workbook;private static Logger logger=null;private InputStream resourceAsStream;public ReadXLSX(String FilePath){ logger=LoggerFactory.getLogger("ReadXLSX"); this.filepath=FilePath; resourceAsStream = ClassLoader.getSystemResourceAsStream(filepath);}public ReadXLSX(InputStream fileStream){ logger=LoggerFactory.getLogger("ReadXLSX"); this.resourceAsStream=fileStream;}private void loadFile() throws FileNotFoundException, NullObjectFoundException{ if(resourceAsStream==null) throw new FileNotFoundException("Unable to locate give file.."); else { try { workbook = new XSSFWorkbook(resourceAsStream); } catch(IOException ex) { } }}// end loadxlsFilepublic String[] getSheetsName(){ int totalsheet=0;int i=0; String[] sheetName=null; try { loadFile(); totalsheet=workbook.getNumberOfSheets(); sheetName=new String[totalsheet]; while(i<totalsheet) { sheetName[i]=workbook.getSheetName(i); i++; } } catch (FileNotFoundException ex) { logger.error(ex); } catch (NullObjectFoundException ex) { logger.error(ex); } return sheetName;}public int[] getSheetsIndex(){ int totalsheet=0;int i=0; int[] sheetIndex=null; String[] sheetname=getSheetsName(); try { loadFile(); totalsheet=workbook.getNumberOfSheets(); sheetIndex=new int[totalsheet]; while(i<totalsheet) { sheetIndex[i]=workbook.getSheetIndex(sheetname[i]); i++; } } catch (FileNotFoundException ex) { logger.error(ex); } catch (NullObjectFoundException ex) { logger.error(ex); } return sheetIndex;}private boolean validateIndex(int index){ if(index < getSheetsIndex().length && index >=0) return true; else return false;}public int getNumberOfSheet(){ int totalsheet=0; try { loadFile(); totalsheet=workbook.getNumberOfSheets(); } catch (FileNotFoundException ex) { logger.error(ex.getMessage()); } catch (NullObjectFoundException ex) { logger.error(ex.getMessage()); } return totalsheet; }public int getNumberOfColumns(int SheetIndex){ int NO_OF_Column=0;XSSFCell cell = null; XSSFSheet sheet=null; try { loadFile(); //load give Excel if(validateIndex(SheetIndex)) { sheet = workbook.getSheetAt(SheetIndex); Iterator rowIter = sheet.rowIterator(); XSSFRow firstRow = (XSSFRow) rowIter.next(); Iterator cellIter = firstRow.cellIterator(); while(cellIter.hasNext()) { cell = (XSSFCell) cellIter.next(); NO_OF_Column++; } } else throw new InvalidSheetIndexException("Invalid sheet index."); } catch (Exception ex) { logger.error(ex.getMessage()); } return NO_OF_Column;}public int getNumberOfRows(int SheetIndex){ int NO_OF_ROW=0; XSSFSheet sheet=null; try { loadFile(); //load give Excel if(validateIndex(SheetIndex)) { sheet = workbook.getSheetAt(SheetIndex); NO_OF_ROW = sheet.getLastRowNum(); } else throw new InvalidSheetIndexException("Invalid sheet index."); } catch (Exception ex) { logger.error(ex);} return NO_OF_ROW;} public String[] getSheetHeader(int SheetIndex){ int noOfColumns = 0;XSSFCell cell = null; int i =0; String columns[] = null; XSSFSheet sheet=null; try { loadFile(); //load give Excel if(validateIndex(SheetIndex)) { sheet = workbook.getSheetAt(SheetIndex); noOfColumns = getNumberOfColumns(SheetIndex); columns = new String[noOfColumns]; Iterator rowIter = sheet.rowIterator(); XSSFRow Row = (XSSFRow) rowIter.next(); Iterator cellIter = Row.cellIterator(); while(cellIter.hasNext()) { cell = (XSSFCell) cellIter.next(); columns[i] = cell.getStringCellValue(); i++; } } else throw new InvalidSheetIndexException("Invalid sheet index."); } catch (Exception ex) { logger.error(ex);} return columns;}//end of method public String[][] getSheetData(int SheetIndex) { int noOfColumns = 0;XSSFRow row = null; XSSFCell cell = null; int i=0;int noOfRows=0; int j=0; String[][] data=null; XSSFSheet sheet=null; try { loadFile(); //load give Excel if(validateIndex(SheetIndex)) { sheet = workbook.getSheetAt(SheetIndex); noOfColumns = getNumberOfColumns(SheetIndex); noOfRows =getNumberOfRows(SheetIndex)+1; data = new String[noOfRows][noOfColumns]; Iterator rowIter = sheet.rowIterator(); while(rowIter.hasNext()) { row = (XSSFRow) rowIter.next(); Iterator cellIter = row.cellIterator(); j=0; while(cellIter.hasNext()) { cell = (XSSFCell) cellIter.next(); if(cell.getCellType() == cell.CELL_TYPE_STRING) { data[i][j] = cell.getStringCellValue(); } else if(cell.getCellType() == cell.CELL_TYPE_NUMERIC) { if (HSSFDateUtil.isCellDateFormatted(cell)) { String formatCellValue = new DataFormatter().formatCellValue(cell); data[i][j] =formatCellValue; } else { data[i][j] = Double.toString(cell.getNumericCellValue()); } } else if(cell.getCellType() == cell.CELL_TYPE_BOOLEAN) { data[i][j] = Boolean.toString(cell.getBooleanCellValue()); } else if(cell.getCellType() == cell.CELL_TYPE_FORMULA) { data[i][j] = cell.getCellFormula().toString(); } j++; } i++; } // outer while } else throw new InvalidSheetIndexException("Invalid sheet index."); } catch (Exception ex) { logger.error(ex);} return data; } public String[][] getSheetData(int SheetIndex,int noOfRows) { int noOfColumns = 0; XSSFRow row = null; XSSFCell cell = null; int i=0; int j=0; String[][] data=null; XSSFSheet sheet=null; try { loadFile(); //load give Excel if(validateIndex(SheetIndex)) { sheet = workbook.getSheetAt(SheetIndex); noOfColumns = getNumberOfColumns(SheetIndex); data = new String[noOfRows][noOfColumns]; Iterator rowIter = sheet.rowIterator(); while(i<noOfRows) { row = (XSSFRow) rowIter.next(); Iterator cellIter = row.cellIterator(); j=0; while(cellIter.hasNext()) { cell = (XSSFCell) cellIter.next(); if(cell.getCellType() == cell.CELL_TYPE_STRING) { data[i][j] = cell.getStringCellValue(); } else if(cell.getCellType() == cell.CELL_TYPE_NUMERIC) { if (HSSFDateUtil.isCellDateFormatted(cell)) { String formatCellValue = new DataFormatter().formatCellValue(cell); data[i][j] =formatCellValue; } else { data[i][j] = Double.toString(cell.getNumericCellValue()); } } j++; } i++; } // outer while }else throw new InvalidSheetIndexException("Invalid sheet index."); } catch (Exception ex) { logger.error(ex); } return data; } please help me to sort out this problem. Thanks Now provide the response and nothing else.
The error is telling you that POI couldn't find a core part of the OOXML file, in this case the content types part. Your file isn't a valid OOXML file, let alone a valid .xlsx file. It is a valid zip file though, otherwise you'd have got an earlier error Can Excel really load this file? I'd expect it wouldn't be able to, as the exception is most commonly triggered by giving POI a regular .zip file! I suspect your file isn't valid, hence the exception . Update: In Apache POI 3.15 (from beta 1 onwards), there's a more helpful set of Exception messages for the more common causes of this problem. You'll now get more descriptive exceptions in this case, eg ODFNotOfficeXmlFileException and OLE2NotOfficeXmlFileException . This raw form should only ever show up if POI really has no clue what you've given it but knows it's broken or invalid.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/6758364', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/423620/']}
jdg_84982
stackexchange
llm_judgeable_groundtruth_similarity
2317686
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 got 2 select statements, returning data like this: Select 1col_a col_bSelect 2col_a col_c If I do union, I get something like col_a col_b And rows joined. What i need is getting it like this: col_a col_b col_c Joined on data in col_a Now provide the response and nothing else.
Use JOIN to join the subqueries and use ON to say where the rows from each subquery must match: SELECT T1.col_a, T1.col_b, T2.col_cFROM (SELECT col_a, col_b, ...etc...) AS T1JOIN (SELECT col_a, col_c, ...etc...) AS T2ON T1.col_a = T2.col_a If there are some values of col_a that are in T1 but not in T2, you can use a LEFT OUTER JOIN instead.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/2317686', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/279408/']}
jdg_84983
stackexchange
llm_judgeable_groundtruth_similarity
19316974
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 iframe and i am redirecting pages in iframe. how to get the event for each page loading finish. main.html <html><body> <iframe src="http://www.child.html" id="childframe" style="height:100px"></iframe> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script> $(window).load(function(){ var Body = $("#childframe").contents().find("body"); var Element = Body.find("tag"); // page is redirecting to new page $(Element[0].click()); window.setTimeout(reallyNext, 1000); function reallyNext() { //how to know inner page is loaded var result= Body.find("#tag1"); //how to get element from anotherpage.html $(result).bind('DOMSubtreeModified', function(event) { //how to reach here }); } }); </script></body></html> child.html <html><head></head><body> <p><a href="../anotherpage.html"></a><br></p></body></html> please tell me how to know the inner page of iframe has done loading? Now provide the response and nothing else.
The problem lies in that the value passed into the channel as a error interface is not nil , but rather a exec.Error pointer which points to nil. The program will behave correctly if you change: go func() { var e *exec.Error = nil if e == nil { errChan <- nil }}() This is the appropriate way to solve the problem because the idiomatic way to report that no error occurred is by passing a nil error interface. However, if you want to change the main instead (maybe because you use a third party package which makes the mistake of returning pointers set to nil), you will have to either do a type assertion to the specific type (*exec.Error) and then check if it is nil, or else use the reflect package. Example using reflect to check for nil: func IsNil(i interface{}) bool { // Check if it is an actual nil-value if i == nil { return true } v := reflect.ValueOf(i) switch v.Kind() { // Only the following kinds can be nil case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice: return v.IsNil() } return false} Working example: http://play.golang.org/p/rpG1PVTwwM You can find a discussion about it here: https://groups.google.com/forum/#!topic/golang-nuts/QzVDKv7p0Vs
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19316974', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/786851/']}
jdg_84984
stackexchange
llm_judgeable_groundtruth_similarity
421683
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: Presuming that I have written some sequential code where it can be broken down into multiple isolated tasks, it seems it might be efficient for concurrency to be introduced. For example print(expensive_calc_one() + expensive_calc_two()) Asuming expensive_calc_one and expensive_calc_two are pure functions but also computationally quite expensive, it would seem sensible for a compiler to optimise the code by introducing concurrency, and allowing the two functions to run in parallel. I know that this also has its downsides (context switching adds overhead, and some computers still only have one logical core). Are there any compilers which would introduce concurrency into previously non-concurrent code, and are there any general patterns for it (or reasons not to do it)? Now provide the response and nothing else.
Asuming expensive_calc_one and expensive_calc_two are pure functions Unfortunately, determining whether a function is pure is equivalent to solving the Halting Problem in the general case. So, you cannot have an Ahead-of-Time compiler which can in the general case decide whether a function is pure or not. You have to help the compiler by explicitly designing the language in such a way that the compiler has a chance to decide purity. You have to force the programmer to explicitly annotate such functions, for example, or do something like Haskell or Clean, where you clearly isolate side effects using the type system. but also computationally quite expensive Unfortunately, determining in an Ahead-of-Time compiler whether a function is "computationally quite expensive" is also equivalent to solving the Halting Problem. So, you would need to force the programmer to explicitly annotate computationally expensive functions for the compiler to parallelize. Now, if you have to force the programmer to explicitly annotate pure and computationally expensive functions as candidates for parallelization, then is it really automatic parallelization? Where is the difference to simply annotating functions for parallelization? Note that some of those problems could be addressed by performing the automatic parallelization at runtime. At runtime, you can simply benchmark a function and see how long it runs, for example. Then, the next time it is called, you evaluate it in parallel. (Of course, if the function performs memoization, then your guess will be wrong.) Are there any compilers which would introduce concurrency into previously non-concurrent code Not really. Auto-parallelization has been (one of) the holy grail(s) of compiler research for over half a century, and is still as far away today as it was 50–70 years ago. Some compilers perform parallelization at a very small scale, by auto-vectorization, e.g. performing multiple arithmetic operations in parallel by compiling them to vector instructions (MMX/SSE on AMD64, for example). However, this is generally done on a scale of only a handful of instructions, not entire functions. There are , however, languages where the language constructs themselves have been designed for parallelism. For example, in Fortress, a for loop executes all its iterations in parallel. That means, of course, that you are not allowed to write for loops where different iterations depend on each other. Another example is Go, which has the go keyword for spawning a goroutine. However, in this case, you either have the programmer explicitly telling the compiler "execute this in parallel", or you have the language explicitly telling the programmer "this language construct will be executed in parallel". So, it's really the same as, say, Java, except it is much better integrated into the language. But doing it fully automatically, is near impossible, unless the language has been specifically designed with it in mind. And even if the language is designed for it, you often have the opposite problem now: you have so much parallelism that the scheduling overhead completely dominates the execution time. As an example: in Excel, (conceptually) all cells are evaluated in parallel. Or more precisely, they are evaluated based on their data dependencies. However, if you were to actually evaluate all formulae in parallel, you would have a massive amount of extremely simple parallel "codelets". There was, apparently, an experiment in having a Haskell implementation evaluate expressions in parallel. Even though the concurrent abstraction in Haskell (a "spark") is quite lightweight (it is just a pointer to a "thunk", which in turn is just a piece of un-evaluated code), this generated so many sparks that the overhead of managing the sparks overwhelmed the runtime. When you do something like this, you essentially end up with the opposite problem compared to an imperative language: instead of having a hard time breaking up huge sequential code into smaller parallel bits, you have a hard time combining tiny parallel bits into reasonably-sized sequential bits. While this is semantically easier, because you cannot break code by serializing pure parallel functions, it is still quite hard to get the degree of parallelism and the size of the sequential bits right.
{}
{'log_upvote_score': 6, 'links': ['https://softwareengineering.stackexchange.com/questions/421683', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/384179/']}
jdg_84985
stackexchange
llm_judgeable_groundtruth_similarity
283679
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: Let $f:[a,b]\to \mathbb{R}$ be a monotone function (say strictly increasing). Then, do for every $\epsilon>0$ exist two step functions $h,g$ so that $g\le f\le h$ and $0\le h-g\le \epsilon$ ? Does there exist some closed form of these functions like the one below? I encountered the problem when trying to prove the Riemann Integrability of monotone functions via the traditional definition of the Riemann Integral (not the one with Darboux sums). The book I am reading proves that a continuous function is integrable via the process below: Let $\mathcal{P}=\left\{ a=x_0<...<x_n=b \right\}$ be a partition of $[a,b]$ . Define $m_i=\min_{x\in [x_{i-1},x_i]}f(x)$ and $M_i=\max_{x\in [x_{i-1},x_i]}f(x)$ . By the Extreme Value theorem $M_i,m_i$ are well defined. We approximate $f$ with step functions: \begin{gather}g=m_1\chi_{[x_0,x_1]}+\sum_{i=2}^nm_i\chi_{(x_{i-1},x_i]}\\h=M_1\chi_{[x_0,x_1]}+\sum_{i=2}^nM_i\chi_{(x_{i-1},x_i]}\end{gather} It is easily seen that they satisfy the "step function approximation" and as $0\le \int_a^bh-g\le \epsilon$ (uniform continuity) by a previous theorem $f$ is integrable. The book then goes on to generalise by discussing regulated functions. I would like however to see a self contained proof similar to the previous one if $f$ is monotone. This question is reduced to the two questions asked in the beggining of the post Now provide the response and nothing else.
Let $\varepsilon>0$ and $N_\varepsilon$ the smallest $n \in \mathbb{N}$ such that$$\frac{1}{n}(b-a)(f(b)-f(a)) \le \varepsilon$$For $n \ge \max\{2,N_\varepsilon\}$ consider the following partition of $[a,b]$:$$\mathcal{P}=\{a=x_0<x_1<\ldots<x_n=b\}, \ x_i=a+i\frac{b-a}{n}\ 0 \le i \le n.$$ Set$$A_i=\begin{cases}[x_0,x_1] & \text{ for } i=0\\(x_i,x_{i+1}]& \text{ for } 1 \le i \le n-1\end{cases}$$Since $f$ is strictly increasing for each $i \in \{0,\ldots,n-1\}$ we have$$f(x_i) \le f(x) \le f(x_{i+1}) \quad \forall\ x_i \le x \le x_{i+1}.$$Setting$$h=\sum_{i=0}^{n-1}f(x_{i+1})\chi_{A_i},\ g=\sum_{i=0}^{n-1}f(x_i)\chi_{A_i}$$we have$$g(x)\le f(x) \le h(x) \quad \forall\ x \in [a,b],$$and$$h(x)-g(x)=\sum_{i=0}^{n-1}\Big(f(x_{i+1})-f(x_i)\Big)\chi_{A_i}(x)>0 \quad \forall\ x \in [a,b].$$In addition\begin{eqnarray}\int_a^b(h-g)&=&\sum_{i=0}^{n-1}(f(x_{i+1})-f(x_i))\int_a^b\chi_{A_i}=\sum_{i=0}^{n-1}(f(x_{i+1})-f(x_i))(x_{i+1}-x_i)\\&=&\frac{b-a}{n}\sum_{i=0}^{n-1}(f(x_{i+1})-f(x_i))=\frac{1}{n}(b-a)(f(b)-f(a))\\&\le&\frac{1}{N_\varepsilon}(b-a)(f(b)-f(a))\le \varepsilon.\end{eqnarray}
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/283679', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/59145/']}
jdg_84986
stackexchange
llm_judgeable_groundtruth_similarity
1071894
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: The PHP documentation says the following about the __call() magic method: __call() is triggered when invoking inaccessible methods in an object context. Is there a way I can have __call() called even when a method exists, before the actual method is called? Or, is there some other hook I can implement or another way that would provide this functionality? If it matters, this is for a static function (and I would actually prefer to use __callStatic ). Now provide the response and nothing else.
How about just make all your other methods protected, and proxy them through __callStatic? namespace test\foo;class A{ public static function __callStatic($method, $args) { echo __METHOD__ . "\n"; return call_user_func_array(__CLASS__ . '::' . $method, $args); } protected static function foo() { echo __METHOD__ . "\n"; }}A::foo();
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1071894', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/83897/']}
jdg_84987
stackexchange
llm_judgeable_groundtruth_similarity
296966
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: What's the motivation of using MCC these days? Isn't it obsolete? How is it better than ROC? I still see people use MCC. Are they too lazy to use a newer method or does MCC give something different? Now provide the response and nothing else.
@0x90 Lazy? Ah ah ah... you must be kidding ;-) Matthews correlation coefficient (MCC) obsolete? Well, it was introduced in 1975, while the ROC curves were introduced during the II World War...Both MCC and ROC curves are not obsolete; but if you want to label "old" something, you should choose the ROC curves. By the way, let's discuss the motivations of prefering MCC. If you have a confusion matrix threshold: If you have a supervised learning binary classification problem, and you have a threshold to use in the confusion matrix to discriminate false positives from true negatives, and false negatives from true positives, then you should use a threhsold-specific rate, such as MCC, F1 score, accuracy, true positive rate (also know as: sensitivity, or recall), true negative rate (also known as: specificity), and other ones . As I explained in my paper " Ten quick tips for machine learning in computational biology " (Tip 8), among all these rates, the advantage of the MCC is that it generates a high score only if your model is able to predict a high percentage of true positives and a high percentage of true negatives, on any balanced or imbalanced dataset. The other rates (F1 score, accuracy, true positive rate, true negative rate, precision, etc) do NOT have this feature. As I explained in my paper , they can lead to misleading results. If you do NOT have a confusion matrix threshold: In cases when you don't have a specific threshold, you need to compute confusion matrices for all the thresholds. You can analyze these confusion matrices through two main tools: the receiver operating characteristic (ROC) curve, and the precision-recall (PR) curve.You can then compute the area under the curve (AUC) of both.As I explained in my paper " Ten quick tips for machine learning in computational biology " (Tip 8), you should calculate both, but then focus on the precision-recall (PR) curve. EDIT 2020-Apr-07 : Regarding this topic, I recently published on BMC Genomics a paper entitled " The advantages of the Matthews correlation coefficient (MCC) over F1 score and accuracy in binary classification evaluation ", that I wrote with my collaborator Giuseppe Jurman. I hope this article can help you understand why using the MCC is the best option in binary classification evaluation.
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/296966', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/21743/']}
jdg_84988
stackexchange
llm_judgeable_groundtruth_similarity
385141
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 WPF application that is using a custom style. In it I have a set of buttons that each have a custom background image. For each button, I'm supplying a normal and a mouse down image. Is there a simple way to do this with a single style (and customize each button on a case by case basis)? Currently I'm creating a new style for each button, and that can't be the best way to do this surely? Now provide the response and nothing else.
For a XAML only solution you could consider this:- I'm assuming you are using a control template as part of your style something like the following:- <Style x:Key="MyButtonStyle" TargetType="{x:Type Button}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type Button}"> <Image x:Name="img" Style="{DynamicResource NormalImage}"/> <ControlTemplate.Triggers> <Trigger Property="IsEnabled" Value="false"> <Setter Property="Source" TargetName="img" Value="Images\DisabledImage.png"/> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter></Style> I've butchered the control template here and yours might be more sophisticated Now if you add the following style in the same area as the above style then this will specify an image to use for the default case <Style x:Key="NormalImage" TargetType="{x:Type Image}"> <Setter Property="Source" Value="Images/DeafultImage.png"/></Style> Further down in you XAML when you need to use the button you could do this:- <Button Style="{DynamicResource MyButtonStyle}" > <Button.Resources> <Style x:Key="NormalImage" TargetType="{x:Type Image}"> <Setter Property="Source" Value="Images/OverrideImage.png"/> </Style> </Button.Resources></Button> It is not pretty but would still allow a master style and be slightly shorter and less duplication than using multiple styles. The way it works is that the resource name "NormalImage" is first searched for in the button's resources (which are usually empty), then the parent container, all the way up to the page/window resources and beyond to the application resources. The first match wins, so in this case the locally defined style called "NormalImage" that references OverrideImage.png is selected ahead of the window/page/container level resource with the same name that references DefaultImage.png To further reduce the amount of text If all the buttons or most of the buttons will use this style then drop the x:Key="MyButtonStyle" from the style definition. That way WPF will use the style on all buttons in the scope without you needing to specify the style explicitly. You can then use the style="{x:null}" to explicitly NOT use the default style. Thus:- <Window.Resources> <Style x:Key="NormalImage" TargetType="{x:Type Image}"> <Setter Property="Source" Value="Images/DeafultImage.png"/> </Style> <Style TargetType="{x:Type Button}"> <Setter Property="Template"> ... </Setter> </Style></Window.Resources><Button > <Button.Resources> <Style x:Key="NormalImage" TargetType="{x:Type Image}"> <Setter Property="Source" Value="Images/OverrideImage.png"/> </Style> </Button.Resources></Button><Button Style="{x:null}>Normal Button</Button>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/385141', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10086/']}
jdg_84989
stackexchange
llm_judgeable_groundtruth_similarity
10125040
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 could be really obvious and I'm completely missing it. I've searched for hours and can't seem to find a way to, using jQuery, reveal a hidden div from the bottom up. What I am trying to achieve is exactly as in the following link, but in reverse: http://jqueryui.com/demos/show/ I can slide a div from the bottom to the top, but this reveals itself as it moves, rather than being 'masked' in. Like I said, this could (should?) be really obvious and I'm not seeing it, but I've been looking for ages and can't find a solution to this relatively simple problem. Thanks, Ronnie Now provide the response and nothing else.
The effect you're looking for is a little tricky to achieve, but it can be done, even without a wrapper element. The main issue here is that elements naturally render top-down, not bottom-up. Animating both the top and height CSS properties of a relatively-positioned element allows us to implement a slide-up effect, but the element will still render top-down: +-------------------------------------------+| | ^| | | Hidden area collapses upwards.| | |+-------------------------------------------+ <-- 'top'| | ^| | Upper part of element (visible). | | | | | | Animation goes bottom-up.| | Element still renders top-down. | | | | | |+--|----------------------------------------+ <-- 'top + height' | | | || | Lower part of element (hidden). | || V | |+-------------------------------------------+ If we want to simulate bottom-up rendering, we have to modify the scrollTop property of the element during the animation, in order for its lower part to always remain in view: +-------------------------------------------+| | ^| | Upper part of element (hidden). | | Hidden area collapses upwards.| | | |+--|----------------------------------------+ <-- 'top' and 'scrollTop'| | | ^| | Element still renders top-down. | | | | | | Animation goes bottom-up.| | Lower part of element (visible). | | | V | |+-------------------------------------------+ <-- 'top + height' We can use animate() with scrollTop , but doing so in conjunction with top and height did not work correctly in my tests (I suspect scrollTop is reset when top or height are modified in the first animation step, so it ends up stuck to 0 ). To work around this, we can handle scrollTop ourselves through the optional step function we can pass to animate() . This function is called with two arguments, now and fx , now being the current value of the animated property and fx being a wrapper object around useful information, like the element and property being animated. Since we always want scrollTop to be the same as top , we only have to test if top is being animated in our step function. If it is, we set scrollTop to now . This solution gives acceptable results, although it flickers a little too much for my taste (that might be an artifact of my browser, though). So, in summary, to implement that effect, we have to: Fetch the element's original height, Make the element position: relative; so we can animate its top property, Collapse the element by setting top to the original height and height to 0 , Show the element (necessary in your fiddle since display: none; is applied), Animate top to 0 and height to the original height, Give scrollTop the value of top on each animation step. Resulting in the following code: $("#click").click(function() { var $revealMe = $("#revealMe"); var originalHeight = $revealMe.height(); $revealMe.css({ position: "relative", top: originalHeight, height: 0 }).show().animate({ top: 0, height: originalHeight }, { duration: 1000, step: function(now, fx) { if (fx.prop == "top") { $(fx.elem).scrollTop(now); } } });}); You can test it in this fiddle .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10125040', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1329260/']}
jdg_84990
stackexchange
llm_judgeable_groundtruth_similarity
21151044
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: How to clear all input fields in a Bootstrap V3 modal when clicking the data-dismiss button? Now provide the response and nothing else.
http://getbootstrap.com/javascript/#modals shows an event for when a modal is hidden. Just tap into that: $('#modal1').on('hidden.bs.modal', function (e) { $(this) .find("input,textarea,select") .val('') .end() .find("input[type=checkbox], input[type=radio]") .prop("checked", "") .end();}) http://jsfiddle.net/5LCSU/ I would suggest the above as it bind the clearing to the modal itself instead of the close button, but I realize this does not address your specific question. You could use the same clearing logic bound to the dismiss buttons: $('[data-dismiss=modal]').on('click', function (e) { var $t = $(this), target = $t[0].href || $t.data("target") || $t.parents('.modal') || []; $(target) .find("input,textarea,select") .val('') .end() .find("input[type=checkbox], input[type=radio]") .prop("checked", "") .end();}) http://jsfiddle.net/jFyH2/
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/21151044', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/353325/']}
jdg_84991
stackexchange
llm_judgeable_groundtruth_similarity
28858359
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Precondition : Consider such a class or struct T , that for two objects a and b of type T memcmp(&a, &b, sizeof(T)) == 0 yields the same result as a.member1 == b.member1 && a.member2 == b.member2 && ... ( memberN is a non-static member variable of T ). Question : When should memcmp be used to compare a and b for equality, and when should the chained == s be used? Here's a simple example: struct vector{ int x, y;}; To overload operator == for vector , there are two possibilities (if they're guaranteed to give the same result): bool operator==(vector lhs, vector rhs){ return lhs.x == rhs.x && lhs.y == rhs.y; } or bool operator==(vector lhs, vector rhs){ return memcmp(&lhs, &rhs, sizeof(vector)) == 0; } Now if a new member were to be added to vector , for example a z component: If == s were used to implement operator== , it would have to be modified. If memcmp was used instead, operator== wouldn't have to be modified at all. But I think using chained == s conveys a clearer meaning. Although for a large T with many members memcmp is more tempting. Additionally, is there a performance improvement from using memcmp over == s? Anything else to consider? Now provide the response and nothing else.
Regarding the precondition of memcmp yielding the same result as member-wise comparisons with == , while this precondition is often fulfilled in practice, it's somewhat brittle . Changing compilers or compiler options can in theory break that precondition. Of more concern, code maintenance (and 80% of all programming work is maintenance, IIRC) can break it by adding or removing members, making the class polymorphic, adding custom == overloads, etc. And as mentioned in one of the comments, the precondition can hold for static variables while it doesn't hold for automatic variables, and then maintenance work that creates non-static objects can do Bad Things™. And regarding the question of whether to use memcmp or member-wise == to implement an == operator for the class, first, this is a false dichotomy, for those are not the only options. For example, it can be less work and more maintainable to use automatic generation of relational operator overloads , in terms of a compare function. The std::string::compare function is an example of such a function. Secondly, the answer to what implementation to choose depends strongly on what you consider important, e.g.: should one seek to maximize runtime efficiency , or should one seek to create clearest code , or should one seek the most terse, fastest to write code, or should one seek to make the class most safe to use, or something else, perhaps? Generating relational operators. You may have heard of CRTP, the Curiously Recurring Template Pattern . As I recall it was invented to deal with the requirement of generating relational operator overloads. I may possibly be conflating that with something else, though, but anyway: template< class Derived >struct Relops_from_compare{ friend auto operator!=( const Derived& a, const Derived& b ) -> bool { return compare( a, b ) != 0; } friend auto operator<( const Derived& a, const Derived& b ) -> bool { return compare( a, b ) < 0; } friend auto operator<=( const Derived& a, const Derived& b ) -> bool { return compare( a, b ) <= 0; } friend auto operator==( const Derived& a, const Derived& b ) -> bool { return compare( a, b ) == 0; } friend auto operator>=( const Derived& a, const Derived& b ) -> bool { return compare( a, b ) >= 0; } friend auto operator>( const Derived& a, const Derived& b ) -> bool { return compare( a, b ) > 0; }}; Given the above support, we can investigate the options available for your question. Implementation A: comparison by subtraction. This is a class providing a full set of relational operators without using either memcmp or == : struct Vector : Relops_from_compare< Vector >{ int x, y, z; // This implementation assumes no overflow occurs. friend auto compare( const Vector& a, const Vector& b ) -> int { if( const auto r = a.x - b.x ) { return r; } if( const auto r = a.y - b.y ) { return r; } return a.z - b.z; } Vector( const int _x, const int _y, const int _z ) : x( _x ), y( _y ), z( _z ) {}}; Implementation B: comparison via memcmp . This is the same class implemented using memcmp ; I think you'll agree that this code scales better and is simpler: struct Vector : Relops_from_compare< Vector >{ int x, y, z; // This implementation requires that there is no padding. // Also, it doesn't deal with negative numbers for < or >. friend auto compare( const Vector& a, const Vector& b ) -> int { static_assert( sizeof( Vector ) == 3*sizeof( x ), "!" ); return memcmp( &a, &b, sizeof( Vector ) ); } Vector( const int _x, const int _y, const int _z ) : x( _x ), y( _y ), z( _z ) {}}; Implementation C: comparison member by member. This is an implementation using member-wise comparisons. It doesn't impose any special requirements or assumptions. But it's more source code. struct Vector : Relops_from_compare< Vector >{ int x, y, z; friend auto compare( const Vector& a, const Vector& b ) -> int { if( a.x < b.x ) { return -1; } if( a.x > b.x ) { return +1; } if( a.y < b.y ) { return -1; } if( a.y > b.y ) { return +1; } if( a.z < b.z ) { return -1; } if( a.z > b.z ) { return +1; } return 0; } Vector( const int _x, const int _y, const int _z ) : x( _x ), y( _y ), z( _z ) {}}; Implementation D: compare in terms of relational operators. This is an implementation sort of reversing the natural order of things, by implementing compare in terms of < and == , which are provided directly and implemented in terms of std::tuple comparisons (using std::tie ). struct Vector{ int x, y, z; friend auto operator<( const Vector& a, const Vector& b ) -> bool { using std::tie; return tie( a.x, a.y, a.z ) < tie( b.x, b.y, b.z ); } friend auto operator==( const Vector& a, const Vector& b ) -> bool { using std::tie; return tie( a.x, a.y, a.z ) == tie( b.x, b.y, b.z ); } friend auto compare( const Vector& a, const Vector& b ) -> int { return (a < b? -1 : a == b? 0 : +1); } Vector( const int _x, const int _y, const int _z ) : x( _x ), y( _y ), z( _z ) {}}; As given, client code using e.g. > needs a using namespace std::rel_ops; . Alternatives include adding all other operators to the above (much more code), or using a CRTP operator generation scheme that implements the other operators in terms of < and = (possibly inefficiently). Implementation E: comparision by manual use of < and == . This implementation is the result not applying any abstraction, just banging away at the keyboard and writing directly what the machine should do: struct Vector{ int x, y, z; friend auto operator<( const Vector& a, const Vector& b ) -> bool { return ( a.x < b.x || a.x == b.x && ( a.y < b.y || a.y == b.y && ( a.z < b.z ) ) ); } friend auto operator==( const Vector& a, const Vector& b ) -> bool { return a.x == b.x && a.y == b.y && a.z == b.z; } friend auto compare( const Vector& a, const Vector& b ) -> int { return (a < b? -1 : a == b? 0 : +1); } Vector( const int _x, const int _y, const int _z ) : x( _x ), y( _y ), z( _z ) {}}; What to choose. Considering the list of possible aspects to value most, like safety, clarity, efficiency, shortness, evaluate each approach above. Then choose the one that to you is clearly best, or one of the approaches that seem about equally best. Guidance: For safety you would not want to choose approach A, subtraction, since it relies on an assumption about the values. Note that also option B, memcmp , is unsafe as an implementation for the general case, but can do well for just == and != . For efficiency you should better MEASURE , with relevant compiler options and environment, and remember Donald Knuth's adage: “premature optimization is the root of all evil” (i.e. spending time on that may be counter-productive).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/28858359', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3425536/']}
jdg_84992
stackexchange
llm_judgeable_groundtruth_similarity
17082
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 usually think of gravitational potential energy as representing just what it sounds like: the energy that we could potentially gain, using gravity. However, the equation for it (derived by integrating Newton's law of gravitational force)... $$PE_1 = -\frac{GMm}{r}$$ ..has me thrown for a loop, especially after this answer . If potential energy really meant what I thought it did, then it would always have to be non-negative... but this equation is always negative. So what does "negative potential energy" mean!? If $KE + PE$ is always a constant, but PE is not only negative but becomes more negative as the particles attract, doesn't that mean the kinetic energy will become arbitrarily large? Shouldn't this mean all particles increase to infinite KE before a collision? If we are near the surface of the earth, we can estimate PE as $$PE_2 = mgh$$ by treating Earth as a flat gravitational plane. However, $h$ in this equation plays exactly the same role as $r$ in the first equation, doesn't it? So why is $PE_1$ negative while $PE_2$ is positive? Why does one increase with $h$ while the other increases inversely with $r$? Do they both represent the same "form" of energy? Since $PE_2$ is just an approximation of $PE_1$, we should get nearly the same answer using either equation, if we were near Earth's surface and knew our distance to its center-of-mass. However, the two equations give completely different answers! What gives!? Can anyone help clear up my confusion? Now provide the response and nothing else.
About negative energies: they set no problem: On this context, only energy differences have significance. Negative energy appears because when you've made the integration, you've set one point where you set your energy to 0. In this case, you have chosen that $PE_1 = 0$ for $r = \infty$. If you've set $PE_1 = 1000$ at $r = \infty$, the energy was positive for some r. However, the minus sign is important, as it is telling you that the test particle is losing potential energy when moving to $r = 0$, this is true because it is accelerating, causing an increase in $KE$: let's calculate the $\Delta PE_1$ for a particle moving in direction of $r = 0$: $r_i = 10$ and $r_f = 1$: $\Delta PE_1 = PE_f - PE_i = Gm(-1 - (-0.1)) = -Gm\times0.9 < 0$ as expected: we lose $PE$ and win $KE$. Second bullet: yes, you are right. However, it is only true IF they are point particles: has they normally have a definite radius, they collide when $r = r_1 + r_2$, causing an elastic or inelastic collision. Third bullet: you are right with $PE_2 = mgh$, however, again, you are choosing a given referential: you are assuming $PE_2 = 0$ for $y = 0$, which, on the previous notation, means that you were setting $PE_1 = 0$ for $ r = r_{earth}$. The most important difference now is that you are saying that an increase in h is moving farther in r (if you are higher, you are farther from the Earth center). By making the analogy to the previous problem, imagine you want to obtain the $\Delta PE_2$. In this case, you begin at $h_i = 10$ and you want move to $h_f = 1$ (moving in direction to Earth center, like $\Delta PE_1$: $\Delta PE_2 = PE_{f} - PE_{i} = 1mg - 10mg = -9mg < 0$. As expected, because we are falling, we are losing $PE$ and winning $KE$, the same result has $PE_1$ Fourth bullet: they both represent the same thing. The difference is that $gh$ is the first term in the Taylor series of the expansion of $PE_1$ near $r = r_{Earth}$. As exercise, try to expand $PE_1(r)$ in a taylor series, and show that the linear term is: $PE_1 = a + \frac{Gm(r-r_{earth})}{r_{earth}^2}$. Them numerically calculate $Gm/r_{earth}^2$ (remember that $m=m_{earth}$). If you haven't made this already, I guess you will be surprised. So, from what I understood, your logic is totally correct, apart from two key points: energy is defined apart of a constant value. in the $PE_1$, increase r means decrease $1/r$, which means increase $PE_2 = -Gm/r$. In $PE_2$, increase h means increase $PE_2=mgh$.
{}
{'log_upvote_score': 6, 'links': ['https://physics.stackexchange.com/questions/17082', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/175/']}
jdg_84993
stackexchange
llm_judgeable_groundtruth_similarity
57274465
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 writing and API in express.js. the original API I wrote only utilized routes and raw SQL queries. I have since rewritten the API for the most part NOW using an ORM to react models and migrations. My question what is the difference and use cases for middleware and controllers. currently only using middleware because most sources online online only explain what a middleware is. I don't understand the use case of a controller. and I don't want to omit it from my API if its used in proper programming conventions Now provide the response and nothing else.
You should see middleware as a step in your API and controllers as the entity that will actually respond to the requests. Bellow is an example where authenticationMiddleware is a middleware because it is a step during the processing but should not return the response. It can though, in case of error. Then getItems actually handle the logic specific to this calls. As a rule of thumb, middleware are often reused more than once and often they do not response. On contrary, controller respond and are most of the time specific to one endpoint. const express = require("express");const app = express();function authenticationMiddleware(req, res, next) { // Check that the user is authenticated using req.headers.Authorization // for example if (authenticated) { // The user is authenticated, we can go to the next step next(); } else { // The user is not authenticated, we stop here res.status(401); res.send("Error during authentication"); }}function getItems(req, res, next) { // Here we focus on the actual response, we assume that the user is authenticated res.send({ items: [] });}app.get("/items", authenticationMiddleware, getItems);app.post("/items", authenticationMiddleware, createItems); // Re-use the same middlewareapp.listen(3000);
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/57274465', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9433924/']}
jdg_84994
stackexchange
llm_judgeable_groundtruth_similarity
817189
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to find the coefficient on the $x$ term of $\displaystyle{\prod_{n = 1}^{20}(x-n)}$. The issue is that the binomial theorem can't be applied since our $b$ value is changing from term to term. Is there any simple way to do this problem, perhaps a way to change the expression so that the binomial theorem applies? I've tried to do that, and tried looking for a pattern on similar expressions, but I haven't come up with anything. Any help you might have would be appreciated. Now provide the response and nothing else.
The coefficient is given by $$\sum_{k=1}^{20}\prod_{n\not=k\atop n=1,\dots,20}{(-n)}=-\sum_{k=1}^{20}\frac{20!}{k}=-20! H_{20}$$where $H_k$ is the $k$-th Harmonic number. Those can be looked up in tables (see A001008 and A002805 ): $H_{20}=\frac{55835135}{15519504}$ and thus the coefficient is given by $-8752948036761600000$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/817189', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/118924/']}
jdg_84995
stackexchange
llm_judgeable_groundtruth_similarity
3985637
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 find the day of the week in php with a particular date. I don't mean date('D', $timestamp); I mean if I was to supply a date like 2010-10-21 it would return "third thursday". Now provide the response and nothing else.
Not directly, you need a helper function for that: function literalDate($timestamp) { $timestamp = is_numeric($timestamp) ? $timestamp : strtotime($timestamp); $weekday = date('l', $timestamp); $month = date('M', $timestamp); $ord = 0; while(date('M', ($timestamp = strtotime('-1 week', $timestamp))) == $month) { $ord++; } $lit = array('first', 'second', 'third', 'fourth', 'fifth'); return strtolower($lit[$ord].' '.$weekday);}echo literalDate('2010-10-21'); // outputs "third thursday" Working example: http://codepad.org/PTWUocx9
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3985637', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/432540/']}
jdg_84996
stackexchange
llm_judgeable_groundtruth_similarity
26173771
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 problem in the comparison line line == a[1] because it doesn't go to this loop. I tried testing the output and found that there is value 'a' in the file already. Below is my code. a = "djsajdlasak"f = open('users.txt','r+')k = 0for line in f: print line if line == a: k = 1if k == 0: f.write(a + '\n')f.close() Now provide the response and nothing else.
The cause: parseBodyFragment() as well as all other parse() -methods use a HTML parser by default . And those add always the HTML-Shell ( <html>…</html> , <head>…</head> etc.). The Solution: Just don't use a HTML-parser, use a XML-parser instead ;-) Document doc = Jsoup.parse(html, "", Parser.xmlParser()); Replace that single line and your problem is solved. Example: final String html = "<p><b>This <i>is</i></b> <i>my sentence</i> of text.</p>";Document docHtml = Jsoup.parse(html);Document docXml = Jsoup.parse(html, "", Parser.xmlParser());System.out.println("******* HTML *******\n" + docHtml);System.out.println();System.out.println("******* XML *******\n" + docXml); Output: ******* HTML *******<html> <head></head> <body> <p><b>This <i>is</i></b> <i>my sentence</i> of text.</p> </body></html>******* XML *******<p><b>This <i>is</i></b> <i>my sentence</i> of text.</p>
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/26173771', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4104796/']}
jdg_84997
stackexchange
llm_judgeable_groundtruth_similarity
36322933
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 BoltDB and Golang, and trying to get your help. So, I understand that I can only save byte array ([]byte) for key and value of BoltDB. If I have a struct of user as below, and key will be the username, what would be the best choice to store the data into BoltDB where it expects array of bytes? Serializing it or JSON? Or better way? type User struct { name string age int location string password string address string } Thank you so much, have a good evening Now provide the response and nothing else.
Yes, I would recommend marshaling the User struct to JSON and then use a unique key []byte slice. Don't forget that marshaling to JSON only includes the exported struct fields, so you'll need to change your struct as shown below. For another example, see the BoltDB GitHub page . type User struct { Name string Age int Location string Password string Address string }func (user *User) save(db *bolt.DB) error { // Store the user model in the user bucket using the username as the key. err := db.Update(func(tx *bolt.Tx) error { b, err := tx.CreateBucketIfNotExists(usersBucket) if err != nil { return err } encoded, err := json.Marshal(user) if err != nil { return err } return b.Put([]byte(user.Name), encoded) }) return err}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/36322933', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3990434/']}
jdg_84998
stackexchange
llm_judgeable_groundtruth_similarity
18502095
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: The following closure function works fine in javascript. function generateNextNumber(startNumber) { var current = startNumber; return function(){ return current += 1; }}var getNextNumber = generateNextNumber(10);for (var i = 0; i < 10; i++) { console.log(getNextNumber());} I tried to do the same in Python def generateNextNumber(startNumber): current = startNumber def tempFunction(): current += 1 return current return tempFunctiongetNextNumber = generateNextNumber(10)for i in range(10): print (getNextNumber()) I get the following error Traceback (most recent call last): File "/home/thefourtheye/Desktop/Test1.py", line 10, in <module> print (getNextNumber()) File "/home/thefourtheye/Desktop/Test1.py", line 4, in tempFunction current += 1UnboundLocalError: local variable 'current' referenced before assignment When I printed the vars() and locals() inside tempFunction , they confirm that current is present. ({'current': 10}, {'current': 10}) But when I modified the program a little like this def generateNextNumber(startNumber): current = {"Number" : startNumber} def tempFunction(): current["Number"] += 1 return current["Number"] return tempFunction it works. I can't reason why this works. Can anyone explain please? Now provide the response and nothing else.
Python assumes that all variables in a function are local. This is to avoid accidental use of a global variable of the same name, or in an enclosing scope. In some important way, this difference is consequence of the fact that in Python local variable declaration is automatic/implicit while in JavaScript it is not (you have to use var ). Solutions: Use a global declaration def generateNextNumber(startNumber): global current current= startNumber def tempFunction(): global current current += 1 return current return tempFunction Valid in some cases, but in yours only one instance of tempFunction could be active at the same time. Use a function attribute def generateNextNumber(startNumber): def tempFunction(): tempFunction.current += 1 return tempFunction.current tempFunction.current= startNumber return tempFunction Uses the fact that functions are objects (and thus can have attributes), that they are instantiated when they are declared, and that they become local to the enclosing function (or module, in which case they are really global). This also works because the name tempFunction is used for the first time inside its own definition with a "member access" . operator and thus not assumed local. Something similar happens with the "call" () , and "element access" [] operators. The later case explains why your code works. Force the name to be assumed non-local def generateNextNumber(startNumber): current= type("OnTheFly",(),{})() current.value= startNumber def tempFunction(): current.value += 1 return current.value return tempFunction This was already explained in the previous section. By using the member access operator . we are saying " current already exists", and thus it's searched in the enclosing scope. In this particular case, we are creating a class using the type function and immediately creating an instance of it (with the second set of parantheses). Instead of a general object, we could have also used a list or a dictionary. The second case was a very common solution. Use a function object def generateNextNumber(startNumber): class TempFunction: def __call__(self): self.current += 1 return self.current tempFunction= TempFunction() tempFunction.current= startNumber return tempFunction Any object whose class has a call method is a function and thus can be called with the function call operator () . This is extremely related to the two previous cases. Use a nonlocal declaration def generateNextNumber(startNumber): current= startNumber def tempFunction(): nonlocal current current += 1 return current return tempFunction In the same way that global means... well, global, nonlocal means "in the immediately preceding scope". Valid in Python 3 and maybe later versions of Python 2. Use generators def generateNextNumber(current): while True : current+= 1 yield current This is probably the most "Pythonic" way to approach not the general problem of nonlocal variable access, but the specific case you used to explain it. I couldn't finish without mentioning it. You need to call it with a minor change, though: getNextNumber = generateNextNumber(10)for i in range(10): print (getNextNumber.next()) When driving a for the call to next() is implicit (but the generator can not be infinite as in my example).
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/18502095', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1903116/']}
jdg_84999
stackexchange
llm_judgeable_groundtruth_similarity
58809360
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 read various posts on Stack Overflow RE: the derefercing type-punned pointer error. My understanding is that the error is essentially the compiler warning of the danger of accessing an object through a pointer of a different type (though an exception appears to be made for char* ), which is an understandable and reasonable warning. My question is specific to the code below: why does casting the address of a pointer to a void** qualify for this warning (promoted to error via -Werror )? Moreover, this code is compiled for multiple target architectures, only one of which generates the warning/error - might this imply that it is legitimately a compiler version-specific deficiency? // main.c#include <stdlib.h>typedef struct Foo{ int i;} Foo;void freeFunc( void** obj ){ if ( obj && * obj ) { free( *obj ); *obj = NULL; }}int main( int argc, char* argv[] ){ Foo* f = calloc( 1, sizeof( Foo ) ); freeFunc( (void**)(&f) ); return 0;} If my understanding, stated above, is correct, a void** , being still just a pointer, this should be safe casting. Is there a workaround not using lvalues that would pacify this compiler-specific warning/error? I.e. I understand that and why this will resolve the issue, but I would like to avoid this approach because I want to take advantage of freeFunc() NULL ing an intended out-arg: void* tmp = f;freeFunc( &tmp );f = NULL; Problem compiler (one of one): user@8d63f499ed92:/build$ /usr/local/crosstool/x86-fc3/bin/i686-fc3-linux-gnu-gcc --version && /usr/local/crosstool/x86-fc3/bin/i686-fc3-linux-gnu-gcc -Wall -O2 -Werror ./main.ci686-fc3-linux-gnu-gcc (GCC) 3.4.5Copyright (C) 2004 Free Software Foundation, Inc.This is free software; see the source for copying conditions. There is NOwarranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE../main.c: In function `main':./main.c:21: warning: dereferencing type-punned pointer will break strict-aliasing rulesuser@8d63f499ed92:/build$ Not-complaining compiler (one of many): user@8d63f499ed92:/build$ /usr/local/crosstool/x86-rh73/bin/i686-rh73-linux-gnu-gcc --version && /usr/local/crosstool/x86-rh73/bin/i686-rh73-linux-gnu-gcc -Wall -O2 -Werror ./main.ci686-rh73-linux-gnu-gcc (GCC) 3.2.3Copyright (C) 2002 Free Software Foundation, Inc.This is free software; see the source for copying conditions. There is NOwarranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.user@8d63f499ed92:/build$ Update: I've further discovered the warning appears to be generated specifically when compiled with -O2 (still with the noted "problem compiler" only) Now provide the response and nothing else.
A value of type void** is a pointer to an object of type void* . An object of type Foo* is not an object of type void* . There is an implicit conversion between values of type Foo* and void* . This conversion may change the representation of the value. Similarly, you can write int n = 3; double x = n; and this has the well-defined behavior of setting x to the value 3.0 , but double *p = (double*)&n; has undefined behavior (and in practice will not set p to a “pointer to 3.0 ” on any common architecture). Architectures where different types of pointers to objects have different representations are rare nowadays, but they are permitted by the C standard. There are (rare) old machines with word pointers which are addresses of a word in memory and byte pointers which are addresses of a word together with a byte offset in this word; Foo* would be a word pointer and void* would be a byte pointer on such architectures. There are (rare) machines with fat pointers which contain information not only about the address of the object, but also about its type, its size and its access control lists; a pointer to a definite type might have a different representation from a void* which needs additional type information at runtime. Such machines are rare, but permitted by the C standard. And some C compilers take advantage of the permission to treat type-punned pointers as distinct to optimize code. The risk of pointers aliasing is a major limitation to a compiler's ability to optimize code, so compilers tend to take advantage of such permissions. A compiler is free to tell you that you're doing something wrong, or to quietly do what you didn't want, or to quietly do what you wanted. Undefined behavior allows any of these. You can make freefunc a macro: #define FREE_SINGLE_REFERENCE(p) (free(p), (p) = NULL) This comes with the usual limitations of macros: lack of type safety, p is evaluated twice. Note that this only gives you the safety of not leaving dangling pointers around if p was the single pointer to the freed object.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/58809360', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5437543/']}
jdg_85000
stackexchange
llm_judgeable_groundtruth_similarity
8849491
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Consider following code in Scala: object Test { class A {} class B extends A {} class AI extends A { def sayHello: String = "Hello from AI" } implicit def AtoAI(a: A): AI = a class BI extends B { def sayHello: String = "Hello from BI" } implicit def BtoBI(b: B): BI = b def main(args: Array[String]) { val a = new A println(a.sayHello) val b = new B println(b.sayHello) }} The use of implicits results in looping code. In fact, disassemblying reveals, that generated conversion methods have only a goto 0 inside: public Test$AI AtoAI(Test$A); Code: 0: goto 0public Test$BI BtoBI(Test$B); Code: 0: goto 0 What causes that behaviour? I understand, that a hierarchy of classes here is a suspect, but implicit conversion should be applied only once. I use Scala 2.9.1 Now provide the response and nothing else.
Not nice but I would definitely not call it a bug. It boils down to class Aclass Bimplicit def aToB(a: A) : B = a There is no need for the two sides of the conversion to be related in any way. The implicit is just the same thing as writing implicit def aToB(a: A): B = aToB(a) because the compiler inserts the aToB call in order to convert the result a to the required return type B . The goto 0 implementation is just a tail call optimization. The compiler might probably gives a warning when it generates a method that starts this way. Maybe there could be a rule that implicit methods are not available as implicits inside their own body. But it does not always create an infinite loop implicit def listAToListB(l: list[A] = l match { case Nil => Nil case x:xs => toB(x) :: xs // equivalent to toB(x) :: listAToList[B](xs)} (ok this is just a map(toB) ). Anyway the same could happen with two mutually recursive implicits. In my opinion, it's not worthwhile to tweak the spec just to avoid some possibility to write an infinite, do nothing loop, among many others. But a warning when such a loop is detected, irrespective of implicits, would be nice.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8849491', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13767/']}
jdg_85001
stackexchange
llm_judgeable_groundtruth_similarity
38659
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: Forgive me if I misunderstand some basic EE principles -- I'm a CS guy. After some googling, nobody really explains how the chip runs faster. I understand voltage must increase per this related article . Do we actually increase the frequency at which the chip operates? A CPU runs at a certain frequency, which is programmed into it's registers. This frequency can be modified at any time to account for drifting, which is used to account for distance between the crystal and the CPU. (This is going from memory from years ago -- chances are every assumption here is inaccurate.) So, the original frequency is defined by the crystal which, by the nature of a crystal, oscillates at a static frequency band. This in turn we program into the CPU, which will go on to do X number of calculations per millisecond. At this point, overclockers manipulate the drift that is programmed into the CPU? My gut tells me that the drift registers can't increase the frequency enough to be relevant. So where does the increase in frequency come from? Something that has just occurred to me is that just by applying more voltage, the 'bits' actually move around a faster..but then that wouldn't mean an increase in frequency, right? Now provide the response and nothing else.
Do we actually increase the frequency at which the chip operates? Yes, we do! Modern CPUs have a unit called PLL - Phase Locked Loop - which make the multiple GHz out of relatively cheap crystals running at something like 33.3 or 100 MHz. These units are programmable in a wide range of output frequencies. That is used to slow down the core(s) when there is less work to do to save power - or to overclock them. You can increase the clock frequency further when the voltage is higher - but at the price of massive additional generated heat. And the silicon will "wear out" faster, as bad things like Electromigration will increase too.
{}
{'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/38659', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/11598/']}
jdg_85002
stackexchange
llm_judgeable_groundtruth_similarity
41611228
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: class Demo { void show() { System.out.println("i am in show method of super class"); }}class Flavor1Demo { // An anonymous class with Demo as base class static Demo d = new Demo() { void show() { super.show(); System.out.println("i am in Flavor1Demo class"); } }; public static void main(String[] args){ d.show(); }} In the above code, I do not understand the use of creating object d of Demo class with static keyword preceding it. If I eliminate the static keyword, it shows an error. Actually, I was going through anonymous inner class concept and got stuck here. Need help.... Can anyone please explain it? Now provide the response and nothing else.
The static keyword in Java means that the variable or function is shared between all instances of that class, not the actual objects themselves. In your case, you try to access a resource in a static method, public static void main(String[] args) Thus anything we access here without creating an instance of the class Flavor1Demo has to be a static resource. If you want to remove the static keyword from Demo class, your code should look like: class Flavor1Demo {// An anonymous class with Demo as base classDemo d = new Demo() { void show() { super.show(); System.out.println("i am in Flavor1Demo class"); }};public static void main(String[] args) { Flavor1Demo flavor1Demo = new Flavor1Demo(); flavor1Demo.d.show();}} Here you see, we have created an instance of Flavor1Demo and then get the non-static resource d The above code wont complain of compilation errors. Hope it helps!
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/41611228', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6950291/']}
jdg_85003
stackexchange
llm_judgeable_groundtruth_similarity
36483804
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 OpenJDK 8 on Ubuntu using sudo apt-get install openjdk-8-jdk , and it was installed to /usr/lib/jvm/java-8-openjdk-amd64 . Where can I find the Java Mission Control (I think called jmc ) and VisualVM (I think called jvisualvm ) programs? I assumed both to be installed with the JDK: The Java Mission Control page states that "Starting with the release of Oracle JDK 7 Update 40 (7u40), Java Mission Control is bundled with the HotSpot JVM." The VisualVM page says "March 18th, 2014: JDK 8 has been released and is available for download here. It contains Java VisualVM tool based on VisualVM 1.3.6." What am I missing? Are both only part of the Oracle JDK, or did I use the wrong install command? If they are not part of the OpenJDK, can I download them using apt-get install ? Now provide the response and nothing else.
Some OpenJDK distribution maintainers are now providing jmc builds like AdoptOpenJDK , Amazon Corretto or Azul Zulu . Java Mission Control (jmc) is open source and hosted on GitHub and openjdk.java.net (as a Mercurial repository). Official nightly builds are available here . It is also rather easy to build jmc yourself using the instructions from the readme file : hg clone http://hg.openjdk.java.net/jmc/jmc/cd jmc/releng/third-partymvn p2:sitemvn jetty:run In a different terminal: cd coremvn clean installcd ..mvn package After installing, you can close the Jetty server running in the first terminal. Alternatively, you can use Docker to build jmc: docker-compose -f docker/docker-compose.yml run jmc To launch jmc: on Linux: target/products/org.openjdk.jmc/linux/gtk/x86_64/jmc on macOS: target/products/org.openjdk.jmc/macosx/cocoa/x86_64/JDK\ Mission\ Control.app/Contents/MacOS/jmc on Windows: target\products\org.openjdk.jmc\win32\win32\x86_64\jmc.exe You should see a splash screen now: More info in this blog post .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/36483804', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2938364/']}
jdg_85004
stackexchange
llm_judgeable_groundtruth_similarity
9979163
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Could anyone help me with writing case statements in Informatica PowerCenter Designer? I am fairly new to Informatica, and based on my limited experience I feel case statements aren't supported. There is a decode function with similar functionality, but I am unable to find any good examples on the syntax. I would really appreciate if anyone could give me some specific examples on how to use case statements/decode function in Informatica. Thanks much for your help! Now provide the response and nothing else.
You're right - there is no CASE statement, but you can use DECODE to simulate it: DECODE( TRUE , DECIMAL_PORT > 0, 'positive value' , DECIMAL_PORT < 0, 'negative value' , 'zero' ) It is an equivalent of the following Transact-SQL CASE statement: CASE WHEN DECIMAL_PORT > 0 THEN 'positive value' WHEN DECIMAL_PORT < 0 THEN 'negative value' ELSE 'zero'END Here's how it works: the 1st parameter is a hard-coded TRUE value, even parameters (2nd, 4th and so on) are the conditions , odd parameters (3rd, 5th and so on) are the return values , the last parameter is the default return value , the first condition that evaluates to the value of the 1st parameter (i.e. the first condition that is true) determines the value that is returned, if none of the conditions is met the last parameter is returned.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9979163', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1090653/']}
jdg_85005
stackexchange
llm_judgeable_groundtruth_similarity
1033648
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 spawning external console application and use async output redirect. as shown in this SO post My problem is it seems that the spawned process needs to produce certain amount of output before I get the OutputDataReceived event notification. I want to receive the OutputDataReceived event as soon as possible. I have a bare-bones redirecting application, and here are some observations: 1. When I call a simple 'while(true) print("X");' console application (C#) I receive output event immediately.2. When I call a 3d party app I am trying to wrap from the command line I see the line-by-line output. 3. When I call that 3d party app from my bare-bone wrapper (see 1) - the output comes in chunks (about one page size). What happens inside that app? FYI: The app in question is a "USBee DX Data Exctarctor (Async bus) v1.0". Now provide the response and nothing else.
I did some more research and have a fix to microsofts Process class. But as my last answer was deleted without a reason, I have had to create a new one. So take this example... Create a windows app and stick a rich textbox on the main form, then add this to the form load... Process p = new Process() { StartInfo = new ProcessStartInfo() { FileName = "cmd.exe", CreateNoWindow = true, UseShellExecute = false, ErrorDialog = false, RedirectStandardInput = true, RedirectStandardOutput = true, RedirectStandardError = true, }, EnableRaisingEvents = true, SynchronizingObject = this }; p.OutputDataReceived += (s, ea) => this.richTextBox1.AppendText(ea.Data); p.Start(); p.BeginOutputReadLine(); This will output something like this... Microsoft Windows [Version 6.1.7601]Copyright (c) 2009 Microsoft Corporation. All rights reserved. The OutputDataReceived event is not fired for the last line. After some ILSpying it appears that this is deliberate because the last line does not end with a crlf, it assumes there is more comming and appends it to the start of the next event. To correct this, I have written a wrapper for the Process class and taken some of the required internal classes out with it so that it all works neatly. Here is the FixedProcess class... using System;using System.Collections;using System.IO;using System.Text;using System.Threading;namespace System.Diagnostics{ internal delegate void UserCallBack(string data); public delegate void DataReceivedEventHandler(object sender, DataReceivedEventArgs e); public class FixedProcess : Process { internal AsyncStreamReader output; internal AsyncStreamReader error; public event DataReceivedEventHandler OutputDataReceived; public event DataReceivedEventHandler ErrorDataReceived; public new void BeginOutputReadLine() { Stream baseStream = StandardOutput.BaseStream; this.output = new AsyncStreamReader(this, baseStream, new UserCallBack(this.FixedOutputReadNotifyUser), StandardOutput.CurrentEncoding); this.output.BeginReadLine(); } public void BeginErrorReadLine() { Stream baseStream = StandardError.BaseStream; this.error = new AsyncStreamReader(this, baseStream, new UserCallBack(this.FixedErrorReadNotifyUser), StandardError.CurrentEncoding); this.error.BeginReadLine(); } internal void FixedOutputReadNotifyUser(string data) { DataReceivedEventHandler outputDataReceived = this.OutputDataReceived; if (outputDataReceived != null) { DataReceivedEventArgs dataReceivedEventArgs = new DataReceivedEventArgs(data); if (this.SynchronizingObject != null && this.SynchronizingObject.InvokeRequired) { this.SynchronizingObject.Invoke(outputDataReceived, new object[] { this, dataReceivedEventArgs }); return; } outputDataReceived(this, dataReceivedEventArgs); } } internal void FixedErrorReadNotifyUser(string data) { DataReceivedEventHandler errorDataReceived = this.ErrorDataReceived; if (errorDataReceived != null) { DataReceivedEventArgs dataReceivedEventArgs = new DataReceivedEventArgs(data); if (this.SynchronizingObject != null && this.SynchronizingObject.InvokeRequired) { this.SynchronizingObject.Invoke(errorDataReceived, new object[] { this, dataReceivedEventArgs }); return; } errorDataReceived(this, dataReceivedEventArgs); } } } internal class AsyncStreamReader : IDisposable { internal const int DefaultBufferSize = 1024; private const int MinBufferSize = 128; private Stream stream; private Encoding encoding; private Decoder decoder; private byte[] byteBuffer; private char[] charBuffer; private int _maxCharsPerBuffer; private Process process; private UserCallBack userCallBack; private bool cancelOperation; private ManualResetEvent eofEvent; private Queue messageQueue; private StringBuilder sb; private bool bLastCarriageReturn; public virtual Encoding CurrentEncoding { get { return this.encoding; } } public virtual Stream BaseStream { get { return this.stream; } } internal AsyncStreamReader(Process process, Stream stream, UserCallBack callback, Encoding encoding) : this(process, stream, callback, encoding, 1024) { } internal AsyncStreamReader(Process process, Stream stream, UserCallBack callback, Encoding encoding, int bufferSize) { this.Init(process, stream, callback, encoding, bufferSize); this.messageQueue = new Queue(); } private void Init(Process process, Stream stream, UserCallBack callback, Encoding encoding, int bufferSize) { this.process = process; this.stream = stream; this.encoding = encoding; this.userCallBack = callback; this.decoder = encoding.GetDecoder(); if (bufferSize < 128) { bufferSize = 128; } this.byteBuffer = new byte[bufferSize]; this._maxCharsPerBuffer = encoding.GetMaxCharCount(bufferSize); this.charBuffer = new char[this._maxCharsPerBuffer]; this.cancelOperation = false; this.eofEvent = new ManualResetEvent(false); this.sb = null; this.bLastCarriageReturn = false; } public virtual void Close() { this.Dispose(true); } void IDisposable.Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing && this.stream != null) { this.stream.Close(); } if (this.stream != null) { this.stream = null; this.encoding = null; this.decoder = null; this.byteBuffer = null; this.charBuffer = null; } if (this.eofEvent != null) { this.eofEvent.Close(); this.eofEvent = null; } } internal void BeginReadLine() { if (this.cancelOperation) { this.cancelOperation = false; } if (this.sb == null) { this.sb = new StringBuilder(1024); this.stream.BeginRead(this.byteBuffer, 0, this.byteBuffer.Length, new AsyncCallback(this.ReadBuffer), null); return; } this.FlushMessageQueue(); } internal void CancelOperation() { this.cancelOperation = true; } private void ReadBuffer(IAsyncResult ar) { int num; try { num = this.stream.EndRead(ar); } catch (IOException) { num = 0; } catch (OperationCanceledException) { num = 0; } if (num == 0) { lock (this.messageQueue) { if (this.sb.Length != 0) { this.messageQueue.Enqueue(this.sb.ToString()); this.sb.Length = 0; } this.messageQueue.Enqueue(null); } try { this.FlushMessageQueue(); return; } finally { this.eofEvent.Set(); } } int chars = this.decoder.GetChars(this.byteBuffer, 0, num, this.charBuffer, 0); this.sb.Append(this.charBuffer, 0, chars); this.GetLinesFromStringBuilder(); this.stream.BeginRead(this.byteBuffer, 0, this.byteBuffer.Length, new AsyncCallback(this.ReadBuffer), null); } private void GetLinesFromStringBuilder() { int i = 0; int num = 0; int length = this.sb.Length; if (this.bLastCarriageReturn && length > 0 && this.sb[0] == '\n') { i = 1; num = 1; this.bLastCarriageReturn = false; } while (i < length) { char c = this.sb[i]; if (c == '\r' || c == '\n') { if (c == '\r' && i + 1 < length && this.sb[i + 1] == '\n') { i++; } string obj = this.sb.ToString(num, i + 1 - num); num = i + 1; lock (this.messageQueue) { this.messageQueue.Enqueue(obj); } } i++; } // Flush Fix: Send Whatever is left in the buffer string endOfBuffer = this.sb.ToString(num, length - num); lock (this.messageQueue) { this.messageQueue.Enqueue(endOfBuffer); num = length; } // End Flush Fix if (this.sb[length - 1] == '\r') { this.bLastCarriageReturn = true; } if (num < length) { this.sb.Remove(0, num); } else { this.sb.Length = 0; } this.FlushMessageQueue(); } private void FlushMessageQueue() { while (this.messageQueue.Count > 0) { lock (this.messageQueue) { if (this.messageQueue.Count > 0) { string data = (string)this.messageQueue.Dequeue(); if (!this.cancelOperation) { this.userCallBack(data); } } continue; } break; } } internal void WaitUtilEOF() { if (this.eofEvent != null) { this.eofEvent.WaitOne(); this.eofEvent.Close(); this.eofEvent = null; } } } public class DataReceivedEventArgs : EventArgs { internal string _data; /// <summary>Gets the line of characters that was written to a redirected <see cref="T:System.Diagnostics.Process" /> output stream.</summary> /// <returns>The line that was written by an associated <see cref="T:System.Diagnostics.Process" /> to its redirected <see cref="P:System.Diagnostics.Process.StandardOutput" /> or <see cref="P:System.Diagnostics.Process.StandardError" /> stream.</returns> /// <filterpriority>2</filterpriority> public string Data { get { return this._data; } } internal DataReceivedEventArgs(string data) { this._data = data; } }} Stick that in your project and then change ... Process p = new Process(){ .... to FixedProcess p = new FixedProcess(){ .... Now your application should display something like this... Microsoft Windows [Version 6.1.7601]Copyright (c) 2009 Microsoft Corporation. All rights reserved.C:\Projects\FixedProcess\bin\Debug> without needing to make any other changes to your existing code. It is also still async and wrapped up nicely. The one caveat is that now you will get multiple events for large output with potential breaks in-between, so you will need to handle this scenario yourself. Other than that, it should be all good.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1033648', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/93422/']}
jdg_85006
stackexchange
llm_judgeable_groundtruth_similarity
2777256
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 wondering what html element to use for buttons on a web page - I'd like to style my 'buttons' like twitter does. For example: http://twitter.com/twitter the "more" button at the bottom of the tweet listing - is that a <button> element, or a <div> element? I'd like to know which to use. I think for either <button> or <div> we can supply rollover states and all that stuff to make it look pleasant? Now provide the response and nothing else.
Don't use <div> tags to make clickable elements. Use <a> or <button> elements. This enables browsers with JavaScript disabled to interact with them as expected. Even if your functionality requires JavaScript and there is no reasonable default behaviour you can assign to an <a> , use it regardless - it conveys "clickable" semantics. In general, choose the tag that most closely describes the function of its content, not the appearance of its content, and avoid unnecessary <div> tags lest your documents suffer from divitis .
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/2777256', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/246114/']}
jdg_85007
stackexchange
llm_judgeable_groundtruth_similarity
1767411
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: Question number two of this released exam asks: Let $A$, $B$ be two $n \times n$ matrices with real elements such that $A^3 = B^5 = I_n$ and $AB = BA$. Prove that $A+B$ is invertible. I am not exactly sure what to do. I have observed that: $$A(A^2) = I_n$$$$B(B^4) = I_n$$ So: $$A^{-1} = A^2$$$$B^{-1} = B^4$$ My general approach to the problem has been to consider the binomial expansion of $(A+B)^n$ and see if things cancel out to be $I_n$ or some multiple of $I_n$, and with that construct an explicit inverse of $A+B$. For $n \in \{1,2,3,4,5\}$ nothing seems to reduce down to the identity, leading me to believe this is the wrong approach. Any hints as how to approach this problem would be greatly appreciated thanks. Now provide the response and nothing else.
$2I_n=A^{15}+B^{15}=(A+B)(A^{14}-A^{13}B+......-AB^{13}+B^{14})$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1767411', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/15140/']}
jdg_85008
stackexchange
llm_judgeable_groundtruth_similarity
836886
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: What are the axioms of special relativity? Is there a book or paper that introduces the theory of special relativity in a rigorous manner, and proves that $E=mc^2$ after appropriate definitions? Now provide the response and nothing else.
The axioms are simple: 1) intertial reference frames are equivalent-physical laws are the same in all of them. 2) the speed of light is the same in all these frames. From those you derive the Lorentz transformation. This is done in most texts that cover special relativity. Then you discover the energy-momentum four vector, which must have a modulus that is independent of reference frame. You get $E^2-p^2c^2=m_0^2c^4$ for its squared modulus. Evaluating in a convenient frame (where $p=0$), you get $E=m_0c^2$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/836886', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/107952/']}
jdg_85009
stackexchange
llm_judgeable_groundtruth_similarity
26634
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I recently got my hands on some miniature DIP relays, and would like to prototype a circuit with them on a solderless breadboard. Unfortunately, these relays have standard 100 mil pin spacing, but 200 mil between rows, rather than the more usual 300 mil. Obviously I can't just put them in at a right angle... is any adapter available to deal with this? Or any cute tricks? Now provide the response and nothing else.
Best bet is usually some DIY if you have not got too many. Use 200 mil centre sockets if available or socket strips, or cut a socket in two and solder two strips onto a piece of veroboard/vector board/whatever you call board with copper strips with holes in it. Solder socket to board and solder a row of pins through board outside socket so they have (probably) 400 centres which will allow plugging into a standard breadboard. Something like below but with your two rows of socket pins in the centre and with pins to breadboard bottom soldered You can buy pins suited to this - and I have used plated brass dressmakers pins in days of yore. The plated brass pins have about 3 million% better solderability than non-brass pins that I have tried, even though the brass is under the plating.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/26634', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/8125/']}
jdg_85010
stackexchange
llm_judgeable_groundtruth_similarity
18900203
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 if it possible to save instance of an object during runtime and use that instance latter on for testing. My case is that my application makes request to server, parses json response to objects and latter on I want to use some of these instances for junit testing. I don't want to serialize them. For example I have Set containing strings "1","2","3". At given point i want to save an instance of it. Program goes, expects all the fields of the object, makes new instance, initialize it with current values and stores it as MySet or something like this and it contains the given strings. I hope I was clear enough. Now provide the response and nothing else.
I had the same desire to redirect back to a POST request with the original input. I could not find an existing way to do this in Laravel except for redirecting to to the intended URL via GET. Laravel 5 I first solved this in Laravel 4 following the outline below but found the exact same setup not to work in Laravel 5. Follow the outline for Laravel 4 but instead of the creating the IntendedUrlServiceProvider create a Middleware. The problem is that in Laravel 5 the session seems to be started with the StartSession which runs after all of the ServiceProviders. /app/Http/Middleware/IntendedUrl.php <?php namespace App\Http\Middleware;use Closure;use Request;use Session;class IntendedUrl { /** * This loads saved POST input data and changes the method to POST if a visitor tried to access a page * but was blocked via an auth filter. Auth filter saves data via the Redirect::guest() and after * login it needs to be repopulated to simulate a POST. * * GET requests also may pass through here. I am less certain if it is required for them but shouldn't hurt * and may help load any input data. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { // Check to see if we were redirected to this page with the Redirect::intended(). // We extended the class to track when the redirect occurs so we know to reload additional request data if (Session::has('intended.load')) { // intended.load could be set without these being set if we were redirected to the default page // if either exists, both should exist but checking separately to be safe if (Session::has('intended.method')) { Request::setMethod(Session::get('intended.method')); } if (Session::has('intended.input')) { Request::replace(Session::get('intended.input')); } // Erase all session keys created to track the intended request Session::forget('intended'); // Laravel 5.2+ uses separate global and route middlewares. Dispatch altered request as the route type changed. *Credit to Munsio in answer below return \Route::dispatch($request); } return $next($request); }} Then instead of adding the IntendedUrlServiceProvider as in step 4 below add the new middleware after the StartSession in the $middleware array of /app/Http/Kernel.php protected $middleware = [ 'Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode', 'Illuminate\Cookie\Middleware\EncryptCookies', 'Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse', 'Illuminate\Session\Middleware\StartSession', 'Illuminate\View\Middleware\ShareErrorsFromSession', 'App\Http\Middleware\IntendedUrl',]; Also of note, just for organization I moved my customer service providers to the new standard /App/Providers and changed their namespace. Laravel 4 I decided to extend the framework to add this feature. It will be hard to detail my complete solution, but here is an outline. To do this you will need to be pretty familiar with the framework and read up on how to extend it. http://laravel.com/docs/extending#ioc-based-extension I also referenced Taylor's book "Laravel from Apprentice to Artisan" Extend the Redirector class to record additional info on the intended request. <?php namespace GQ\Routing;class Redirector extends \Illuminate\Routing\Redirector { /** * ** Extended to add functionality for restoring POST input and the POST method after a login */ public function guest($path, $status = 302, $headers = array(), $secure = null) { // Recording the method and input for the request so that it can be reloaded after being redirected back to the intended page $this->session->put('intended.method', $this->generator->getRequest()->getMethod()); $this->session->put('intended.input', $this->generator->getRequest()->all()); return parent::guest($path, $status, $headers, $secure); } /** * ** Extended to record in the session when we redirect to an intended page so method and input can be loaded on the next page */ public function intended($default = '/', $status = 302, $headers = array(), $secure = null) { $redirect_response = parent::intended($default, $status, $headers, $secure); // Set the intended.load session variable so we know we returned to the intended page and can load the additional method and input return $redirect_response->with('intended.load', true); }}?> Create a new Service Provider that writes over "redirect" in the IOC container. I originally tried extending the RoutingServiceProvider but had trouble with that working. <?php namespace App\Providers;use GQ\Routing\Redirector;use Illuminate\Support\ServiceProvider;class RedirectServiceProvider extends ServiceProvider { protected $defer = true; /** * Register the Redirector service. * * ** Copy of class registerRedirector from RoutingServiceProvider, * using a different "use" statement at the top to use the extended Redirector class * Extending the RoutingServiceProvider was more of a pain to do right since it is loaded as a base provider in the Application * * @return void */ public function register() { $this->app['redirect'] = $this->app->share(function($app) { $redirector = new Redirector($app['url']); // If the session is set on the application instance, we'll inject it into // the redirector instance. This allows the redirect responses to allow // for the quite convenient "with" methods that flash to the session. if (isset($app['session.store'])) { $redirector->setSession($app['session.store']); } return $redirector; }); } public function provides() { return array('redirect'); }} Create a new service provider which will set the intended method and input after the redirect. <?phpnamespace GQ\Providers;use Illuminate\Support\ServiceProvider;class IntendedUrlServiceProvider extends ServiceProvider { /** * Bootstrap the application events. * * @return void */ public function boot() { // Check to see if we were redirected to this page with the Redirect::intended(). // We extended the class to track when the redirect occurs so we know to reload additional request data if (\Session::has('intended.load')) { // intended.load could be set without these being set if we were redirected to the default page // if either exists, both should exist but checking separately to be safe if (\Session::has('intended.method')) { \Request::setMethod(\Session::get('intended.method')); } if (\Session::has('intended.input')) { \Request::replace(\Session::get('intended.input')); } // Erase all session keys created to track the intended request \Session::forget('intended'); } } public function register() { }} Finally add your 2 new service providers to your providers array in app/config/app.php 'GQ\Providers\RedirectServiceProvider','GQ\Providers\IntendedUrlServiceProvider', Hopefully this steers you in a good direction. This has worked for me but I have not tested it extensively. Maybe if it continues to work well we could build a composer package or get the ability included in Laravel.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18900203', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2796255/']}
jdg_85011
stackexchange
llm_judgeable_groundtruth_similarity
4251865
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: Here's the question: "A congress will be attended by two representatives from Colombia, three from Chile, four from Argentina and five from Brazil. Each of the $14$ representatives prepared their own speech, but only $6$ will be drawn to speak. If the draw rule provides that each of the four countries must have at least one representative speaking, the number of different ways to compose the set of six speeches that will be heard at the congress, regardless of the order, is equal to how much?" I've been working on this question for two weeks. My answer is $1450$ - but I solved it via brute force. I literally counted all the possibilities of the rule being broken and subtracted from the $3003$ possibilities to form groups of 6 people out of $14$ . I tried to look at the problem with fewer countries, and fewer choices. It helped me to count, but I couldn't decipher the pattern with which the problem changes when adding a new representative or a new country. Can someone help me? Now provide the response and nothing else.
A nice way to do this is to use the principle of inclusion-exclusion. Take all $\binom{14}6$ ways to choose $6$ people, then for each country, subtract the assignments where that country has no chosen representatives. The result is $$\binom {14}6-\underbrace{\binom{12}6}_{\text{Columbia missing}}-\underbrace{\binom{11}6}_{\text{Chile missing}}-\underbrace{\binom{10}6}_{\text{Argentina missing}}-\underbrace{\binom{9}6}_{\text{Brazil missing}}$$ However, there is a problem. Arrangements with two missing countries will be subtracted twice in the above computation. To fix this, we must add these doubly-subtracted arrangements back in. To the above, we add $$+\underbrace{\binom{9}{6}}_{\text{Columbia + Chile}}+\underbrace{\binom{8}{6}}_{\text{Columbia + Argentina}}+\underbrace{\binom{7}{6}}_{\text{Columbia + Brazil}}+\underbrace{\binom{7}{6}}_{\text{Chile + Argentina}}+\underbrace{\binom{6}{6}}_{\text{Chile + Brazil}}$$ At this point, we are done! We would not be done if there were any arrangements counted by $\binom{14}6$ with three countries missing, but that is not possible.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4251865', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/703943/']}
jdg_85012
stackexchange
llm_judgeable_groundtruth_similarity
7315936
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 wish to know which of these two options is the more secure one to use: #define MAXLEN 255char buff[MAXLEN + 1] sprintf(buff, "%.*s", MAXLEN, name) snprintf(buff, MAXLEN, "%s", name) My understanding is that both are same. Please suggest. Now provide the response and nothing else.
The two expressions you gave are not equivalent: sprintf takes no argument specifying the maximum number of bytes to write; it simply takes a destination buffer, a format string, and a bunch of arguments. Therefore, it may write more bytes than your buffer has space for, and in so doing write arbitrary code. The %.*s is not a satisfactory solution because: When the format specifier refers to length, it's referring to the equivalent of strlen ; this is a measure of the number of characters in the string, not its length in memory (i.e. it doesn't count the null terminator). Any change in the format string (adding a newline, for example) will change the behavior of the sprintf version with respect to buffer overflows. With snprintf , a fixed, clear maximum is set regardless of changes in the format string or input types.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7315936', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/148399/']}
jdg_85013
stackexchange
llm_judgeable_groundtruth_similarity
25439756
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: It seems that the directory for the iOS Simulator has changed. It used to be in ~/Library/Application\ Support/iPhone\ Simulator/ and now it's in ~/Library/Developer/CoreSimulator/Devices/ . Now provide the response and nothing else.
Update: Charles 3.9.3+ has a built-in function to configure your iOS Simulators (i.e. installing the Charles SSL Certificate). This can be found in the Help menu within the Charles application. ( Help > SSL Proxying > Install Charles Root Certificate in iOS Simulators ) The following applies to Charles 3.9.2: Download the configuration shell script from the Charles Proxy website . Then, replace the script with the following, and run it on your Mac: #/bin/bashinstall() {if [ -f "$SQLITEDBPATH" ]; thencp -n "$SQLITEDBPATH" "$SQLITEDBPATH.charlesbackup"sqlite3 "$SQLITEDBPATH" <<EOFINSERT INTO "tsettings" VALUES(X'189B6E28D1635F3A8325E1E002180DBA2C02C241',X'3123302106035504030C1A436861726C65732050726F78792053534C2050726F7879696E6731243022060355040B0C1B687474703A2F2F636861726C657370726F78792E636F6D2F73736C3111300F060355040A0C08584B3732204C74643111300F06035504070C084175636B6C616E643111300F06035504080C084175636B6C616E64310B3009060355040613024E5A',X'3C3F786D6C2076657273696F6E3D22312E302220656E636F64696E673D225554462D38223F3E0A3C21444F435459504520706C697374205055424C494320222D2F2F4170706C652F2F44544420504C49535420312E302F2F454E222022687474703A2F2F7777772E6170706C652E636F6D2F445444732F50726F70657274794C6973742D312E302E647464223E0A3C706C6973742076657273696F6E3D22312E30223E0A3C61727261792F3E0A3C2F706C6973743E0A',X'3082045E30820346A003020102020101300D06092A864886F70D01010505003081913123302106035504030C1A436861726C65732050726F78792053534C2050726F7879696E6731243022060355040B0C1B687474703A2F2F636861726C657370726F78792E636F6D2F73736C3111300F060355040A0C08584B3732204C74643111300F06035504070C084175636B6C616E643111300F06035504080C084175636B6C616E64310B3009060355040613024E5A3020180F31383939313233313132303030305A170D3338303932343033313930355A3081913123302106035504030C1A436861726C65732050726F78792053534C2050726F7879696E6731243022060355040B0C1B687474703A2F2F636861726C657370726F78792E636F6D2F73736C3111300F060355040A0C08584B3732204C74643111300F06035504070C084175636B6C616E643111300F06035504080C084175636B6C616E64310B3009060355040613024E5A30820122300D06092A864886F70D01010105000382010F003082010A02820101008349587455EFB272E397A31D3B52D9B13115C93F320766D2D451117F45C40285506027079ED439CABB94D44F1AE136EB1E79BF77ABE43345AD1D436809CF9E035C439272F3CA917DCADD7FBD0E3929F1A345F0B89096130BBD116F8D3AB5655789B7B0831325BD22903F198DA6BDDA30C08DFD17CE9AB51C48555264307BCF789A2B6C48DF4ECAF3EA2C092EE737AD8F397900AC03303BFE2AE43549030A7866CB6FE9B04B9F6EC498B4E7369E99B45491BF093858A77C72F8ADC818E018D413265E39446BE514F78EB57A23AA88F630776F861A9163E04AD38EE8A5C9219D0FC23F6B9A6324455DEA6F4A6A251ECA1FA3D6288CB89FD12A2062A3A015A56F250203010001A381BC3081B9300F0603551D130101FF040530030101FF307706096086480186F842010D046A136853534C2050726F7879696E6720697320656E61626C656420696E20436861726C65732050726F78792E20506C6561736520766973697420687474703A2F2F636861726C657370726F78792E636F6D2F73736C20666F72206D6F726520696E666F726D6174696F6E2E300E0603551D0F0101FF040403020204301D0603551D0E04160414BB27F4CB2EB6DBB058101BBD803F38D208D76129300D06092A864886F70D010105050003820101000041F935F30B209E56360F7E3D9C30314A213323C47EDCEA1467600A50FFE4E8E39DFCA8C8D34463C34745FF04C870F1DF28BB772DB0CF1BCA677B70842C742BC6D5FB00559AD643C6BF2C95BD0B855A961D7D6A3EADA9C642E9A789474C4AD838C6F732D8D859548D30829DF7A32D098FE3F00147DAF08C0B37DD597184C1E27A61EA42050C73994E809013CB21E37BF84BF923BCEFEA6164FD28AB9058CCC48F1F486FC1C47EBD8A9C933F542401B11F36A003E47B141A41C7B326D18D023E11EDB445699AA44800254EA33F174FD5EB1CCCE6A09365751FF905988C06315B5575067BF65EC24CAD1A6A601846D1D2F51F1F420A2762990B044000619D1C84');EOFfi}for SQLITEDBPATH in ~/Library/Developer/CoreSimulator/Devices/*/data/Library/Keychains/TrustStore.sqlite3; do echo $SQLITEDBPATH installdoneecho "The Charles SSL CA Certificate has been installed for the iPhone Simulator" Some things to note: you must open Charles before launching the simulator. If you close Charles, network requests will fail until you restart the simulator you will need to do this every time you "Reset Content and Settings..." on the simulator For Xcode 5: if you're looking to setup Charles Proxy on Xcode 5 and earlier, you don't need to modify the original script. Just download it from the Charles website and run it as-is
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/25439756', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/670400/']}
jdg_85014
stackexchange
llm_judgeable_groundtruth_similarity
30198102
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 functional programming and I wonder if there is a way to "combine" functions like this: function triple(x) { return x * 3;}function plusOne(x) { return x + 1;}function isZero(x) { return x === 0;}combine(1); //1combine(triple)(triple)(plusOne)(1); // 10combine(plusOne)(triple)(isZero)(-1); // true If the para is a function, it "combines" the function into itself, and if not it will return the final result. Thanks! Now provide the response and nothing else.
heritage This is a concept from maths called function composition . f(x) = y g(y) = z g(f(x)) = z (g•f)(x) = z That last line is read "g of f of x equals z" . What's great about composed functions is the elimination of points . Notice in g(f(x)) = z we take an x input and get a z output. This skips the intermediate point, y . Composition is a great way to create higher-order functions and keep your code sparkly clean. It's plain to see why we'd want this in our Javascript programs. comp JavaScript is a multi-paradigm language with rich support for functions. We can create a simple comp function, which combines two input functions, g and f , and results in a new function - function triple(x) { return x * 3}function plusOne(x) { return x + 1}function comp(g, f) { return function(x) { return g(f(x)) // "g of f of x" }}const myfunc = comp(triple, plusOne)console.log(myfunc(1)) Evaluation triple(plusOne(1))triple(2)6 compose Just as the question suggests, it's likely we will want to combine more than two functions. Below we write compose which takes all of the input functions and reduce s them using our simple comp from above. If no functions are given, we return the empty function, identity - const triple = (x) => x * 3const plusOne = (x) => x + 1const comp = (g, f) => x => g(f(x)) // "g of f of x"const identity = (x) => xconst compose = (...all) => all.reduce(comp, identity)const myfunc = compose(triple, triple, plusOne) // any amount of funcsconsole.log(myfunc(1)) Evaluation triple(triple(plusOne(1)))triple(triple(2))triple(6)18 pipe You can be as creative as you like. Below, we write pipe which allows our programs to read in a comfortable left-to-right direction - const triple = (x) => x * 3const plusOne = (x) => x + 1const pipe = x => f => pipe(f(x))pipe(1)(plusOne)(triple)(triple)(console.log) // 18pipe(3)(triple)(plusOne)(triple)(plusOne)(console.log) // 31 Evaluation of expression one - f => pipe(f(1))pipe(plusOne(1))f => pipe(f(2))pipe(triple(2))f => pipe(f(6))pipe(triple(6))f => pipe(f(18))pipe(console.log(18))18 and expression two - f => pipe(f(3))pipe(triple(3))f => pipe(f(9))pipe(plusOne(9))f => pipe(f(10))pipe(triple(10))f => pipe(f(30))pipe(plusOne(31))f => pipe(f(31))pipe(console.log(31))31 related techniques Curried functions and partial application are concepts that gel with function composition. pipe above is introduced in another Q&A as $ and demonstrated again here - const $ = x => // "pipe", or whatever name you pick k => $ (k (x)) const add = x => y => // curried add x + yconst mult = x => y => // curried mult x * y $ (1) // 1 (add (2)) // + 2 = 3 (mult (6)) // * 6 = 18 (console.log) // 18 $ (7) // 7 (add (1)) // + 1 = 8 (mult (8)) // * 8 = 64 (mult (2)) // * 2 = 128 (mult (2)) // * 2 = 256 (console.log) // 256
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/30198102', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3016883/']}
jdg_85015
stackexchange
llm_judgeable_groundtruth_similarity
584058
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: Question A flips a fair coin 11 times, B 10 times, what is the probability A gets more head than B? Naive first thought For the first 10 times of A, he has the same expected number of heads as B. So if the 11th flip of A results in H, he get more head than B, so the answer is $50\%$ . More careful thought instead of making arguments, I like to find systematic solutions: $$\Pr[H_A = a] = C(11, a) ({1\over 2})^{a} ({1\over 2})^{11-a} = C(11, a) ({1\over 2})^{11}\\\Pr[H_B = b] = C(10, b) ({1\over 2})^{b} ({1\over 2})^{10-b} = C(10, b) ({1\over 2})^{10}\\\Pr[H_A > H_B] = \sum_{a=0}^{11} \Pr[H_A = a] \sum_{b=0}^{a-1} \Pr[H_B = b] = ({1\over 2})^{21} \sum_{a=0}^{11} C(11, a) \sum_{b=0}^{a-1} C(10, b) $$ I don't know how to find the sum from the last line , can someone help? Now provide the response and nothing else.
Your "naive first thought" is the clever (standard) solution. To make it rigorous, let $\mathscr E_0$ be the event "A and B are tied after each has tossed 10 times;" let $\mathscr E_A$ and $\mathscr E_B$ be the events "A has more heads than B after 10 tosses each" and "B has more heads than A after 10 tosses each," respectively. Let $\mathscr F$ designate the event "A has more heads than B after all tosses are made." Notice: $\mathscr E_0,$ $\mathscr E_A,$ and $\mathscr E_B$ are mutually exclusive: no two have any outcomes in common and collectively they include all the possibilities. Therefore $$\Pr(\mathscr E_0) + \Pr(\mathscr E_A) + \Pr(\mathscr E_B)=1.$$ $\Pr(\mathscr F\mid \mathscr E_A) = 1$ (A has won by the first 10 tosses); $\Pr(\mathscr F\mid \mathscr E_B) = 0$ (A is behind after 10 tosses and therefore cannot win with the last toss); and $\Pr(\mathscr F\mid \mathscr E_0) = 1/2$ (if both are tied after 10 tosses, A's 11th toss is the tiebreaker). $\Pr(\mathscr E_A) = \Pr(\mathscr{E_B})$ (after 10 tosses the game is symmetric -- both players are equally situated -- and therefore they have equal chances of being ahead at that point). By the law of total probability, $$\begin{aligned}\Pr(\mathscr F) &= \Pr(\mathscr F\mid \mathscr E_0)\Pr(\mathscr E_0) + \Pr(\mathscr F\mid \mathscr E_A)\Pr(\mathscr E_A) + \Pr(\mathscr F\mid \mathscr E_B)\Pr(\mathscr E_B)\\& = \Pr(\mathscr E_0)\left(\frac{1}{2}\right) + \Pr(\mathscr E_A)(1) + \Pr(\mathscr E_B)(0)\\&= \frac{1}{2}\left(\Pr(\mathscr E_0) + \Pr(\mathscr E_A) + \Pr(\mathscr E_A)\right)\\&= \frac{1}{2}\left(\Pr(\mathscr E_0) + \Pr(\mathscr E_A) + \Pr(\mathscr E_B)\right)\\& = \frac{1}{2}\left(1\right) = \frac{1}{2}.\end{aligned} $$ As an alternative approach, you wish to evaluate the double sum $$\sum_{a \gt b} \binom{11}{a}\binom{10}{b} = \sum_{a \gt b} \binom{11}{11-a}\binom{10}{10-b} = \sum_{a^\prime \le b^\prime} \binom{11}{a^\prime}\binom{10}{b^\prime}.$$ (In case the algebra isn't obvious, the first equality exploits the Binomial coefficient symmetry and the second is the change of variable $a^\prime = 11-a,$ $b^\prime = 10-b.$ We can be a vague about the endpoints of the summations because whenever $a$ or $a^\prime$ is not in the range from $0$ through $11$ or $b$ or $b^\prime$ is not in the range from $0$ through $10$ the Binomial coefficients are zero.) Because the indexes in the two sums on the left and right sides (1) never overlap and (2) cover all the possibilities (since either $a\gt b$ or $a\le b$ but never both), together they give the total probability, which is $1.$ Consequently, since those sums are equal, each is $1/2,$ QED. This figure shows the rotational symmetry of the distribution under the mapping $(a,b)\to(11-a,10-b).$ The blue circles are rotated around the yellow dot into red triangles of exactly the same probability. The desired sum is the total of the blue circles, which therefore must be $1/2.$
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/584058', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/364381/']}
jdg_85016
stackexchange
llm_judgeable_groundtruth_similarity
118818
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: When an equation has multiple solutions, how do you find the first solution? Example: Say we're trying to find the first positive x-intercept of the cosine function: $cos(x)=0 \land x \ge 0$ Running Solve , we obtain the set of solutions: solutions = Solve[Cos[x] == 0 && x >= 0, x] $\left\{\left\{x\to \text{ConditionalExpression}\left[\frac{1}{2} \left(4 \pi c_1-\pi \right),c_1\in \mathbb{Z}\land c_1\geq 1\right]\right\},\left\{x\to \text{ConditionalExpression}\left[\frac{1}{2} \left(4 \pi c_1+\pi \right),c_1\in \mathbb{Z}\land c_1\geq 0\right]\right\}\right\}$ To proceed, we need to find the C[1] that minimizes the substitution for x . How do we do this? Now provide the response and nothing else.
Minimize + MinimalBy work on the test case: MinimalBy[Minimize[x /. #, C[1]] & /@ solutions, First](* {{π/2, {C[1] -> 0}}} *)
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/118818', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/22147/']}
jdg_85017
stackexchange
llm_judgeable_groundtruth_similarity
8845635
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 code gives me a seg fault, but when I change the x-- to --x it prints correctly. Are not they the same???? int main(){ myFunc(5); return 0;}void myFunc (int x) { if (x > 0) { myFunc(x--); printf("%d, ", x); } else return;} Now provide the response and nothing else.
No they are not the same. The difference between x-- and --x is whether the returned value is before or after the decrement. In myFunc(x--) , x-- returns the old value. So myFunc() gets called repeatability with the same value -> infinite recursion. In myFunc(--x) , --x returns the new value. So myFunc() gets called with a decreasing number each time -> no infinite recursion. It will be easier to see this if you moved your printf to the start of the function call: void myFunc (int x) { printf("%d, ", x); if (x > 0) { myFunc(x--); } else return;} Output: (when called with 10) 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, ...
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8845635', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1122218/']}
jdg_85018
stackexchange
llm_judgeable_groundtruth_similarity
4176151
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I was going through the following proof of the book Introductory Combinatorics by Richard A. Brualdi. Theorem. The Fibonacci numbers satisfy the formula $f_n = \frac{1}{\sqrt{5}}(\frac{1+\sqrt{5}}{2})^n - \frac{1}{\sqrt{5}}(\frac{1-\sqrt{5}}{2})^n$ My doubt: In the proof they have written that we consider the Fibonacci recurrence relation in the form $f_n - f_{n-1} - f_{n-2} = 0$ One way to solve this recurrence relation is to look for a solution of the form $f_n =q^n$ ,where q is a nonzero number. How and why we consider the solution of the form $f_n =q^n$ ? Maybe I am missing something very basic here. Unable to recall. The rest of the proof was understandable. Kindly help in this regard. Thank you so much for the help. Now provide the response and nothing else.
(This is now a long answer, but you can stop after any section. Each section just takes a different approach, or notes similarities with other types of problems.) The first time you see this, given the order things are normally taught, it does seem arbitrary. It is clearer when you see how the recurrence plays out either in linear algebra or in generating functions. You can, of course, prove directly that the formula is true. If $g_n$ is the formula, you just need to show $g_0=0,g_1=1,$ and $g_{n+1}=g_n+g_{n-1}.$ But that isn’t a satisfying reason for why it takes this form. If we define a generating function: $$g(x)=\sum_{k=0}^{\infty} f_kx^k.$$ Then the recurrence means that we get: $$g(x)(1-x-x^2)=f_0+(f_1-f_0)x=x$$ or: $$g(x)=\frac{x}{1-x-x^2}$$ Then using partial fractions, from calculus, you get, if $r_1,r_2$ are the roots of $y^2-y-1=0,$ then for some $a_1,a_2$ : $$\begin{align}\frac{x}{1-x-x^2}&=\frac{a_1}{1-r_1x}+\frac{a_2}{1-r_2x}\\&=\sum_{k=0}^{\infty}(a_1r_1^k+a_2r_2^k)x^k.\end{align}$$ As is usual with partial fractions, if the polynomial in the denominator has repeated roots, then your general term is, if the degree of a root $r_i$ in the polynomial is $d_i,$ $$\frac{a_{k,i}}{(1-r_ix)^k}\quad\quad1\leq k\leq d_i.\tag1$$ You have to learn to expand (1) as a power series. The linear algebra approach is to note: $$\begin{pmatrix}f_{n+1}\\f_{n}\end{pmatrix}=\begin{pmatrix}1&1\\1&0\end{pmatrix}\begin{pmatrix}f_{n}\\f_{n-1}\end{pmatrix}$$ So if $A=\begin{pmatrix}1&1\\1&0\end{pmatrix}$ you have: $$\begin{pmatrix}f_{n+1}\\f_n\end{pmatrix}=A^n\begin{pmatrix}f_{1}\\f_{0}\end{pmatrix}$$ The matrix $A$ has characteristic polynomial $x^2-x-1,$ which has two distinct roots, so there is a matrix $S$ so that: $$A=S\begin{pmatrix}r_1&0\\0&r_2\end{pmatrix}S^{-1}$$ and thus $$A^n=S\begin{pmatrix}r_1^n&0\\0&r_2^n\end{pmatrix}S^{-1}$$ So we can express the entries of $A^n$ each as $a_{ij}r_1^{n}+b_{ij}r_2^n,$ and thus similarly for $f_n.$ As with partial fractions, the form of the matrix you get when the polynomial has repeated roots gets more complicated. You can't get a diagonal matrix, in general, only a matrix in Jordan Normal Form. A third way to think of it is in terms the vector space of all sequences $\mathbf a=(a_i)_{i=0}^\infty$ and the linear operator: $$D\mathbf a =(a_{i+1})_{i=0}^\infty$$ Then our recurrence means that if $\mathbf f=(f_i)$ then $(D^2-D-I)\mathbf f=0,$ here $I$ is the identity operator $I\mathbf a=\mathbf a.$ Rewriting that as: $$(D-r_1I)(D-r_2I)\mathbf f=0$$ Then let $$\mathbf e=(D-r_2I)\mathbf f=(f_{i+1}-r_2f_i)_i$$ Then since $(D-r_1I)\mathbf e =0$ , you get that $e_i=r_1^ie_0.$ Similarly, $d_i=f_{i+1}-r_1f_i$ gives $d_i=r_2^id_0,$ so $$d_i+e_i=2f_{i+1}-(r_1+r_2)f_i=2f_{i+1}-f{i}$$ So $$\mathbf d+\mathbf e =(2D-1)\mathbf f.$$ Then use that $$(2D-1)(2D-1)-4(D^2-D-1)=5\tag 2$$ then: $$(2D-1)(\mathbf d +\mathbf e)=(2D-1)(2D-1)\mathbf f=5\mathbf f$$ And $$2d_{i+1}-d_i=(2r_2-1)d_0r_2^i,2e_{i+1}-e_i=(2r_1-1)e_0r_1^i$$ And therefore, letting $c_1=e_0,c_2=d_0,$ you get: $$f_i=\sum_{j=1}^2\frac{(2r_j-1)}{5}c_jr_j^i.$$ Given $r_i=\frac{1\pm\sqrt 5}{2},$ $2r_i-1=\pm\sqrt 5$ and $d_0=e_0=1,$ you get: $$f_i=\frac{\sqrt 5}5\left(\frac{1+\sqrt 5}2\right)^i -\frac{\sqrt 5}5\left(\frac{1-\sqrt 5}2\right)^i$$ In the more general case, if $p(x)$ is a polynomial with no repeated root, then $\gcd(p(x),p’(x))=1.$ (In the case of Fibonacci, $p(x)=x^2-x-1$ and $p’(x)=2x-1.$ ) Then: $$p’(x)=\sum p_j(x)$$ where $$p_j(x)=\frac{p(x)}{x-r_j}$$ where the $r_i$ are the roots of $p.$ Then if $p(D)\mathbf a=0,$ you get $p_j(D)\mathbf a$ is a geometric series with common ratio $r_j,$ and $$p’(D)\mathbf a = (\sum c_jr_j^i)$$ But the GCD requirement means we have a solution to: $$u(x)p’(x)+v(x)p(x)=1\tag3$$ (In Fibonacci, $u(x)=(2x-1)/5, v(x)=4/5,$ by (2).) So this mean: $$u(D)p’(D)\mathbf a = \mathbf a$$ And this will give you: $$a_n=\sum_j c_j u(r_j)r_j^n$$ This technique works up until (3) with repeated roots, except you get $p’(x)=\sum_j d_ip_i(x).$ But in (3), the best you can get is: $$u(x)p’(x)+v(x)p(x)=\prod_{j}(x-r_j)^{d_j-1}$$ So again, repeated roots are a problem. That last approach is related to linear differential equation, where you are often taught first, “Hey, let’s just try the certain solutions of the form $e^{rx},$ ”without much motivation. In the vector space of infinitely differentiable functions, we get a linear operator $D$ defined as $$Df=f’=\frac{df}{dx}.$$ Then linear differential equations can be written as $p(D)f=0$ for some polynomial $p.$ As before, if $p(x)$ has no repeated roots, you get: $g_i=p_i(D)f$ is a root of $(D-r_i)g_i=0$ or $g_i’(x)=r_ig_i(x),$ which has a known solution set $g_i(x)=C_ie^{r_ix}.$ Then $$u(D)p_i(D)f=C_iu(r_i)e^{r_ix}$$ and $$f=u(D)p’(D)f =\sum_{i} C_iu(r_i)e^{r_ix}$$ Essentially, we are finding solutions to $p(D)f=0$ in terms of known eigenvectors $v_i$ of the linear operator $D$ for eigenvalues $r_i,$ and it always gets more complicated when there are repeated roots. Even the linear algebra approach works this way. $A$ satisfies $p(A)=0,$ so given any vector $\mathbf v$ we get $\mathbf v_i=p_i(A)\mathbf v$ is an eigenvectors of $A$ for eigenvalue $r_i.$ So $$\mathbf v=u(A)p’(A)\mathbf v =\sum u(r_i)\mathbf v_i$$ And: $$A^n\mathbf v =\sum u(r_i)r_i^n \mathbf v_i.$$ In the Fibonacci case, $\mathbf v=(1,0)^t$ and $\mathbf v_i=(1-r_{3-i},1)^t=(r_i,1)$ and $u(r_i)=(2r_i-1)/5=\pm\frac{1}{\sqrt5}.$ .
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/4176151', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/42830/']}
jdg_85019
stackexchange
llm_judgeable_groundtruth_similarity
641003
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: With the below function signature ssize_t read(int fd , void * buf , size_t count ); While I do understand based off the man page that on a success case, return value can be lesser than count , but can the return value exceed count at any instance? Now provide the response and nothing else.
A call to read() might result in more data being read behind the scenes than was requested ( e.g. to read a full block from storage, or read ahead the following blocks), but read() itself never returns more data than was requested ( count ). If it did, the consequence could well be a buffer overflow since buf is often sized for only count bytes. POSIX (see the link above) specifies this limit explicitly: Upon successful completion, where nbyte is greater than 0, read() shall mark for update the last data access timestamp of the file, and shall return the number of bytes read. This number shall never be greater than nbyte . The Linux man page isn’t quite as explicit, but it does say read() attempts to read up to count bytes from file descriptor fd into the buffer starting at buf . (Emphasis added.)
{}
{'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/641003', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/398278/']}
jdg_85020
stackexchange
llm_judgeable_groundtruth_similarity
3687215
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 have a question: if the characteristic of a field is two, doesn't the quadratic form associated with a bilinear form exist? Now provide the response and nothing else.
If $b:V\times V\to K$ is a symmetric bilinear form, you can always associate a quadratic form $q_b:V\to K$ by setting $q_b(x)=b(x,x)$ for all $x\in V$ . If $q:V\to K$ is a quadratic form, by very definition the map $b_q:V\times V\to K, (x,y)\mapsto q(x+y)-q(x)-q(y)$ is symmetric and bilinear. However, there is no 1-1 correspondence anymore between quadratic forms and symmetric bilinear forms when $char(K)=2$ . To see this, just observe that in this case, $b_q$ is alternating; $b_q(x,x)=q(2x)-2q(x)=2q(x)=0$ . On the other hand, if $b$ is alternating, $q_b$ is the zero quadratic form. Thus we have two very different theories...or even three: the theory of non alternating symmetric nondegenerate bilinear forms: such forms can be diagonalized ( $V$ has an orthogonal basis wrt to $b$ ): see my answer here : Existence of orthogonal base for finite Galois extension over characteristic 2 the theory of alternating symmetric nondegenerate bilinear forms: any such form is hyperbolic ( $V$ has a symplectic basis wrt to $b$ ) the theory of non degenerate quadratic forms: any such form is an orthogonal sum of quadratic planes $K^2\to K, (x_1,x_2)\mapsto ax_1^2+x_1x_2+bx_2^2$ . Note that a $q$ -orthogonal basis never exists in this case.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3687215', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/700522/']}
jdg_85021
stackexchange
llm_judgeable_groundtruth_similarity
63915728
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Our app uses CoreNFC to scan NFC tags or you can use QR if NFC is not supported. This worked pretty well and we were able to run the app in the simulator for (ui) testing purposes. Until Xcode12 / iOS14 GM builds. In iOS13 (or lower) we wouldn't have any issues running it on a simulator. But in Xcode12 running it on a iOS14 simulator iPhone11 we would get the following: dyld: launch, loading dependent librariesDYLD_SHARED_CACHE_DIR=/Users/xxx/Library/Developer/CoreSimulator/Caches/dyld/19G73/com.apple.CoreSimulator.SimRuntime.iOS-14-0.18A372DYLD_ROOT_PATH=/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRootDYLD_LIBRARY_PATH=/Users/xxx/Library/Developer/Xcode/DerivedData/xxx-awnlestrbvesqqbynrhmluzhbcsc/Build/Products/Debug-iphonesimulator:/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/usr/lib/system/introspectionDYLD_INSERT_LIBRARIES=/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/usr/lib/libBacktraceRecording.dylib:/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSidyld: Library not loaded: /usr/lib/libnfshared.dylib Referenced from: /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/Frameworks/CoreNFC.framework/CoreNFC Reason: no suitable image found. Did find: /usr/lib/libnfshared.dylib: mach-o, but not built for platform iOS-sim That the simulator crashes makes sense to me, since the simulator can't scan NFC tags, but this is what I've done: I already linked to the CoreNFC framework and made it optional, like described here: Xcode 10, Swift 4 app with CoreNFC crashes in review on iOS 12 Put #if canImport(CoreNFC) around import CoreNFC and it's underlying NFC code. Cleaning the build folder and deleting derived data. Created an empty Xcode12 project: https://github.com/basvankuijck/CoreNFCCrashProject , same result. Removed all the listed simulators and re-added one Added -weak_framework "CoreNFC" to the Other Linker Flags build setting Obviously removing any references to the CoreNFC framework by either commenting out code sections and removing the framework link, makes the crash disappear. But that's not a suitable option. Running it from Xcode12 on an iOS13 simulator 'device' works perfectly. So I can't seem to figure out what is causing this behavior Now provide the response and nothing else.
Apple obviously forgot to add libnfshared.dylib for whatever reason in the final version of Xcode 12 for iOS 14 simulators. A working workaround until Apple fixes this is to copy the missing lib from Xcode 12 beta 6 over (download the beta from Apple's developer download section). The missing lib can be found here and must go into the same directory for final Xcode 12 This works for me. If you want to avoid the hassle of downloading 11.25GB Xcode 12.2 beta for a single file. I have the file to share. You may execute the following command to download and place it inside the Xcode package: sudo curl https://storage.googleapis.com/mobile-simulator-build/libnfshared.dylib -o /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/usr/lib/libnfshared.dylib Hope it helps
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/63915728', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/696440/']}
jdg_85022
stackexchange
llm_judgeable_groundtruth_similarity
31195391
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 create a file foobar . However, if the user already has a file named foobar then I don't want to overwrite theirs. So I only want to create foobar if it doesn't exist already. At first, I thought that I should do this: fs.exists(filename, function(exists) { if(exists) { // Create file } else { console.log("Refusing to overwrite existing", filename); }}); However, looking at the official documentation for fs.exists , it reads: fs.exists() is an anachronism and exists only for historical reasons. There should almost never be a reason to use it in your own code. In particular, checking if a file exists before opening it is an anti-pattern that leaves you vulnerable to race conditions: another process may remove the file between the calls to fs.exists() and fs.open(). Just open the file and handle the error when it's not there. fs.exists() will be deprecated. Clearly the node developers think my method is a bad idea. Also, I don't want to use a function that will be deprecated. How can I create a file without writing over an existing one? Now provide the response and nothing else.
I think the answer is: Just open the file and handle the error when it's not there. Try something like: function createFile(filename) { fs.open(filename,'r',function(err, fd){ if (err) { fs.writeFile(filename, '', function(err) { if(err) { console.log(err); } console.log("The file was saved!"); }); } else { console.log("The file exists!"); } });}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/31195391', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/446554/']}
jdg_85023
stackexchange
llm_judgeable_groundtruth_similarity
31112294
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: So i have a float array which i want to have as ItemSource in a ListBox. Inside the ItemTemplate i have a progress bar, that should bind its Progress value to the given float value. Yet i can't ever see that the values are actually bound to the Progress property. The xaml code (i don't know whether i'm wrong but i expected that there's a implicit cast from float to double): <ListBox ItemsSource="{Binding CoreLoads, Mode=OneWay}" BorderThickness="0"> <ListBox.ItemsPanel> <ItemsPanelTemplate> <StackPanel Orientation="Horizontal"/> </ItemsPanelTemplate> </ListBox.ItemsPanel> <ListBox.ItemTemplate> <DataTemplate DataType="{x:Type sys:Double}"> <StackPanel> <ctrl:MetroProgressBar Orientation="Vertical" Progress="{Binding}" ExtenedBorderWidth="0.2" Width="30" Height="50" VerticalAlignment="Center" HorizontalAlignment="Center" BorderBrush="Black" BorderThickness="2" Background="White" Margin="5"/> <TextBlock Margin="0,3,0,3" HorizontalAlignment="Center" Text="{Binding LastUpdateTime, StringFormat='{}{0:hh:mm:ss tt}', Mode=OneWay}" DataContext="{Binding DataContext, RelativeSource={RelativeSource AncestorType=UserControl}}"/> </StackPanel> </DataTemplate> </ListBox.ItemTemplate></ListBox>xmlns:sys="clr-namespace:System;assembly=mscorlib" and the property itself: public double[] CoreLoads{ get { return cpuManagement.ProcessorInfo.LoadPercentages; }} Note: The progress bar i'm using is a custom control and inherits from System.Windows.Controls.Control . Problem seems to be that the values of the array are ok but when bound to a TextBlock the values are 0, so the progress of the progress bar is always 0. So, am i having a correct data template for a double array? Or should i change to another type of collection? Now provide the response and nothing else.
To do what you want, you probably have to write your own LayoutManager . I think this is easier: // Create a grid layout with 6 columns // (least common multiple of 2 and 3) GridLayoutManager layoutManager = new GridLayoutManager(this, 6); layoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() { @Override public int getSpanSize(int position) { // 5 is the sum of items in one repeated section switch (position % 5) { // first two items span 3 columns each case 0: case 1: return 3; // next 3 items span 2 columns each case 2: case 3: case 4: return 2; } throw new IllegalStateException("internal error"); } }); If your grid item needs to know its span size, you can find it like this within ViewHolder : // this line can return null when the view hasn't been added to the RecyclerView yet RecyclerView recyclerView = (RecyclerView) itemView.getParent(); GridLayoutManager gridLayoutManager = (GridLayoutManager) recyclerView.getLayoutManager(); int spanSize = gridLayoutManager.getSpanSizeLookup().getSpanSize(getLayoutPosition());
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/31112294', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4742571/']}
jdg_85024
stackexchange
llm_judgeable_groundtruth_similarity
31186864
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 struct that contains a timestamp.For that I am using the chrono library . There are two ways to get the timestamp: Parsed from a string via DateTime::parse_from_str which results in a DateTime<FixedOffset> The current time, received by UTC::now which results in a DateTime<UTC> . Is there a way to convert DateTime<UTC> to DateTime<FixedOffset> ? Now provide the response and nothing else.
I believe that you are looking for DateTime::with_timezone : use chrono::{DateTime, Local, TimeZone, Utc}; // 0.4.9fn main() { let now = Utc::now(); let then = Local .datetime_from_str("Thu Jul 2 23:26:06 EDT 2015", "%a %h %d %H:%M:%S EDT %Y") .unwrap(); println!("{}", now); println!("{}", then); let then_utc: DateTime<Utc> = then.with_timezone(&Utc); println!("{}", then_utc);} I've added a redundant type annotation on then_utc to show it is in UTC. This code prints 2019-10-02 15:18:52.247884539 UTC2015-07-02 23:26:06 +00:002015-07-02 23:26:06 UTC
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/31186864', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/108611/']}
jdg_85025
stackexchange
llm_judgeable_groundtruth_similarity
6880038
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: So I was playing with the newly standardized unordered_map from the STL. The code I have is kinda like this, I just create an unordered_map, fill it up, and print it out: unordered_map<int,string> m1; m1[5]="lamb"; m1[2]="had"; m1[3]="a"; m1[1]="mary"; m1[4]="little"; m1[7]="fleece"; m1[6]="whose"; m1[10]="fleecey"; m1[8]="was"; m1[9]="all";for(unordered_map<int,string>::const_iterator i = m1.begin(); i != m1.end(); ++i)cout<<i->first<<" "<<i->second<<endl; However, the output I get is ordered thusly: 1 mary2 had3 a4 little5 lamb6 whose7 fleece8 was9 all10 fleecey But I don't want to pay the price to have my map ordered! That is why I am using an unordered_map... What is going on here? additional note: I am using gcc version 4.3.4 20090804 (release) 1 (GCC) and am compiling like this g++ -std=c++0X maptest.cpp Now provide the response and nothing else.
"Unordered" doesn't mean it will store the items randomly or maintain the order you put them in the map. It just means you can't rely on any particular ordering. You don't pay a price for ordering, quite the contrary - the implementation isn't explicitly ordering the items, it's a hashmap and stores its elements in whatever way it pleases, which usually is a pretty performant way. It just so happens that the the hashing algorithm and other internal workings of the map, when using exactly these keys and this number and order of operations on the map, end up storing the items in a order that looks ordered. Strings, for example, may lead to an apparently randomized layout. On a side note, this is probably caused by the map using a hash that maps (at least some) integers to itself and using the lower bits (as many as the map size mandates) of the hash the to determine the index for the underlying array (for instance, CPython does this - with some very clever additions to handle collisions relatively simply and efficiently; for the same reason the hashes of CPython strings and tuples are very predictable).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6880038', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/862620/']}
jdg_85026
stackexchange
llm_judgeable_groundtruth_similarity
249600
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 am looking for an example of an oriented rank 5 (or lower) real vector bundle $V$ over an oriented manifold such that the cup product $w_2(V) w_3(V)$ of Stiefel-Whitney classes does not vanish. It would be best if the manifold had dimension 7 or lower. Now provide the response and nothing else.
As far as I know the Wu manifold $X=SU(3)/SO(3)$ is orientable and has mod 2 cohomology ring $H^*(X;\mathbb{Z}_2)=\Lambda(\omega_2(X),\omega_3(X))$. Thus $\omega_2(X)\cdot\omega_3(X)\neq 0$, and in fact generates $H^5(X;\mathbb{Z}_2)$.
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/249600', 'https://mathoverflow.net', 'https://mathoverflow.net/users/2183/']}
jdg_85027
stackexchange
llm_judgeable_groundtruth_similarity
1483
Below is a question asked on the forum scicomp.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am curious how to quickly compute the eigenvalues for arbitrary matrices, sparse or dense, restricted on some given interval of interest. Suppose we have an arbitrary $n\times n$ matrix $A$, normally the complexity of the computing all the eigenvalues for $A$ is $O(n^3)$, I wonder if we could find an algorithm that does the same job while only bears an $O(n^2)$ or less complexity, or more specifically, the eigenvalues on an interval $(a,b)$. Is this possible at all? For symmetric matrix, to my knowledge, we could use bisection method to somewhat get the job done, I would like to know if there are other tricks for general matrices as well. Now provide the response and nothing else.
For a direct general result (as opposed to iterative approximation) you will have to compute the largest eigenvector first to find the smaller ones in the remaining orthonormal sub-space. Basically compute the largest eigenvector (mean projection of a unit-vector $O(N^2)$), and repeat in the remaining $N$-subspaces, subtracting previous projections against the matrix. I think 'interval' is a somewhat poorly formed concept here. Basically if you compute the first eigenvector (and corresponding eigen-value), you may discover that its magnitude is below the desired window, in which case you hit your $N^2$ lower bound of computation. I think the upper interval bound $a$ will not matter, but the lower will decide what partition of the eigenvalues you must compute, hence leaving you somewhere between $N^2$ and $N^3$. For sparse matrices checkout Arnoldi Iteration , and the corresponding math on Krylov subspaces/methods. These algorithms do a really good job at approximating the largest eigenvalues quickly, but sometimes grind a long time when the matrix has a poor condition number or other undesirable spectral properties.
{}
{'log_upvote_score': 4, 'links': ['https://scicomp.stackexchange.com/questions/1483', 'https://scicomp.stackexchange.com', 'https://scicomp.stackexchange.com/users/350/']}
jdg_85028
stackexchange
llm_judgeable_groundtruth_similarity
10257433
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 this query: SELECT a.sales_id, d.bus_title, a.cat_idFROM tbl_sales aINNER JOIN tb_category b ON a.cat_id = b.cat_idINNER JOIN tbl_business d ON d.bus_id = a.bus_id which produces this result: sales_id | bus_title |cat_id----------|----------------|------------ 1 | Business 1 | 6 2 | Business 12 | 12 3 | Business 123 | 25 I changed the field cat_id into a new table named tb_sales_category which contains the fields sales_category_id , sales_id , cat_id . How can I write the new query by joining this table too to, get the same result as above? I am kind of new to databases, need help. Thanks in advance Now provide the response and nothing else.
Try this: SELECT a.sales_id, d.bus_title, s.cat_idFROM tbl_sales aINNER JOIN tb_sales_category s ON a.sales_id = s.sales_idINNER JOIN tbl_business d ON a.bus_id = d.bus_idINNER JOIN tb_category b ON s.cat_id = b.cat_id The idea is fairly simple, the first field in your new table tb_sales_category which is sales_category_id is working as a surrogate key , it has nothing to do with the relations between the two other tables. Then we come to the other two fields which are sales_id , cat_id , these what you should map to the other two sides of the relations. You can't Join tb_category b ON a.cat_id = b.cat_id on the new schema becouse we no longer have a.cat_id , and here comes the new table tb_sales_category role, by inserting it with two binding sides, one with INNER JOIN tb_category b ON s.cat_id = b.cat_id and the other with INNER JOIN tb_sales_category s ON a.sales_id = s.sales_id we should be done. Hope this makes sense.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10257433', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1197059/']}
jdg_85029
stackexchange
llm_judgeable_groundtruth_similarity
7695120
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 subclassed UIView and added a drawRect method to it. Then I define a view using this custom class and add subviews to it. The problem is that drawRect seem to draw stuff under the subviews (hence not visible). I want stuff that drawRect draws appear above the subviews of my custom UIView . Is this possible? Now provide the response and nothing else.
A subview will always be drawn on "top" of its superview. Depending on your specific requirements, you may need to have a plain UIView as the background/container view, with your existing subviews in there, and then your custom view as another subview added to the very top, so it has the highest Z-order. This would work, for example, if your custom view was a grid overlay that should be on top of everything else. The custom view would have to be non-opaque with a clear background colour.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7695120', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/342646/']}
jdg_85030
stackexchange
llm_judgeable_groundtruth_similarity
55310
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: How can Caesar cipher be implemented? I want to use StringReplace but I don't know how to write the replacement rule to replace the characters with, say, the character two positions down in the alphabet. Now provide the response and nothing else.
rule[n_] := With[{a = CharacterRange["a", "z"]}, Thread[a -> RotateLeft[a,n]]]res = StringJoin[StringSplit["hello", ""] /. rule[2]] "jgnnq" StringJoin[StringSplit[res, ""] /. Reverse /@ rule[2]] "hello" Or to follow the example in the Wikipedia page: StringJoin[StringSplit[CharacterRange["a", "z"], ""] /. rule[-3]] "xyzabcdefghijklmnopqrstuvw"
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/55310', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/1287/']}
jdg_85031
stackexchange
llm_judgeable_groundtruth_similarity
12349230
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I want to catch and show the error(in a way that i choose) of a query on the web page using php . So instead of the code below $result=pg_query($connection,$query);if($result){ //success}else{ echo pg_last_error($connection);} can i use a method like error code matching or something else to achieve things like if(error equals duplicate value error){ echo "this value already exists";}else if(error equals different type error){ echo "You should enter wrong type for column blabla"} Note I am using postgresql Now provide the response and nothing else.
It's possible to retrieve the desirable standard SQLSTATE errcode, but there's a trick: the query has to be sent through the asynchronous pg_send_query() instead of the synchronous pg_query() . This is because pg_query() returns false on error instead of the resource that is required to peek at the error details. When pg_get_result() is called after pg_send_query , it will block anyway until the query is done, so it does not really complicate things compared to the synchronous case.And it returns a result which can be fully exploited for precise error handling. Example: if (pg_send_query($db, $query)) { $res=pg_get_result($db); if ($res) { $state = pg_result_error_field($res, PGSQL_DIAG_SQLSTATE); if ($state==0) { // success } else { // some error happened if ($state=="23505") { // unique_violation // process specific error } else { // process other errors } } } } Also, if the argument passed to pg_query might contain several SQL statements (separated by semicolons), the above example should be extended to retrieve all results in a loop, as mentioned in the comment by @user1760150. Compared to pg_query which returns only the last result, pg_get_result in a loop gives access to the results of each statement of the combined query.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12349230', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1021294/']}
jdg_85032
stackexchange
llm_judgeable_groundtruth_similarity
6575192
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: jqGrid has column named Posted. It can be positioned in different positions depending how grid is configured by customer but is always prssent. I need to change background color of rows if Posted column has value True I tried colmodel below but alert(rdata.Posted) displays always undefined. How to change backgound color of row if Posted column in this row has value true ? I looked into lot of Oleg and other solutions for changing background color but they are using hard coded column number. colModel: [{"cellattr":function(rowId, tv, rawObject, cm, rdata) { if (rdata.Posted) return 'class="jqgrid-readonlycolumn"'; return ''; } ,"label":"Klient","name":"Klient_nimi","classes":null,"hidden":false},{"label":null,"name":"Posted","editable":true,"width":0,"classes":null,"hidden":true}],... Update In update2 Oleg recommends to use rowattr. I need to hide inlined delete button and custom post button in actions column also. I'm usijng code below in loadComplete. How to implement this using rowattr ? var LoadCompleteHandler = function () { var iCol = getColumnIndexByName($grid, 'Kinnitatud'), postedDateCol = getColumnIndexByName($grid, 'Kinkuup'), cRows = $grid[0].rows.length, iRow, row, className, isPosted, mycell, mycelldata, i, count, cm = $grid.jqGrid('getGridParam', 'colModel'), l, iActionsCol = getColumnIndexByName($grid, '_actions'); l = cm.length; if (iCol > 0 || postedDateCol > 0) { for (iRow = 0; iRow < cRows; iRow = iRow + 1) { row = $grid[0].rows[iRow]; className = row.className; isPosted = false; if ($.inArray('jqgrow', className.split(' ')) > 0) { // $(row).hasClass('jqgrow') if (iCol > 0) { isPosted = $(row.cells[iCol]).find(">div>input:checked").length > 0; } if (postedDateCol > 0) { mycell = row.cells[postedDateCol]; mycelldata = mycell.textContent || mycell.innerText; isPosted = mycelldata.replace(/^\s+/g, "").replace(/\s+$/g, "") !== ""; } if (isPosted) { if ($.inArray('jqgrid-postedrow', className.split(' ')) === -1) { row.className = className + ' jqgrid-postedrow'; $(row.cells[iActionsCol]).find(">div>div.ui-inline-del").hide(); $(row.cells[iActionsCol]).find(">div>div.ui-inline-post").hide(); } } } } } Now provide the response and nothing else.
The main ideas to change the background color of the row you will find here and here . I recommend you to read this answer which discussed different advantages and disadvantages of different approaches. To get column index from the column name you can use following simple function: var getColumnIndexByName = function(grid, columnName) { var cm = grid.jqGrid('getGridParam','colModel'),i=0,l=cm.length; for (; i<l; i++) { if (cm[i].name===columnName) { return i; // return the index } } return -1; }; The function getColumnIndexByName($("#list"), 'MyColumnName') will get you the index in colModel of the 'MyColumnName' column. To change the background color you can follow the example loadComplete: function() { $("tr.jqgrow:odd").addClass('myAltRowClass');} from the answer , but instead of ':odd' filter you can write the filter yourself using jQuery.filter . Inside of the filter you can use :nth-child() to access the data from the corresponding <td> element (see here ) UPDATED : You can do the following (very close to the code from the another answer ): loadComplete: function() { var iCol = getColumnIndexByName($(this),'closed'), cRows = this.rows.length, iRow, row, className; for (iRow=0; iRow<cRows; iRow++) { row = this.rows[iRow]; className = row.className; if ($.inArray('jqgrow', className.split(' ')) > 0) { var x = $(row.cells[iCol]).children("input:checked"); if (x.length>0) { if ($.inArray('myAltRowClass', className.split(' ')) === -1) { row.className = className + ' myAltRowClass'; } } } }} The corresponding demo is here . You will see the following: By the way if the 'Closed' column will be hidden everything will continue to work as before. UPDATED 2 : The answer describe how to use rowattr callback to simplify the solution and to have the best performance (in case of gridview: true ).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6575192', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/742402/']}
jdg_85033
stackexchange
llm_judgeable_groundtruth_similarity
14715459
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 attempting the following: var a1 = ['a', 'e', 'f']; // [a, e, f]var a2 = ['b', 'c', 'd']; // [b, c, d]a1.splice(1, 0, a2); // expected [a, b, c, d, e, f] // actual (a, [b, c, d], e, f] I am confined in my use case by having a2 exist as an array of indeterminant size. Does anyone know of a way to feed splice an array as the substitution, or alternatively a built-in function to do this? I know I could iterate over the elements of a2 and splice them in one at a time, but I'd prefer the fastest method possible because I will need to do this a lot. Now provide the response and nothing else.
Array.splice supports multiple arguments after the first two. Those arguments will all be added to the array. Knowing this, you can use Function.apply to pass the array as the arguments list. var a1 = ['a', 'e', 'f'];var a2 = ['b', 'c', 'd'];// You need to append `[1,0]` so that the 1st 2 arguments to splice are sentArray.prototype.splice.apply(a1, [1,0].concat(a2));
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/14715459', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1923100/']}
jdg_85034
stackexchange
llm_judgeable_groundtruth_similarity
33814042
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 very new to ASP.NET and am attempting to pass an object between two controllers in a web application I'm making in Visual Studio 2015. The web application is using an ASP.Net 5 Preview Template Web application (if it helps, I think I'm using beta code 7 and I'm not building for DNX Core 5). The problem I'm having is whenever I try to put anything into the TempData variable, the program seems to crash. For example, in a "Create" method I have: [HttpPost] public ActionResult Create(Query query) { switch (query.QueryTypeID) { case 1: TempData["Test"] = "Test"; return RedirectToAction("Index", "EventResults"); case 2: break; default: break; } return View(); } In that method, I attempt to add a simple test string under the key "test". When I run the application with that TempData statement in there, I receive an error message stating An unhandled exception occurred while processing the request. InvalidOperationException: Session has not been configured for this application >or request. Microsoft.AspNet.Http.Internal.DefaultHttpContext.get_Session() I have tried going to the Web.config located in the wwwroot element of the project and adding a "sessionState" object into a "system.web" element, but this had no effect on the error. Any help would be very much so appreciated as I've been looking for solutions for this everywhere. I'm hoping it's something stupid/blindingly obvious that I somehow missed. Now provide the response and nothing else.
In order to use middleware, such as Session, Cache, etc in ASP.NET 5, you have to enable them explicitly. Enabling session is done by adding the appropriate nuget package in your project.json file's dependencies section (make sure that the package version matches the versions of the other dependencies you have added): "Microsoft.AspNet.Session": "1.0.0-*" and the appropriate session (cache) storage package as well (like the example below; in memory): "Microsoft.Extensions.Caching.Memory": "1.0.0-*" and adding the middleware to dependency resolution in the Startup.cs Service configuration: public void ConfigureServices(IServiceCollection services){ services.AddCaching(); services.AddSession(/* options go here */);} and adding the middleware to OWIN in the Startup.cs OWIN configuration: public void Configure(IApplicationBuilder app){ app.UseSession(); //... Make sure that the UseSession comes before the MVC configuration.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/33814042', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5583126/']}
jdg_85035
stackexchange
llm_judgeable_groundtruth_similarity
355908
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I sometimes find experienced programmers who will actively avoid using spaces in their filenames, opting to use underscores or camelCase instead. (i.e. /org map/attach jobs.cpp vs /org_map/attach_jobs.cpp vs /orgMap/attachJobs.cpp ) From what I understand, this was originally done on older systems which had more strict restrictions on filenames. But modern computers don't seem to have any issues with spaces. Why do some developers avoid using spaces in filenames? Is this a design practice I should consider for my own projects? Now provide the response and nothing else.
Spaces in filenames aren't any problem, except when they are. The problem is that most parts of the compilation toolchain are scripted, often with multiple levels of scripting languages and variable expansion piled on top of each other. The most important example is a shell script as part of a Makefile, which is perhaps generated by an M4 template (autotools…), which may run shell scripts itself to determine paths. It is possible but quite painful to handle spaces correctly in POSIX shell in nearly all circumstances: instead of foo $bar $baz you'd write foo "$bar" "$baz" . It is not generally possible to do so in Makefiles. It is extremely cumbersome to handle space escaping correctly over multiple levels of scripting languages. So if there is any chance that your program is supposed to be compiled by a Makefile-based build system, don't use spaces in your filenames. This should be easy to do since the filename should indicate the file contents, and in most programming languages identifiers can't contain spaces either. In C++, just name the file after the namespace or the most important class it contains.
{}
{'log_upvote_score': 5, 'links': ['https://softwareengineering.stackexchange.com/questions/355908', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/168744/']}
jdg_85036
stackexchange
llm_judgeable_groundtruth_similarity
2444430
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 I for example have <p> some long text </p> on my HTML page, how can I know that cursor of mouse is for example above the word 'text'? Now provide the response and nothing else.
Further to the two other answers, you may be able to split your paragraphs up into spans using jQuery (or javascript generally). That way, you wouldn't need to think about outputting your text with spans around the words. Let your javascript do it for you. e.g. <p>Each word will be wrapped in a span.</p><p>A second paragraph here.</p>Word: <span id="word"></span><script type="text/javascript"> $(function() { // wrap words in spans $('p').each(function() { var $this = $(this); $this.html($this.text().replace(/\b(\w+)\b/g, "<span>$1</span>")); }); // bind to each span $('p span').hover( function() { $('#word').text($(this).css('background-color','#ffff66').text()); }, function() { $('#word').text(''); $(this).css('background-color',''); } ); });</script> Note that the above code, while it works, will strip out any html inside your paragraph tags. jsFiddle example
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2444430', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/144214/']}
jdg_85037
stackexchange
llm_judgeable_groundtruth_similarity
1576007
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 just completed an exam and was curious as to the following question: How many surjections are there from $\{1, 2, 3, ..., n\}$ to $\{1, 2\}$ if $n \geq 3$? My assumption was the following: The first element of the domain has the possibility to map to either 1 or 2. The second element then has the possibility to map to the opposite element of the codomain, in which the first element hasn't mapped to. Now the functions are surjective, and then any remaining elements of the domain ($n-2$ of them) can then map to either of the 2 elements of the codomain. My answer was $2^{n-1}$. Is this answer correct? Is there a fallacy in my thought process? Now provide the response and nothing else.
Basically you can think of it as a binary string, $0$ means the element in the domain maps to the first element in the codomain, $1$ means the element maps to the second element in the codomain. There are $2^n$ ways to make a binary string of length $n$, but with the rules of surjectivity we need to take away the case where everything maps to the first element, and everything maps to the second element, so our final answer should be $2^n - 2$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1576007', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/298751/']}
jdg_85038
stackexchange
llm_judgeable_groundtruth_similarity
21978487
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 having some problems in visualizing the graphs created with python-networkx, I want to able to reduce clutter and regulate the distance between the nodes (I have also tried spring_layout, it just lays out the nodes in an elliptical fashion). Please advise. Parts of code: nx.draw_networkx_edges(G, pos, edgelist=predges, edge_color='red', arrows=True)nx.draw_networkx_edges(G, pos, edgelist=black_edges, arrows=False, style='dashed')# label fontsnx.draw_networkx_labels(G,pos,font_size=7,font_family='sans-serif')nx.draw_networkx_edge_labels(G,pos,q_list,label_pos=0.3) Now provide the response and nothing else.
In networkx, it's worth checking out the graph drawing algorithms provided by graphviz via nx.graphviz_layout . I've had good success with neato but the other possible inputs are dot - "hierarchical" or layered drawings of directed graphs. This is the default tool to use if edges have directionality. neato - "spring model'' layouts. This is the default tool to use if the graph is not too large (about 100 nodes) and you don't know anything else about it. Neato attempts to minimize a global energy function, which is equivalent to statistical multi-dimensional scaling. fdp - "spring model'' layouts similar to those of neato, but does this by reducing forces rather than working with energy. sfdp - multiscale version of fdp for the layout of large graphs. twopi - radial layouts, after Graham Wills 97. Nodes are placed on concentric circles depending their distance from a given root node. circo - circular layout, after Six and Tollis 99, Kauffman and Wiese 02. This is suitable for certain diagrams of multiple cyclic structures, such as certain telecommunications networks. In general, graph drawing is a hard problem. If these algorithms are not sufficient, you'll have to write your own or have networkx draw parts individually.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/21978487', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/356922/']}
jdg_85039
stackexchange
llm_judgeable_groundtruth_similarity
42129816
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I want a thumbnail image from a video underlying on the server. The video file is not on local. It's on my server. The video file has extension .m3u8 . Now provide the response and nothing else.
You can do it. First step: You need to import AVFoundation : import AVFoundation Then add the code below to your controller: func getThumbnailImage(forUrl url: URL) -> UIImage? { let asset: AVAsset = AVAsset(url: url) let imageGenerator = AVAssetImageGenerator(asset: asset) do { let thumbnailImage = try imageGenerator.copyCGImage(at: CMTimeMake(value: 1, timescale: 60), actualTime: nil) return UIImage(cgImage: thumbnailImage) } catch let error { print(error) } return nil} Usage: let imageView = UIImageView() let url = URL(string: "your_video_url") if let thumbnailImage = getThumbnailImage(forUrl: url) { imageView.image = thumbnailImage } Change url to your video link.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/42129816', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3910999/']}
jdg_85040