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
|
26545668
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have the following project structure I would like to package: ├── doc│ └── source├── src│ ├── core│ │ ├── config│ │ │ └── log.tmpl│ │ └── job│ ├── scripts│ └── test└── tools I would like to package core under src but exclude test . Here is what I tried unsuccessfully: setup(name='core', version=version, package_dir = {'': 'src'}, # Our packages live under src but src is not a package itself packages = find_packages("src", exclude=["test"]), # I also tried exclude=["src/test"] install_requires=['xmltodict==0.9.0', 'pymongo==2.7.2', 'ftputil==3.1', 'psutil==2.1.1', 'suds==0.4', ], include_package_data=True, ) I know I can exclude test using the MANIFEST.in file, but I would be happy if you could show me how to do this with setup and find_packages . Update: After some more playing around, I realized that building the package with python setup.py install does what I expected (that is, it excludes test ). However, issuing python setup.py sdist causes everything to be included (that is, it ignores my exclude directive). I don't know whether it is a bug or a feature, but there is still the possibility of excluding files in sdist using MANIFEST.in .
Now provide the response and nothing else.
|
find_packages("src", exclude=["test"]) works. The trick is to remove stale files such as core.egg-info directory. In your case you need to remove src/core.egg-info . Here's setup.py I've used: from setuptools import setup, find_packagessetup(name='core', version='0.1', package_dir={'':'src'}, packages=find_packages("src", exclude=["test"]), # <- test is excluded ####packages=find_packages("src"), # <- test is included author='J.R. Hacker', author_email='jr@example.com', url='http://stackoverflow.com/q/26545668/4279', package_data={'core': ['config/*.tmpl']},) To create distributives, run: $ python setup.py sdist bdist bdist_wheel To enable the latter command, run: pip install wheel . I've inspected created files. They do not contain test but contain core/__init__.py , core/config/log.tmpl files.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/26545668', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/492620/']}
|
jdg_375441
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
17095360
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm running into problems knowing when and what to call after mysqli_stmt_execute How do you know when to call mysqli_stmt_bind_result mysqli_stmt_store_result mysqli_stmt_fetch
Now provide the response and nothing else.
|
mysqli_stmt_bind_result() tells mysqli which variable you want to be populate when you fetch a row, but it doesn't fetch() anything yet. This is necessary to call once, before you call fetch. mysqli_stmt_store_result() sets an optional behavior so that the client downloads all rows when you fetch() the first row, and caches the whole result set in the client (i.e. PHP). Subsequent fetch() calls will simply iterate over this client-cached result set. But setting this option itself does not cause a fetch() yet either. This function is totally optional. mysqli_stmt_fetch() returns the next row in the result set, and causes it to be stored in a bound variable. You must call this function in a loop, for each row of the result set. That is, until the fetch returns false.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17095360', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1279820/']}
|
jdg_375442
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
13905661
|
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 write, using DLL injection method, application which displays bitmaps used by another program and I want to get for this specific process list of GDI Handles which it is using (list like in GDIView.exe utility). I found article about NtQuerySystemInformation function, but this description only works with handles to Kernel Objects. Can somebody help?
Now provide the response and nothing else.
|
Here is a console application code that dumps all GDI handles out for a given process identifier. It should compile and work fine for 32 or 64-bit applications, as well as 32-bit application running on 64-bit OSes. It uses a lot of undocumented functions so don't rely on it :-) Credits on structures for the shared GDI table goes to Feng Yuan original work. (I had to adapt it for WOW64). Here is a sample output when ran on a Notepad (64-bit) process: [C:\Temp\EnumGdi\Debug]EnumGdi.exe 5916DC handle:0xF20105DBBitmap handle:0xDF05118BFont handle:0xDC0A19E0Font handle:0xAB0A1A62DC handle:0xA3011A63Region handle:0xAF041B7BBrush handle:0x11101C5BFont handle:0x280A1CA1Font handle:0xBB0A1D13Bitmap handle:0xA3051DD8Font handle:0xB40A1DDCRegion handle:0x3A041EE4Brush handle:0x0B101F04Region handle:0xC6041F3DFont handle:0x2C0A2384Brush handle:0xBA1024DA EnumGdi.cpp: #include "stdafx.h"#include "enumgdi.h"int _tmain(int argc, _TCHAR* argv[]){ if (argc < 2) { printf("Format is EnumGdi <process id>\n"); return 0; } // get process identifier DWORD dwId = _wtoi(argv[1]); // open the process HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, dwId); DWORD err = 0; if (hProcess == NULL) { printf("OpenProcess %u failed\n", dwId); err = GetLastError(); return -1; } // determine if 64 or 32-bit processor SYSTEM_INFO si; GetNativeSystemInfo(&si); // NOTE: as this is undocumented, it *may vary* depending on bitness (32/64) and on Windows version. // use WinDbg "dt ntdll!_PEB" command and search for GdiSharedHandleTable offset to find the truth out DWORD GdiSharedHandleTableOffset = si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64 ? 0xF8 : 0x94; DWORD tableCount = 16384; // count of GDI table cells // determine if this process is running on WOW64 BOOL wow; IsWow64Process(GetCurrentProcess(), &wow); // read basic info to get PEB address, we only need the beginning of PEB DWORD pebSize = GdiSharedHandleTableOffset + 8; LPBYTE peb = (LPBYTE)malloc(pebSize); ZeroMemory(peb, pebSize); if (wow) { // we're running as a 32-bit process in a 64-bit process PROCESS_BASIC_INFORMATION_WOW64 pbi; ZeroMemory(&pbi, sizeof(pbi)); // get process information from 64-bit world _NtQueryInformationProcess query = (_NtQueryInformationProcess)GetProcAddress(GetModuleHandleA("ntdll.dll"), "NtWow64QueryInformationProcess64"); err = query(hProcess, 0, &pbi, sizeof(pbi), NULL); if (err != 0) { printf("NtWow64QueryInformationProcess64 failed\n"); CloseHandle(hProcess); return -1; } // read PEB from 64-bit address space _NtWow64ReadVirtualMemory64 read = (_NtWow64ReadVirtualMemory64)GetProcAddress(GetModuleHandleA("ntdll.dll"), "NtWow64ReadVirtualMemory64"); err = read(hProcess, pbi.PebBaseAddress, peb, pebSize, NULL); if (err != 0) { printf("NtWow64ReadVirtualMemory64 PEB failed\n"); CloseHandle(hProcess); return -1; } // get GDI table ptr from PEB GDICELL_WOW64* gdiTable = (GDICELL_WOW64*)*(LPVOID*)(peb + GdiSharedHandleTableOffset); // address in remote process adress space if (gdiTable == NULL) { printf("GDI32.DLL is not loaded in the process\n"); CloseHandle(hProcess); return -1; } free(peb); DWORD tableSize = sizeof(GDICELL_WOW64) * tableCount; // size of GDI table GDICELL_WOW64* table = (GDICELL_WOW64*)malloc(tableSize); // local table copied over to our address space // copy GDI table err = read(hProcess, gdiTable, table, tableSize, NULL); if (err != 0) { printf("NtWow64ReadVirtualMemory64 GdiTable failed\n"); free(table); CloseHandle(hProcess); return -1; } for(DWORD i = 0; i < tableCount; i++) { GDICELL_WOW64 cell = table[i]; if (cell.wProcessId != dwId) continue; HGDIOBJ gdiHandle = (HGDIOBJ)((cell.wUpper << 16) + i); WORD type = cell.wType & 0x7F; switch(type) { case 1: printf("DC handle:0x%08X\n", gdiHandle ); break; case 4: printf("Region handle:0x%08X\n", gdiHandle); break; case 5: printf("Bitmap handle:0x%08X\n", gdiHandle); break; case 8: printf("Palette handle:0x%08X\n", gdiHandle); break; case 10: printf("Font handle:0x%08X\n", gdiHandle); break; case 16: printf("Brush handle:0x%08X\n", gdiHandle); break; case 48: printf("Pen handle:0x%08X\n", gdiHandle); break; default: printf("Unknown type handle:0x%08X\n", gdiHandle); break; } } free(table); } else { // we're running as a 32-bit process in a 32-bit OS, or as a 64-bit process in a 64-bit OS PROCESS_BASIC_INFORMATION pbi; ZeroMemory(&pbi, sizeof(pbi)); // get process information _NtQueryInformationProcess query = (_NtQueryInformationProcess)GetProcAddress(GetModuleHandleA("ntdll.dll"), "NtQueryInformationProcess"); err = query(hProcess, 0, &pbi, sizeof(pbi), NULL); if (err != 0) { printf("NtQueryInformationProcess failed\n"); CloseHandle(hProcess); return -1; } // read PEB _NtReadVirtualMemory read = (_NtReadVirtualMemory)GetProcAddress(GetModuleHandleA("ntdll.dll"), "NtReadVirtualMemory"); err = read(hProcess, pbi.PebBaseAddress, peb, pebSize, NULL); if (err != 0) { printf("NtReadVirtualMemory PEB failed\n"); CloseHandle(hProcess); return -1; } // get GDI table ptr GDICELL* gdiTable = (GDICELL*)*(LPVOID*)(peb + GdiSharedHandleTableOffset); // address in remote process adress space if (gdiTable == NULL) { printf("GDI32.DLL is not loaded in the process\n"); CloseHandle(hProcess); return -1; } free(peb); DWORD tableSize = sizeof(GDICELL) * tableCount; // size of GDI table GDICELL* table = (GDICELL*)malloc(tableSize); // local table copied over to our address space // read GDI table err = read(hProcess, gdiTable, table, tableSize, NULL); if (err != 0) { printf("NtReadVirtualMemory GdiTable failed\n"); free(table); CloseHandle(hProcess); return -1; } for(DWORD i = 0; i < tableCount; i++) { GDICELL cell = table[i]; if (cell.wProcessId != dwId) continue; HGDIOBJ gdiHandle = (HGDIOBJ)((cell.wUpper << 16) + i); WORD type = cell.wType & 0x7F; switch(type) { case 1: printf("DC handle:0x%08X\n", gdiHandle ); break; case 4: printf("Region handle:0x%08X\n", gdiHandle); break; case 5: printf("Bitmap handle:0x%08X\n", gdiHandle); break; case 8: printf("Palette handle:0x%08X\n", gdiHandle); break; case 10: printf("Font handle:0x%08X\n", gdiHandle); break; case 16: printf("Brush handle:0x%08X\n", gdiHandle); break; case 48: printf("Pen handle:0x%08X\n", gdiHandle); break; default: printf("Unknown type handle:0x%08X\n", gdiHandle); break; } } free(table); } CloseHandle(hProcess);} EnumGdi.h: #pragma once#include "stdafx.h"// defines a GDI CELLtypedef struct{ LPVOID pKernelAddress; USHORT wProcessId; USHORT wCount; USHORT wUpper; USHORT wType; LPVOID pUserAddress;} GDICELL;// defines a GDI CELL for WOW64typedef struct{ PVOID64 pKernelAddress; USHORT wProcessId; USHORT wCount; USHORT wUpper; USHORT wType; PVOID64 pUserAddress;} GDICELL_WOW64;// NtQueryInformationProcess for pure 32 and 64-bit processestypedef NTSTATUS (NTAPI *_NtQueryInformationProcess)( IN HANDLE ProcessHandle, ULONG ProcessInformationClass, OUT PVOID ProcessInformation, IN ULONG ProcessInformationLength, OUT PULONG ReturnLength OPTIONAL );typedef NTSTATUS (NTAPI *_NtReadVirtualMemory)( IN HANDLE ProcessHandle, IN PVOID BaseAddress, OUT PVOID Buffer, IN SIZE_T Size, OUT PSIZE_T NumberOfBytesRead);// NtQueryInformationProcess for 32-bit process on WOW64typedef NTSTATUS (NTAPI *_NtWow64ReadVirtualMemory64)( IN HANDLE ProcessHandle, IN PVOID64 BaseAddress, OUT PVOID Buffer, IN ULONG64 Size, OUT PULONG64 NumberOfBytesRead);// PROCESS_BASIC_INFORMATION for pure 32 and 64-bit processestypedef struct _PROCESS_BASIC_INFORMATION { PVOID Reserved1; PVOID PebBaseAddress; PVOID Reserved2[2]; ULONG_PTR UniqueProcessId; PVOID Reserved3;} PROCESS_BASIC_INFORMATION;// PROCESS_BASIC_INFORMATION for 32-bit process on WOW64// The definition is quite funky, as we just lazily doubled sizes to match offsets...typedef struct _PROCESS_BASIC_INFORMATION_WOW64 { PVOID Reserved1[2]; PVOID64 PebBaseAddress; PVOID Reserved2[4]; ULONG_PTR UniqueProcessId[2]; PVOID Reserved3[2];} PROCESS_BASIC_INFORMATION_WOW64;
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13905661', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1658355/']}
|
jdg_375443
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4132869
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I was trying to insert a xml node before another xmlnode and I have got an exception saying "The reference node is not a child of this node." This is my initial xml : <?xml version="1.0" encoding="utf-8" ?><Details xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <sampleData> <otherNodes></otherNodes> </sampleData></Details> I wanted to insert following xml datas(b:dataTobeInserted1,b:dataTobeInserted2 and b:dataTobeInserted3) as a Child of Details but before sampleData . Details1.xml <?xml version="1.0" encoding="utf-8" ?><DataInserted1 xmlns:b="http://example.com/data"> <b:dataTobeInserted1> <b:otherDetails1></b:otherDetails1> </b:dataTobeInserted1></DataInserted1> Details2.xml <?xml version="1.0" encoding="utf-8" ?><DataInserted2 xmlns:b="http://example.com/data"> <b:dataTobeInserted2> <b:otherDetails2></b:otherDetails2> </b:dataTobeInserted2></DataInserted2> Details3.xml <?xml version="1.0" encoding="utf-8" ?><DataInserted3 xmlns:b="http://example.com/data"> <b:dataTobeInserted3> <b:otherDetails3></b:otherDetails3> </b:dataTobeInserted3></DataInserted3> I want my Output as <?xml version="1.0" encoding="utf-8" ?><Details xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:b="http://example.com/data"> <b:dataTobeInserted1> <b:otherDetails1></b:otherDetails1> </b:dataTobeInserted1> <b:dataTobeInserted2> <b:otherDetails2></b:otherDetails2> </b:dataTobeInserted2> <b:dataTobeInserted3> <b:otherDetails3></b:otherDetails3> </b:dataTobeInserted3> <sampleData> <otherNodes></otherNodes> </sampleData></Details> This is what I did to achieve my desired output. XmlDocument xmldoc = new XmlDocument(); xmldoc.Load(@"..\..\initial-Doc.xml"); xmldoc.DocumentElement.SetAttribute("xmlns:b", "http://example.com/data"); XmlDocument detail1 = new XmlDocument(); detail1.Load(@"..\..\DataToBeInserted1.xml"); XmlNode detail1Node = xmldoc.ImportNode(detail1.DocumentElement, true); XmlDocument detail2 = new XmlDocument(); detail2.Load(@"..\..\DataToBeInserted2.xml"); XmlNode detail2Node = xmldoc.ImportNode(detail2.DocumentElement, true); XmlDocument detail3 = new XmlDocument(); detail3.Load(@"..\..\DataToBeInserted3.xml"); XmlNode detail3Node = xmldoc.ImportNode(detail3.DocumentElement, true); xmldoc.InsertBefore(detail1Node, xmldoc.DocumentElement.FirstChild); xmldoc.InsertBefore(detail2Node, xmldoc.DocumentElement.FirstChild); xmldoc.InsertBefore(detail3Node, xmldoc.DocumentElement.FirstChild); xmldoc.Save(@"..\..\initial-Doc-new.xml"); Is the new namespace is causing the problem?Please tell me where I went wrong. ThanksAlex
Now provide the response and nothing else.
|
Looks to me like the problem is exactly what the exception says: "The reference node is not a child of this node." The only tricky part is figuring out which nodes they're referring to. :-) Here " this node " means the XmlNode whose InsertBefore() method you're calling, and " the reference node " means the second argument to InsertBefore (). So in the following line: xmldoc.InsertBefore(detail1Node, xmldoc.DocumentElement.FirstChild); It's saying that xmldoc.DocumentElement.FirstChild is not a child of xmldoc . Which is true. xmldoc.DocumentElement.FirstChild is a child of xmldoc.DocumentElement . So if you change that line to the following, the problem should be fixed: xmldoc.DocumentElement.InsertBefore(detail1Node, xmldoc.DocumentElement.FirstChild);
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4132869', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/415745/']}
|
jdg_375444
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
314394
|
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have 20GB for my Mint-KDE 18 root partition. There is no extra home partition. I am doing nothing special, just Chrome, KRDC, Teamviewer and the partition was half empty. One thing I did was copying in Dolphin from webdavs repo on the internet to my network drive via samba. Nothing was stored on my PC. Now I got the message that my disk is full. When I open my root or home directory in Dolphin it says 0 MB free. What is the fastest way via terminal to view my directories and files, biggest first or newest etc?
Now provide the response and nothing else.
|
du -h -d 1 / This will display the size for all of the top-level directories in your root directory in 'human readable' format. You can also just do du -h -d 1 / | grep '[0-9]\+G' to only see the ones taking a couple GB or more. For a more granular level of detail, do something like ls -R -shl / | grep '^[0-9.]\{4,12\}\+[KG]' which will show all files in and below your root directory that are 1G or over in size. ** note that you might need to prepend sudo to the commands above. edit -- just saw you want them sorted by newest or largest Try this du -h -d 1 / | grep '[0-9]\+G' | sort -h
|
{}
|
{'log_upvote_score': 6, 'links': ['https://unix.stackexchange.com/questions/314394', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/135657/']}
|
jdg_375445
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1172324
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
(Sorry for the newbie question.) In Ruby, what is the difference between the loops: @cars.each do |car| and for car in @cars do ? is there a difference in efficiency, or why do we need two (or more) ways to express the same thing? The second way seems more elegant/natural to me, but I may be missing some crucial observation, why the first may be the better choice.
Now provide the response and nothing else.
|
More people use the @cars.each notation because that generalizes to other methods (like #inject , #each_with_index , #map , etc, as well as non-iterator callbacks). for/in is mainly just syntactic sugar for #each . The main difference in how the two work is in variable scoping: irb> @cars = %w{ ford chevy honda toyota }#=> ["ford", "chevy", "honda", "toyota"]irb> @cars.each { |car| puts car }fordchevyhondatoyota#=> ["ford", "chevy", "honda", "toyota"]irb> carNameError: undefined local variable or method `car` for #<Object:0x399770 @cars=["ford", "chevy", "honda", "toyota"]> from (irb):3 from /usr/local/bin/irb:12:in `<main>`irb> for car in @cars puts car.reverse enddrofyvehcadnohatoyot#=> ["ford", "chevy", "honda", "toyota"]irb> car#=> "toyota" for/in leaves the iterator variable in scope afterwards, while #each doesn't. Personally, I never use ruby's for/in syntax.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1172324', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/117493/']}
|
jdg_375446
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
19348430
|
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 doing problem five in Project Euler: "2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?" I have constructed the following code which finds the correct value 2520 when using 1 - 10 as divisors but code seems to be going on forever when using 1 - 20.Again I don't want the code just a pointer or two on where I am going wrong.Thanks def smallestDiv(n): end=False while end == False: divisors = [x for x in range(1,21)] # get divisors allDivisions = zip(n % i for i in divisors) # get values for n % all integers in divisors check = all(item[0] == 0 for item in allDivisions ) # check if all values of n % i are equal to zero if check: # if all values are equal to zero return n end = True return n else: # else increase n by 1 n +=1 EDIT: I used some code I found relating to LCM and used reduce to solve the problem: def lcm(*values): values = [value for value in values] if values: n = max(values) m = n values.remove(n) while any( n % value for value in values ): n +=m return n return 0print reduce(lcm, range(1,21))
Now provide the response and nothing else.
|
If a problem is hard, trying solving a simpler version. Here, how to calculate the lowest common multiple of two numbers. If you've read any number theory book (or think about prime factors), you can do that using the greatest common divisor function (as implemented by the Euclidean algorithm). from fractions import gcddef lcm(a,b): "Calculate the lowest common multiple of two integers a and b" return a*b//gcd(a,b) Observing lcm(a,b,c) ≡ lcm(lcm(a,b),c) it's simple to solve your problem with Python's reduce function >>> from functools import reduce>>> reduce(lcm, range(1,10+1))2520>>> reduce(lcm, range(1,20+1))232792560
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/19348430', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2141635/']}
|
jdg_375447
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
150164
|
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:
So I am doing an exercise in which there are $n$ people who are either knight or rogue, more than $\frac{n}{2}$ are knights. You are a princess and would like to marry a knight and do not want to accidentally marry a rogue. You can select any pair of the $n$ people to make them point out each other's identity. The knight will always tell the truth, while the rogue may or may not. If there are two rogues being interrogated, they may say each other is good to deceive you. How can I design an efficient algorithm for the princess to find out a knight? My attempt: So I can pit one person j against the other $n-1$ persons to find out if j is knight or rogue. There are $k > \frac{n}{2}$ knights, and $r \leq \frac{n}{2}-1$ rogues. If j is a knight, then he will be pitted against $k-1$ other knights and $r$ rogues. So there are $\geq \frac{n}{2}$ cases in which both say the other person is knight, and there will be $\leq \frac{n}{2} - 1$ cases that at least 1 person is accused of being a rogue. If j is a rogue, then j will be pitted against $k$ knights and $r-1$ other rogues, resulting in $k$ cases of at least one rogue accusation, and at most $r-1$ cases of both being said to be knight (as the 2 rogues may or may not team up to deceive the princess). Looking at the distribution of cases "both say the other is knight" and "at least one rogue accusation", we can identity if the person being examined is a knight or rogue. If I am to brute force, then I can do $O(n)$ queries for each person, giving $O(n^2)$ time. But I am uncertain how to do divide and conquer here. I can eliminate dividing naively into $\frac{n}{2}$ sizes, because the distribution of knights and rogues will no longer follow the initial more than $\frac{n}{2}$ knights. One idea I have is, initially pick one person j and do the pairing with $n-1$ others to see if he is knight or rogue. If he is knight then we're done.If he is rogue, then we can know which in the previous results must be rogues. The other person in the cases of "both knights" must be rogue. Also, in the cases of "one knight one rogue", those who say j is knight are lying and must be rogues. So we select the ones who are either a rogue that didn't lie, or a knight, and recurse on them. The worst case would be that every rogue does not lie. What are you thoughts on this? Thank you!
Now provide the response and nothing else.
|
An efficient algorithm using stack Initialize an empty stack. For each person $p$ in the given people: If the stack is empty, push $p$ to the stack. Otherwise, pit $p$ against the person at the top of the stack. If both say the other one is a knight, either both are knights or both are rogues. Push $p$ to the stack. Otherwise, at least one of them is a rogue. Pop the stack once. Return the person at the top of the stack. The time-complexity of the algorithm is $O(n)$ . The space-complexity of the algorithm is $O(1)$ if we can reuse the input array as a stack. Two Exercises Exercise 1 (easy). Explain why all people in stack at the end are knights. Exercise 2 (easy). Suppose the number of knights is equal to the number of rogues instead. Show that it is impossible to find a knight for sure in the worst case.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://cs.stackexchange.com/questions/150164', 'https://cs.stackexchange.com', 'https://cs.stackexchange.com/users/149323/']}
|
jdg_375448
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
11900470
|
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 thought it was really simple but it isn't. SELECT TO_TIMESTAMP('10/08/2012','DD/MM/YYYY') - 1/(24*50*60*1000) data FROM dual; It simply doesn't work. Other details: SELECT TO_TIMESTAMP('10/08/2012','DD/MM/YYYY') - NUMTODSINTERVAL(1/(24*50*60*1000),'HOUR') data FROM dual; doesn't work.. The right seems to be SELECT TO_TIMESTAMP('10/08/2012','DD/MM/YYYY') - NUMTODSINTERVAL(1/(24*25*60*1000),'HOUR') data FROM dual; Why? How does it work?
Now provide the response and nothing else.
|
For adding or subtracting an amount of time expressed as a literal you can use INTERVAL. SELECT TO_TIMESTAMP('10/08/2012','DD/MM/YYYY') - INTERVAL '0.001' SECOND FROM dual; As well there are now standard ways to express date and time literals and avoid the use of various database specific conversion functions. SELECT TIMESTAMP '2012-10-08 00:00:00' - INTERVAL '0.001' SECOND DATAFROM dual; For your original question the time part of a day is stored in fractional days. So one second is: 1 / (hours in day * minutes in hour * seconds in a minute) Divide by 1000 to get milliseconds. 1 / (24 * 60 * 60 * 1000)
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/11900470', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/196210/']}
|
jdg_375449
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
351569
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
How can we use the Intermediate Value Theorem to show that the function $$\;f(x) = x^{20}-70x^3+1\;$$ has a zero in the interval $\;[0, 1]\,$? (To use the theorem I need to show that the function satisfies all required assumptions.)
Now provide the response and nothing else.
|
Recall: A "zero" of a polynomial $f(x)$ is a value $x_i$ such that $f(x_i) = 0$. Prompts : Is $\;f(x) = x^{20} - 70x^3 + 1\;$ continuous on $[0, 1]\;?\;\;$ Just recall what you know about the continuity of polynomials on $\mathbb R$. What is $f(0)\;?\;\;$ What is $f(1)\;?\quad$. What does the Intermediate Value Theorem tell you withrespect to whether there exists a $c \in [0, 1],\;$ such that $\;0 \lt c \lt 1\;$ and $f(c) = 0$? If you can justify (and it is indeed possible to justify) that there exists such a $c$, then $x_i = c$ is a zero of $f(x)$. Note: you don't have to actually find the value of the zero; only that such a zero exists in the interval $[0, 1]$ Comment:It would be good for you to include, in your post , what is your understanding of the Intermediate Value Theorem so you can ensure that the conditions for its application are met. You'll want to be able to know the theorem well enough so you can recall it as needed, and state it in your own words.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/351569', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/71008/']}
|
jdg_375450
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
42236
|
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 was trying to understand UART fundamentals.It is understood that It is an asynchronous communication protocol and hence the TX and RX clocks are independent of each other The data reception is guaranteed by the usage of start bit and one or more stop bits .Additionally the receiver must be aware of the data rate so as to generate suitable clock to drive the SIPO register used for reception. The questions here are It is mentioned that normally a clock of 16X the bit rate is used to recover the data. So how is the conversion of bps to clock frequency possible? Please provide me some references to study the clocking mechanism employed in UART receiver.
Now provide the response and nothing else.
|
Transmitter and receiver clocks are independent of each other, in the way that they're generated independently, but they should be matched well to ensure proper transmission. The start bit, which is low, and the stop bit, which is high, guarantee that between two bytes there's always a high-to-low transition the receiver can synchronize on, but after that it's on its own: there are no further time cues it can use to tell successive bits apart. All it has is its own clock. So the most simple thing to do is starting from the start bit sample each bit at the middle of its time. For example, at 9600 bps a bit time is 104 µs, then it would sample the start bit at \$T_0\$ + 52 µs, the first data bit at \$T_0\$ + 52 µs + 104 µs, the second data bit at \$T_0\$ + 52 µs + 2 \$\times\$ 104 µs, and so on. \$T_0\$ is the falling edge of the start bit. While sampling the start bit isn't really necessary (you know it's low) it's useful to ascertain that the start edge wasn't a spike. For a 52 µs timing you need twice the 9600 bps clock frequency, or 19200 Hz. But this is only a basic detecting method. More advanced (read: more accurate) methods will take several samples in a row, to avoid hitting just that one spike. Then you may indeed need a 16 \$\times\$ 9600 Hz clock to get 16 ticks per bit, of which you may use, say, 5 or so in what should be the middle of a bit. And the use a voting system to see whether it should be read as high or low. If I recall correctly the 68HC11 took a few samples at the beginning, in the middle and at the end of a bit, the first and last presumably to resync if there would be a level change (which isn't guaranteed). The sampling clock is not derived from the bit rate, it's the other way around. For 9600 bps you'll have to set the sampling clock to 153 600 Hz, which you'll derive through a prescaler from the microcontroller's clock frequency. Then the bit clock is derived from that by another division by 16. unmatched clocks This is what will happen if the receiver's clock isn't synchronous with the transmitter's: The receiver's clock is 6.25 % slow, and you can see that sampling for every next bit will be later and later. A typical UART transmission consists of 10 bits: 1 start bit, a payload of 8 data bits, and 1 stop bit. Then if you sample in the middle of a bit you can afford to be half a bit off at the last bit, the stop bit. Half a bit on ten bits is 5 %, so with our 6.25 % deviation we'll run into problems. That shows clearly in the picture: already at the third data bit we're sampling near the edge.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/42236', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/13589/']}
|
jdg_375451
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
5447498
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am confused about the meaning of access modifiers with respect to inheritance. What is the difference between inheritance involving the private , protected and public keywords?
Now provide the response and nothing else.
|
what are Access Specifiers? There are 3 access specifiers for a class/struct/Union in C++. These access specifiers define how the members of the class can be accessed. Of course, any member of a class is accessible within that class(Inside any member function of that same class). Moving ahead to type of access specifiers, they are: Public - The members declared as Public are accessible from outside the Class through an object of the class. Protected - The members declared as Protected are accessible from outside the class BUT only in a class derived from it. Private - These members are only accessible from within the class. No outside Access is allowed. An Source Code Example: class MyClass{ public: int a; protected: int b; private: int c;};int main(){ MyClass obj; obj.a = 10; //Allowed obj.b = 20; //Not Allowed, gives compiler error obj.c = 30; //Not Allowed, gives compiler error} Inheritance and Access Specifiers Inheritance in C++ can be one of the following types: Private Inheritance Public Inheritance Protected inheritance Here are the member access rules with respect to each of these: First and most important rule Private members of a class are never accessible from anywhere except the members of the same class. Public Inheritance: All Public members of the Base Class become Public Members of the derived class & All Protected members of the Base Class become Protected Members of the Derived Class. i.e. No change in the Access of the members. The access rules we discussed before are further then applied to these members. Code Example: Class Base{ public: int a; protected: int b; private: int c;};class Derived:public Base{ void doSomething() { a = 10; //Allowed b = 20; //Allowed c = 30; //Not Allowed, Compiler Error }};int main(){ Derived obj; obj.a = 10; //Allowed obj.b = 20; //Not Allowed, Compiler Error obj.c = 30; //Not Allowed, Compiler Error} Private Inheritance: All Public members of the Base Class become Private Members of the Derived class & All Protected members of the Base Class become Private Members of the Derived Class. An code Example: Class Base{ public: int a; protected: int b; private: int c;};class Derived:private Base //Not mentioning private is OK because for classes it defaults to private { void doSomething() { a = 10; //Allowed b = 20; //Allowed c = 30; //Not Allowed, Compiler Error }};class Derived2:public Derived{ void doSomethingMore() { a = 10; //Not Allowed, Compiler Error, a is private member of Derived now b = 20; //Not Allowed, Compiler Error, b is private member of Derived now c = 30; //Not Allowed, Compiler Error }};int main(){ Derived obj; obj.a = 10; //Not Allowed, Compiler Error obj.b = 20; //Not Allowed, Compiler Error obj.c = 30; //Not Allowed, Compiler Error} Protected Inheritance: All Public members of the Base Class become Protected Members of the derived class & All Protected members of the Base Class become Protected Members of the Derived Class. A Code Example: Class Base{ public: int a; protected: int b; private: int c;};class Derived:protected Base { void doSomething() { a = 10; //Allowed b = 20; //Allowed c = 30; //Not Allowed, Compiler Error }};class Derived2:public Derived{ void doSomethingMore() { a = 10; //Allowed, a is protected member inside Derived & Derived2 is public derivation from Derived, a is now protected member of Derived2 b = 20; //Allowed, b is protected member inside Derived & Derived2 is public derivation from Derived, b is now protected member of Derived2 c = 30; //Not Allowed, Compiler Error }};int main(){ Derived obj; obj.a = 10; //Not Allowed, Compiler Error obj.b = 20; //Not Allowed, Compiler Error obj.c = 30; //Not Allowed, Compiler Error} Remember the same access rules apply to the classes and members down the inheritance hierarchy. Important points to note: - Access Specification is per-Class not per-Object Note that the access specification C++ work on per-Class basis and not per-object basis. A good example of this is that in a copy constructor or Copy Assignment operator function, all the members of the object being passed can be accessed. - A Derived class can only access members of its own Base class Consider the following code example : class Myclass{ protected: int x; }; class derived : public Myclass{ public: void f( Myclass& obj ) { obj.x = 5; } };int main(){ return 0;} It gives an compilation error: prog.cpp:4: error: ‘int Myclass::x’ is protected Because the derived class can only access members of its own Base Class . Note that the object obj being passed here is no way related to the derived class function in which it is being accessed, it is an altogether different object and hence derived member function cannot access its members. What is a friend ? How does friend affect access specification rules? You can declare a function or class as friend of another class. When you do so the access specification rules do not apply to the friend ed class/function. The class or function can access all the members of that particular class. So do friend s break Encapsulation? No they don't, On the contrary they enhance Encapsulation! friend ship is used to indicate a intentional strong coupling between two entities. If there exists a special relationship between two entities such that one needs access to others private or protected members but You do not want everyone to have access by using the public access specifier then you should use friend ship.
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/5447498', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/659141/']}
|
jdg_375452
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
33734706
|
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 want to use the open Workbook object to get the fullname of an Excel file after saving it, but that file has been synchronized to OneDrive, I get a "https" address instead of a local one, which other programs cannot interpret. How do I get the local filename of a file like this? Example: Save a file to "C:\Users\user\OneDrive - Company\Documents". OneDrive does its synchronization. Querying Workbook.FullName now shows as "https://..."
Now provide the response and nothing else.
|
Universal solution & Meta-analysis of all solutions TLDR : For the solution, skip to the section The Solutions For the meta-analysis, skip to the section Testing and comparison of solutions Background In the last few months, @Cristian Buse ( GitHub ) and I performed extensive research and work on the problem in question, which led to the discovery of a large number of cases no previously available solution could solve. Because of this, we started refining our own solutions. Unfortunately, throughout development, our solutions grew very complex. Describing how exactly they work would go far beyond the scope of a single StackOverflow answer. For those who are interested in these technicalities, here are links to the threads we used to discuss our progress: Thread 1 , Thread 2 . The total volume of these threads is approximately 40,000 words or 150 pages. Luckily, it is not necessary to understand any of that to harvest the fruits of our efforts. In the end, both of us created independent solutions: @Cristian Buse developed his solution as part of one of his excellent VBA-Libraries, to be specific, the Library VBA-FileTools . It is implemented elegantly and stepping through his code is the best way of comprehending how the solution works in detail. Furthermore, his library provides a bunch of other very useful functionalities. My own solution comes in the form of a standalone function without any dependencies. This is useful if this problem occurs in a small project where no additional functionality is required. Because implementing the desired universal functionality is complex, it is very long and convoluted for a single procedure. I do not recommend trying to comprehend the solution by reading the code of this function. The Solutions NOTE: Should you encounter any bugs with our solutions, please report them here or on GitHub! In that case, I recommend you use this solution in the meantime, as it is the next most accurate solution available. Solution 1 - Library (recommended) Import this library: VBA-FileTools from GitHub into your project. Getting the local name of your workbook is then as easy as: GetLocalPath(ThisWorkbook.FullName) Solution 2 - Standalone Function Copy this function , either from GitHub Gist or from this answer directly, into any standard code module. The version on GitHub Gist includes more information and some comments in and on the code, including information about the optional parameters of the function. Getting the local name of your workbook now works in the same way as with Solution 1: GetLocalPath(ThisWorkbook.FullName) Here is the code of the function: 'Author: Guido Witt-Dörring'https://gist.github.com/guwidoe/038398b6be1b16c458365716a921814d'Function for converting OneDrive/SharePoint Web Paths of any kind to a local 'path on your current pc.'This function only works on Windows.Public Function GetLocalPath(ByVal path As String, _ Optional ByVal rebuildCache As Boolean = False, _ Optional ByVal returnAll As Boolean = False, _ Optional ByVal preferredMountPointOwner As String = "") _ As String#If Mac Then GetLocalPath = path: Exit Function#End If Dim webRoot As String, locRoot As String, vKey As Variant, vItem As Variant Static locToWebDict As Object Dim resDict As Object: Set resDict = CreateObject("Scripting.Dictionary") Dim pmpo As String: pmpo = LCase(preferredMountPointOwner) If Not locToWebDict Is Nothing And Not rebuildCache Then For Each vKey In locToWebDict.Keys locRoot = vKey: webRoot = locToWebDict(vKey)(0) If InStr(1, path, webRoot, vbBinaryCompare) = 1 Then _ resDict.Add Key:=locToWebDict(vKey)(1), _ item:=Replace(Replace(path, webRoot, locRoot, , 1), "/", "\") Next vKey If resDict.count = 0 Then GetLocalPath = path: Exit Function If returnAll Then GetLocalPath = Join(resDict.Items, "/"): Exit Function If resDict.Exists(pmpo) Then GetLocalPath = resDict(pmpo): Exit Function GetLocalPath = resDict.Items()(0): Exit Function End If Set locToWebDict = Nothing Set locToWebDict = CreateObject("Scripting.Dictionary") Dim cid As String, fileNum As Long, line As Variant, parts() As String Dim tag As String, mainMount As String, relPath As String, email As String Dim b() As Byte, n As Long, i As Long, s As String, size As Long Dim parentID As String, folderID As String, folderName As String Dim folderIdPattern As String, fileName As String, folderType As String Dim siteID As String, libID As String, webID As String, lnkID As String Dim odFolders As Object, cliPolDict As Object Dim sig1 As String: sig1 = StrConv(Chr$(&H2), vbFromUnicode) Dim sig2 As String: sig2 = ChrW$(&H1) & String(3, vbNullChar) Dim vbNullByte As String: vbNullByte = MidB$(vbNullChar, 1, 1) Dim settPath As String, wDir As String, clpPath As String settPath = Environ("LOCALAPPDATA") & "\Microsoft\OneDrive\settings\" clpPath = Environ("LOCALAPPDATA") & "\Microsoft\Office\CLP\" Dim oneDriveSettDirs As Collection: Set oneDriveSettDirs = New Collection Dim dirName As Variant: dirName = Dir(settPath, vbDirectory) Do Until dirName = "" If dirName = "Personal" Or dirName Like "Business#" Then _ oneDriveSettDirs.Add dirName dirName = Dir(, vbDirectory) Loop For Each dirName In oneDriveSettDirs wDir = settPath & dirName & "\" If Dir(wDir & "global.ini", vbNormal) = "" Then GoTo NextFolder fileNum = FreeFile() Open wDir & "global.ini" For Binary Access Read As #fileNum ReDim b(0 To LOF(fileNum)): Get fileNum, , b Close #fileNum: fileNum = 0 For Each line In Split(b, vbNewLine) parts = Split(line, " = ") If parts(0) = "cid" Then: cid = parts(1): Exit For Next line If cid = "" Then GoTo NextFolder If (Dir(wDir & cid & ".ini") = "" Or _ Dir(wDir & cid & ".dat") = "") Then GoTo NextFolder If dirName Like "Business#" Then folderIdPattern = Replace(Space(32), " ", "[a-f0-9]") ElseIf dirName = "Personal" Then folderIdPattern = Replace(Space(16), " ", "[A-F0-9]") & "!###*" End If fileName = Dir(clpPath, vbNormal) Do Until fileName = "" If InStr(1, fileName, cid) And cid <> "" Then _ email = LCase(left(fileName, InStr(fileName, cid) - 2)): Exit Do fileName = Dir Loop Set cliPolDict = CreateObject("Scripting.Dictionary") fileName = Dir(wDir, vbNormal) Do Until fileName = "" If fileName Like "ClientPolicy*.ini" Then fileNum = FreeFile() Open wDir & fileName For Binary Access Read As #fileNum ReDim b(0 To LOF(fileNum)): Get fileNum, , b: s = b Close #fileNum: fileNum = 0 Set cliPolDict(fileName) = CreateObject("Scripting.Dictionary") For Each line In Split(b, vbNewLine) If InStr(1, line, " = ", vbBinaryCompare) Then tag = left(line, InStr(line, " = ") - 1) s = Mid(line, InStr(line, " = ") + 3) Select Case tag Case "DavUrlNamespace" cliPolDict(fileName).Add Key:=tag, item:=s Case "SiteID" s = Replace(LCase(s), "-", "") If Len(s) > 3 Then s = Mid(s, 2, Len(s) - 2) cliPolDict(fileName).Add Key:=tag, item:=s Case "IrmLibraryId" s = Replace(LCase(s), "-", "") If Len(s) > 3 Then s = Mid(s, 2, Len(s) - 2) cliPolDict(fileName).Add Key:=tag, item:=s Case "WebID" s = Replace(LCase(s), "-", "") If Len(s) > 3 Then s = Mid(s, 2, Len(s) - 2) cliPolDict(fileName).Add Key:=tag, item:=s End Select End If Next line End If fileName = Dir Loop fileNum = FreeFile Open wDir & cid & ".dat" For Binary Access Read As #fileNum ReDim b(0 To LOF(fileNum)): Get fileNum, , b: s = b: size = LenB(s) Close #fileNum: fileNum = 0 Set odFolders = CreateObject("Scripting.Dictionary") For Each vItem In Array(16, 8) i = InStrB(vItem, s, sig2) Do While i > vItem And i < size - 168 If MidB$(s, i - vItem, 1) = sig1 Then i = i + 8: n = InStrB(i, s, vbNullByte) - i If n < 0 Then n = 0 If n > 39 Then n = 39 folderID = StrConv(MidB$(s, i, n), vbUnicode) i = i + 39: n = InStrB(i, s, vbNullByte) - i If n < 0 Then n = 0 If n > 39 Then n = 39 parentID = StrConv(MidB$(s, i, n), vbUnicode) i = i + 121 n = -Int(-(InStrB(i, s, vbNullChar) - i) / 2) * 2 If n < 0 Then n = 0 folderName = MidB$(s, i, n) If folderID Like folderIdPattern Then odFolders.Add folderID, VBA.Array(parentID, folderName) End If End If i = InStrB(i + 1, s, sig2) Loop If odFolders.count > 0 Then Exit For Next vItem fileNum = FreeFile() Open wDir & cid & ".ini" For Binary Access Read As #fileNum ReDim b(0 To LOF(fileNum)): Get fileNum, , b Close #fileNum: fileNum = 0 Select Case True Case dirName Like "Business#" mainMount = "" For Each line In Split(b, vbNewLine) Select Case left$(line, InStr(line, " = ") - 1) Case "libraryScope" webRoot = "": parts = Split(line, """"): locRoot = parts(9) If locRoot = "" Then locRoot = Split(line, " ")(2) folderType = parts(3): parts = Split(parts(8), " ") siteID = parts(1): webID = parts(2): libID = parts(3) If mainMount = "" And folderType = "ODB" Then mainMount = locRoot: fileName = "ClientPolicy.ini" If cliPolDict.Exists(fileName) Then _ webRoot = cliPolDict(fileName)("DavUrlNamespace") Else fileName = "ClientPolicy_" & libID & siteID & ".ini" If cliPolDict.Exists(fileName) Then _ webRoot = cliPolDict(fileName)("DavUrlNamespace") End If If webRoot = "" Then For Each vItem In cliPolDict.Items If vItem("SiteID") = siteID And vItem("WebID") = _ webID And vItem("IrmLibraryId") = libID Then webRoot = vItem("DavUrlNamespace"): Exit For End If Next vItem End If locToWebDict.Add locRoot, VBA.Array(webRoot, email) Case "libraryFolder" webRoot = "": locRoot = Split(line, """")(1) libID = Split(line, " ")(3) For Each vKey In locToWebDict.Keys If vKey = libID Then s = "": parentID = left(Split(line, " ")(4), 32) Do Until Not odFolders.Exists(parentID) s = odFolders(parentID)(1) & "/" & s parentID = odFolders(parentID)(0) Loop webRoot = locToWebDict(vKey)(0) & s: Exit For End If Next vKey locToWebDict.Add locRoot, VBA.Array(webRoot, email) Case "AddedScope" webRoot = "": parts = Split(line, """") relPath = parts(5): If relPath = " " Then relPath = "" parts = Split(parts(4), " "): siteID = parts(1) webID = parts(2): libID = parts(3): lnkID = parts(4) fileName = "ClientPolicy_" & libID & siteID & lnkID & ".ini" If cliPolDict.Exists(fileName) Then: _ webRoot = cliPolDict(fileName)("DavUrlNamespace") _ & relPath If webRoot = "" Then For Each vItem In cliPolDict.Items If vItem("SiteID") = siteID And vItem("WebID") = _ webID And vItem("IrmLibraryId") = libID Then webRoot = vItem("DavUrlNamespace") & relPath Exit For End If Next vItem End If s = "": parentID = left(Split(line, " ")(3), 32) Do Until Not odFolders.Exists(parentID) s = odFolders(parentID)(1) & "\" & s parentID = odFolders(parentID)(0) Loop locRoot = mainMount & "\" & s locToWebDict.Add locRoot, VBA.Array(webRoot, email) Case Else For Each vKey In locToWebDict.Keys If vKey Like "#*" Then locToWebDict.Remove vKey Next vKey Exit For End Select Next line Case dirName = "Personal" If Not cliPolDict.Exists("ClientPolicy.ini") Then GoTo NextFolder For Each line In Split(b, vbNewLine) If line Like "library = *" Then _ locRoot = Split(line, """")(3): Exit For Next line webRoot = cliPolDict("ClientPolicy.ini")("DavUrlNamespace") If locRoot = "" Or webRoot = "" Or cid = "" Then GoTo NextFolder locToWebDict(locRoot) = VBA.Array(webRoot & "/" & cid, email) If Dir(wDir & "GroupFolders.ini") = "" Then GoTo NextFolder cid = "": fileNum = FreeFile() Open wDir & "GroupFolders.ini" For Binary Access Read As #fileNum ReDim b(0 To LOF(fileNum)): Get fileNum, , b Close #fileNum: fileNum = 0 For Each line In Split(b, vbNewLine) If InStr(line, "BaseUri = ") And cid = "" Then cid = LCase(Mid(line, InStrRev(line, "/") + 1, 16)) folderID = left(line, InStr(line, "_") - 1) ElseIf cid <> "" Then locToWebDict.Add locRoot & "\" & odFolders(folderID)(1), _ VBA.Array(webRoot & "/" & cid & "/" & _ Mid(line, Len(folderID) + 9), email) cid = "": folderID = "" End If Next line End SelectNextFolder: cid = "": s = "": email = "": Set odFolders = Nothing Next dirName For Each vKey In locToWebDict.Keys locRoot = vKey: webRoot = locToWebDict(vKey)(0) email = locToWebDict(vKey)(1) If right(webRoot, 1) = "/" Then webRoot = left(webRoot, Len(webRoot) - 1) If right(locRoot, 1) = "\" Then locRoot = left(locRoot, Len(locRoot) - 1) locToWebDict.Remove vKey End If locToWebDict(locRoot) = VBA.Array(webRoot, email) Next vKey GetLocalPath = GetLocalPath(path, False, returnAll, pmpo)End Function How do the solutions work? Both solutions get all of the required information for translating the UrlPath / WebPath to a LocalPath from the OneDrive settings files inside of the directory %localappdata%\Microsoft\OneDrive\settings\... . This means, contrary to most other solutions online, the registry is not used! The reasons for this are explained in the Gist repository of Solution 2 . The following files will be read: (Wildcards: * - zero or more characters; ? - one character) ????????????????.dat????????????????.iniglobal.iniGroupFolders.ini????????-????-????-????-????????????.dat????????-????-????-????-????????????.iniClientPolicy*.ini All of the .ini files can be read easily as they use UTF-16 encoding.The .dat files are much more difficult to decipher, because they use a proprietary binary format. Luckily, the information we need can be extracted by looking for certain byte-patterns inside these files and copying and converting the data at a certain offset from these "signature" bytes. Data from all of these files is used, to create a "dictionary" of all the local mount points on your pc, and their corresponding WebPath . For example, for your personal OneDrive, such a local mount point could look like this: C:\Users\Username\OneDrive , and the corresponding WebPath could look like this: https://d.docs.live.net/f9d8c1184686d493 . This "dictionary" can then be used to "translate" a given WebPath to a local path by replacing the part that is equal to one of the elements of the dictionary with the corresponding local mount point. For example, this WebPath : https://d.docs.live.net/f9d8c1184686d493/Folder/File.xlsm will be correctly "translated" to C:\Users\Username\OneDrive\Folder\File.xlsm Because all possible WebPaths for the local machine can be translated by the same dictionary, it is implemented as Static in both solutions. This means it will only be written the first time the function is called, all subsequent function calls will find the "dictionary" already initialized leading to shorter run time. Testing and comparison of solutions I conducted extensive testing of all solutions I could find online. A selection of these tests will be presented here. This is a list of some of the tested solutions: Nr. Author Solution Tests passed 1 Koen Rijnsent https://stackoverflow.com/a/71753164/12287457 0/45 2 Cooz2 adapted for excel by LucasHol https://social.msdn.microsoft.com/Forums/office/en-US/1331519b-1dd1-4aa0-8f4f-0453e1647f57/how-to-get-physical-path-instead-of-url-onedrive 0/45 3 Claude https://stackoverflow.com/a/64657459/12287457 0/45 4 Variatus https://stackoverflow.com/a/68568909/12287457 0/45 5 MatChrupczalski https://social.msdn.microsoft.com/Forums/office/en-US/1331519b-1dd1-4aa0-8f4f-0453e1647f57/how-to-get-physical-path-instead-of-url-onedrive 2/45 6 tsdn https://stackoverflow.com/a/56326922/12287457 2/45 7 Alain YARDIM https://stackoverflow.com/a/65967886/12287457 2/45 8 Peter G. Schild https://stackoverflow.com/a/60990170/12287457 2/45 9 TWMIC https://stackoverflow.com/a/64591370/12287457 3/45 10 Philip Swannell https://stackoverflow.com/a/54182663/12287457 4/45 11 Horoman https://stackoverflow.com/a/60921115/12287457 4/45 12 RMK https://stackoverflow.com/a/67697487/12287457 5/45 13 beerockxs https://stackoverflow.com/a/67582367/12287457 5/45 14 COG https://stackoverflow.com/a/51316641/12287457 5/45 15 Virtuoso https://stackoverflow.com/a/33935405/12287457 5/45 16 mohnston https://stackoverflow.com/a/68569925/12287457 5/45 17 Tomoaki Tsuruya (鶴谷 朋亮) https://tsurutoro.com/vba-trouble2/ 5/45 18 Christoph Ackermann https://stackoverflow.com/a/62742852/12287457 7/45 19 Schoentalegg https://stackoverflow.com/a/57040668/12287457 7/45 20 Erlandsen Data Consulting https://www.erlandsendata.no/?t=vbatips&p=4079 7/45 21 Kurobako (黒箱) https://kuroihako.com/vba/onedriveurltolocalpath/ 7/45 22 Tim Williams https://stackoverflow.com/a/70610729/12287457 8/45 23 Erik van der Neut https://stackoverflow.com/a/72709568/12287457 8/45 24 Ricardo Diaz https://stackoverflow.com/a/65605893/12287457 9/45 25 Iksi https://stackoverflow.com/a/68963896/12287457 11/45 26 Gustav Brock , Cactus Data ApS https://stackoverflow.com/a/70521246/12287457 11/45 27 Ricardo Gerbaudo https://stackoverflow.com/a/69929678/12287457 14/45 28 Guido Witt-Dörring short solution https://stackoverflow.com/a/72736924/12287457 24/45 29 Ion Cristian Buse https://github.com/cristianbuse/VBA-FileTools 45/45 30 Guido Witt-Dörring universal solution https://gist.github.com/guwidoe/ 038398b6be1b16c458365716a921814d 45/45 Each line in the table in the below image represents one solution in the above table and they can be correlated using the solution number. Likewise, each column represents a test case, they can be correlated to the test-table at the end of this post by using the test-number. Most solutions pass very few tests. Many of these tests are relatively dificult to solve, some are absolute edge cases, such as tests nr. 40 to 45, that test how a solution deals with WebPaths that are synced to multiple different local paths, which can only happen if multiple Business OneDrive accounts are logged in on the same PC and even then needs some special setup. (More information on that can be found here in Thread 2 ) Another reason why many solutions perform poorly is that the environment variables Environ("OneDrive") , Environ("OneDriveCommercial") , Environ("OneDriveConsumer") , which many solutions build on, are not reliable, especially when you have multiple business OneDrive accounts logged in at the same time, like I do. If you have another different solution you would like me to test, let me know and I'll add it to this section. Every test can be found in the following table. Descriptions had to be omitted because of the length limit for answers. Nr. WebPath LocalPath1 LocalPath2 1 https://d.docs.live.net/f9d8c1184686d493/Testfolder_toplvl/test.xlsm C:\Users\UN\OneDrive\Testfolder_toplvl\test.xlsm 2 https://d.docs.live.net/f9d8c1184686d493/The X Company/Test/Test/Test/test.xlsm C:\Users\UN\OneDrive\The X Company\Test\Test\Test\test.xlsm 3 https://d.docs.live.net/f9d8c1184686d493/test.xlsm C:\Users\UN\OneDrive\test.xlsm 4 https://d.docs.live.net/35f3889de6a905a8/Personal/test.xlsm C:\Users\UN\OneDrive\Personal\test.xlsm 5 https://d.docs.live.net/35f3889de6a905a8/Business1/test.xlsm C:\Users\UN\OneDrive\Business1\test.xlsm 6 https://d.docs.live.net/56aedc5c5f2afc2b/FirstLevel/SecondLevel/test.xlsm C:\Users\UN\OneDrive\SecondLevel\test.xlsm 7 https://d.docs.live.net/56aedc5c5f2afc2b/Test/Test/Test/test.xlsm C:\Users\UN\OneDrive\Test\Test\test.xlsm 8 https://d.docs.live.net/35f3889de6a905a8/Test (1)/SecondLevel/Test (1)/FourthLevel/Test (1)/Test/test.xlsm C:\Users\UN\OneDrive\FourthLevel\Test (1)\Test\test.xlsm 9 https://d.docs.live.net/35f3889de6a905a8/Test/Test/Test/Test/test.xlsm C:\Users\UN\OneDrive\Test (1)\Test\test.xlsm 10 https://d.docs.live.net/35f3889de6a905a8/Test (2)/SecondLevel/Test (1)/FourthLevel/Test (1)/Test/test.xlsm C:\Users\UN\OneDrive\Test (1) (1)\FourthLevel\Test (1)\Test\test.xlsm 11 https://d.docs.live.net/35f3889de6a905a8/Test (3)/SecondLevel/Test (1)/FourthLevel/Test (1)/Test/test.xlsm C:\Users\UN\OneDrive\Test (1) (2)\Test\test.xlsm 12 https://d.docs.live.net/35f3889de6a905a8/Test (4)/SecondLevel/Test (1)/FourthLevel/Test (1)/Test/test.xlsm C:\Users\UN\OneDrive\Test (1) (3)\Test\test.xlsm 13 https://d.docs.live.net/7aef338a1493aec9/Test/Test/Test/test.xlsm C:\Users\UN\OneDrive\Test (2)\Test\test.xlsm 14 https://d.docs.live.net/56aedc5c5f2afc2b/Test (1)/Test/Test/test.xlsm C:\Users\UN\OneDrive\Test (3)\Test\test.xlsm 15 https://org1-my.sharepoint.com/personal/person1_org1_com/Documents/-Test-/test.xlsm C:\Users\UN\OneDrive - org1\-Test-\test.xlsm 16 https://org1-my.sharepoint.com/personal/person1_org1_com/Documents/Test/Test/Test.xlsm C:\Users\UN\OneDrive - org1\Test\Test\Test.xlsm 17 https://org2-my.sharepoint.com/personal/person1_org2_com/Documents/Test/Test/Test/test.xlsm C:\Users\UN\OneDrive - org2\Test\Test\Test\test.xlsm 18 https://org2.sharepoint.com/sites/TestLinkLib2/Shared Documents/test.xlsm C:\Users\UN\OneDrive - org2\Documents - TestLinkLib2\test.xlsm 19 https://org2.sharepoint.com/sites/TestLib2/Shared Documents/TestOnlyAddedAsLink/Test/Test/test.xlsm C:\Users\UN\OneDrive - org2\Test - TestLinkLib\test.xlsm 20 https://org2.sharepoint.com/sites/TestLib2/Shared Documents/firstLevelFolder/test2.xlsm C:\Users\UN\OneDrive - org2\TestLinkParent\firstLevelFolder\test2.xlsm 21 https://org2.sharepoint.com/sites/TestLib2/Shared Documents/level1/level2/level3/level4/level5/level6/level7/test2.xlsm C:\Users\UN\OneDrive - org2\TestLinkParent\LinkParentLevel2\linkParentLevel3\level7\test2.xlsm 22 https://org1-my.sharepoint.com/personal/person3_org1_com/Documents/Shared Folder/Beispiel import.xlsm C:\Users\UN\org1\Person3 - Person1\Beispiel import.xlsm 23 https://org1-my.sharepoint.com/personal/person3_org1_com/Documents/Shared Folder/Test/ C:\Users\UN\org1\Person3 - Person1\Test\ 24 https://org1-my.sharepoint.com/personal/person2_org1_com/Documents/Test/File/Test/3.xlsm C:\Users\UN\org1\Person2 - Test\3.xlsm 25 https://org1.sharepoint.com/sites/AI/Shared Documents/Test/test.xlsm C:\Users\UN\org1\AI - Dokumente\Test\test.xlsm 26 https://org1.sharepoint.com/sites/workspaces/project1as/Shared Documents/Test.xlsm C:\Users\UN\org1\project1 After Sales - Documents\Test.xlsm 27 https://org1.sharepoint.com/sites/workspaces/project1/Shared Documents/100_Business Development/ C:\Users\UN\org1\project1 - Documents\100_Business Development\ 28 https://org1.sharepoint.com/sites/project2/Shared Documents/General/2021/04_Working/- Archiv -/test.xlsm C:\Users\UN\org1\project2 - General\2021\04_Working\- Archiv -\test.xlsm 29 https://org2.sharepoint.com/sites/MySite/Shared Documents/test.xlsm C:\Users\UN\org2\MySite - Documents\test.xlsm 30 https://org2.sharepoint.com/sites/TestLib3rdLvlMount/Shared Documents/Test/Test/test.xlsm C:\Users\UN\org2\TestLib3rdLvlMount - Test\test.xlsm 31 https://org2.sharepoint.com/sites/InitialName/Shared Documents/Test (1)/Test/Test/Test/test.xlsm C:\Users\UN\org2\ChangedName - Test\test.xlsm 32 https://org2.sharepoint.com/sites/SpaceinName/Shared Documents/Test/Test/test.xlsm C:\Users\UN\org2\Space in Name - Test\test.xlsm 33 https://org2.sharepoint.com/sites/TestLib3rdLvlMount/Shared Documents/2ndLevel/3rdLevel/test.xlsm C:\Users\UN\org2\TestLib3rdLvlMount - 3rdLevel\test.xlsm 34 https://org2.sharepoint.com/sites/TestLib3rdLvlMount/Shared Documents/Test (1)/Test/Test/Test/Test/Test/Test/Test/Test/test.xlsm C:\Users\UN\org2\TestLib3rdLvlMount - Test (1)\Test\Test\test.xlsm 35 https://org2.sharepoint.com/sites/TestLib3rdLvlMount/Shared Documents/Level1/Level2/Level3/Level4/Level5/Level6/test.xlsm C:\Users\UN\org2\TestLib3rdLvlMount - Level6\test.xlsm 36 https://org2.sharepoint.com/sites/InitialName/Shared Documents/Test (2)/Test/Test/test.xlsm C:\Users\UN\org2\ChangedNameAgain - Test\test.xlsm 37 https://org2.sharepoint.com/sites/InitialName/Shared Documents/Test (2)/Test/Test/Test/test.xlsm C:\Users\UN\org2\ChangedNameAgain - Test\Test\test.xlsm 38 https://org2.sharepoint.com/sites/InitialName/Shared Documents/Test (2)/Test/Test/Test/Test/Test/test.xlsm C:\Users\UN\org2\ChangedNameAgain - Test\Test\Test\Test\test.xlsm 39 https://org2.sharepoint.com/sites/InitialName/Shared Documents/Test (2)/Test/Test/Test/Test/Test/Test/test.xlsm C:\Users\UN\org2\ChangedNameAgain - Test\Test\Test\Test\Test\test.xlsm 40 https://org2.sharepoint.com/sites/InitialName/Shared Documents/2ndLevel/3rdLevel/test.xlsm C:\Users\UN\org2\ChangedName - 3rdLevel\test.xlsm C:\Users\UN\org2\Team site - 3rdLevel\test.xlsm 41 https://org2.sharepoint.com/sites/InitialName/Shared Documents/Test/Test/test.xlsm C:\Users\UN\org2\ChangedName - Test (1)\test.xlsm C:\Users\UN\org2\Team site - Test\test.xlsm 42 https://org2.sharepoint.com/sites/TestLib22/Shared Documents/Test/Test/Test/Test/test.xlsm C:\Users\UN\org2\TestLib - Test (3)\Test\Test\test.xlsm C:\Users\UN\org2\TestLib - Test (2)\Test\test.xlsm 43 https://org2.sharepoint.com/sites/TestLib3rdLvlMount/Shared Documents/TestMountAtTwoDifferentLevels/Test/Test/Test/Test/test.xlsm C:\Users\UN\org2\TestLib - Test\test.xlsm C:\Users\UN\org2\TestLib - Test (1)\Test\Test\test.xlsm 44 https://org2.sharepoint.com/sites/TestLib2/Shared Documents/Level2/Level3/test.xlsm C:\Users\UN\OneDrive - org2\Level3\test.xlsm C:\Users\UN\org2\TestLinkLib - Level2\Level3\test.xlsm 45 https://org2.sharepoint.com/sites/TestLib2/Shared Documents/Test/Test/Test/test.xlsm C:\Users\UN\OneDrive - org2\TestLinkParent\Test - TestLinkLib\Test\test.xlsm C:\Users\UN\org2\TestLinkLib - Test\Test\test.xlsm
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/33734706', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1847477/']}
|
jdg_375453
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
33661714
|
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 looking for a way to grep a certain branch. Simple? To show a specific file in a branch, one would use: git show branch:my_branch bla_sheep.txt Similar syntax is used to diff, etc. Is there a way to simply grep a branch: git grep branch:my_branch <regex>
Now provide the response and nothing else.
|
To look at multiple commits, starting at some branch tip and working backwards: git grep can look in any particular tree (hence any particular commit since any given commit identifies a particular tree), but to iterate over every commit contained within some branch, you will need to do your own git rev-list : git rev-list branch | while read rev; do git grep <regexp> $rev; done for instance (but you may want to fancy this up more so that your grep stops once you've found what you are looking for). If you want to look once, at the commit that is the tip of branch <branch> , and find (or fail to find) any instances of <regexp> , just do a simple: git grep <regexp> branch The loop form is only for the case where you want to start at that tip commit and keep working backwards through previous commits on the branch as well.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/33661714', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1778980/']}
|
jdg_375454
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3491183
|
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:
We define recursive sequences $a_{n+1}=1+\frac 1{1+a_n}$ , $a_1=1$ and $b_{n+1}=\frac{b_n^2+2}{2b_n}$ , $b_1=1$ . I wish to show that $b_{n+1}=a_{2^n}$ . This can be proven using closed forms expressions related to continued fractions. I know that $a_n$ can be expressed as $$a_n=\sqrt2\cdot \frac{(1+\sqrt 2)^n +(1-\sqrt 2)^n}{(1+\sqrt 2)^n - (1-\sqrt 2)^n}$$ On the other hand, we can prove inductively that $$\frac{b_{n+1}-\sqrt 2}{b_{n+1}+\sqrt 2}=\left(\frac{1-\sqrt 2}{1+\sqrt 2}\right)^{2^n}$$ So the relation $a_{2^n}=b_{n+1}$ can be deduced by expanding the fractions. However the computation is rather tedious, I am looking for a proof that does not involve expanding everything into closed form expressions. Thanks.
Now provide the response and nothing else.
|
Define the sequences $\,a_n := c_n/d_n\,$ where $\,c\,$ and $\,d\,$ are OEISsequences A001333 and A000129 . Consider the matrix $$ M := \begin{pmatrix} 1 & 1 \\ 2 & 1 \end{pmatrix} \tag{1}$$ whose powers are $$ M^n = \begin{pmatrix} c_n & d_n \\ 2d_n & c_n \end{pmatrix}. \tag{2}$$ Since $\,M^{n+1} = M^n\, M\,$ this explains the $\,a_n\,$ recursion. Notice the algebraic matrix identity $$ \begin{pmatrix} c & d \\ 2d & c \end{pmatrix}^2 =\begin{pmatrix} c^2+2d^2 & 2cd \\ 4cd & c^2+2d^2 \end{pmatrix}. \tag{3}$$ Since $\,M^{2^{n+1}} = (M^{2^n})^2,\,$ this explains the $\,a_{2^n}\,$ recursion. Note that the matrix $\,M\,$ is equivalent to $\,m:=1\pm\sqrt{2}.\,$ Thus equation $(2)$ is equivalent to $\,m^n = c_n\pm d_n\sqrt{2}\,$ and equation $(3)$ is equivalent to $\,(c\pm d\sqrt{2})^2 = (c^2+2d^2)\pm(2cd)\sqrt{2}.$
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3491183', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/319071/']}
|
jdg_375455
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
895658
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
How can I show that: $$\int_{0}^{\infty}\frac{\log(x)}{e^{x}+1}dx=-\frac{\log^{2}(2)}{2}$$ EDIT: This is equivalent to showing that $\eta'(1)=-\ln2\gamma-\dfrac{\ln^2(2)}{2}$.
Now provide the response and nothing else.
|
$\newcommand{\angles}[1]{\left\langle\, #1 \,\right\rangle} \newcommand{\braces}[1]{\left\lbrace\, #1 \,\right\rbrace} \newcommand{\bracks}[1]{\left\lbrack\, #1 \,\right\rbrack} \newcommand{\ceil}[1]{\,\left\lceil\, #1 \,\right\rceil\,} \newcommand{\dd}{{\rm d}} \newcommand{\ds}[1]{\displaystyle{#1}} \newcommand{\expo}[1]{\,{\rm e}^{#1}\,} \newcommand{\fermi}{\,{\rm f}} \newcommand{\floor}[1]{\,\left\lfloor #1 \right\rfloor\,} \newcommand{\half}{{1 \over 2}} \newcommand{\ic}{{\rm i}} \newcommand{\iff}{\Longleftrightarrow} \newcommand{\imp}{\Longrightarrow} \newcommand{\pars}[1]{\left(\, #1 \,\right)} \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}} \newcommand{\pp}{{\cal P}} \newcommand{\root}[2][]{\,\sqrt[#1]{\vphantom{\large A}\,#2\,}\,} \newcommand{\sech}{\,{\rm sech}} \newcommand{\sgn}{\,{\rm sgn}} \newcommand{\totald}[3][]{\frac{{\rm d}^{#1} #2}{{\rm d} #3^{#1}}} \newcommand{\verts}[1]{\left\vert\, #1 \,\right\vert}$$$\int_{0}^{\infty}{\ln\pars{x} \over \expo{x} + 1}\,\dd x=\lim_{\mu\to 0}\partiald{}{\mu}\int_{0}^{\infty}{x^{\mu}\expo{-x} \over 1 + \expo{-x}}\,\dd x$$ \begin{align}\int_{0}^{\infty}{x^{\mu}\expo{-x} \over 1 + \expo{-x}}\,\dd x&=\sum_{n = 0}^{\infty}\pars{-1}^{n}\int_{0}^{\infty}x^{\mu}\expo{-\pars{n + 1}x}\,\dd x=\sum_{n = 0}^{\infty}{\pars{-1}^{n} \over \pars{n + 1}^{\mu + 1}}\int_{0}^{\infty}x^{\mu}\expo{-x}\,\dd x\\[3mm]&=\Gamma\pars{\mu + 1}\sum_{n = 1}^{\infty}{\pars{-1}^{n + 1} \over n^{\mu + 1}}=-\Gamma\pars{\mu + 1}{\rm Li}_{\mu + 1}\pars{-1}\\[3mm]&=\Gamma\pars{\mu + 1}\pars{1 - 2^{-\mu}}\zeta\pars{\mu + 1}\end{align} \begin{align}&\color{#66f}{\large\int_{0}^{\infty}{\ln\pars{x} \over \expo{x} + 1}\,\dd x}=\lim_{\mu\ \to\ 0}\partiald{\bracks{\Gamma\pars{\mu + 1}\pars{1 - 2^{-\mu}}\zeta\pars{\mu + 1}}}{\mu}\tag{1}\\[3mm]&=\color{#66f}{\large -\,\half\,\ln^{2}\pars{2}} \approx -0.2402\end{align} See the Dirichlet Eta Function link and the PolyLogarithm Function Link . ADDENDA The limit, in expression $\pars{1}$ has to be handled carefully because $\ds{\zeta\pars{\mu + 1} \sim {1 \over \mu}}$ when $\ds{\mu \sim 0}$. It has the Laurent Expansion $$\zeta\pars{\mu + 1}={1 \over \mu} + \sum_{n = 0}^{\infty}{\pars{-1}^{n} \over n!}\,\gamma_{n}\,\mu^{n}$$where $\ds{\gamma_{n}}$'s are the Stieltjes Constants.Let's consider the limit evaluation. In order to evaluate the limit we just need the expansion, up to order one, of each factor in( $\ds{\gamma}$ is the Euler-Mascheroni Constant ):$$\Gamma\pars{\mu + 1}\,{1 - 2^{-\mu} \over \mu}\,\bracks{\mu\zeta\pars{\mu + 1}}\,,\qquad\left\vert\begin{array}{ccl}\ \Gamma\pars{\mu + 1} & \sim & 1 - \gamma\mu\\[2mm]\ {1 - 2^{-\mu} \over \mu} & \sim & \ln\pars{2} - \half\,\ln^{2}\pars{2}\mu\\[2mm]\ \mu\zeta\pars{\mu + 1} & \sim & 1 + \gamma\mu\,,\quad\gamma_{0} = \gamma\end{array}\right.$$From these expression we see that the product$\ds{\Gamma\pars{\mu + 1}\bracks{\mu\zeta\pars{\mu + 1}} \sim1 - \gamma^{2}\mu^{2}}$ is already of order $\ds{\mu^{2}}$. We are left with the'middle factor' $\ds{1 - 2^{-\mu} \over \mu}$ such that\begin{align}&\lim_{\mu\ \to\ 0}\partiald{\bracks{\Gamma\pars{\mu + 1}\pars{1 - 2^{-\mu}}\zeta\pars{\mu + 1}}}{\mu}=\lim_{\mu\ \to\ 0}\partiald{\bracks{\ln\pars{2} - \ln^{2}\pars{2}\mu/2}}{\mu}\\[3mm]&=\color{#66f}{\large -\,\half\,\ln^{2}\pars{2}}\end{align}
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/895658', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/166353/']}
|
jdg_375456
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1389162
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Something I have been wondering about properties for a while. When you are using properties, do you need to override the release message to ensure the properties are released properties? i.e. is the following (fictitious) example sufficient? @interface MyList : NSObject {NSString* operation;NSString* link;}@property (retain) NSString* operation;@property (retain) NSString* link;@end@implementation MyList@synthesize operation,link;@end
Now provide the response and nothing else.
|
You should always release the backing variables in dealloc: - (void) dealloc { [operation release]; [link release]; [super dealloc];} Another way: - (void) dealloc { self.operation = nil; self.link = nil; [super dealloc];} That's not the preferred way of releasing the objects, but in case you're using synthesized backing variables , it's the only way to do it. NOTE: to make it clear why this works, let's look at the synthesized implementation of the setter for link property, and what happens when it is set to nil : - (void) setLink:(MyClass *) value { [value retain]; // calls [nil retain], which does nothing [link release]; // releases the backing variable (ivar) link = value; // sets the backing variable (ivar) to nil} So the net effect is that it will release the ivar.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1389162', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/84118/']}
|
jdg_375457
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
160235
|
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am in the process of writing a security vulnerabilities report on an application used at my employer, having completed an application audit. One discovered vulnerability can lead to unauthorized deletion / destruction of data. In the context of the CIA security principles,I associate integrity to be concerned with safeguarding data from unauthorized modification, such as through MITM and availability with safeguarding data from DoS such as through smurf or teardrop attacks. I am inclined to say that unauthorized deletion of data is an attack on Availability principle given the data can no longer be accessed by legitimate users. However, one of my colleagues disagrees and considers such to be an attack on the Integrity principle, because data was modified by being destroyed without authorization . Is the unauthorized deletion of data considered a breach of integrity or availability?
Now provide the response and nothing else.
|
However, one of my colleagues disagrees and considers such to be an attack on the Integrity principle, because data was modified by being destroyed without authorization. Your colleague has a point. Unauthorized data deletion is foremost a breach of integrity since deletion can be considered a special case of modification. This can have an impact on availability, but it doesn't have to. E.g, an attacker who manages to delete all logfiles on a web server probably wouldn't impact the server's uptime. But obviously a breach of integrity often implies impaired availability since a service with corrupted resources will likely not function properly. I wouldn't always force a vulnerability into one of the three CIA categories, though. The impact of unauthorized data deletion is quite obvious, so I'm not sure categorizing it according to the CIA triad adds any clarification. Also note that there are many alternative models such as the Parkerian hexad that give you a few more options to choose from.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://security.stackexchange.com/questions/160235', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/106510/']}
|
jdg_375458
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
725914
|
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:
When $\lim_{n\to\infty} x_n = a$, and $\lim_{n\to\infty} y_n = b$, find the limit,$$\lim_{n\to\infty} \frac{x_1 y_n + x_2 y_{n-1} + \cdots + x_n y_1}{n}.$$Thank you for your help in advance.
Now provide the response and nothing else.
|
We can use the standard result: If $x_{n} \to x$ as $n \to \infty$ then $$\lim_{n \to \infty}\frac{x_{1} + x_{2} + \cdots + x_{n}}{n} = x$$ This is pretty standard and its proof is available on MSE. Now for the current question let $x_{n} = a + e_{n}$ and then $e_{n} \to 0$ as $n \to \infty$. We have $$\begin{aligned}\frac{x_{1}y_{n} + x_{2}y_{n - 1} + \cdots + x_{n}y_{1}}{n} &= a\cdot\frac{y_{1} + y_{2} + \cdots + y_{n}}{n}\\&+ \frac{e_{1}y_{n} + e_{2}y_{n - 1} + \cdots + e_{n}y_{1}}{n}\end{aligned}$$ Now in the above the first term tends to $a\cdot b = ab$. For the second term we need to note that the sequence $y_{n}$ is bounded by some $K > 0$ and therefore in absolute value the second term is no greater than $K\cdot\dfrac{|e_{1}| + |e_{2}| + \cdots + |e_{n}|}{n}$. Since $e_{n} \to 0$ therefore this term also tends to $0$. So the desired limit is $ab$.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/725914', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/134856/']}
|
jdg_375459
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3009
|
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 understand that people explain (in layman's terms at least) that the presence of mass "warps" space-time geometry, and this causes gravity. I have also of course heard the analogy of a blanket or trampoline bending under an object, which causes other objects to come together, but I always thought this was a hopelessly circular explanation because the blanket only bends because of "real" gravity pulling the object down and then pulling the other objects down the sloped blanket.In other words, to me, it seems that curved space wouldn't have any actual effect on objects unless there's already another force present. So how is curved space-time itself actually capable of exerting a force (without some source of a fourth-dimensional force)? I apologize for my ignorance in advance, and a purely mathematical explanation will probably go over my head, but if it's required I'll do my best to understand.
Now provide the response and nothing else.
|
Luboš's answer is of course perfectly correct. I'll try to give you some examples why the straightest line is physically motivated (besides being mathematically exceptional as an extremal curve). Image a 2-sphere (a surface of a ball). If an ant lives there and he just walks straight, it should be obvious that he'll come back where he came from with his trajectory being a circle. Imagine a second ant and suppose he'll start to walk from the same point as the first ant and at the same speed but into a different direction. He'll also produce circle and the two circles will cross at two points (you can imagine those circles as meridians and the crossing points as a north resp. south poles). Now, from the ants' perspective who aren't aware that they are living in a curved space, this will seem that there is a force between them because their distance will be changing in time non-linearly (think about those meridians again). This is one of the effects of the curved space-time on movement on the particles (these are actually tidal forces). You might imagine that if the surface wasn't a sphere but instead was curved differently, the straight lines would also look different. E.g. for a trampoline you'll get ellipses (well, almost, they do not close completely, leading e.g. to the precession of the perihelion of the Mercury). So much for the explanation of how curved space-time (discussion above was just about space; if you introduce special relativity into the picture, you'll get also new effects of mixing of space and time as usual). But how does the space-time know it should be curved in the first place? Well, it's because it obeys Einstein's equations (why does it obey these equations is a separate question though). These equations describe precisely how matter affects space-time. They are of course compatible with Newtonian gravity in low-velocity, small-mass regime, so e.g. for a Sun you'll obtain that trampoline curvature and the planets (which will also produce little dents, catching moons, for example; but forget about those for a moment because they are not that important for the movement of the planet around the Sun) will follow straight lines, moving in ellipses (again, almost ellipses).
|
{}
|
{'log_upvote_score': 6, 'links': ['https://physics.stackexchange.com/questions/3009', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/1358/']}
|
jdg_375460
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
5113186
|
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 have a quick question about the GAC I created an assembly Awesome.DLL. Had it signed, then installed into the GAC: C:\MyApps\Awesome\Awesome\Awesome\bin\Release>sn -k Awesome.snkMicrosoft (R) .NET Framework Strong Name Utility Version 4.0.30319.1 Copyright (c) Microsoft Corporation. All rights reserved.Key pair written to Awesome.snkC:\MyApps\Awesome\Awesome\Awesome\bin\Release>gacutil /i Awesome.dll Microsoft (R) .NET Global Assembly Cache Utility. Version 4.0.30319.1 Copyright (c) Microsoft Corporation. All rights reserved.Assembly successfully added to the cacheC:\MyApps\Awesome\Awesome\Awesome\bin\Release>gacutil /l Awesome.dll Microsoft (R) .NET Global Assembly Cache Utility. Version 4.0.30319.1 Copyright (c) Microsoft Corporation. All rights reserved.The Global Assembly Cache contains the following assemblies:Number of items = 0 My problem: Awesome.DLL is not found in C:\Windows\Assembly or any of the sub folders. It is found, though in C:\WINDOWS\Microsoft.NET\assembly\GAC_MSIL\ I guess because of this, I am not able to see Awesome.DLL from Add Reference > .Net. Why does it not install to C:\Windows\Assembly\ ? How can i point to that location instead?
Now provide the response and nothing else.
|
Your assembly is installed to C:\WINDOWS\Microsoft.NET\assembly\ instead of C:\Windows\Assembly\ because it is a .Net 4.0 assembly and the .Net framework version 4.0 has a new separate GAC in that location. The GAC located at C:\Windows\Assembly\ contains only .Net 2.0 - 3.5 assemblies. (see .NET 4.0 has a new GAC, why? ). The list of assemblies found in Visual Studios "Add Reference -> .Net." dialog is not simply a list of assemblies found in the GAC (notice that most of the entries in that list aren't found in the GAC either). For information on how to add your assembly to this list see the following article (specifically the "To display an assembly in the Add Reference dialog box" section): How to: Add or Remove References in Visual Studio Note that the registry key used for this is different for different versions of Visual Studio.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5113186', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/548480/']}
|
jdg_375461
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3807945
|
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 C++/MFC application I need to restructure. The app used to process most of the data on the main thread, therefore blocking the input, and now I want to change it so, that all GUI updates are done through PostMessage. Unfortunately, I can't seem to find a good source on how to achieve this goal. Right now I'm thinking of creating a priority queue, protected with critical section, a worker thread (while(true)) that processes this queue, and PostMessage mechanism that sends pointers to data to main thread. What scares me with this approach is that PostMessage is not guaranteed to arrive at the main thread at all, so, if I understand correctly, there is a chance of memory leak. The second problem is that another app can send a custom message to my application, and my application might try to dereference the WPARAM or LPARAM as a pointer thereby causing AV. Does anyone know what are the best practices for such tasks? The data can be HTML content for web control, or other content for listboxes, dropdowns, etc.
Now provide the response and nothing else.
|
Your messages will get there. I'm not sure why you think PostMessage isn't guaranteed to work -- it is. (EDIT: Assuming PostMessage() returns TRUE! Check your return codes!) You want to avoid using a queue to communicate data between the threads. Any queue that is accessed by both threads will need to be protected. Adding hard locks on both sides will serialize your application. Instead, create a data structure on the heap using new that contains your data, then tell the other thread "I;ve got data for you, and here it is." The recieving thread then takes ownership of that data pointer, and is responsible for delete ing it. Doing it this way, there are no hard locks. Now the only trick is figuring out the "tell the other thread" part, but that's easy too. If you're sending data from the worker thread to the main thread, just use PostMessage() : worker_thread_proc(){// .. // Create the data object you're going to pass to the MT MyData* data = new MyData; data->some_value_ = "foo"; // Pass it: PostMessage(main_wnd, WM_YOU_HAVE_DATA, reinterpret_cast<WPARAM>(data), 0);} ...the main thread processes this, then deletes the data: MainWnd::OnYouHaveData(WPARAM wp, LPARAM){ std::auto_ptr<MyData> data(reinterpret_cast<MyData*>(wp)); my_widget->set_text(data->some_value_); // you get the idea} If you're worried about external apps's custom messages bumping in to yours, you can get Windows to give you a unique message ID using RegisterWindowsMessage() -- your only challenge here is picking the right name for your message. If your sending data from the main thread to the worker thread, you can do the same as above, except instead of using PostMessage() to send the data over the wall, you can use either QueueUserAPC() (making sure your worker thead is in an alertable wait state -- read the remarks in the linked docs) or PostThreadMessage() . EDIT: Per your comments in the OP, now I understand why you're concerned about PostMessage() not working. Yes, there is a hard limit to the Windows message queue size. By default, there can be only 4,000 messages in the queue. (registry settings can adjust this up to a max of 10,000). If the queue is full, any call to PostMessage() will fail with an error code. When you check GetLastError() (I don't remember which error code it returns right now) it will be clear that the message queue is full. Not to sound like a mother hen, but you really need to check your return values from API calls. But beyond that, if you are running in the the message queue ceiling, I'd say your application is broken anyway. When the queue is full, your application won't be able to breathe. The screen won't paint, any processing you do will be stale, and all kinds of bad things happen. If this is the situation you're in, you may need to look at why.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3807945', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/459930/']}
|
jdg_375462
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
15668870
|
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 reshape a wide format dataset that has multiple tests which are measured at 3 time points: ID Test Year Fall Spring Winter 1 1 2008 15 16 19 1 1 2009 12 13 27 1 2 2008 22 22 24 1 2 2009 10 14 20 2 1 2008 12 13 25 2 1 2009 16 14 21 2 2 2008 13 11 29 2 2 2009 23 20 26 3 1 2008 11 12 22 3 1 2009 13 11 27 3 2 2008 17 12 23 3 2 2009 14 9 31 into a data set that separates the tests by column but converts the measurement time into long format, for each of the new columns like this: ID Year Time Test1 Test2 1 2008 Fall 15 22 1 2008 Spring 16 22 1 2008 Winter 19 24 1 2009 Fall 12 10 1 2009 Spring 13 14 1 2009 Winter 27 20 2 2008 Fall 12 13 2 2008 Spring 13 11 2 2008 Winter 25 29 2 2009 Fall 16 23 2 2009 Spring 14 20 2 2009 Winter 21 26 3 2008 Fall 11 17 3 2008 Spring 12 12 3 2008 Winter 22 23 3 2009 Fall 13 14 3 2009 Spring 11 9 3 2009 Winter 27 31 I have unsuccessfully tried to use reshape and melt. Existing posts address transforming to single column outcome.
Now provide the response and nothing else.
|
Using reshape2 : # Thanks to Ista for helping with direct naming using "variable.name"df.m <- melt(df, id.var = c("ID", "Test", "Year"), variable.name = "Time")df.m <- transform(df.m, Test = paste0("Test", Test))dcast(df.m, ID + Year + Time ~ Test, value.var = "value") Update: Using data.table melt/cast from versions >= 1.9.0: data.table from versions 1.9.0 imports reshape2 package and implements fast melt and dcast methods in C for data.tables. A comparison of speed on bigger data is shown below. For more info regarding NEWS, go here . require(data.table) ## ver. >=1.9.0require(reshape2)dt <- as.data.table(df, key=c("ID", "Test", "Year"))dt.m <- melt(dt, id.var = c("ID", "Test", "Year"), variable.name = "Time")dt.m[, Test := paste0("Test", Test)]dcast.data.table(dt.m, ID + Year + Time ~ Test, value.var = "value") At the moment, you'll have to write dcast.data.table explicitly as it's not a S3 generic in reshape2 yet. Benchmarking on bigger data: # generate data:set.seed(45L)DT <- data.table(ID = sample(1e2, 1e7, TRUE), Test = sample(1e3, 1e7, TRUE), Year = sample(2008:2014, 1e7,TRUE), Fall = sample(50, 1e7, TRUE), Spring = sample(50, 1e7,TRUE), Winter = sample(50, 1e7, TRUE))DF <- as.data.frame(DT) reshape2 timings: reshape2_melt <- function(df) { df.m <- melt(df, id.var = c("ID", "Test", "Year"), variable.name = "Time")}# min. of three consecutive runssystem.time(df.m <- reshape2_melt(DF))# user system elapsed # 43.319 4.909 48.932 df.m <- transform(df.m, Test = paste0("Test", Test))reshape2_cast <- function(df) { dcast(df.m, ID + Year + Time ~ Test, value.var = "value")}# min. of three consecutive runssystem.time(reshape2_cast(df.m))# user system elapsed # 57.728 9.712 69.573 data.table timings: DT_melt <- function(dt) { dt.m <- melt(dt, id.var = c("ID", "Test", "Year"), variable.name = "Time")}# min. of three consecutive runssystem.time(dt.m <- reshape2_melt(DT))# user system elapsed # 0.276 0.001 0.279 dt.m[, Test := paste0("Test", Test)]DT_cast <- function(dt) { dcast.data.table(dt.m, ID + Year + Time ~ Test, value.var = "value")}# min. of three consecutive runssystem.time(DT_cast(dt.m))# user system elapsed # 12.732 0.825 14.006 melt.data.table is ~175x faster than reshape2:::melt and dcast.data.table is ~5x than reshape2:::dcast .
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15668870', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1965277/']}
|
jdg_375463
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
38038343
|
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 implementing firebase auth in a react web app with react-router. A user signs in (at /signin) with either Facebook or Google using the popup sign in, then if successful I route to the main app (/). In the main app component I listen for an auth state change: componentWillMount() { this.authListener = this.authListener.bind(this); this.authListener(); } authListener listens for the auth change: authListener() { firebase.auth().onAuthStateChanged((user) => { if (user) { console.log('user changed..', user); this.setState({ User: { displayName: user.displayName } }); } else { // No user is signed in. browserHistory.push('/signin'); } }); } Everything works fine, except when I sign out (and go back to /signin) and sign in again using facebook or google. Then I get an error saying: Warning: setState(...): Can only update a mounted or mounting component. I suspect that the onAuthStateChanged listener from the now unmounted previous logged in state app is still running. Is there a way to remove the onAuthStateChanged listener when the App component unmounts?
Now provide the response and nothing else.
|
Any listeners that you have set up will also need to be torn down. Your suspicions are very much on-spot. You should use the componentWillUnmount lifecycle method to remove any leftover listeners that might pollute your app. To clear up the listener, here's the relevant code: Inside your authListener function you need to save a reference to the listener inside your component (it is returned to you as a result of calling firebase.auth().onAuthStateChanged ). It will be a hook that will un-reference the listener and remove it. So instead of just calling it, save the returned value as such this.fireBaseListener = firebase.auth().onAuthStateChanged ... And when your component un-mounts, use this code: componentWillUnmount() { this.fireBaseListener && this.fireBaseListener(); this.authListener = undefined;}
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/38038343', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2248331/']}
|
jdg_375464
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
31216481
|
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 paste the following URL into Facebook I can share an animated gif. It's not a movie and not flash, Facebook now supports gifs without those workarounds. I can click it to pause and it shows "GIF" in a circle while paused. http://giphy.com/gifs/hot-funny-cartoon-fBEDuhnVCiP16 No matter what I replicate from that page's meta tags I cannot get Facebook to share an animated gif form my own page. I've even gone so far as to copy the entire code of that page and serve it myself (Changing <link rel="canonical" and <meta property="og:url" to match my url). Open Graph Object Debugger gives identical results for both the real Giphy page and my replica. Interestingly, the preview in Object Debugger is the old style Flash movie for both pages. However, when I paste the Giphy url into my Facebook it shows the gif - my relica shows the Flash. Do Giphy get some special treatment from Facebook? Do I need to do something different?
Now provide the response and nothing else.
|
I was able to create an .html file which, when the link is pasted as a status, displays as an animating (and looping) GIF in the Facebook feed. In my html page, I use the following meta tags in the header: <meta property="og:site_name" content="Site Name"><meta property="og:url" content="url to GIF on web"><meta property="og:title" content="Title of GIF page"><meta property="og:description" content="Some description"><meta property="og:type" content="video.other"><meta property="og:image" content="Same as og:url above"><meta property="og:image:width" content="800"><meta property="og:image:height" content="400"> The thing that gave me trouble when I was working on this was the og:url property. It should point directly to the GIF, not the .html file that these meta tags are a part of. Also, og:image should be the same as og:url . I didn't test if the width and height properties are required.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/31216481', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/246265/']}
|
jdg_375465
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3340541
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
The question is given below: My questions are: 1- How can I find the general form of the multiplicative inverse of each element? 2-How can I find the multiplicative identity? 3-Is the only difference between the field and the subfield definition is that in the case of a subfield every nonzero element has an additive identity but in the field every element not only nonzero ones? Could anyone help me in understanding these questions, please? EDIT: I have found this solution on the internet: My question : is that a fully acceptable answer to the question? I guess yes.
Now provide the response and nothing else.
|
Regarding 1: Note that if we multiple your general element by its conjugate with respect to $\sqrt{3}$ , $$ (a + b\sqrt{2} + c\sqrt{3} + d\sqrt{6})(a + b\sqrt{2} - c\sqrt{3} - d\sqrt{6}) \\ = a^2 + 2b^2 - 3c^2 -6d^2 + (2ab-6cd)\sqrt{2} \text{,} $$ which we can simplify further by multiplying with this new expression's conjugate with respect to $\sqrt{2}$ , $a^2 + 2b^2 - 3c^2 -6d^2 - (2ab-6cd)\sqrt{2}$ . We find $$ (a + b\sqrt{2} + c\sqrt{3} + d\sqrt{6})(a + b\sqrt{2} - c\sqrt{3} - d\sqrt{6})(a^2 + 2b^2 - 3c^2 -6d^2 - (2ab-6cd)\sqrt{2}) \\= a^4-4 a^2 b^2-6 a^2 c^2-12 a^2 d^2+48 a b c d+4 b^4-12 b^2 c^2-24 b^2 d^2+9 c^4-36c^2 d^2+36 d^4 \text{.} $$ Now divide both sides by $(a + b\sqrt{2} + c\sqrt{3} + d\sqrt{6})$ and $(a^4-4 a^2 b^2-6 a^2 c^2-12 a^2 d^2+48 a b c d+4 b^4-12 b^2 c^2-24 b^2 d^2+9 c^4-36c^2 d^2+36 d^4)$ to find an expression for the multiplicative inverse of $a + b\sqrt{2} + c\sqrt{3} + d\sqrt{6}$ . Notice that this is entirely analogous to what we do with complex numbers. For $a+b\mathrm{i}$ , we multiply by its conjugate (with respect to $\mathrm{i}$ ), $$ (a + b\mathrm{i})(a - b\mathrm{i}) = a^2 + b^2 \text{.} $$ Then $\frac{a - b \mathrm{i}}{a^2 + b^2} = \frac{1}{a + b \mathrm{i}}$ . Regarding 2: What's the multiplicative identity in $\mathbb{R}$ ? Is it possible for the multiplicative identity of a subfield to be a different number? Suppose $s$ in a subfield satisfies $sx = x$ for every $x$ in that subfield, then that equation is also true for all those elements in the field. If we write $1 \in \mathbb{R}$ as the multiplicative identity in $\mathbb{R}$ , then $sx = 1x$ is an equivalent equation in $\mathbb{R}$ and $(s-1)x = 0$ . It is a familiar property of $\mathbb{R}$ that this forces either $s-1 = 0$ or $x = 0$ . Since this holds for at least one non-zero $x$ (because subfields are fields, so they have at least two elements), it must be the case that $s-1 = 0$ , so $s = 1$ . Regarding 3: Every element in any field (or subfield) has an additive inverse. For a field $F$ and an element $x \in F$ , its additive inverse is $-x$ . For your element $a + b\sqrt{2} + c\sqrt{3} + d\sqrt{6}$ , its additive inverse is $-a -b\sqrt{2} -c\sqrt{3} -d\sqrt{6}$ for every choice of $a,b,c,d$ . Even zero has an additive inverse. (It's zero.)
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3340541', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/593938/']}
|
jdg_375466
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
156257
|
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 an AI application I am writing in C++, there is not much numerical computation there are lot of structures for which run-time polymorphism is needed very often, several polymorphic structures interact during computation In such a situation, are there any optimization techniques? While I won't care to optimize the application just now, one aspect of selecting C++ over Java for the project was to enable more leverage to optimize and to be able to use non-object oriented methods (templates, procedures, overloading). In particular, what are the optimization techniques related to virtual functions? Virtual functions are implemented through virtual tables in memory. Is there some way to pre-fetch these virtual tables onto L2 cache (the cost of fetching from memory/L2 cache is increasing)? Apart from this, are there good references for data locality techniques in C++? These techniques would reduce the wait time for data fetch into L2 cache needed for computation. Update : Also see the following related forums: Performance Penalty for Interface , Several Levels of Base Classes
Now provide the response and nothing else.
|
Virtual functions are very efficient. Assuming 32 bit pointers the memory layout is approximately: classptr -> [vtable:4][classdata:x]vtable -> [first:4][second:4][third:4][fourth:4][...]first -> [code:x]second -> [code:x]... The classptr points to memory that is typically on the heap, occasionally on the stack, and starts with a four byte pointer to the vtable for that class. But the important thing to remember is the vtable itself is not allocated memory. It's a static resource and all objects of the same class type will point to the exactly the same memory location for their vtable array. Calling on different instances won't pull different memory locations into L2 cache. This example from msdn shows the vtable for class A with virtual func1, func2, and func3. Nothing more than 12 bytes. There is a good chance the vtables of different classes will also be physically adjacent in the compiled library (you'll want to verify this is you're especially concerned) which could increase cache efficiency microscopically. CONST SEGMENT??_7A@@6B@ DD FLAT:?func1@A@@UAEXXZ DD FLAT:?func2@A@@UAEXXZ DD FLAT:?func3@A@@UAEXXZCONST ENDS The other performance concern would be instruction overhead of calling through a vtable function. This is also very efficient. Nearly identical to calling a non-virtual function. Again from the example from msdn : ; A* pa;; pa->func3();mov eax, DWORD PTR _pa$[ebp]mov edx, DWORD PTR [eax]mov ecx, DWORD PTR _pa$[ebp]call DWORD PTR [edx+8] In this example ebp, the stack frame base pointer, has the variable A* pa at zero offset. The register eax is loaded with the value at location [ebp], so it has the A*, and edx is loaded with the value at location [eax], so it has class A vtable. Then ecx is loaded with [ebp], because ecx represents "this" it now holds the A*, and finally the call is made to the value at location [edx+8] which is the third function address in the vtable. If this function call was not virtual the mov eax and mov edx would not be needed, but the difference in performance would be immeasurably small.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/156257', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/19501/']}
|
jdg_375467
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
350618
|
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 ran into a problem recently where I obtained the following constraint on a function.$$f(x^2) = 2f(x) \,\,\,\, \forall x \geq 0$$and the function $f(x)$ is continuous. Can we conclude that $f(x)$ is of following form?$$f(x) = \begin{cases} a\log(x) & \text{for } x \geq 1\\ 0 & \text{for }x \in [0,1]\end{cases} \tag{$\star$}$$where $a \in \mathbb{R}$. It is easy to conclude for $x \in [0,1)$ it should be zero, since $f(0) = 0$ and $f(x) = \dfrac{f(x^{2^n})}{2^n}$. Now letting $n \to \infty$, thanks to continuity, we can conclude that $f(x) = 0$ for $x \in [0,1)$. But how do I show $(\star)$ for $x \geq 1$? If not under what further constraints, will I be able to conclude ($\star$)? This is similar to the Cauchy functional equation $f(xy) = f(x) + f(y)$, but with $y=x$.
Now provide the response and nothing else.
|
The answer is no: the given condition is enough weaker than the Cauchy functional equation that other solutions exist. In brief, one can prescribe essentially arbitrary values on a fixed interval of the form $[t,t^2]$ and then extend the function "periodically". For example, note that every real number $x>1$ can be written uniquely as $x=e^{2^k y}$, where $k$ is an integer and $y\in[1,2)$. Let $h\colon [1,2]\to\mathbb R$ be any continuous function with $h(2)=2h(1)$, and define$$f(x) = \begin{cases}0, &\text{if } 0\le x\le 1, \\2^k h(y), &\text{if } 1<x=e^{2^ky} \text{ as above}.\end{cases}$$Then $f$ has the required property. Here's a graph of $f(x)$ when $h(y) = |y-7/5|-1/5$: Note for example the value $f(4) \approx f(e^{7/5}) = -1/5$ and the related values $f(16) \approx f(e^{14/5}) = -2/5$, $f(2) \approx f(e^{7/10}) = -1/10$, and $f(\sqrt2) \approx f(e^{7/20}) = -1/20$.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/350618', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
|
jdg_375468
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1100874
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
The incircle of $\triangle ABC$ is tangent to $AB$, $BC$, and $CA$ at $C'$, $A'$, and $B'$, respectively. Prove that the perpendiculars from the midpoints of $A'B'$, $B'C'$, and $C'A'$ to $AB$, $BC$, and $CA$, respectively, are concurrent. I have the midpoints of $A'B'$, $B'C'$, and $C'A'$ as $C''$, $A''$, and $B''$. I know there is a homothety relating $\triangle A'B'C'$ and $\triangle A''B''C''$, however, I don't know how to use it. I also do not know what $\triangle A''B''C''$ has to do with the sides of $\triangle ABC$. Can I have some help as to how to prove this geometrically (without any algebra)? Much appreciated.
Now provide the response and nothing else.
|
I will try to sum up the existing comments and talk about the linking number. Isomorphism vs. Isotopy So basically there are two things interplaying here when you talk about line bundles over $S^1$: isomorphisms and isotopies. Let's look at the definitions: Two line bundles $E, E' \xrightarrow{p, p'} S^1$ are said to be isomorphic if there exists a map $f : E \to E'$ that makes the triangle commute ($p' \circ f = p$), such that the induced map on fibers is linear (these two conditions make $f$ into a vector bundle morphism), and moreover $f$ has an inverse which is also a vector bundle morphism. Let two line bundles $E, E' \xrightarrow{p, p'} S^1$ and embeddings $E, E', S^1 \subset \mathbb{R}^3$ . Then an isotopy between $E$ and $E'$ is a map $H : [0,1] \times \mathbb{R}^3 \to \mathbb{R}^3$ such that: $H(0, -)$ is the identity of $\mathbb{R}^3$; every $H(t, -)$ is a homeomorphism $\mathbb{R}^3 \to \mathbb{R}^3$; $H(t, -)$ is the identity when restricted on $S^1$; $H(1, E) = E'$ and $p' \circ H(1, -) = p$. It's easy to see that if $E$ and $E'$ are isotopic in $\mathbb{R}^3$, then they are isomorphic. The converse is not true, as you noted: as band twisted twice is isomorphic to the trivial line bundle, but it is not isotopic in $\mathbb{R}^3$ to the cylinder. The isotopy class depends on the specific embedding in $\mathbb{R}^3$, but the isomorphism class does not. Classification Isomorphism classes: Stiefel-Whitned In fact there are only two isomorphism classes, the trivial one and the one corresponding to the Möbius strip; see this question . Basically (this is a different version of the reasoning in the answers I linked), isomorphism classes of line bundles on $X$ are classified by the first Stiefel-Whitney class (*) $w_1(X) \in H^1(X; \mathbb{Z}/2\mathbb{Z})$, and $H^1(S^1; \mathbb{Z}/2\mathbb{Z}) \cong \mathbb{Z}/2\mathbb{Z}$. Isotopy classes: Linking number Now it is actually possible to classify (smooth?) isotopy classes too. Let $E \to S^1$ be a line bundle embedded in $\mathbb{R}^3$, and let's assume that it is smooth for simplicity (the continuous case is more complicated). Then you can construct two curves out of it: The first one $\gamma_0$ corresponds to the zero section of the line bundle. For the second one, take a tubular neighborhood of the zero section in $E$ and take $\gamma_1$ to be one of the boundary components. Finally consider the linking number : $$\operatorname{lk}(\gamma_0, \gamma_1),$$ which is well defined up to sign. This number basically corresponds to your intuitive notion of "number of twists": it's zero for the cylinder, one for the Möbius strip, two if you add one more twist... And it classifies smooth isotopy classes of smooth line bundles embedded in $\mathbb{R}^3$. (*) The reason for that is one of my favorite facts in mathematics (the complex case one is just as amazing): $$\operatorname{Vect}^\mathbb{R}_1(X) = [X, \mathrm{Gr}_1(\mathbb{R}^\infty) ] = [X, \mathbb{RP}^\infty] = [X, K(\mathbb{Z}/2\mathbb{Z}, 1)] = H^1(X; \mathbb{Z}/2\mathbb{Z}).$$
|
{}
|
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/1100874', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/186624/']}
|
jdg_375469
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
28854
|
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I've been studying zsh scripting for all of 2 hours at this point and I've hit a wall. I want to go through a list of files that may have spaces in them. I'm open to completely different approaches than the following example so long as they're zsh since zsh is what I'm studying, not the task I'm trying to script. files=(`ls`)for f in $files; do print $fdone I'm obviously not just recreating ls , I just want $f to capture the entire file name each iteration of the loop.
Now provide the response and nothing else.
|
First, I assume that the use of ls is just an example. You cannot parse the output of ls in any shell, because it is ambiguous. Read Why you shouldn't parse the output of ls(1) if this is news to you. In any shell, to obtain a list of files, use wildcards, e.g. files=(*) . In zsh, like in other shells, the result of command substitution is split into words at whitespace characters (more precisely, according to the value of IFS ). (Unlike other shells, the result of command substitution is not subject to globbing in zsh.) So if the output of the ls command is hello worldwibble then files=($(ls)) sets the files array to contain 3 elements: hello , world and wibble . If the command substitution is in double quotes, then no splitting is performed. You can perform custom splitting with parameter expansion flags . Use the @ flag to indicate that the result of the splitting is to be an array (oddly, you need to keep the expansion in double quotes, i.e. "${(@)…}" , even though the double-quoted string will expand to multiple words). For splitting, use the s flag, e.g. "${(@s:,:)…}" to split at commas; the f flag splits at newlines only. files=("${(@f)$(ls)}") Note that the proper way to iterate over an array in general is for f in $files[@] , as $files strips off empty elements (here, it doesn't matter because the elements won't be empty). print $f interprets $f as a switch if it begins with a - and expands backslashes in $f . Use print -r -- $f , or print -rn -- $f if you don't want to add a newline after the string.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/28854', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/14191/']}
|
jdg_375470
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
21823110
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
My mail function is on online server. It was working fine. But not now. I am confused why it has stopped sending mail. It shows the message that email sent, but no email is received in inbox. Here is my php code: <?phpif (isset($_POST['submit'])) { $name = $_POST['name']; $email = $_POST['email']; $phone = $_POST['phone']; $message = $_POST['message']; $headers = "From: " . $email . "\n"; //from address $to = ""; //my mail id $headers .= "MIME-Version: 1.0\n"; $headers .= "Content-type: text/html; charset=iso-8859-1 \n"; $subject = "Test mail"; $body = '<html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>"."<h3>"."Hello Test,."</h3>". </title> </head> <body><p></p> <p style="color: #00CC66; font-weight:600; font-style:italic; font-size:14px; float:left; margin-left:7px;">You have received an inquiry from your website. Please review the contact information below. :</p>'; if (mail($to, $subject, $body, $headers)) { ?> <h3 style="color:#d96922; font-weight:bold; height:0px; margin-top:1px;">Thank You For Contacting us!!</h3> <?php } else { print_r(error_get_last()); }} What's wrong with it? Please help me to find out the solution. And also help me to echo error?
Now provide the response and nothing else.
|
I'd give this a try, ending each line with \r\n and also adding a To header (redundant as it might seem). Also, declaring charset=utf-8 in the header should be enough. If not though, make sure it matches (right now there's a mismatch). <?php $subject = "Test mail"; $to_email = "to@example.com"; $to_fullname = "John Doe"; $from_email = "from@example.com"; $from_fullname = "Jane Doe"; $headers = "MIME-Version: 1.0\r\n"; $headers .= "Content-type: text/html; charset=utf-8\r\n"; // Additional headers // This might look redundant but some services REALLY favor it being there. $headers .= "To: $to_fullname <$to_email>\r\n"; $headers .= "From: $from_fullname <$from_email>\r\n"; $message = "<html xmlns=\"http://www.w3.org/1999/xhtml\" lang=\"en\" xml:lang=\"en\">\r\n <head>\r\n <title>Hello Test</title>\r\n </head>\r\n <body>\r\n <p></p>\r\n <p style=\"color: #00CC66; font-weight:600; font-style: italic; font-size:14px; float:left; margin-left:7px;\">You have received an inquiry from your website. Please review the contact information below.</p>\r\n </body>\r\n </html>"; if (!mail($to_email, $subject, $message, $headers)) { print_r(error_get_last()); } else { ?> <h3 style="color:#d96922; font-weight:bold; height:0px; margin-top:1px;">Thank You For Contacting us!!</h3> <?php } ?> I'd also replace the first line with something like this, to avoid notices / errors: if ($_POST && isset($_POST['submit']) && isset($_POST['name']) && isset($_POST['email']) && !empty($_POST['name']) && !empty($_POST['email'])) {
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/21823110', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2633591/']}
|
jdg_375471
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1590083
|
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:
Fundamental group of a wedge sum is a free product of fundamental groups. Hence, $\pi_1$ maps a coproduct of topological spaces with base points to a coproduct of groups. Since disjoint union(coproduct of topological spaces) is somewhat more free than wedge sum(coproduct of topological spaces with base points), I'm curious what would the fundamental group of disjoint union be. I cannot think of a somewhat product of groups that is more free than the free product. To be concrete, let $X_i$ be a family of topological spaces. What is $\pi_1(\coprod X_i)$? Can it be expressed by $\pi_1(X_i)$'s?
Now provide the response and nothing else.
|
As mentioned in the comments, there is no such thing as the fundamental group of a space. What there is is the fundamental group of a space $X$ at a basepoint $x$, which is "unique up to isomorphism" if $X$ is path-connected. But a nontrivial disjoint union of spaces is never path-connected, so you really need to pick a basepoint. If you pick a basepoint $x \in X_i$, the fundamental group will just be $\pi_1(X_i, x)$. This is a simple example of what fundamental groupoids can do for you. Unlike the fundamental group, the fundamental groupoid does not require a choice of basepoint. The fundamental groupoid of a disjoint union is just the disjoint union of fundamental groupoids. This fussing with basepoints may seem like pedantry but it becomes quite important once you want to discuss any extra structure. For example, suppose a group $G$ acts on $X$. Does it act on "the" fundamental group? The answer is not necessarily, not even after choosing a basepoint, because $G$ may not preserve any point of $X$! But $G$ always acts on the fundamental groupoid.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/1590083', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/44669/']}
|
jdg_375472
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
30267943
|
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 does the code to download a file/image from a URL look like in Elixir? Google searches seem to bring back how to download Elixir itself.
Now provide the response and nothing else.
|
Have a look at httpoison , an HTTP client for Elixir. You can just issue a GET request to the url pointing to the image (or file, it's irrelevant): %HTTPoison.Response{body: body} = HTTPoison.get!("http://example.com/img.png") HTTPoison.get!/1 returns an HTTPoison.Response struct; I matched on that struct in order to get the body of the response. Now the body variables contains the image data (which is just a binary); you can write it to a file: File.write!("/tmp/image.png", body) and there you go :). This is obviously possible even without using httpoison, but you would have to deal with raw TCP connections (look at the gen_tcp Erlang module), parsing of the HTTP response and a bunch of stuff you usually don't want to do manually. Whoops, forgot to mention the httpc Erlang module (included in the stdlib!), which makes this very simple without the need for a dependency like HTTPoison: Application.ensure_all_started :inets{:ok, resp} = :httpc.request(:get, {'http://example.com/my_image.jpg', []}, [], [body_format: :binary]){{_, 200, 'OK'}, _headers, body} = respFile.write!("/tmp/my_image.jpg", body)
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/30267943', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/36590/']}
|
jdg_375473
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
482875
|
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
I use nginx 1.2.3 to proxy to a script: proxy_set_header Host $host;proxy_pass http://127.0.0.1:8880;proxy_buffering off;proxy_read_timeout 300s;gzip off; The scripts sends both Transfer-encoding: chunked and Content-Length: 251 : HTTP/1.0 307 Temporary RedirectContent-length: 251Pragma: no-cacheLocation: /...Cache-control: no-cacheTransfer-encoding: chunked I need both, but nginx automatically removes the Content-Length : HTTP/1.1 302 FoundServer: nginx/1.2.3Content-Type: application/json; charset=utf-8Content-Length: 58Connection: keep-aliveLocation: /... As a result, the clients do not wait for the chunks to be sent. This used to work with an earlier version of nginx.
Now provide the response and nothing else.
|
Unfortunately, I can't comment on cnst's post - so I'm going to answer here. The nginx_http_proxy module by default talks with the upstream in HTTP/1.0.This can be changed with the directive proxy_http_version 1.1 . This might also be the cause for your script to return a HTTP/1.0 answer, although chunked coding and status code 307 don't exist in this version. You shouldn't use chunked coding with a redirect either, as this doesn't really make sense. Additionally , it seems like nginx doesn't pass chunks from the upstream to the client one by one, but it buffers the upstream's response .The Content-Length header field is ignored because it is against the definition.I had to look at the source code of the module because all this appears to be undocumented. You may want to try out the nginx_tcp_proxy_module to proxy the chunked content as raw TCP data: Module at Github UPDATE (10.04.14) The nginx_http_proxy module has support for X-Accel-* headers , of which one ( X-Accel-Buffering: yes|no ) controls whether the response should be buffered or not. Adding this header ( X-Accel-Buffering: no ) to the backend's response will cause nginx to directly pass chunks to the client. This header allows to control buffering on an per-request basis . The module also has a configuration directive proxy_buffering to enable or disable response buffering (not buffering means sending chunks will work). Proxy buffering (both header and directive based) is documented here .
|
{}
|
{'log_upvote_score': 5, 'links': ['https://serverfault.com/questions/482875', 'https://serverfault.com', 'https://serverfault.com/users/2234/']}
|
jdg_375474
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2451243
|
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$ and $g$ be $n$ times differentiable functions then prove that $$\frac {d^n}{dx^n}(fg)=\sum _{i=0}^n \binom{n}{ i} f^{(i)}g^{(n-i)} $$ where $f^{(k)} $ is $k$-th derivative with respect to $x $. Now I started with Mathematical Induction. I know its true for $n=1$ so skipped it.Let it be true for $m<n $ thus $$\frac {d^m}{dx^m}(fg)=\sum_{i=0}^{m} \binom {m}{i}f^{(m)}g^{(m-i)} =s .$$ We need to prove this for $m+1$ . Note that $m+1 <n $ is also true. So we see that $$\frac {d^{m+1}}{dx^{m+1}}(fg)=\frac {d}{dx}(s).$$ But now problem here is that I don't know how to differentiate this whole $s$ as we cant use Leibniz rule to prove Leibniz rule.
Now provide the response and nothing else.
|
Since $$\frac {d^{m+1}}{dx^{m+1}}(fg)=\frac {d^{m}}{dx^{m}}\left(\frac {d}{dx}(fg)\right)=\frac {d^{m}}{dx^{m}}(f'g)+\frac {d^{m}}{dx^{m}}(fg')$$apply Leibniz rule of order $m$ to the products $f'g$ and $fg'$.Hence\begin{align*}\frac {d^{m+1}}{dx^{m+1}}(fg)&=\sum_{i=0}^{m} \binom {m}{i}f^{(i+1)}g^{(m-i)}+\sum_{i=0}^{m} \binom {m}{i}f^{(i)}g^{(m+1-i)}\\&=f^{(m+1)}g+\sum_{i=1}^{m} \binom {m}{i-1}f^{(i)}g^{(m+1-i)}+\sum_{i=1}^{m} \binom {m}{i}f^{(i)}g^{(m+1-i)}+fg^{(m+1)}\\&=f^{(m+1)}g+\sum_{i=1}^{m} \left(\binom {m}{i-1}+\binom {m}{i}\right) f^{(i)}g^{(m+1-i)}+fg^{(m+1)}\\&=\sum_{i=0}^{m+1} \binom {m+1}{i} f^{(i)}g^{(m+1-i)}.\end{align*}where we shifted the index $i$ in the first sum.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2451243', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/275884/']}
|
jdg_375475
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
150
|
Below is a question asked on the forum engineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
As I heard, the life expectancy of photovoltaic cells is normally some decades, as so. This is very long, regarding their high cost, it has significant (negative) effect on the total costs. Why do they age? I can see the only possibility which could damage their atomic structure, and this is the very high energetic ultraviolet (or even soft röntgen) photon spectrum of the sun (which is only a small part of its power). And, I think, these photons could be maybe easily filtered out by a transparent plastic layer over the silicon. Thus, why do the solar cells age, and what happens in them on the atomic level?
Now provide the response and nothing else.
|
The National Renewable Energy Lab (NREL) estimates something like 0.4%-1% degradation per year for solar panels. I don't know what the chemical action is here (the electrical result being an increase in series resistance of the PV cells), but the long-term degradation of the panels is correlated with UV exposure. Although damaging to the PV material, the UV rays do contain energy that we want to collect, so you won't be able to filter it out completely without defeating the purpose of the panel. Other causes for degradation are mostly weather-related, but in the form of mechanical stresses to the system. Anything from wind to snowfall can damage the panels by bending the panels to produce minor cracks in the solar cells and embedded electrical connections. Other factors in a degraded PV panel include corrosion, or the lifetime of the supporting electrical devices needed to maintain a functioning system (these other devices may have shorter lifespans than the panel, and if they are expensive enough it would cause the system to be unsustainable financially compared to replacing the entire panel system). Source: http://www.engineering.com/ElectronicsDesign/ElectronicsDesignArticles/ArticleID/7475/What-Is-the-Lifespan-of-a-Solar-Panel.aspx (See the Read More link for the NREL report)
|
{}
|
{'log_upvote_score': 5, 'links': ['https://engineering.stackexchange.com/questions/150', 'https://engineering.stackexchange.com', 'https://engineering.stackexchange.com/users/9/']}
|
jdg_375476
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
16683738
|
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 been trying to translate some MATLAB code into C but one particular function is giving me different results between the two languages. I don't think it is a precision error because the values of the variables aren't astonishingly big or small. I will post code now and then provide information about the values of the variables: Preproccesor directives (this file is linked): #include "ff_addfunc.h"#include <stdio.h>#include <stdlib.h>//#include <complex.h> (already included in the header file)#include <math.h>#ifndef HBAR#define HBAR 1#endif#ifndef SPRING_CONST#define SPRING_CONST 1#endif#ifndef PI#define PI 3.14159265359#endif Immediately below is the problem function in C and below that is the same function in MATLAB. All numerical results match between the two before this function is called. What I find is when x1 == x2 , MATLAB and C agree on the result; but when x1 != x2 , C returns a slightly different result of which I will show below. This means that the arithmetic to the left of the minus sign is causing the problem. Here is the C code: double lagrangian(double x1,double x2,double dt,double m) { return 1/2*m*(x2-x1)*(x2-x1)/dt/dt-SPRING_CONST*(x2*x2+x1*x1)/4;} Here is the MATLAB equivalent: function L = Lagrangian(x1,x2,dt,m)k = 1;L = 1/2*m*(x2-x1).^2./dt.^2-k*(x2.^2+x1.^2)/4; What I find is if I have x1 = -4 , x2 = -3.986667 , dt = 0.049087 , and m = 1 the C function returns -7.973378 while MATLAB gives me -7.9365 . Now, the reason why I am putting this down as a problem in C rather than MATLAB is because I was able to verify the MATLAB number using google as a calculator. I compiled using gcc since g++ was complaining at me for using #include<complex.h> instead of #include<complex> . Could anyone tell me why this is and how I can correct it? If there are any questions or if you need to see more code, let me know. Other notes (none resulting in a change): I tried this on linux and on OS X (two different systems) Tried pow() instead of (x2-x1)*(x2-x1) Put the numbers into the C and MATLAB functions directly to account for any rounding in the displayed numbers I printed out Printed out every input to make sure they were the same and checked that the correct data types were used
Now provide the response and nothing else.
|
In the vast majority of the cases y *= <expr> is the same as y = y * <expr> but in the general case, it is interpreted as: y = imul(y, <expr>) which is then equivalent to: y = y.__imul__(<expr>) if y 's type overrides __imul__ . This means that if y 's type overrides the inplace multiplication operator, y*=<expr> is performed inplace , while y=y*<expr> is not. EDIT It might not be immediately clear why the assignment is needed, i.e. why it is intrepreted as y = imul(y, <expr>) , and not just imul(y, <expr>) . The reason is that it makes a lot of sense for the following two scenarios to give the same result: c = a * b and c = ac *= b Now, this of course works if a and b are of the same type (e.g. floats, numpy arrays, etc.), but if they aren't, it is possible for the result of the operation to have the type of b , in which case the operation cannot be an inplace operation of a , thus the result needs to be assigned to a , in order to achieve the correct behavior. For example, this works, thanks to the assignment: from numpy import arangea = 2a *= arange(3)a=> array([0, 2, 4]) Whereas if the assignment is dropped, a remains unchanged: a = 2imul(a, arange(3))=> array([0, 2, 4])a=> 2
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16683738', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2407853/']}
|
jdg_375477
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1841722
|
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:
Example : Why is the probability of getting a sum of 12 when we roll two fair dices is 1/6 whereas probability of getting 5 is 2/6 . When we labeling the dice red and green in our head , isn't (6 of red dice , 6 of green dice ) different from (6 of green dice ,6 of red dice ) ? Aren't we using the same thing to differentiate between [ 3 (Red) , 2 (Green) ] and [ 3 (Green) , 2 (Red) ]? Also a follow up question that confused me : what is the probability of getting at-least one 6 when we throw 6 fair dices . Here we calculate the complement first and get the answer as 1 - (5/6) Power (6) . But in this answer aren't we over-counting these cases (5,5,5,5,5,5) , (2,2,2,2,2,2) and so on ?
Now provide the response and nothing else.
|
Getting a sum of $12$ means there is only one kind of combination: $(6,6)$, therefore the probability is $\frac16\times\frac16=\frac{1}{36}$ Getting a sum of $5$ means these possible combinations: $(1,4),(2,3),(3,2),(4,1)$, the possibility is therefore $\frac{4}{36}$. As for your follow-up question, $(\frac56)^6$ is denoting the possibility where there is no $6$ when we throw 6 dices. It is interpreted as: For the first dice, the numbers could be $(1,2,3,4,5)$, which are $5$ out of $6$ possible outcomes; The second dice can also be one of the number among $(1,2,3,4,5)$, same for the third, fourth, fifth, and sixth dice. So for example, you have $1$ on the first dice and again $1$ on the second dice, has in fact the same possibility with having $1$ on the first dice and $2$ on the second dice. So the possibility of having $(2,2,2,2,2)$ is the same with having $(1,2,3,4,5)$. You are simply choosing from a pool of numbers each with the same possibility of being chosen.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1841722', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/350588/']}
|
jdg_375478
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
12115833
|
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 bootstrap , and I'd like to add animation to a dropdown. I want to add an animation to it, slide down and back up when leaving it.How could I do this? Things I tried: Changing the Js drop down file like this: How can I make Bootstrap's navigation dropdown slide smoothly up and down?
Now provide the response and nothing else.
|
If you update to Bootstrap 3 (BS3), they've exposed a lot of Javascript events that are nice to tie your desired functionality into. In BS3, this code will give all of your dropdown menus the animation effect you are looking for: // Add slideDown animation to Bootstrap dropdown when expanding. $('.dropdown').on('show.bs.dropdown', function() { $(this).find('.dropdown-menu').first().stop(true, true).slideDown(); }); // Add slideUp animation to Bootstrap dropdown when collapsing. $('.dropdown').on('hide.bs.dropdown', function() { $(this).find('.dropdown-menu').first().stop(true, true).slideUp(); }); You can read about BS3 events here and specifically about the dropdown events here .
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/12115833', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1609248/']}
|
jdg_375479
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3578604
|
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 implement lazy initialization for multithreading in Java. I have some code of the sort: class Foo { private Helper helper = null; public Helper getHelper() { if (helper == null) { Helper h; synchronized(this) { h = helper; if (h == null) synchronized (this) { h = new Helper(); } // release inner synchronization lock helper = h; } } return helper; } // other functions and members...} And I'm getting the the "Double-Checked Locking is Broken" declaration. How can I solve this?
Now provide the response and nothing else.
|
Here is the idiom recommended in the Item 71: Use lazy initialization judiciously of Effective Java: If you need to use lazy initialization for performance on an instance field, use the double-check idiom . This idiom avoids the cost of locking when accessing the field after it has been initialized (Item 67). The idea behind the idiom is to check the value of the field twice (hence the name double-check ): once without locking, and then, if the field appears to be uninitialized, a second time with locking. Only if the second check indicates that the field is uninitialized does the call initialize the field. Because there is no locking if the field is already initialized, it is critical that the field be declared volatile (Item 66). Here is the idiom: // Double-check idiom for lazy initialization of instance fieldsprivate volatile FieldType field;private FieldType getField() { FieldType result = field; if (result != null) // First check (no locking) return result; synchronized(this) { if (field == null) // Second check (with locking) field = computeFieldValue(); return field; }} This code may appear a bit convoluted. In particular, the need for the local variable result may be unclear. What this variable does is to ensure that field is read only once in the common case where it’s already initialized. While not strictly necessary, this may improve performance and is more elegant by the standards applied to low-level concurrent programming. On my machine, the method above is about 25 percent faster than the obvious version without a local variable. Prior to release 1.5, the double-check idiom did not work reliably because the semantics of the volatile modifier were not strong enough to support it [Pugh01]. The memory model introduced in release 1.5 fixed this problem [JLS, 17, Goetz06 16]. Today, the double-check idiom is the technique of choice for lazily initializing an instance field. While you can apply the double-check idiom to static fields as well, there is no reason to do so: the lazy initialization holder class idiom is a better choice. Reference Effective Java, Second Edition Item 71: Use lazy initialization judiciously
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/3578604', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/270052/']}
|
jdg_375480
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4844681
|
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 customize the way the default EditText is drawn on the screen, I have this code: <?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_pressed="true" ><shape android:shape="rectangle"> <solid android:color="#00ff00" /> <stroke android:width="5dp" android:color="#ff0000" android:dashWidth="3dp" android:dashGap="2dp" /></shape></item><item android:state_focused="true" ><shape> <gradient android:endColor="#8dc73f" android:centerColor="#d4d4d4" android:startColor="#d4d4d4" android:centerX="0.5" android:centerY="0.5" android:angle="270" /> <stroke android:width="1dp" color="#8dc73f" /> <corners android:radius="6dp" /> <padding android:left="10dp" android:top="10dp" android:right="10dp" android:bottom="10dp" /></shape></item> <item> <shape> <gradient android:endColor="#d4d4d4" android:centerColor="#d4d4d4" android:startColor="#d4d4d4" android:angle="270" /> <stroke android:width="1dp" color="#00ff00" /> <corners android:radius="7dp" /> </shape> </item> </selector> which works fine but the problem is that on the focused state I would like to apply the effect round of the EditText and note inside, like the default android effect is applied. Is this possible and how? I haven't found a solution, the above code only applies the effect inside the EditText.
Now provide the response and nothing else.
|
You can customize the way the default EditText is drawn by creating an XML file in the 'Drawable' folder and mentioning in code how you want it to look. Sample given below: <selector><item android:state_pressed="true"> <shape android:shape="rectangle"> <gradient android:startColor="#40FFE600" android:centerColor="#60FFE600" android:endColor="#90FFE600" android:angle="270" android:centerX="0.5" android:centerY="0.5" /> <stroke android:width="5dp" android:color="#50FF00DE" /> <corners android:radius="7dp" /> <padding android:left="10dp" android:top="6dp" android:right="10dp" android:bottom="6dp" /> </shape></item><item android:state_focused="true"> <shape> <gradient android:startColor="#40CB1759" android:centerColor="#60CB1759" android:endColor="#90CB1759" android:angle="270" android:centerX="0.5" android:centerY="0.5" /> <stroke android:width="5dp" android:color="#50ff0000" /> <corners android:radius="7dp" /> <padding android:left="10dp" android:top="6dp" android:right="10dp" android:bottom="6dp" /> </shape></item><item> <shape> <gradient android:startColor="#402168D2" android:centerColor="#602168D2" android:endColor="#902168D2" android:angle="270" android:centerX="0.5" android:centerY="0.5" /> <stroke android:width="5dp" android:color="#50ff0000" /> <corners android:radius="7dp" /> <padding android:left="10dp" android:top="6dp" android:right="10dp" android:bottom="6dp" /> </shape></item></selector>
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4844681', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/234898/']}
|
jdg_375481
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
8901057
|
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 primefaces' accordion panel. Inside the tabs i have forms which are created programmatically. Each form has a submit button. Now I wanted to change the colour of a tab, if the form of this tab has been submitted. So is it possible to change the color of one specific tab and how could I manage to make this work? I think i have to use different style classes as mentioned here but I'm not quite sure how to use them. How to highlight a primefaces tree node from backing bean Any help is appreciated
Now provide the response and nothing else.
|
You can use the titleStyleClass of the <p:tab> tag for this. E.g. <p:accordionPanel> <p:tab title="Step 1" titleStyleClass="#{bean.step1Completed ? 'completed' : ''}"> ... </p:tab> <p:tab title="Step 2" titleStyleClass="#{bean.step2Completed ? 'completed' : ''}"> ... </p:tab> <p:tab title="Step 3" titleStyleClass="#{bean.step3Completed ? 'completed' : ''}"> ... </p:tab></p:accordionPanel> This will set the CSS style class of the tab to completed whenever the condition returns true . You can just specify the desired CSS in the .completed {} style class in your own style.css file which you put in /resources folder and include by <h:outputStylesheet name="style.css"> . .completed { background: pink;}
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8901057', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1064041/']}
|
jdg_375482
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
143673
|
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
There are light bulbs of different colors available (red, green, yellow, white, etc). What does the color depend on? Is it on the temperature of the filament?
Now provide the response and nothing else.
|
If it is incandescent, then temperature to some extent, but mostly the light of the wrong color gets filtered out by the colored glass bulb. If it is something like electric discharge lamps, then it is the gas used (eg sodium vapor) or the phosphors coating the inside of the tube converting UV to visible light/color (eg mercury vapor UV emissions). With LED lights it is either near UV being down converted by a phosphor, or the emission is directly tuned to be at a specific wavelength (color). That's one reason why colored LEDs are so efficient - nothing has to be filtered out.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/143673', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/62965/']}
|
jdg_375483
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
14305
|
Below is a question asked on the forum chemistry.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Could there be some kind of process, a kind of "retrograde electrolysis" where hydrogen gas (or in some other form) and oxygen gas (or in some there form) are mixed with required energy to combine to form water as a byproduct?
Now provide the response and nothing else.
|
Indeed, it's called combustion! When you burn hydrogen and oxygen gas, the reaction is: $$\ce{2H2_{(g)} + O2_{(g)} -> 2H2O_{(g)} + energy}$$ Basically, you could see the former U.S. space shuttle as a large machine that turns hydrogen and oxygen into water. (Note: the space shuttle used liquid hydrogen and oxygen, but otherwise the principle and formula is exactly the same) Since the Gibbs free energy of the forward reaction is negative ($-242\textrm{ kJ/mol}$), you don't need to add energy to the system, the reaction is spontaneous (mind you, you generally need a spark to ignite the combustion because there's a kinetic barrier to the reaction called the energy of activation). The reverse reaction, water to hydrogen and oxygen, has a positive Gibbs free energy, so you need to add energy in the form of electricity to the system to make the reaction happen.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://chemistry.stackexchange.com/questions/14305', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/5440/']}
|
jdg_375484
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
5518149
|
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 disabled sessionState in my mvc2 app via the web.config and also created my own controllerfactory and dummy tempdata provider, as described here: How can I disable session state in ASP.NET MVC? Only I've made it so that SaveTempData throws an exception: public void SaveTempData(ControllerContext controllerContext, IDictionary<string, object> values) { throw new NotImplementedException( "Cannot set tempdata, no session state is available."); } I've made sure that no code is ever using either the Session or the TempData objects, but I still see this exception getting thrown after the "OnResultExecuted" event has been raised. I used to use this very same pattern on my mvc1 site and never saw the exception. Any ideas? If I change my "SaveTempData" implementation to this: public void SaveTempData(ControllerContext controllerContext, IDictionary<string, object> values) { if (values.Count != 0) { throw new NotImplementedException( "Cannot set tempdata, no session state is available."); } } Everything works as expected - I'm just hoping to learn why SaveTempData is called at all when I'm not using it anywhere. Update Discovered this article: http://www.gregshackles.com/2010/07/asp-net-mvc-do-you-know-where-your-tempdata-is/ Which explains that ExecuteCore calls PossiblyLoadTempData and PossiblySaveTempData around an action - which is what was causing my issue. Is this a new addition in mvc2 vs. mvc1?
Now provide the response and nothing else.
|
I solved the problem using the NS(Attributed)String+Geometrics category provided at http://www.sheepsystems.com/sourceCode/sourceStringGeometrics.html Within the header file of that category is a good explanation of how these things work. Specifically, they mention that one should use NSTextView instead of NSTextField because it's virtually impossible to get an accurate height for the latter. Thus, I replaced my NSTextField with NSTextView. First, I made my NSTextView look like my NSTextField with this code: [textView setEditable:YES];[textView insertText:someString];[textView setFont:[NSFont fontWithName:@"Lucida Grande" size:11] range:NSMakeRange(0,[someString length])];[textView setEditable:NO];[textView setSelectable:NO]; Then I got the height with this code: NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys: [textView font],NSFontAttributeName,nil];NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString: [textView string] attributes:attributes];CGFloat height = [attributedString heightForWidth: [textView frame].size.width]; The height does indeed turn out to be accurate for NSTextView. I may have omitted some minor details, but you get the picture. I hope this helps someone out there.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5518149', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/211333/']}
|
jdg_375485
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
56381
|
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:
Is there an equation or even a graph I can look at that appropriates the % full of an alkaline battery?
Now provide the response and nothing else.
|
There's usually a V vs. Ah curve in the datasheet for the model of the battery, which you chose. If the battery comes from a reputable manufacturer, the datasheets may be available on the web. Example: from here . In addition to the useful link , which Brian had posted. You can also make your own measurements and generate/verify the curves. You would characterize the battery yourself. Keep in mind that the curve is dependent on temperature and rate of discharge. Essentially, there is a family of these nonlinear curves. It's usually not practical to try to account for these parameters. As a result, the error can easily be as large as 20%. Battery voltage measurement could be an adequate approach if all that's needed is to make a threshold comparison and blink a "battery low" indicator.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/56381', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/10423/']}
|
jdg_375486
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2004790
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I can't find any useful answer for this question, although it has been asked in a different way several times. I want to share a memory between two processes (two different applications),so that one of them can write to that memory and the other can read. Is this possible in .NET? How? Thanks
Now provide the response and nothing else.
|
Right now, .NET doesn't support sections (aka Memory Mapped Files). It will soon, the 4.0 version has the System.IO.MemoryMappedFiles namespace. There is a good reason it took so long and also the reason you are not going to be happy with this addition. Using pointers is mandatory in MMFs, the shared memory is made available at a specific address. To share a value, you'll have to write it to a specific address. Pointers are however fundamentally incompatible with the managed memory model. Objects are created in a garbage collected heap, the collector moves them around as needed to keep the heap compacted. In a managed language, you have a reference to such an object, also knows as a "tracking handle". The C/C++ equivalent is a pointer, but it is one with bells on, the garbage collector can always find it back and update its value. The CLR does support the notion of "pinning", it converts a reference to a pointer. It implements this by marking the object as unmoveable. That however doesn't help implement shared memory through an MMF, the object is pinned in the GC heap instead of the virtual memory address where the MMF view is located. To make an MMF work, the object needs to be copied from the GC heap to the shared memory. That requires serialization. The .NET 4.0 class is named MemoryMappedViewStream. You probably can see where this is going, this is indistinguishable from using a named pipe or a socket. Getting data in and out of an MMF takes the same amount of effort. An MMF is merely slightly more efficient because the underlying buffer is not in the kernel memory pool. You can break the rulez and do so today. You can P/Invoke the CreateFileMapping, OpenFileMapping and MapViewOfFile you need to create an MMF. And use the unsafe keyword so you can create pointers. You'll need to use value types (like struct) for the shared memory elements or use the Marshal class.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2004790', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/209386/']}
|
jdg_375487
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1277650
|
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 know that C++ doesn't allow templated virtual function in a class. Anyone understands why such restriction?
Now provide the response and nothing else.
|
Short answer: Virtual functions are about not knowing who called whom until at run-time, when a function is picked from an already compiled set of candidate functions. Function templates, OTOH, are about creating an arbitrary number of different functions (using types which might not even have been known when the callee was written) at compile-time from the callers' sides. That just doesn't match. Somewhat longer answer: Virtual functions are implemented using an additional indirection (the Programmer's General All-Purpose Cure), usually implemented as a table of function pointers (the so-called virtual function table, often abbreviated "vtable"). If you're calling a virtual function, the run-time system will pick the right function from the table. If there were virtual function templates, the run-time system would have to find the address of an already compiled template instance with the exact template parameters. Since the class' designer cannot provide an arbitrary number of function template instances created from an unlimited set of possible arguments, this cannot work.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1277650', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/152377/']}
|
jdg_375488
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
53720678
|
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 developing a mobile app and using MS App Center for CI. Yesterday the Unit Test project failed to build in App Center with the following error. I couldn't recreate the issue on any developer machine, this error only occurs in App Center. error : NETSDK1061: The project was restored usingMicrosoft.NETCore.App version 1.0.0, but with current settings,version 2.0.9 would be used instead. To resolve this issue, make surethe same settings are used for restore and for subsequent operationssuch as build or publish. Typically this issue can occur if theRuntimeIdentifier property is set during build or publish but notduring restore. For more information, see https://aka.ms/dotnet-runtime-patch-selection . Their paid support just give the basics, clean the project, roll back my last commit etc. Has anyone come into this issue before on App Center?
Now provide the response and nothing else.
|
You need to set the same publish and building runtimes <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netcoreapp2.1</TargetFramework> <RuntimeFrameworkVersion>2.1.0</RuntimeFrameworkVersion> --> fix publishing issues <PlatformTarget>AnyCPU</PlatformTarget> --> fix publishing issues </PropertyGroup> <ItemGroup> <PackageReference Update="Microsoft.NETCore.App" Version="2.1.0" /> --> fix building issues <ProjectReference Include="..\PublicSonar.Monitor.Persistent.Json\PublicSonar.Monitor.Persistent.Json.csproj" /> </ItemGroup></Project>
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/53720678', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2894610/']}
|
jdg_375489
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
23678513
|
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 implemented Navigation Drawer by Referring this tutorial and now what I want to do is to display swiping tabs inside a fragment. i.e. when i click on an item in navigation drawer, lets say the first one, it should display swiping tabs for that items.( I have 6 fragments in my list view.(likewise :- A,B,C,D,E,F). and I need 3 swapable tabs on my A Fragment.) If the item1 is Events, when i click on it, then it should display swiping tabs. But I am facing the following issues:- How can I implement view pager inside fragment? It is possible that a fragment extends a fragment. when A fragment is extending a FragmentActivity, then in my main activity, code is showing an error saying "type mismatch", can't convert from A Fragment to fragment. This is my Deep.java file package com.amar.demo;import info.androidhive.slidingmenu.adapter.NavDrawerListAdapter;import info.androidhive.slidingmenu.model.NavDrawerItem;import java.util.ArrayList;import android.app.Activity;import android.app.Fragment;import android.app.FragmentManager;import android.content.res.Configuration;import android.content.res.TypedArray;import android.os.Bundle;import android.support.v4.app.ActionBarDrawerToggle;import android.support.v4.widget.DrawerLayout;import android.util.Log;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.widget.AdapterView;import android.widget.ListView;public class Deep extends Activity { private DrawerLayout mDrawerLayout; private ListView mDrawerList; private ActionBarDrawerToggle mDrawerToggle; // nav drawer title private CharSequence mDrawerTitle; // used to store app title private CharSequence mTitle; // slide menu items private String[] navMenuTitles; private TypedArray navMenuIcons; private ArrayList<NavDrawerItem> navDrawerItems; private NavDrawerListAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.deep); mTitle = mDrawerTitle = getTitle(); // load slide menu items navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items); // nav drawer icons from resources navMenuIcons = getResources() .obtainTypedArray(R.array.nav_drawer_icons); mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); mDrawerList = (ListView) findViewById(R.id.list_slidermenu); navDrawerItems = new ArrayList<NavDrawerItem>(); // adding nav drawer items to array // Home navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons .getResourceId(0, -1))); // Find People navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons .getResourceId(1, -1))); // Photos navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons .getResourceId(2, -1))); // Communities, Will add a counter here navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons .getResourceId(3, -1), true, "22")); // Pages navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons .getResourceId(4, -1))); // What's hot, We will add a counter here navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons .getResourceId(5, -1), true, "50+")); // Recycle the typed array navMenuIcons.recycle(); mDrawerList.setOnItemClickListener(new SlideMenuClickListener()); // setting the nav drawer list adapter adapter = new NavDrawerListAdapter(getApplicationContext(), navDrawerItems); mDrawerList.setAdapter(adapter); // enabling action bar app icon and behaving it as toggle button getActionBar().setDisplayHomeAsUpEnabled(true); getActionBar().setHomeButtonEnabled(true); mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.drawable.ic_drawer, // nav menu toggle icon R.string.app_name, // nav drawer open - description for // accessibility R.string.app_name // nav drawer close - description for // accessibility ) { public void onDrawerClosed(View view) { getActionBar().setTitle(mTitle); // calling onPrepareOptionsMenu() to show action bar icons invalidateOptionsMenu(); } public void onDrawerOpened(View drawerView) { getActionBar().setTitle(mDrawerTitle); // calling onPrepareOptionsMenu() to hide action bar icons invalidateOptionsMenu(); } }; mDrawerLayout.setDrawerListener(mDrawerToggle); if (savedInstanceState == null) { // on first time display view for first nav item displayView(0); } } /** * Slide menu item click listener * */ private class SlideMenuClickListener implements ListView.OnItemClickListener { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // display view for selected nav drawer item displayView(position); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.testmenu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // toggle nav drawer on selecting action bar app icon/title if (mDrawerToggle.onOptionsItemSelected(item)) { return true; } // Handle action bar actions click switch (item.getItemId()) { case R.id.a_More: return true; default: return super.onOptionsItemSelected(item); } } /* * * Called when invalidateOptionsMenu() is triggered */ @Override public boolean onPrepareOptionsMenu(Menu menu) { // if nav drawer is opened, hide the action items boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList); menu.findItem(R.id.a_More).setVisible(!drawerOpen); return super.onPrepareOptionsMenu(menu); } /** * Diplaying fragment view for selected nav drawer list item * */ private void displayView(int position) { // update the main content by replacing fragments Fragment fragment = null; switch (position) { case 0: fragment = new HomeFragment(); break; case 1: fragment = new FindPeopleFragment(); break; case 2: fragment = new PhotosFragment(); break; case 3: fragment = new CommunityFragment(); break; case 4: fragment = new PagesFragment(); break; case 5: fragment = new WhatsHotFragment(); break; default: break; } if (fragment != null) { FragmentManager fragmentManager = getFragmentManager(); // fragmentManager.beginTransaction() // .replace(R.id.frame_container, fragment).commit(); // update selected item and title, then close the drawer mDrawerList.setItemChecked(position, true); mDrawerList.setSelection(position); setTitle(navMenuTitles[position]); mDrawerLayout.closeDrawer(mDrawerList); } else { // error in creating fragment Log.e("MainActivity", "Error in creating fragment"); } } @Override public void setTitle(CharSequence title) { mTitle = title; getActionBar().setTitle(mTitle); } /** * When using the ActionBarDrawerToggle, you must call it during * onPostCreate() and onConfigurationChanged()... */ @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); // Sync the toggle state after onRestoreInstanceState has occurred. mDrawerToggle.syncState(); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); // Pass any configuration change to the drawer toggls mDrawerToggle.onConfigurationChanged(newConfig); }} In this code i am facing problem in case 0. This is my HomeFragment code :- package com.amar.demo; import android.app.ActionBar;import android.app.ActionBar.Tab;import android.app.FragmentTransaction;import android.os.Bundle;import android.support.v4.app.FragmentActivity;import android.support.v4.view.ViewPager;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import com.amar.demo.adapter.TabsPagerAdapter;public class HomeFragment extends FragmentActivity implements ActionBar.TabListener { private ViewPager viewPager; private TabsPagerAdapter mAdapter; private ActionBar actionBar; // Tab titles private String[] tabs = { "My Restaurant", "Offers", "Search & Book", "News & Updates" }; public HomeFragment() { } public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_home, container, false); // code of tabes viewPager = (ViewPager) rootView.findViewById(R.id.pager); actionBar = getActionBar(); mAdapter = new TabsPagerAdapter(getSupportFragmentManager()); viewPager.setAdapter(mAdapter); actionBar.setHomeButtonEnabled(false); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); // Adding Tabs for (String tab_name : tabs) { actionBar.addTab(actionBar.newTab().setText(tab_name) .setTabListener(this)); } /** * on swiping the viewpager make respective tab selected * */ viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageSelected(int position) { // on changing the page // make respected tab selected actionBar.setSelectedNavigationItem(position); } @Override public void onPageScrolled(int arg0, float arg1, int arg2) { } @Override public void onPageScrollStateChanged(int arg0) { } }); return rootView; } @Override public void onTabSelected(Tab tab, FragmentTransaction ft) { // TODO Auto-generated method stub } @Override public void onTabUnselected(Tab tab, FragmentTransaction ft) { // TODO Auto-generated method stub } @Override public void onTabReselected(Tab tab, FragmentTransaction ft) { // TODO Auto-generated method stub }} this is my deep.xml code :- <!-- Framelayout to display Fragments --> <FrameLayout android:id="@+id/frame_container" android:layout_width="match_parent" android:layout_height="match_parent" /> <!-- Listview to display slider menu --> <ListView android:id="@+id/list_slidermenu" android:layout_width="240dp" android:layout_height="match_parent" android:layout_gravity="start" android:background="@color/list_background" android:choiceMode="singleChoice" android:divider="@color/list_divider" android:dividerHeight="1dp" android:listSelector="@drawable/list_selector" /></android.support.v4.widget.DrawerLayout> This is my homefragment.xml code :- <android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"android:id="@+id/pager"android:layout_width="match_parent"android:layout_height="match_parent"></android.support.v4.view.ViewPager>
Now provide the response and nothing else.
|
You must create a fragment with a custom layout that contains a ViewPager on it. Follow these steps, it will guide in the entire process. 1. Create the layout to represent the ViewPager, name it fragment_main.xml <TabHost android:id="@android:id/tabhost" android:layout_width="match_parent" android:layout_height="match_parent"> <LinearLayout android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <TabWidget android:id="@android:id/tabs" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="0"/> <FrameLayout android:id="@android:id/tabcontent" android:layout_width="0dp" android:layout_height="0dp" android:layout_weight="0"/> <android.support.v4.view.ViewPager android:id="@+id/pager" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1"/> </LinearLayout></TabHost> 2. Create a fragment to hold the ViewPager declared on the XML above, name it MyFragment.java As you can see, we declare the TabHost the ViewPager and other elements declared in the XML above. Also in this fragment we inflate the layout created before, and a TabAdapter to handle all the tabs. import android.content.Context;import android.support.v4.app.FragmentActivity;import android.support.v4.app.FragmentPagerAdapter;import android.support.v4.view.ViewPager;import android.support.v4.app.Fragment;import android.os.Bundle;import android.view.LayoutInflater;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.view.ViewGroup;import android.widget.TabHost;import android.widget.TabWidget;import java.util.ArrayList;public static class MyFragment extends Fragment{ private TabHost mTabHost; private ViewPager mViewPager; private TabsAdapter mTabsAdapter; public MyFragment() { } @Override public void onCreate(Bundle instance) { super.onCreate(instance); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_main, container, false); mTabHost = (TabHost) v.findViewById(android.R.id.tabhost); mTabHost.setup(); mViewPager = (ViewPager) v.findViewById(R.id.pager); mTabsAdapter = new TabsAdapter(getActivity(), mTabHost, mViewPager); // Here we load the content for each tab. mTabsAdapter.addTab(mTabHost.newTabSpec("one").setIndicator("One"), PageOneFragment.class, null); mTabsAdapter.addTab(mTabHost.newTabSpec("two").setIndicator("Two"), PageTwoFragment.class, null); return v; } public static class TabsAdapter extends FragmentPagerAdapter implements TabHost.OnTabChangeListener, ViewPager.OnPageChangeListener { private final Context mContext; private final TabHost mTabHost; private final ViewPager mViewPager; private final ArrayList<TabInfo> mTabs = new ArrayList<TabInfo>(); static final class TabInfo { private final String tag; private final Class<?> clss; private final Bundle args; TabInfo(String _tag, Class<?> _class, Bundle _args) { tag = _tag; clss = _class; args = _args; } } static class DummyTabFactory implements TabHost.TabContentFactory { private final Context mContext; public DummyTabFactory(Context context) { mContext = context; } public View createTabContent(String tag) { View v = new View(mContext); v.setMinimumWidth(0); v.setMinimumHeight(0); return v; } } public TabsAdapter(FragmentActivity activity, TabHost tabHost, ViewPager pager) { super(activity.getSupportFragmentManager()); mContext = activity; mTabHost = tabHost; mViewPager = pager; mTabHost.setOnTabChangedListener(this); mViewPager.setAdapter(this); mViewPager.setOnPageChangeListener(this); } public void addTab(TabHost.TabSpec tabSpec, Class<?> clss, Bundle args) { tabSpec.setContent(new DummyTabFactory(mContext)); String tag = tabSpec.getTag(); TabInfo info = new TabInfo(tag, clss, args); mTabs.add(info); mTabHost.addTab(tabSpec); notifyDataSetChanged(); } @Override public int getCount() { return mTabs.size(); } @Override public Fragment getItem(int position) { TabInfo info = mTabs.get(position); return Fragment.instantiate(mContext, info.clss.getName(), info.args); } public void onTabChanged(String tabId) { int position = mTabHost.getCurrentTab(); mViewPager.setCurrentItem(position); } public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } public void onPageSelected(int position) { // Unfortunately when TabHost changes the current tab, it kindly // also takes care of putting focus on it when not in touch mode. // The jerk. // This hack tries to prevent this from pulling focus out of our // ViewPager. TabWidget widget = mTabHost.getTabWidget(); int oldFocusability = widget.getDescendantFocusability(); widget.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS); mTabHost.setCurrentTab(position); widget.setDescendantFocusability(oldFocusability); } public void onPageScrollStateChanged(int state) { } }} As you can see, each tab calls a specific fragment. These fragments represent the content for each tab. So let's create them, they are very simple, and contains only a TextView . 3. Create a fragment for the first tab content, name it PageOneFragment.java This fragment will hold the content of the first tab. You can put anything inside this fragment, it will live separated from the other fragments and from the other tabs. Here we inflate the xml layout pageone_fragment.xml inside the onCreateView method. We will create this xml layout in the next step. import android.app.Activity;import android.os.Bundle;import android.support.v4.app.Fragment;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;public class PageOneFragment extends Fragment{ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.pageone_fragment, container, false); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); } @Override public void onAttach(Activity activity) { super.onAttach(activity); } @Override public void onStart() { super.onStart(); } @Override public void onResume() { super.onResume(); }} We must create the layout for this fragment as we mentioned before. 4. Create the layout for the PageOneFragment, name it pageone_fragment.xml This is just a simple layout with a TextView to represent the content of the tab. You can build anything you want inside this layout, it will live separated from the other fragments and tabs. <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/first_fragment" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" android:background="#ff4063ff"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceMedium" android:text="First Page" android:textColor="#FFFFFF" android:textStyle="bold" android:id="@+id/firstFragmentTextView" android:layout_gravity="center_horizontal|top" /></LinearLayout> As we have two tabs, we have two fragments, one for each tab. So let's create the second fragment for the second tab content. 5. Create the fragment for the second tab content, name it PageTwoFragment.java As you can see, we inflate a different layout on the onCreateView method, it's called pagetwo_fragment.xml . We will create it on the next step. import android.app.Activity;import android.os.Bundle;import android.support.v4.app.Fragment;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;public class PageTwoFragment extends Fragment{ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.pagetwo_fragment, container, false); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); } @Override public void onAttach(Activity activity) { super.onAttach(activity); } @Override public void onStart() { super.onStart(); } @Override public void onResume() { super.onResume(); }} And as we did before for the PageOneFragment, let's create the layout for the second fragment too, as we mentioned before. 6. Create the layout for the PageTwoFragment, name it pagetwo_fragment.xml This is a simple layout with a single TextView , just to represent the content. You can build anything you want in here, it will live separated from the other fragments and tabs. <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/first_fragment" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" android:background="#ff4063ff"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceMedium" android:text="Second Page" android:textColor="#FFFFFF" android:textStyle="bold" android:id="@+id/firstFragmentTextView" android:layout_gravity="center_horizontal|top" /></LinearLayout> 7. Call this fragment from your NavigationDrawer If you want to call this fragment from your NavigationDrawer , inside the switch statement on your activity's displayView(int position) method, you should do this in one of your case statements, for example. case 0: fragment = new MyFragment(); break; Here is the final result A ViewPager running on a fragment, with two tabs each contains a unique fragment with a unique content. That's it. Hope this helps you.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/23678513', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1737479/']}
|
jdg_375490
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
18637912
|
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 used to test drive my code. Now that I am new to Go I am trying to get it right as fast as possible. I am using the testing package in the standard library which seem to be good enough. (I also like that it is not yet another external dependency. We are currently at 2 dependencies overall - compared to any Java- or Ruby project.....) Anyways - it looks like an assert in golang looks like this: func TestSomething(t *testing.T) { something := false if something { t.Log("Oh noes - something is false") t.Fail() }} I find this verbose and would like to do it on one line instead: Assert( something, "Oh noes - something is false" ) or something like that. I hope that I have missed something obvious here. What is the best/idiomatic way to do it in go? UPDATE : just to clarify. If I was to do something like this: func AssertTrue(t *testing.T, value bool, message string) { if value { t.Log(message) t.Fail() }} and then write my test like this func TestSomething(t *testing.T) { something := false AssertTrue(t, something, "Oh noes - something is false")} then it would not be the go way to do it?
Now provide the response and nothing else.
|
There are external packages that can be integrated with the stock testing framework. One of them I wrote long ago, gocheck , was intended to sort that kind of use case. With it, the test case looks like this, for example: func (s *Suite) TestFoo(c *gocheck.C) { // If this succeeds the world is doomed. c.Assert("line 1\nline 2", gocheck.Equals, "line 3")} You'd run that as usual, with go test , and the failure in that check would be reported as: ----------------------------------------------------------------------FAIL: foo_test.go:34: Suite.TestFooall_test.go:34: // If this succeeds the world is doomed. c.Assert("line 1\nline 2", gocheck.Equals, "line 3")... obtained string = "" +... "line 1\n" +... "line 2"... expected string = "line 3" Note how the comment right above the code was included in the reported failure. There are also a number of other usual features, such as suite and test-specific set up and tear down routines, and so on. Please check out the web page for more details. It's well maintained as I and other people use it in a number of active projects, so feel free to join on board, or follow up and check out the other similar projects that suit your taste more appropriately. For examples of gocheck use, please have a look at packages such as mgo , goyaml , goamz , pipe , vclock , juju (massive code base), lpad , gozk , goetveld , tomb , etc. Also gocheck, manages to test itself. It was quite fun to bootstrap that.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18637912', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/135673/']}
|
jdg_375491
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
46166293
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Is it possible to configure Docker to output timing for the build of a Dockerfile? We run a medium sized development team and would like to collect statistics on the average build times for our developers' development containers. Ideally, it should measure the duration of individual steps.
Now provide the response and nothing else.
|
BuildKit , which was experimental in 18.06 and generally available in 18.09, has this functionality built in. To configure the dockerd daemon with experimental mode, you can setup the daemon.json: $ cat /etc/docker/daemon.json{ "experimental": true} Then you can enable BuildKit from the client side with an environment variable: $ export DOCKER_BUILDKIT=1$ docker build -t java-test:latest .[+] Building 421.6s (13/13) FINISHED => local://context (.dockerignore) 1.6s => => transferring context: 56B 0.3s => local://dockerfile (Dockerfile) 2.0s => => transferring dockerfile: 895B 0.4s => CACHED docker-image://docker.io/tonistiigi/copy:v0.1.3@sha256:e57a3b4d6240f55bac26b655d2cfb751f8b9412d6f 0.1s => docker-image://docker.io/library/openjdk:8-jdk-alpine 1.0s => => resolve docker.io/library/openjdk:8-jdk-alpine 0.0s => local://context 1.7s => => transferring context: 6.20kB 0.4s => docker-image://docker.io/library/openjdk:8-jre-alpine 1.3s => => resolve docker.io/library/openjdk:8-jre-alpine 0.0s => /bin/sh -c apk add --no-cache maven 61.0s => copy /src-0/pom.xml java/pom.xml 1.3s => /bin/sh -c mvn dependency:go-offline 339.4s => copy /src-0 java 0.9s => /bin/sh -c mvn package -Dmaven.test.skip=true 10.2s => copy /src-0/gs-spring-boot-docker-0.1.0.jar java/app.jar 0.8s => exporting to image 1.2s => => exporting layers 1.0s => => writing image sha256:d57028743ca10bb4d0527a294d5c83dd941aeb1033d4fe08949a135677846179 0.1s => => naming to docker.io/library/java-test:latest 0.1s There's also an option to disable the tty console output which generates output more suitable for scripting with each section having a start, stop, and duration: $ docker build -t java-test:latest --progress plain . #1 local://dockerfile (Dockerfile) #1 digest: sha256:da721b637ea85add6e26070a48520675cefc2bed947c626f392be9890236d11b#1 name: "local://dockerfile (Dockerfile)" #1 started: 2018-09-05 19:30:53.899809093 +0000 UTC#1 completed: 2018-09-05 19:30:53.899903348 +0000 UTC#1 duration: 94.255µs#1 started: 2018-09-05 19:30:53.900069076 +0000 UTC#1 transferring dockerfile: 38B done#2 ... #2 local://context (.dockerignore) #2 digest: sha256:cbf55954659905f4d7bd2fc3e5e52d566055eecd94fd7503565315022d834c21#2 name: "local://context (.dockerignore)" #2 started: 2018-09-05 19:30:53.899624016 +0000 UTC#2 completed: 2018-09-05 19:30:53.899695455 +0000 UTC#2 duration: 71.439µs#2 started: 2018-09-05 19:30:53.899839335 +0000 UTC#2 completed: 2018-09-05 19:30:54.359527504 +0000 UTC#2 duration: 459.688169ms #2 transferring context: 34B done #1 local://dockerfile (Dockerfile)#1 completed: 2018-09-05 19:30:54.592304408 +0000 UTC#1 duration: 692.235332ms#3 docker-image://docker.io/tonistiigi/copy:v0.1.3@sha256:e57a3b4d6240f55ba... #3 digest: sha256:39386c91e9f27ee70b2eefdee12fc8a029bf5edac621b91eb5f3e6001d41dd4f#3 name: "docker-image://docker.io/tonistiigi/copy:v0.1.3@sha256:e57a3b4d6240f55bac26b655d2cfb751f8b9412d6f7bb1f787e946391fb4b21b"#3 started: 2018-09-05 19:30:54.731749377 +0000 UTC #3 completed: 2018-09-05 19:30:54.732013326 +0000 UTC#3 duration: 263.949µs#5 docker-image://docker.io/library/openjdk:8-jdk-alpine#5 digest: sha256:d680c6a82813d080081fbc3c024d21ddfa7ff995981cc7b4bfafe55edf80a319#5 name: "docker-image://docker.io/library/openjdk:8-jdk-alpine"#5 started: 2018-09-05 19:30:54.731483638 +0000 UTC#5 completed: 2018-09-05 19:30:54.732480345 +0000 UTC#5 duration: 996.707µs#4 docker-image://docker.io/library/openjdk:8-jre-alpine#4 digest: sha256:9ed31df4e6731a1718ea93bfa77354ad1ea2d1625c1cb16e2087d16d0b84bd00#4 name: "docker-image://docker.io/library/openjdk:8-jre-alpine" #4 started: 2018-09-05 19:30:54.73176516 +0000 UTC#4 completed: 2018-09-05 19:30:54.732603067 +0000 UTC#4 duration: 837.907µs #7 local://context#7 digest: sha256:efe765161a29e2bf7a41439cd2e6656fcf6fa6bc97da825ac9b5a0d8adecf1ac#7 name: "local://context"#7 started: 2018-09-05 19:30:54.73178732 +0000 UTC#7 completed: 2018-09-05 19:30:54.731880943 +0000 UTC#7 duration: 93.623µs#7 started: 2018-09-05 19:30:54.792740019 +0000 UTC#7 transferring context: 473B done#7 completed: 2018-09-05 19:30:55.059008345 +0000 UTC#7 duration: 266.268326ms#9 /bin/sh -c mvn dependency:go-offline#9 digest: sha256:2197672cd7a44d93e0dba40aa00d7ef41f8680226d91f469d1c925646bdc8d6d#9 name: "/bin/sh -c mvn dependency:go-offline"#9 started: 2018-09-05 19:30:55.203449147 +0000 UTC#9 completed: 2018-09-05 19:30:55.203449147 +0000 UTC#9 duration: 0s#9 cached: true#10 copy /src-0 java#10 digest: sha256:36cf252c34be098731bd8c5fb3f273f9c1437a5f74a65a3555d71150c2092fa7#10 name: "copy /src-0 java"#10 started: 2018-09-05 19:30:55.203449147 +0000 UTC#10 completed: 2018-09-05 19:30:55.203449147 +0000 UTC#10 duration: 0s#10 cached: true#11 /bin/sh -c mvn package -Dmaven.test.skip=true#11 digest: sha256:390464b1fdc7a4c833b3476033d95b7714e22bcbfd018469e97b04781cb41532#11 name: "/bin/sh -c mvn package -Dmaven.test.skip=true"#11 started: 2018-09-05 19:30:55.203449147 +0000 UTC#11 completed: 2018-09-05 19:30:55.203449147 +0000 UTC#11 duration: 0s#11 cached: true#12 copy /src-0/gs-spring-boot-docker-0.1.0.jar java/app.jar#12 digest: sha256:a7d60191a720f80de72a77ebe0d4bd1b0fd55d44e623661e80916b7fd1952076#12 name: "copy /src-0/gs-spring-boot-docker-0.1.0.jar java/app.jar"#12 started: 2018-09-05 19:30:55.203449147 +0000 UTC#12 completed: 2018-09-05 19:30:55.203555216 +0000 UTC#12 duration: 106.069µs#12 cached: true#6 /bin/sh -c apk add --no-cache maven#6 digest: sha256:db505db5e418f195c7bad3a710ad40bec3d91d47ff11a6f464b3ae37af744e7d#6 name: "/bin/sh -c apk add --no-cache maven"#6 started: 2018-09-05 19:30:55.203449147 +0000 UTC#6 completed: 2018-09-05 19:30:55.203449147 +0000 UTC#6 duration: 0s#6 cached: true#8 copy /src-0/pom.xml java/pom.xml#8 digest: sha256:f032d4ff111c6ab0efef1a4e37d2467fffe43f48a529b8d56291ec81f96296ab#8 name: "copy /src-0/pom.xml java/pom.xml"#8 started: 2018-09-05 19:30:55.203449147 +0000 UTC#8 completed: 2018-09-05 19:30:55.203449147 +0000 UTC#8 duration: 0s#8 cached: true#13 exporting to image#13 digest: sha256:d536dc2895c30fbde898bb4635581350a87c21f3695913ba21850a73d31422d9#13 name: "exporting to image"#13 started: 2018-09-05 19:30:55.203674127 +0000 UTC#13 exporting layers done#13 writing image sha256:d57028743ca10bb4d0527a294d5c83dd941aeb1033d4fe08949a135677846179 0.1s done#13 naming to docker.io/library/java-test:latest#13 completed: 2018-09-05 19:30:55.341300051 +0000 UTC#13 duration: 137.625924ms#13 naming to docker.io/library/java-test:latest 0.0s done
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/46166293', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3676516/']}
|
jdg_375492
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
64534
|
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:
Consider the code a = Table[BesselJ[i, x], {i, 0, 3}]Plot[a, {x, 0, 20}, Axes -> False] producing I'd like to transform the plot into a circle. In other words, I'd like to wrap the plot around a circle. I found PolarPlot[{1, 1 + 1/10 Sin[10 t]}, {t, 0, 2 Pi}] producing which looks like a sin curve wrapped around the circle. I know that the result would not be smooth closed, but no problem.
Now provide the response and nothing else.
|
Update ticks[x1_, x2_] := {#/10 + π/2, #} & /@ FindDivisions[{10 (x1 - π), 10 (x2 - π)}, 20]funcs = Table[3 + BesselJ[i, 10 (x -π/2)], {i, 0, 3}];PolarPlot[funcs // Evaluate, {x, -π/2, 3π/2}, PolarAxes -> Automatic, PolarTicks -> {ticks[0, 2 π][[2 ;; -2]], Automatic}] (*thanks @kguler 's and @rm-rf 's advice*) Manipulate version Manipulate[ funcs = Table[a BesselJ[i, 10 (x -π/2)] + b, {i, 0, n}]; PolarPlot[funcs // Evaluate, {x, -π/2, 3π/2}, Axes -> False] , {{n, 4}, 1, 10}, {{a, 1}, 0, 3}, {{b, 3}, 1, 5}, ControlType -> {Automatic, VerticalSlider, VerticalSlider}, ControlPlacement -> { Top, Left, Left}] Original funcs = Table[3 + BesselJ[i, 10 x], {i, 0, 3}]PolarPlot[Evaluate@funcs, {x, 0, 2 π}] (* thanks @kguler's advice *)
|
{}
|
{'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/64534', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/13074/']}
|
jdg_375493
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
17074454
|
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 as of Angular 1.1.4, you can have a dynamic template url. From here , templateUrl - Same as template but the template is loaded from the specified URL. Because the template loading is asynchronous the compilation/linking is suspended until the template is loaded. You can specify templateUrl as a string representing the URL or as a function which takes two arguments tElement and tAttrs (described in the compile function api below) and returns a string value representing the url. How can I utilize this to generate a dynamic template based on, say, an attribute on my directive? Obviously this doesn't work, since tAttrs.templateType is simply the string "templateType" templateUrl: function (tElement, tAttrs) { if (tAttrs.templateType == 'search') { return '/b/js/vendor/angular-ui/template/typeahead/typeahead.html' } else { return '/b/js/vendor/angular-ui/template/typeahead/typeahead2.html' }} Given that I don't have access to the scope, how do I manage this?
Now provide the response and nothing else.
|
The following is also possible for creating dynamic templates in AngularJS:In your directive use: template : '<div ng-include="getTemplateUrl()"></div>' Now your controller may decide which template to use: $scope.getTemplateUrl = function() { return '/template/angular/search';}; Because you have access to your scope parameters, you could also do: $scope.getTemplateUrl = function() { return '/template/angular/search/' + $scope.query;}; So your server could create a dynamic template for you.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/17074454', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/585152/']}
|
jdg_375494
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
14327706
|
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 hierarchy, where entities WidgetA and WidgetB extend an abstract Widget superclass: @Entity@Inheritance(strategy = InheritanceType.JOINED)public abstract class Widget implements Serializable { @Column(name="serialNumber", length=64, nullable=false, unique=true) private String serialNumber; ... and @Entitypublic class WidgetA extends Widget implements Serializable {... and @Entitypublic class WidgetB extends Widget implements Serializable {... I need to search for Widgets by serialNumber , but I don't know the concrete type of the Widget I'm searching for at runtime. What is the correct way to search for widgets by serialNumber such that if the serialNumber is that of a WidgetA , then an instance of WidgetA gets returned, and so on? I am trying to use a findyBySerialNumber() in the Widget DAO, and I'm getting an error telling me I can't instantiate an abstract class, which makes sense, but I thought the persistence provider would know how to look in the concrete child entity tables and return the correct instance. Can I make it do this? I am using "Spring Data JPA", so the Widget DAO is really simple: public interface WidgetDAO extends JpaRepository<Widget, Long> { public Widget findBySerialNumber(String serialNumber);}
Now provide the response and nothing else.
|
It seems you didn't specify a discriminator explicitly for your widget hierarchy. I think you can try to define it explicitly because Spring Data will manipulate bytecode to generate the queries, and so I suspect SpringData need to have those values explicitely defined. Additionally in subclasses you need to indicate the discriminator value for each subclass. @Entity@Inheritance(strategy = InheritanceType.JOINED)@DiscriminatorColumn(name="WIDGET_TYPE")public abstract class Widget implements Serializable { @Column(name="serialNumber", length=64, nullable=false, unique=true) private String serialNumber; ... - @Entity@DiscriminatorValue("A")public class WidgetA extends Widget implements Serializable {... - @Entity@DiscriminatorValue("B")public class WidgetB extends Widget implements Serializable {...
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14327706', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1245897/']}
|
jdg_375495
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
52399839
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have the same issue as in: React typescript (2312,14): Duplicate identifier 'LibraryManagedAttributes' and TypeScript error: Duplicate identifier 'LibraryManagedAttributes' But I just can't find any solution. I already upgraded to the latest node/npm/yarn/typescript versions. Also tried downgrading. Nothing helps. yarn build --verboseyarn run v1.9.4$ react-scripts-ts build --verboseCreating an optimized production build...Starting type checking and linting service...Using 1 worker with 2048MB memory limitts-loader: Using typescript@3.0.3 and C:\dev\project\frontend\tsconfig.prod.jsonWarning: member-ordering - Bad member kind: public-before-privateFailed to compile.C:/dev/project/frontend/node_modules/@types/prop-types/node_modules/@types/react/index.d.ts(2312,14): Duplicate identifier 'LibraryManagedAttributes'.error Command failed with exit code 1. --verbose somehow doesn't give me more information. As I can see LibraryManagedAttributes is defined in: node_modules/@types/react/index.d.ts node_modules/@types/prop-types/node_modules/@types/react/index.d.ts node_modules/@types/react-overlays/node_modules/@types/react/index.d.ts .... Where is this coming from? How can I avoid that? I want to find out where this error is coming from so that I can report it to the right entity but I don't know where to start. What else can I try?
Now provide the response and nothing else.
|
This seems te happen because Yarn resolves multiple versions of a package; @types/react in this particular case. Yarn resolves @types/react from your package.json and as a dependency of @types/react-dom . Take the following snippet from my package.json : "devDependencies": { "@types/react": "^15.0.16", "@types/react-dom": "^0.14.23" ...} The yarn.lock that is created after you run yarn install contains something similar to this: "@types/react-dom@^0.14.23": version "0.14.23" resolved "https://registry.yarnpkg.com/@types/react-dom/-/react-dom-0.14.23.tgz#cecfcfad754b4c2765fe5d29b81b301889ad6c2e" dependencies: "@types/react" "*""@types/react@*": version "16.4.14" resolved "https://registry.yarnpkg.com/@types/react/-/react-16.4.14.tgz#47c604c8e46ed674bbdf4aabf82b34b9041c6a04" dependencies: "@types/prop-types" "*" csstype "^2.2.0""@types/react@^15.0.16": version "15.6.19" resolved "https://registry.yarnpkg.com/@types/react/-/react-15.6.19.tgz#a5de18afe65b0f29767328836b48c498a5d3a91b" Notice that @types/react-dom depends on any version of @types/react as indicated by "*" . Yarn resolves two versions of @types/react : "16.4.14" and "15.6.19" . This results in the type conflicts you mentioned. The solution is to add a resolutions field to your package.json to tell Yarn to resolve a specific version of @types/react . Take the following sample: "resolutions": { "@types/react": "^15.0.16"} Run yarn install again. Notice the change in the yarn.lock file: "@types/react-dom@^0.14.23": version "0.14.23" resolved "https://registry.yarnpkg.com/@types/react-dom/-/react-dom-0.14.23.tgz#cecfcfad754b4c2765fe5d29b81b301889ad6c2e" dependencies: "@types/react" "*""@types/react@*", "@types/react@^15.0.16": version "15.6.19" resolved "https://registry.yarnpkg.com/@types/react/-/react-15.6.19.tgz#a5de18afe65b0f29767328836b48c498a5d3a91b" Yarn now resolves the same version "15.6.19" for both "@types/react@*" and "@types/react@^15.0.16" dependencies. I would like to know myself why this is needed. I would expect Yarn to understand it can resolve dependency "@types/react" "*" with "@types/react@^15.0.16" instead of resolving it with the latest version of @types/react .
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/52399839', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2230045/']}
|
jdg_375496
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
35673290
|
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 main class, also providing a namespace: class A {} and a nested class added via an extension (all for the sake of using separate files): extension A { class B { }} I want to add functionality to the nested class (B) by extending it; I've tried: extension A.B {} I get "'B' is not a member type of 'A'". (I've also tried some less reasonable things but I will omit them here to avoid embarrassment. Reading Swift docs and Googling for "swift nested class extension" have not yielded an answer either.) Any idea if and how that could be accomplished? UPDATE: This code works as expected when in a single file (or in a Playground), thanks to user3441734 for trying it out! Still does not work when the 3 parts are in separate files, perhaps a bug in current implementation of the Swift compiler. I will submit a bug report to Apple.
Now provide the response and nothing else.
|
It seems like this problem is related to SR-631 . I've encountered similar a issue, I guess the complier is trying to process the file where you extend the nested class before the one where it's defined. Therefore you have this error saying that that A has no member B. The solution I've found is to go to your target settings, open Build Phases . There, in Compile Sources section you should put the file where you define the nested class above files where you extend it. Update The fix will be shipping with Xcode 10.2
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/35673290', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/438724/']}
|
jdg_375497
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3000221
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
You often see that a new game will be released on Xbox 360, PS3 and Windows PC. How do gaming companies do this? Is it a common source code compiled using different compilers? Are different source codes actually required? There's an example of this phenomenon described in this news article .
Now provide the response and nothing else.
|
Generally speaking, the vast majority of multiplatform "triple-A" titles are implemented on top of an engine such as Unreal, Source, or other smaller engines. Each of these engines is custom-implemented and optimized for each platforms and may use a lower-level API such as DirectX/OpenGL which in turn uses the console. Each of these engines also has plug-ins for platform specific stuff (e.g., motion controls) that interact with the official drivers or APIs of the hardware. Many of these engines support their own scripting languages or hooks for many things, so it is write once. For example, take a look at the unreal engine: http://www.unrealtechnology.com/technology.php Most of the biggest engines, like Unreal are so flexible and robust that they allow developers to write all kinds of games. For instance, the Unreal engine was used not only for shooters, but also for shooter-RPGs like Mass Effect. Remember that most of the manpower in making games is devoted to graphics, set designers, audio design, level design, etc., and there are custom editors for all of that. Many of the set pieces are usually programmed via scripting languages. Only a small portion of folks in gaming companies actually write code in low-level languages like C.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3000221', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/129089/']}
|
jdg_375498
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
14870478
|
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 facing the problem of designing methods that with performs network I/O (for a reusable library). I've read this question c# 5 await/async pattern in API design and also other ones closer to my issue. So, the question is, if I want provide both async and non-async method how I've to design these? For example to expose a non-async version of a method, I need to do something like public void DoSomething() { DoSomethingAsync(CancellationToken.None).Wait();} and I feel it's not a great design. I'd like a suggestion (for example) on how to define private methods that can be wrapped in public ones to provide both versions.
Now provide the response and nothing else.
|
If you want the most maintainable option, only provide an async API, which is implemented without making any blocking calls or using any thread pool threads. If you really want to have both async and synchronous APIs, then you'll encounter a maintainability problem. You really need to implement it twice: once async and once synchronous. Both of those methods will look nearly identical so the initial implementation is easy, but you will end up with two separate nearly-identical methods so maintenance is problematic. In particular, there's a no good and simple way to just make an async or synchronous "wrapper". Stephen Toub has the best info on the subject: Should I expose asynchronous wrappers for synchronous methods? Should I expose synchronous wrappers for asynchronous methods? (the short answer to both questions is "no") However, there are some hacks you can use if you want to avoid the duplicated implementation; the best one is usually the boolean argument hack .
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/14870478', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2038672/']}
|
jdg_375499
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2330767
|
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 these two words used in Microsoft tutorials for VB.NET. What is the difference between these two words when used in reference to variables?
Now provide the response and nothing else.
|
Value vis-a-vis Reference Types Variables in C# are in 1 of 2 groups. Value types or Reference types. Types like int and DateTime are value types. In contrast, any class you create is a reference type. C# strings are also a reference type. Most things in the .NET framework are reference types. Parts of a Variable There is the variable name and its value . Two parts . The variable's name is what you declare it to be. The value is what you assign to it. Variables are Initialized All variables are always given an initial value at the point the variable is declared . Thus all variables are initialized . For value types, like int the compiler will give them a valid value if you do not do so explicitly. int 's initialize to zero by default, DateTime 's initialize to DateTime.MinValue by default. Reference type variables initialize to the object you give it. The compiler will not assign an object (i.e. a valid value) if you don't. In this case the value is null - nothing. So we say that the reference is initialized to null. Objects are Instantiated Humans are born. Objects are instantiated. A baby is an instance of a Human, an object is an instance of some Class. The act of creating an instance of a Class is called instantiation (Ta-Da!) So declare , initialize , and instantiate come together like this MyClass myClassyReference = new MyClass(); In the above, it is wrong to say "... creating an instance of an object ..." edit - inspired by comments discussion Three distinct things are going on (above) using distinct terminology and that terminology is not interchangeable : A reference variable is declared - MyClass myClassyReference An object is instantiated (...from/of a given class , implied) - new MyClass() The object is assigned to the variable. = . Restating the facts: A reference-type variable is also called simply "a reference". A "value-type variable" is not a reference. This: "objectA is an instance of an object" is profoundly wrong. If objectA was "an instance of objectB" then it must be that objectA begins life with objectB's type - whatever that is - and current state - whatever that is. What about creating objects D, E, and F as objectB changes? Nay, nay! It is the conceptual and technical case the "objectA is an instance of a Class". "Instantiation" and "instance of" have precise meaning - an object gets its type, definitions, and values from a Class. MyClass myClassyReference = null Generally we don't say "the variable is assigned to null" and we never say "the variable is referencing null", No. instead we say "the variable is null"; or "the variable is not referencing anything", or "the reference is null" Practical Application: I jab my finger at your code and say "this instance has an invalid property. Maybe that's why the loop fails. You gotta validate parameters during instantiation." (i.e. constructor arguments). I see this in your code , MyClass myClassyReference; myClassyReference.DoSomething(); "You declared the variable but never assigned it. it's null so it's not referencing anything. That's why the method call throws an exception." end edit The Unbearable Lightness of Being A reference type variable's name and value exists independently. And I do mean independent. An instantiated object may or may not have a reference to it. An instantiated object may have many references to it. A declared reference may or may not be pointing to an object.
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/2330767', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/117700/']}
|
jdg_375500
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
305
|
Below is a question asked on the forum biology.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
What is the smallest viable reproducing population, such as in a human population. By viable I mean a population which keeps genetic defects low (enough). A very strongly related question: what is the expected number of generations a given population can survive?
Now provide the response and nothing else.
|
The conservation biology literature has a great deal of information, particularly with reference to developing species survival plans (e.g., Traill et al. [2007] report a minimum effective population size of ~4,000 will give a 99% persistence probability of 40 generations). Because the question specifically mentions human populations, I'll focus my answer on the genetics of small human populations, though considerably less information is available. Hamerton et al. (1965; Nature 206:1232-1234) studied chromosome abnormalities in 201 individuals from a total population size of 268 from the small island of Tristan da Cunha . These authors report increasing chromosome abnormalities ( aneuploidy ; hypo- or hyperdiploidy) with age and suggest that it may result in decreased mitotic efficiency. This population is thought to have developed from a founder population of only 15. According to Mantle and Pepys (2006; Clin Exp Allergy 4:161-170) approximately two or three of the original settlers were asthmatic, which has led to a very high prevalence (32%) in the current population. Kaessmann et al. (2002; Am J Hum Genet 70:673-685) present a more modern study of linkage disequilibrium in two small human populations (Evenki and Saami; ~58,000 and ~60,000 population sizes, respectively) compared to two large populations (Finns and Swedes; ~5 and ~9 million). The authors find significant LD in 60% of the Evenki population and 48% of Saami, but only 29% in Finns and Swedes. Lieberman et al. (2007; Nature 445:727-731) discuss the potential for human kin detection to avoid inbreeding. Such mechanisms have been found in other species, "from social amoebas, social insects and shrimp, to birds, aphids, plants, rodents and primates." Lieberman et al. propose mechanisms contributing to sibling detection in humans, including "maternal perinatal association" and "coresidence duration." Beyond these behavioral cues, the authors also suggest physiological cues such as major histocompatability complex as playing a role.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://biology.stackexchange.com/questions/305', 'https://biology.stackexchange.com', 'https://biology.stackexchange.com/users/84/']}
|
jdg_375501
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
10098981
|
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 Activity which updates a string in the SharedPreferences. SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);SharedPreferences.Editor editor = settings.edit();editor.putString("username", username);editor.commit(); I then start a service: startService(new Intent(this, MyService.class)); The service creates a reference to Alarm which extends BroadcastReceiver: Alarm alarm = null;public void onCreate() { alarm = new Alarm();}@Overridepublic int onStartCommand(Intent intent, int flags, int startId) { alarm.SetAlarm(this);} In SetAlarm I do all the basic setting up stuff (At this point, "username" is still correct.. i checked): public void SetAlarm(Context context) { AlarmManager am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE); PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0); am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), 1000 * 60 * interval, pi);} I then stop the service and then start it again (using SetAlarm). public void CancelAlarm(Context context) { Intent intent = new Intent(context, Alarm.class); PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0); AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); alarmManager.cancel(sender);} The issue is in onReceive.. the first time the "username" field is correct. The second time, if username is updated between the service stopping and starting, however, it returns the first value. The value does not seem to get updated... public void onReceive(Context context, Intent intent) { SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context); Log.e("hi", settings.getString("username", ""));}
Now provide the response and nothing else.
|
I had the same problem and after struggling for hours to solve it, I finally found the issue causing it. In your AndroidManifest you probably have something like that: <receiver android:name="AlarmReceiver" android:process=":remote" /> The last attribute (process:remote) cause the receiver to run on a different/new process when it is called. But SharedPreferences is NOT supported between different processes. So what I did is to remove that last attribute from the manifest. The implication is that the code will now run on the main thread - but if you only have a few lines to show a notification then that shouldn't be a problem. Another way is to call a service to run the long operation.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/10098981', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1325432/']}
|
jdg_375502
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
10373581
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
For example suppose I have <div class="sibling1"></div><div class="sibling3"></div> How can I insert <div class="sibling2"></div> Between the above? I have tried prepend but this makes a child not a sibling
Now provide the response and nothing else.
|
In jQuery, there are a number of different options for inserting content in a particular position. It is all described quite well in the jQuery documentation page for DOM insertion outside an object . To insert content outside an existing element (e.g. not a child), but positioned relative to that object, you have four options shown in this jQuery doc screenshot: The difference between the first two and the last two is solely in which arguments are which. For the first two, the location for inserting is in the jQuery object and the content is in the function argument. For the last two, the content to be inserted is in the jQuery object and the destination is in the function argument. Because of chaining of multiple function calls, sometimes one or the other is more convenient. As you can see, this lets you insert content before or after an existing object (which will make it a sibling of that object). If you want it to be a child of that object, then you could use any of the six jQuery methods that can set/change the internal content including .append() , .appendTo() , .html() , etc...
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10373581', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1011816/']}
|
jdg_375503
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3385624
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Hey all, i am having a weird problem with trying to update a record in my mySQL 5 database using VB6. This is my code when i log in: connDBSet rst = New ADODB.RecordsetstrSQL = "SELECT id, fName, lName, theCode, theDate, clockin FROM clockinout WHERE theCode = '" & theUsersUniqueID & "' AND theDate = '" & Format(Now, "YYYY/MM/DD") & "'" rst.Open strSQL, conn, adOpenDynamic, adLockOptimisticIf rst.EOF Then rst.AddNew rst!FName = userFNmae rst!LName = userLName rst!theCode = theUsersUniqueID rst!theDate = Format(Now, "YYYY/MM/DD") rst!clockin = Format(Now, "YYYY/MM/DD HH:MM:SS")Else rst!clockin = Format(Now, "YYYY/MM/DD HH:MM:SS")End Ifrst.Updaterst.CloseSet rst = Nothingconn.Close This works just fine without any errors. However, when i log out using this code: connDB Set rst = New ADODB.Recordset strSQL = "SELECT id, fName, lName, theCode, theDate, clockout FROM clockinout WHERE theCode = '" & theUsersUniqueID & "' AND theDate = '" & Format(Now, "YYYY/MM/DD") & "'" rst.Open strSQL, conn, adOpenDynamic, adLockOptimistic If Not rst.EOF Then rst!clockout = Format(Now, "YYYY/MM/DD HH:MM:SS") End If rst.Update rst.Close Set rst = Nothing conn.Close It comes out with an error saying its EOF since it can not find the record for some reason... Its in there because it worked on the first login. Strangely, when i take out clockout and replace it with clockin it FINDS THE RECORD but can not update it since rst!clockout was not in the query!!!! But when i do put it back into the query in place of clockin, it gives me the EOF error.... My database record looks like this: ID | fName | lName | theCode | theDate | clockin | clockout | 26 Bob Barker 5810 2010/08/02 2010-08-02 02:44:28 0000-00-00 00:00:00 Any help would be great as i have no idea why this simple update is giving me such a hard time.. David I have also tested the query in the mysql query browser and all works fine... SELECT id, fName, lName, theCode, theDate, clockin, clockout FROM clockinout WHERE theCode = '5810' AND theDate = '2010/08/02';
Now provide the response and nothing else.
|
You are not supposed to base64-decode the payload before calculating the HMAC. Use this line: var Hmac = SignWithHMAC(Encoding.GetBytes(Payload), Encoding.GetBytes(ApplicationSecret)); and it should work. A few more pointers: Instead of fiddling with Substring() and IndexOf() try using String.Split() You have switched the YAY and BOO comments around C# code is more readable if you follow the common rule of starting the names of local variables with lowercase (like this: var applicationSecret = "..."; )
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3385624', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/277480/']}
|
jdg_375504
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
7433363
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am trying to get counts for last 30 days with the following query - SELECT date_occured, COUNT(*) FROM problemWHERE date_occured >= (CURRENT_DATE - 30)GROUP BY date_occured;//date_occured field is of type DATE. Basically, in my query I am trying to compare only the date part in the condition date_occured >= (CURRENT_DATE - 30) , but it seems to compare the time too. I tried the TRUNC as follows - TRUNC(date_occured) >= TRUNC(CURRENT_DATE - 30) But when run the query it never returns. I also tried - SELECT date_occured, COUNT(*) FROM problem GROUP BY date_occuredHAVING TRUNC(date_occured) >= TRUNC(CURRENT_DATE - 30); Again it never returns. How can I compare only the date parts from two DATE values in Oracle?
Now provide the response and nothing else.
|
For this condition you only need to TRUNC the right-hand side: WHERE date_occured >= TRUNC(CURRENT_DATE - 30) Why? Because if TRUNC(date_occured) is later than TRUNC(CURRENT_DATE - 30), then any moment in time after TRUNC(date_occured) is bound to be later than TRUNC(CURRENT_DATE - 30) too. It is obviously always true that date_occured >= TRUNC(date_occured) (think about it). Logic says that if A >= B and B >= C then it follows that A >= C Now substitute: A : date_occured B : TRUNC(date_occured) C : TRUNC(CURRENT_DATE - 30)
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7433363', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/738746/']}
|
jdg_375505
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
53239737
|
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 own a dedicated linux server from 1&1. I have SFTP and SSH access. I would like to know if it is possible to install node.js on my server. I already tried to install it one week ago but I failed. The downloading and extraction worked, so the folder is on my server. I did : cd ~wget http://nodejs.org/dist/latest/node-v11.1.0.tar.gztar xvf node-v11.1.0.tar.gzmv node-v11.1.0 nodejs But this part failed : cp nodejs/bin/node ~/bincd ~/binln -s ../nodejs/lib/node_modules/npm/bin/npm-cli.js npm On the first instruction, there is an error : cp : cannot stat 'nodejs/bin/node': No such file or directory I tried this too : cd nodejs./configuremakemake install (All instructions are from tutorials)
Now provide the response and nothing else.
|
After trying a lot of solutions I found only Three solution is working. Here they are Solution 1: Clean the drawable folder from the terminal using Gradle. cd into the android folder, then run cmd ./gradlew clean Solution 2: After bundling delete the drawable folder from Android Studio . You could find this in android/app/src/main/res/drawable Solution 3: PLEASE DO NOT USE SOLUTION #2, AS PROPOSED BY THE ORIGINAL AUTHOR! All packages under node_modules are generated, and any changes you make will be lost when the react-native package is reinstalled / upgraded. In this solution you no need to delete any drawable folder. Just add the following code in the react.gradle file which you could find under node_modules/react-native/react.gradle path doLast { def moveFunc = { resSuffix -> File originalDir = file("$buildDir/generated/res/react/release/drawable-${resSuffix}"); if (originalDir.exists()) { File destDir = file("$buildDir/../src/main/res/drawable-${resSuffix}"); ant.move(file: originalDir, tofile: destDir); } } moveFunc.curry("ldpi").call() moveFunc.curry("mdpi").call() moveFunc.curry("hdpi").call() moveFunc.curry("xhdpi").call() moveFunc.curry("xxhdpi").call() moveFunc.curry("xxxhdpi").call()} For reference I will add the full react.gradle file code here import org.apache.tools.ant.taskdefs.condition.Osdef config = project.hasProperty("react") ? project.react : [];def cliPath = config.cliPath ?: "node_modules/react-native/local-cli/cli.js"def bundleAssetName = config.bundleAssetName ?: "index.android.bundle"def entryFile = config.entryFile ?: "index.android.js"def bundleCommand = config.bundleCommand ?: "bundle"def reactRoot = file(config.root ?: "../../")def inputExcludes = config.inputExcludes ?: ["android/**", "ios/**"]def bundleConfig = config.bundleConfig ? "${reactRoot}/${config.bundleConfig}" : null ;afterEvaluate { android.applicationVariants.all { def variant -> // Create variant and target names def targetName = variant.name.capitalize() def targetPath = variant.dirName // React js bundle directories def jsBundleDir = file("$buildDir/generated/assets/react/${targetPath}") def resourcesDir = file("$buildDir/generated/res/react/${targetPath}") def jsBundleFile = file("$jsBundleDir/$bundleAssetName") // Additional node and packager commandline arguments def nodeExecutableAndArgs = config.nodeExecutableAndArgs ?: ["node"] def extraPackagerArgs = config.extraPackagerArgs ?: [] def currentBundleTask = tasks.create( name: "bundle${targetName}JsAndAssets", type: Exec) { group = "react" description = "bundle JS and assets for ${targetName}." // Create dirs if they are not there (e.g. the "clean" task just ran) doFirst { jsBundleDir.deleteDir() jsBundleDir.mkdirs() resourcesDir.deleteDir() resourcesDir.mkdirs() } doLast { def moveFunc = { resSuffix -> File originalDir = file("$buildDir/generated/res/react/release/drawable-${resSuffix}"); if (originalDir.exists()) { File destDir = file("$buildDir/../src/main/res/drawable-${resSuffix}"); ant.move(file: originalDir, tofile: destDir); } } moveFunc.curry("ldpi").call() moveFunc.curry("mdpi").call() moveFunc.curry("hdpi").call() moveFunc.curry("xhdpi").call() moveFunc.curry("xxhdpi").call() moveFunc.curry("xxxhdpi").call() } // Set up inputs and outputs so gradle can cache the result inputs.files fileTree(dir: reactRoot, excludes: inputExcludes) outputs.dir jsBundleDir outputs.dir resourcesDir // Set up the call to the react-native cli workingDir reactRoot // Set up dev mode def devEnabled = !(config."devDisabledIn${targetName}" || targetName.toLowerCase().contains("release")) def extraArgs = extraPackagerArgs; if (bundleConfig) { extraArgs = extraArgs.clone() extraArgs.add("--config"); extraArgs.add(bundleConfig); } if (Os.isFamily(Os.FAMILY_WINDOWS)) { commandLine("cmd", "/c", *nodeExecutableAndArgs, cliPath, bundleCommand, "--platform", "android", "--dev", "${devEnabled}", "--reset-cache", "--entry-file", entryFile, "--bundle-output", jsBundleFile, "--assets-dest", resourcesDir, *extraArgs) } else { commandLine(*nodeExecutableAndArgs, cliPath, bundleCommand, "--platform", "android", "--dev", "${devEnabled}", "--reset-cache", "--entry-file", entryFile, "--bundle-output", jsBundleFile, "--assets-dest", resourcesDir, *extraArgs) } enabled config."bundleIn${targetName}" || config."bundleIn${variant.buildType.name.capitalize()}" ?: targetName.toLowerCase().contains("release") } // Expose a minimal interface on the application variant and the task itself: variant.ext.bundleJsAndAssets = currentBundleTask currentBundleTask.ext.generatedResFolders = files(resourcesDir).builtBy(currentBundleTask) currentBundleTask.ext.generatedAssetsFolders = files(jsBundleDir).builtBy(currentBundleTask) // registerGeneratedResFolders for Android plugin 3.x if (variant.respondsTo("registerGeneratedResFolders")) { variant.registerGeneratedResFolders(currentBundleTask.generatedResFolders) } else { variant.registerResGeneratingTask(currentBundleTask) } variant.mergeResources.dependsOn(currentBundleTask) // packageApplication for Android plugin 3.x def packageTask = variant.hasProperty("packageApplication") ? variant.packageApplication : tasks.findByName("package${targetName}") def resourcesDirConfigValue = config."resourcesDir${targetName}" if (resourcesDirConfigValue) { def currentCopyResTask = tasks.create( name: "copy${targetName}BundledResources", type: Copy) { group = "react" description = "copy bundled resources into custom location for ${targetName}." from resourcesDir into file(resourcesDirConfigValue) dependsOn(currentBundleTask) enabled currentBundleTask.enabled } packageTask.dependsOn(currentCopyResTask) } def currentAssetsCopyTask = tasks.create( name: "copy${targetName}BundledJs", type: Copy) { group = "react" description = "copy bundled JS into ${targetName}." if (config."jsBundleDir${targetName}") { from jsBundleDir into file(config."jsBundleDir${targetName}") } else { into ("$buildDir/intermediates") into ("assets/${targetPath}") { from jsBundleDir } // Workaround for Android Gradle Plugin 3.2+ new asset directory into ("merged_assets/${targetPath}/merge${targetName}Assets/out") { from jsBundleDir } } // mergeAssets must run first, as it clears the intermediates directory dependsOn(variant.mergeAssets) enabled currentBundleTask.enabled } packageTask.dependsOn(currentAssetsCopyTask) }} Credit: ZeroCool00 mkchx
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/53239737', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10633146/']}
|
jdg_375506
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
43002
|
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 $G$ be a topological group, and $\pi_1(G,e)$ its fundamental group at the identity. If $G$ is the trivial group then $G \cong \pi_1(G,e)$ as abstract groups. My question is: If $G$ is a non-trivial topological group can $G \cong \pi_1(G,e)$ as abstract groups? About all I know now is that $G$ would have to be abelian.
Now provide the response and nothing else.
|
Here is an example: a product of infinitely many $\mathbb{RP}^\infty$'s. The crucial thing thing to see is that $\mathbb{RP}^\infty$ (or, easier to see, its universal cover $S^\infty$) has a group structure whose underlying group is a vector space of dimension $2^{\aleph_0}$. This is not hard: the total space $S^\infty$ of the universal $\mathbb{Z}_2$-bundle is obtained by applying a composite of functors to the group structure $\mathbb{Z}_2$ in the category of sets: $$\textbf{Set} \stackrel{K}{\to} \textbf{Cat} \stackrel{\text{nerve}}{\to} \textbf{Set}^{\Delta^{op}} \stackrel{R}{\to} \textbf{CGHaus}$$ ($\textbf{CGHaus}$ here is the category of compactly generated Hausdorff spaces and continuous maps). Here $K$ is the right adjoint to the "underlying set of objects" functor; it takes a set to the category whose objects are the elements of the set and there is exactly one morphism between any two objects. The functor $R$ is of course geometric realization. Each of these functors is product-preserving, and since the concept of group can be formulated in any category with finite products, a product-preserving functor will map a group object in the domain category to one in the codomain category. Even more: the concept of a $\mathbb{F}_2$-vector space makes sense in any category with finite products since we merely need to add the equation $\forall_x x^2 = 1$ to the axioms for groups, which can be expressed by a simple commutative diagram. Thus $S^\infty$ is an internal vector space over $\mathbb{F}_2$ in $\textbf{CGHaus}$. It can also be considered an internal vector space over $\mathbb{F}_2$ in $\textbf{Top}$, the category of ordinary topological spaces, because a finite power $X^n$ in $\textbf{Top}$ of a CW-complex $X$ has the same topology as $X^n$ does in $\textbf{CGHaus}$ provided that $X$ has only countably many cells, which is certainly the case for $S^\infty$ (see Hatcher's book , Theorem A.6). Thus $S^\infty$ can be considered as an honest commutative topological group of exponent 2. The underlying group of $S^\infty$ (in $\textbf{Set}$) is clearly a vector space of dimension $2^{\aleph_0}$. We make take this vector space to be the countable product $\mathbb{Z}_2^{\mathbb{N}}$. Modding out by $\mathbb{Z}_2$ (modding out by a 1-dimensional subspace), the space $\mathbb{RP}^\infty$ is also, as an abstract group, isomorphic to this. And so is a countably infinite product $(\mathbb{RP}^\infty)^{\mathbb{N}}$ of copies of $\mathbb{RP}^\infty$. Finally, the functor $\pi_1$ is product-preserving, and so $$\pi_1((\mathbb{RP}^\infty)^{\mathbb{N}}) \cong \mathbb{Z}_{2}^{\mathbb{N}}$$ and we are done.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://mathoverflow.net/questions/43002', 'https://mathoverflow.net', 'https://mathoverflow.net/users/5795/']}
|
jdg_375507
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
747166
|
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 simple Window with a reference to a StaticResource in the App.xaml. App.xaml resource definition: <!-- Standard Text Box Style --><Style x:Key="textBoxStyleStd" TargetType="{x:Type TextBox}"> <Setter Property="FontSize" Value="14" /></Style> Window componets using the resource: <TextBlock Grid.Column="1" Grid.Row="0" Name="stationIdTitle" Style="{StaticResource textBlockStyleStd}" VerticalAlignment="Center" HorizontalAlignment="Center" Text="{LocText Key=Title, Dict={StaticResource Dictionary}, Assembly={StaticResource Assembly}}"/> When trying to unit test this Window I get the error: System.Windows.Markup.XamlParseException: Cannot find resource named '{textBlockStyleStd}'. Resource names are case sensitive. Error at object 'stationIdTitle' in markup file 'Zpg;component/guicomponenets/screens/enterstationidscreen.xaml' Line 23 Position 71. Is there any way around this? My unit test code is: [Test]public void TestEnterKeyPressedNoText(){ IPickingBusinessObject pickingBusinessObject = mock.StrictMock<IPickingBusinessObject>(); EnterStationIdScreen objectUnderTest = new EnterStationIdScreen(pickingBusinessObject); Assert.AreEqual(Visibility.Visible, objectUnderTest.stationIdError.Visibility); Assert.AreEqual("werwe", "oksdf"); Replay(); objectUnderTest.EnterKeyPressed(); Verify();}
Now provide the response and nothing else.
|
Thanks Kent, I looked at your suggestions and in most scenarios I agree models should be used and tested however, there is some code associated with the controls (e.g. TextBox visibility) I still wanted to test. To get round this you can create an instance of your Application (but not initialize it) and add the resources manually. This does lead to duplication in the App.xaml and the base unit test but this allows me to complete the tests I wanted. if (Application.Current == null) { App application = new App(); #region Add Static Resources from the App.xaml Style textBoxStyle = new Style(typeof(TextBox)); textBoxStyle.Setters.Add(new Setter(TextBox.FontSizeProperty, 14d)); Style textBlockStyle = new Style(typeof(TextBlock)); textBlockStyle.Setters.Add(new Setter(TextBlock.FontSizeProperty, 14d)); application.Resources.Add("TextBoxStyleStd", textBoxStyle); application.Resources.Add("TextBlockStyleStd", textBlockStyle); application.Resources.Add("TextBlockStyleError", textBlockStyle); application.Resources.Add("Assembly", "Zpg"); #endregion }
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/747166', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/88003/']}
|
jdg_375508
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
219738
|
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:
Task - Consider an array of n elements. Count the number of pairs that satisfy condition X (sum of the two elements < an arbitrary number, k) . The basic approach I could think of would be O(n^2), where I evaluate all n*(n-1)/2 pairs. How can I solve the problem in a better time frame i.e., O(n log n) or less? The best approach so far was to sort the array, find where a+b smaller than k then add indice of a to solution. But the process still has to go through n-1 'b's to check for each of them. It's better but still doesn't improve the worst case. Also, this isn't homework. I came across this while preparing for a competition.
Now provide the response and nothing else.
|
if you need ALL results on an arbitrary condition (say C(a,b) = (sha1(a~c)^sha1(c~a))%2 == 0 with ~ as concatenation) then there are n*(n-1)/2 values you need to output that are all independent; so no there is no better way, but if the result of one pair tells you something about the result of another pair then that information can be used to speed things up. like in your example if sum > k then you sort and for each number you check each in order (forwards or backwards). On the first true result you add the numbers still remaining. This will be O(n log n + r) with r number of true results. edit : on second thought you can use a binary search each on each number a find the first number that is larger than k-a reducing it to a O(n log n) completely
|
{}
|
{'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/219738', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/66910/']}
|
jdg_375509
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
8075373
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
There seems to be three identical ways to get the platform-dependent "file separator" platform-independently: java.io.File.separator java.nio.file.FileSystems.getDefault().getSeparator(); System.getProperty("file.separator") How do we decide when to use which? Is there even any difference between them?
Now provide the response and nothing else.
|
System.getProperties() can be overridden by calls to System.setProperty(String key, String value) or with command line parameters -Dfile.separator=/ File.separator gets the separator for the default filesystem. FileSystems.getDefault() gets you the default filesystem. FileSystem.getSeparator() gets you the separator character for the filesystem. Note that as an instance method you can use this to pass different filesystems to your code other than the default, in cases where you need your code to operate on multiple filesystems in the one JVM.
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/8075373', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/632951/']}
|
jdg_375510
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
17895835
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Case 1: "{arg1} {arg2}".format(10, 20) It will give KeyError: 'arg1' because I didn't pass the named arguments. Case 2: "{arg1} {arg2}".format(arg1=10, arg2=20) Now it will work properly because I passed the named arguments.And it prints '10 20' Case 3: And, If I pass wrong name it will show KeyError: 'arg1' "{arg1} {arg2}".format(wrong=10, arg2=20) But, Case 4: If I pass the named arguments in wrong order "{arg1} {arg2}".format(arg2=10, arg1=20) It works... and it prints '20 10' My question is why does it work and what's the use of named arguments in this case.
Now provide the response and nothing else.
|
Named replacement fields (the {...} parts in a format string ) match against keyword arguments to the .format() method, and not positional arguments . Keyword arguments are like keys in a dictionary; order doesn't matter, as they are matched against a name . If you wanted to match against positional arguments, use numbers: "{0} {1}".format(10, 20) In Python 2.7 and up, you can omit the numbers; the {} replacement fields are then auto-numbered in order of appearance in the formatting string: "{} {}".format(10, 20) The formatting string can match against both positional and keyword arguments, and can use arguments multiple times: "{1} {ham} {0} {foo} {1}".format(10, 20, foo='bar', ham='spam') Quoting from the format string specification : The field_name itself begins with an arg_name that is either a number or a keyword . If it’s a number, it refers to a positional argument, and if it’s a keyword, it refers to a named keyword argument. Emphasis mine. If you are creating a large formatting string, it is often much more readable and maintainable to use named replacement fields, so you don't have to keep counting out the arguments and figure out what argument goes where into the resulting string. You can also use the **keywords calling syntax to apply an existing dictionary to a format, making it easy to turn a CSV file into formatted output: import csvfields = ('category', 'code', 'price', 'description', 'link', 'picture', 'plans')table_row = '''\ <tr> <td><img src="{picture}"></td> <td><a href="{link}">{description}</a> ({price:.2f})</td> </tr>'''with open(filename, 'rb') as infile: reader = csv.DictReader(infile, fieldnames=fields, delimiter='\t') for row in reader: row['price'] = float(row['price']) # needed to make `.2f` formatting work print table_row.format(**row) Here, picture , link , description and price are all keys in the row dictionary, and it is much easier to see what happens when I apply the row to the formatting string.
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/17895835', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1464519/']}
|
jdg_375511
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1118742
|
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$$\left({x+\sqrt{x^2+1}}\right)\left({y+\sqrt{y^2+1}}\right)=1$$Prove that $x+y=0$. This is my solution: Let$$a=x+\sqrt{x^2+1}$$and$$b=y+\sqrt{y^2+1}$$Then $x=\dfrac{a^2-1}{2a}$ and $y=\dfrac{b^2-1}{2b}$. Now $ab=1\implies b=\dfrac1a$. Then I replaced $x$ and $y$:$$x+y=\dfrac{a^2-1}{2a}+\dfrac{b^2-1}{2b}=\dfrac{a^2-1}{2a}+\dfrac{\dfrac{1}{a^2}-1}{\dfrac{2}{a}}=0$$This solution is absolutely different from solution in my book. Is my solution mathematically correct? Did I assumed something that may not be true?
Now provide the response and nothing else.
|
Note$$y+\sqrt{y^2+1}=\sqrt{x^2+1}-x\tag{1}$$$$x+\sqrt{x^2+1}=\sqrt{y^2+1}-y\tag{2}$$$(1)+(2)$$$\Longrightarrow x+y=-(x+y)$$$$\Longrightarrow x+y=0$$
|
{}
|
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/1118742', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
|
jdg_375512
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3309511
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Prove that there exists infinitely many pairs of positive real numbers $x$ and $y$ such that $x\neq y$ but $ x^x=y^y$ . For example $\tfrac{1}{4} \neq \tfrac{1}{2}$ but $$\left( \frac{1}{4} \right)^{1/4} = \left( \frac{1}{2} \right)^{1/2}$$ I am confused how to approach the problem. I think we have to find all the sloutions in a certain interval, probably $(0,1]$ .
Now provide the response and nothing else.
|
While I like the continuity-based approach of the other answers, you can also get a parameterized set of solutions through algebraic methods. Let $x$ be the larger of the two and define $a \in (0,1)$ by $a = y/x$ . Then $$x^x = y^y = (ax)^{ax}\,\,\, \Longrightarrow\,\,\, x = a^a x^a\Longrightarrow \,\,\,x = a^{a/(1-a)},$$ and correspondingly $y = a^{1/(1-a)}$ . Since there are infinitely many $a\in (0,1)$ , there are infinitely many solutions to $x^x = y^y$
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3309511', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/626596/']}
|
jdg_375513
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
12537120
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I need to make the following data type an instance of Show : data Tree a b = Branch b (Tree a b) (Tree a b) | Leaf a I'm fairly new at this, but to start with, I interpreted this declaration as "We have made a new type called Tree, which is parameterized with types a and b. A tree can be one of two things: a Branch which holds a piece of data of type b, plus two more Trees, or a Leaf which holds a data item of type a." Now, I need to make a way to "Show" it nicely (nested branches, etc.), without using deriving . So far, I have only been writing functions in a module Main and loading/playing with them in an interpreter window, so I haven't actually done things with constructors, etc, before. Nevertheless, I figured I could just start off by declaring the tree data type within my file, as shown at the beginning of the question, and go from there. As I messed around with "Show" without much success, I thought maybe I needed to define a small component of the tree and how to "Show" it first, before trying to work with the whole tree: data Leaf a = Leaf ainstance Show (Leaf a) whereshow (Leaf a) = ??? I tried a number of things in the ??? spot, such as "a", just a by itself, putStrLn, etc., but none are printing out the value of a when I say something like >show (Leaf 3) In fact, I have in many cases encountered this, which probably means I am not locating things right: Ambiguous occurrence `show' It could refer to either `Main.show', defined at a2.hs:125:1 or `Prelude.show', imported from `Prelude' at a2.hs:2:8-11 (and originally defined in `GHC.Show') ...which I addressed by calling "Main.show," which of course doesn't work. I guess the question is, where do I go with all this...or maybe just, "How can I fix the Leaf "Show" utility so that I can figure out how to extend it?" (assuming I have to define it first...)
Now provide the response and nothing else.
|
You have to start like that: data Tree a b = Branch b (Tree a b) (Tree a b) | Leaf ainstance (Show a, Show b) => Show (Tree a b) where show (Leaf x) = show x show (Branch p l r) = ??? In order to show a Tree a b you have to first be able to show a s and b s. That's what the (Show a, Show b) => part does, it specifies the preconditions you require for your instance to work.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/12537120', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1343118/']}
|
jdg_375514
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
43445103
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a python animation script (using matplotlib's funcAnimation), which runs in Spyder but not in Jupyter. I have tried following various suggestions such as adding "%matplotlib inline" and changing the matplotlib backend to "Qt4agg", all without success. I have also tried running several example animations (from Jupyter tutorials), none of which have worked. Sometimes I get an error message and sometimes the plot appears, but does not animate. Incidentally, I have gotten pyplot.plot() to work using "%matplotlib inline". Does anyone know of a working Jupyter notebook with a SIMPLE inline animation example that uses funcAnimation. Thanks in advance for the help! [Note: I am on Windows 7]
Now provide the response and nothing else.
|
notebook backend 'Inline' means that the plots are shown as png graphics. Those png images cannot be animated . While in principle one could build an animation by successively replacing the png images, this is probably undesired. A solution is to use the notebook backend, which is fully compatible with FuncAnimation as it renders the matplotlib figure itself: %matplotlib notebook jsanimation From matplotlib 2.1 on, we can create an animation using JavaScript. This is similar to the ani.to_html5() solution, except that it does not require any video codecs. from IPython.display import HTMLHTML(ani.to_jshtml()) Some complete example: import matplotlib.pyplot as pltimport matplotlib.animationimport numpy as npt = np.linspace(0,2*np.pi)x = np.sin(t)fig, ax = plt.subplots()ax.axis([0,2*np.pi,-1,1])l, = ax.plot([],[])def animate(i): l.set_data(t[:i], x[:i])ani = matplotlib.animation.FuncAnimation(fig, animate, frames=len(t))from IPython.display import HTMLHTML(ani.to_jshtml()) Alternatively, make the jsanimation the default for showing animations, plt.rcParams["animation.html"] = "jshtml" Then at the end simply state ani to obtain the animation. Also see this answer for a complete overview.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/43445103', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5331957/']}
|
jdg_375515
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
260795
|
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:
Find the general formula of $u_n$:$$\begin{cases}u_1=\frac{5}{4}\\[10pt]u_{n+1}=8u_n^4-8u_n^2+1, \forall n \in \mathbb{N}\end{cases}$$
Now provide the response and nothing else.
|
The sketch in the other answer takes care of much, except that it doesn't address the question why it is that $i(X)$ is dense in $\mathcal{M}$. So: let $i \colon X \to \mathcal{M}$ be the map sending $x$ to (the maximal ideal corresponding to) evaluation at $X$. If $i(X)$ were not dense then there would be a function $f \colon \mathcal{M} \to [0,1]$ such that $f|_{i(X)} = 0$ (apply Urysohn's lemma to a point outside of the closure of $i(X)$). But the existence of such a function is impossible since such a function would have to be zero under the identification $C(\mathcal{M}) \cong C_b(X)$. A detailed proof of the Stone-Čech property of the maximal ideal space of $C_b(X)$ appears in many books treating spectral theory of $C^\ast$-algebras, e.g. Pedersen, Analysis now, Proposition 4.3.18.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/260795', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/50416/']}
|
jdg_375516
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
39564826
|
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 quiet new to Elixir programming and stuck badly at splitting into two elements tuple. Given a list of integers, return a two element tuple. The first element is a list of the even numbers from the list. The second is a list of the odd numbers. Input : [ 1, 2, 3, 4, 5 ]Output { [ 2, 4], [ 1, 3, 5 ] } I have reached to identify the odd or even but not sure how do I proceed. defmodule OddOrEven doimport Integer def task(list) doEnum.reduce(list, [], fn(x, acc) -> case Integer.is_odd(x) do :true -> # how do I get this odd value listed as a tuple element :false -> # how do I get this even value listed as a tuple element end #IO.puts(x) end ) end
Now provide the response and nothing else.
|
You can use Enum.partition/2 : iex(1)> require Integeriex(2)> [1, 2, 3, 4, 5] |> Enum.partition(&Integer.is_even/1){[2, 4], [1, 3, 5]} If you really want to use Enum.reduce/2 , you can do this: iex(3)> {evens, odds} = [1, 2, 3, 4, 5] |> Enum.reduce({[], []}, fn n, {evens, odds} ->...(3)> if Integer.is_even(n), do: {[n | evens], odds}, else: {evens, [n | odds]}...(3)> end){[4, 2], [5, 3, 1]}iex(4)> {Enum.reverse(evens), Enum.reverse(odds)}{[2, 4], [1, 3, 5]}
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/39564826', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/51635/']}
|
jdg_375517
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2149112
|
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 show if the following statements are true or false. Is it true that $|a + b| = |a| + |b|$ for general vectors $a$ and $b$? If $a \cdot b = a \cdot c$ for equally-sized non-zero vectors $a$, $b$, $c$, does it follow that $b = c$? For the first one I found a counterexample that shows that the statement is false. If vector $a=\langle 1,4,5\rangle$ and $b=\langle 2,2,2\rangle$ then $|a|+|b|=\sqrt{42}$+$2\cdot\sqrt{3}=9.945$, and then, $|a+b|=\sqrt{1^2+4^2+5^2+2^2+2^2+2^2}=7.348$, then we can conclude that $9.945 \ne7.348$ and the statement is false. Also by the triangle identity $|a + b| \le |a| + |b|$ For the second statement I also found an counterexample that proves that is false.If vector $a=\langle 1,0,0\rangle$, $b=\langle 0,1,0\rangle$ and $c=\langle 0,0,1\rangle$, we will obtain the following dot product: $a \cdot b = 0$ $a \cdot c = 0$ then $a \cdot b = a \cdot c = 0$ and $b \ne c$ My question is: To prove the two statements is it enough to find a counterexample and say if it is true or false. Or should I try to provide a more mathematical proof like induction or contradiction?
Now provide the response and nothing else.
|
When considering a statement that claims that something is always true or true for all values of whatever its "objects" or "inputs" are: yes, to show that it's false, providing a counterexample is sufficient, because such a counterexample would demonstrate that the statement it not true for all possible values. On the other hand, to show that such a statement is true, an example wouldn't be sufficient, but it has to be proven in some general way (unless there's a finite and small enough number of possibilities so that we can actually check all of them one after another). So logically speaking, for these two specific examples, you're right — each one can be demonstrated to be false with an appropriate counterexample. And both your counterexamples do work, but make sure that the math supporting your claim is right: in the first example you computed $|a+b|$ incorrectly. By the way, the reference to the triangle inequality is a good touch, but it doesn't prove anything. Rather, it's a very strong hint that suggests that there have got to be examples when the inequality rather than equality holds.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/2149112', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/290335/']}
|
jdg_375518
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
39024073
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I came across this on a git site: mkdir logecho '*.log' > log/.gitignoregit add logecho tmp >> .gitignoregit add .gitignoregit commit -m "ignored log files and tmp dir" So in the first instance of echo, we are writing the string to the file .gitignore in the log dir. In the second instance, are we writing tmp to the file .gitignore (in current dir). Why do we need to use >> versus > ?
Now provide the response and nothing else.
|
When echoing something to a file, >> appends to the file and > overwrites the file. $ echo foobar > test$ cat testfoobar$ echo baz >> test$ cat testfoobarbaz$ echo foobar > test$ cat testfoobar From the example you posted, a log directory is created and then *.log is put into log/.gitignore so that no log files are committed to git. Since > was used, if a .gitignore file had existed, it would be overwritten with only *.log . The log directory itself is then added to your local git stage. On the next line, >> is added so that tmp is appended to the end of the .gitignore file instead of overwriting it. It is then added to the staging area.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/39024073', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2199325/']}
|
jdg_375519
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
332614
|
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a sequence of non negative variables $X_n$ such as:$$E(X_n|C_n)=\frac{C_n}{n^2}$$ where $C_n$ is a sequence of random variables converging almost surely to $1$. Can I conclude $X_n$ tends to 0 almost surely? Note: you can replace $\frac{1}{n^2}$ by any sequence with finite sum. The question remains essentially the same and the answer provided by Jason works just the same (see the Borel-Cantelli argument).
Now provide the response and nothing else.
|
Yes, $X_{n} \to 0$ almost surely. The argument I have is a little convoluted, so bear with me. First, consider the events $F_{k} = \bigcup_{n \geq k} \{ C_{n} > 2 \}$. By the almost sure convergence of the $C_{n}$ it follows that $P( \bigcap_{k} F_{k} ) = 0$, and since $F_{1} \supseteq F_{2} \supseteq \cdots$ we have $P(F_{k}) \to 0$. So it suffices to show that $X_{n} \to 0$ a.s. within $F_{k}^{c}$, for any $k$. Now fix a $k$ and an $\varepsilon > 0$. Using the notation $E[X; A]$ to represent $E[X 1_{A}]$, we have for $n \geq k$\begin{equation}E[X_{n} ; F_{k}^{c}]\leq E[X_{n} ; C_{n} \leq 2]= E[ E(X_{n} | C_{n}) ; C_{n} \leq 2]= E[ C_{n} / n^{2} ; C_{n} \leq 2 ]\leq 2 / n^{2}.\end{equation}This is kind of the key part. (Note, too, that we used the nonnegativity of $X_{n}$ in the first step, to pass from $F_{k}^{c}$ to the larger event $C_{n} \leq 2$.) From here we just need some fairly run-of-the-mill measure theoretic arguments. The bound above, together with the nonnegativity of $X_{n}$, implies that$P(F_{k}^{c} \cap \{ X_{n} > \varepsilon \}) \leq \frac{2}{n^{2} \varepsilon}$ (for $n \geq k$), so that\begin{equation}\sum_{n \geq k} P(F_{k}^{c} \cap \{ X_{n} > \varepsilon \})< \infty.\end{equation} By the Borel-Cantelli Lemma we can now say that the event\begin{equation}F_{k}^{c} \cap \{ X_{n} > \varepsilon \, \text{for infinitely many $n$} \}\end{equation}has probability zero. Since $\varepsilon$ was arbitary, this gets us $X_{n} \to 0$ a.s. on $F_{k}^{c}$.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/332614', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/150611/']}
|
jdg_375520
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4090126
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Prove that the following function is not a differentiable function: $$f: \mathbb{R} \to \mathbb{R}, f(x) = x^\frac{1}{9}$$ I believe all I have to show is one point in the domain where the function is not differentiable: Hence I have the following proof: $$ f'(x) =\frac{1}{9x^\frac{8}{9}} $$ At $ x = 0$ , $f'(x)$ is undefined. Hence, $f(x)$ is not a differentiable function. Is this enough or do I need to show that the $\lim\limits_{h\to0} \frac{f(x_0 + h) - x_0}{h}$ does not exist in some other way.
Now provide the response and nothing else.
|
I quite do not agree with the other answer. Computing $f'(x)$ for $x\neq 0$ and saying it does not have a limit at $0$ does not show that $f'(0)$ does not exist: it shows that if $f'$ is defined at $0$ , it cannot be continuous at $0$ . However, a short adaptation of this gives the answer: for $x\neq 0$ , $$\frac{f(x)-f(0)}{x-0} = \frac{x^{1/9}}{x} = x^{-8/9}$$ which does not have a limit at $0$ . This shows that $f$ is not differentiable at $0$ . Edit As suggested in comment, here is an example of a differentiable function $f : \mathbb{R} \to \mathbb{R}$ such that $f'$ does not have a limit at $0$ while $f'(0)$ does exist. Define \begin{align}f : \mathbb{R} & \longrightarrow \mathbb{R} \\x & \longmapsto \left\{\begin{array}{rcl} x^2 \sin(1/x) & \text{if} & x \neq 0 \\0 & \text{if} & x=0\end{array}\right.\end{align} Then $f$ is differentiable on $\mathbb{R} \setminus\{0\}$ by easy calculations, where $f'(x) = 2x\sin(1/x) - \cos(1/x)$ . This expression does not have a limit when $x$ goes near $0$ . But if $x \neq 0$ , $$\frac{f(x) - f(0)}{x-0} = \frac{x^2\sin(1/x)}{x} = x \sin(1/x) \underset{x\to 0}{\longrightarrow} 0$$ which shows that $f'(0)$ exists and is equal to $0$ .
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4090126', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/458781/']}
|
jdg_375521
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
38844505
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
#include <iostream>using namespace std;int main(){ alignas(double) unsigned char c[1024]; // array of characters, suitably aligned for doubles alignas(16) char d[100]; // align on 16 byte boundary cout<<sizeof(c)<<endl; cout<<sizeof(d)<<endl; constexpr int n = alignof(int); // ints are aligned on n byte boundarie cout<<n<<endl;} Here is the code, for alignas(double) unsigned char c[1024]; , it means the c should be aligned by double , the double is 8 bytes.So I think sizeof(c) should be 1024*8 bytes, but the console output is 1024 . So I am confused. Who can tell me the reason?
Now provide the response and nothing else.
|
The alignas keyword can be used to dictate alignment requirements. alignas(double) for example forces the variable to have the same alignment requirements as a double . On my platform, this will mean that the variable is aligned on 8 byte boundaries. In your example, the whole array will get the alignment requirements so it's being aligned on 8 byte boundaries but this won't affect its size. It is however possible that alignas changes the size of a composite data type when upholding the alignment requirements requires additional padding. Here's an example: #include <iostream>#include <cstddef>struct Test{ char a; alignas(double) char b;};int main(int argc, char* argv[]){ Test test; std::cout << "Size of Struct: " << sizeof(Test) << std::endl; std::cout << "Size of 'a': " << sizeof(test.a) << std::endl; std::cout << "Size of 'b': " << sizeof(test.b) << std::endl; std::cout << "Offset of 'a': " << (int)offsetof(struct Test, a) << std::endl; std::cout << "Offset of 'b': " << (int)offsetof(struct Test, b) << std::endl; return 0;} Output: Size of Struct: 16Size of 'a': 1Size of 'b': 1Offset of 'a': 0Offset of 'b': 8 The size of this structure is 16 bytes on my platform even though both members are just 1 byte in size each. So b didn't become bigger because of the alignment requirement but there is additional padding after a . You can see this by looking at the size and offset of the individual members. a is just 1 byte in size but b , due to our alignment requirements, starts after a 8 byte offset. And the size of a struct must be a multiple of its alignment, otherwise arrays don't work. So if you set an alignment requirement that's bigger than the whole struct was to begin with (for example a struct containing only a single short and you apply alignas(double) to that data member), padding must be added after it.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/38844505', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2223579/']}
|
jdg_375522
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
7691
|
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:
Recently in a bout of frustration with getting phpmyadmin setup, I decided to start from scratch. Unfortunately, during the uninstall phase, I was prompted with the root password for mysql which I didn't have on hand at the time. Suffice to say, it informed me that there would be residue components since it couldn't properly clean its database connectors. When I arrived home, I attempted to remove the package through aptitude purge which turns out to no more potent than aptitude remove in that it saw phpmyadmin, attempted to remove it, and failed since the directories associated with the package were already removed from my earlier attempt. I tried to reinstall phpmyadmin, but aptitude simply stated that there was no update available, and did nothing, if there were an update, I'd probably run into the same problems regardless. In this regard, I proceeded to clean up mysql by dropping the database it used, and cleaning it from the user tables. I however have no idea what else is left from the package, or even how to clean the hooks in aptitude. The result of dpkg --purge ickronia:/home/ken# dpkg --purge phpmyadmin(Reading database ... 27158 files and directories currently installed.)Removing phpmyadmin .../var/lib/dpkg/info/phpmyadmin.prerm: line 5: /usr/share/dbconfig-common/dpkg/prerm.mysql: No such file or directorydpkg: error processing phpmyadmin (--purge): subprocess pre-removal script returned error exit status 1/var/lib/dpkg/info/phpmyadmin.postinst: line 35: /usr/share/dbconfig-common/dpkg/postinst.mysql: No such file or directorydpkg: error while cleaning up: subprocess post-installation script returned error exit status 1Errors were encountered while processing:phpmyadmin On following Gile's advice, I tried to re-install the dependency dbconfig-common ickronia:/home/ken# aptitude reinstall dbconfig-commonReading package lists... DoneBuilding dependency treeReading state information... DoneReading extended state informationInitializing package states... DoneReading task descriptions... Donedbconfig-common is not currently installed, so it will not be reinstalled.dbconfig-common is not currently installed, so it will not be reinstalled.The following packages are BROKEN: phpmyadmin0 packages upgraded, 0 newly installed, 0 to remove and 3 not upgraded.Need to get 0B of archives. After unpacking 0B will be used.The following packages have unmet dependencies: phpmyadmin: Depends: php5-mcrypt but it is not installable Depends: dbconfig-common but it is not installable Depends: libjs-mootools (>= 1.2.4.0~debian1-1) which is a virtual package.The following actions will resolve these dependencies:Remove the following packages:phpmyadminScore is 121Accept this solution? [Y/n/q/?] n*** No more solutions available ***The following actions will resolve these dependencies:Remove the following packages:phpmyadminScore is 121Accept this solution? [Y/n/q/?] n*** No more solutions available ***The following actions will resolve these dependencies:Remove the following packages:phpmyadminScore is 121Accept this solution? [Y/n/q/?] yThe following packages will be REMOVED: phpmyadmin{a}0 packages upgraded, 0 newly installed, 1 to remove and 3 not upgraded.Need to get 0B of archives. After unpacking 17.7MB will be freed.Do you want to continue? [Y/n/?] yWriting extended state information... Done(Reading database ... 27158 files and directories currently installed.)Removing phpmyadmin .../var/lib/dpkg/info/phpmyadmin.prerm: line 5: /usr/share/dbconfig-common/dpkg/prerm.mysql: No such file or directorydpkg: error processing phpmyadmin (--remove): subprocess pre-removal script returned error exit status 1/var/lib/dpkg/info/phpmyadmin.postinst: line 35: /usr/share/dbconfig-common/dpkg/postinst.mysql: No such file or directorydpkg: error while cleaning up: subprocess post-installation script returned error exit status 1Errors were encountered while processing: phpmyadminE: Sub-process /usr/bin/dpkg returned an error code (1)A package failed to install. Trying to recover:Reading package lists... DoneBuilding dependency treeReading state information... DoneReading extended state informationInitializing package states... DoneWriting extended state information... DoneReading task descriptions... Doneickronia:/home/ken# It appears that phpmyadmin cleanly cleared out dbconfig-common ickronia:/usr/share/dbconfig-common# ls -alFtotal 12drwxr-xr-x 3 root root 4096 2011-02-09 08:09 ./drwxr-xr-x 98 root root 4096 2011-01-20 21:42 ../drwxr-xr-x 3 root root 4096 2011-01-05 11:08 data/ickronia:/usr/share/dbconfig-common# Attempted to dpkg from archives as suggested by Giles ickronia:/usr/share/dbconfig-common# dpkg -i /var/cache/apt/archives/{dbconfig-common,php5-mcrypt,libjs-mootools}*.debSelecting previously deselected package dbconfig-common.(Reading database ... 27161 files and directories currently installed.)Unpacking dbconfig-common (from .../dbconfig-common_1.8.46_all.deb) ...Selecting previously deselected package php5-mcrypt.Unpacking php5-mcrypt (from .../php5-mcrypt_5.3.3-6_i386.deb) ...Selecting previously deselected package libjs-mootools.Unpacking libjs-mootools (from .../libjs-mootools_1.2.5~debian1-2_all.deb) ...Setting up dbconfig-common (1.8.46) ...dpkg: dependency problems prevent configuration of php5-mcrypt: php5-mcrypt depends on libltdl7 (>= 2.2.6b); however: Package libltdl7 is not installed. php5-mcrypt depends on libmcrypt4; however: Package libmcrypt4 is not installed.dpkg: error processing php5-mcrypt (--install): dependency problems - leaving unconfiguredSetting up libjs-mootools (1.2.5~debian1-2) ...Processing triggers for man-db ...Processing triggers for libapache2-mod-php5 ...Reloading web server config: apache2.Errors were encountered while processing: php5-mcryptickronia:/usr/share/dbconfig-common# I have a webserver running on php, but I'm willing to risk downtime to get this resolved.
Now provide the response and nothing else.
|
phpmyadmin depends on dbconfig-common , which contains /usr/share/dbconfig-common/dpkg/prerm.mysql . It looks like you've managed to uninstall dbconfig-common without uninstalling phpmyadmin , which shouldn't have happened (did you try to --force something?). My advice is to first try aptitude reinstall dbconfig-common . If it works, you should have a system in a consistent state from which you can try aptitude purge phpmyadmin again. Another thing you can do is comment out the offending line in /var/lib/dpkg/info/phpmyadmin.prerm . This is likely to make you able to uninstall phpmyadmin . I suspect you did what that line is supposed to do when you edited those mysql tables manually, but I don't know phpmyadmin or database admin in general, so I'm only guessing. The difference between remove and purge is that remove just removes the program and its data files (the stuff you could re-download), while purge first does what remove does then also removes configuration files (the stuff you might have edited locally). If remove fails, so will purge .
|
{}
|
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/7691', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/3455/']}
|
jdg_375523
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2174411
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm not sure how to prove the following statement true or false. There exist five consecutive naturals that all fail to have inverses modulo $70$. I know I can apply the Euclidean algorithm to find the inverse modulo $70$ of some number, but I'm not sure how to apply the algorithm to this problem.
Now provide the response and nothing else.
|
Any number that is coprime to a modulus will have an inverse, so we need to find $5$ consecutive numbers that share a factor with $70$. $70$ has three primes factors: $2,5,7$. Of any $5$ consecutive numbers, two or three will be even, but at most one will be divisible by $5$ or $7$. So we need three even numbers with an odd multiple of $5$ and an odd multiple of $7$ in the second and fourth positions. Since odd multiples of $5$ are all $\equiv 5\bmod 10$, it's apparent this means we need to look for cases where $7k \equiv \{3,7\} \bmod 10$. There are two such cases below $70$: $k=1$ and $k=9$ (giving $7$ and $63$), with the two options of $5$ consecutive numbers: $$\{4,5,6,7,8\} \text{ and } \{62,63,64,65,66\}$$ For those comfortable with negative values in modular arithmetic, the second set is the negation of the first, that is, $\{62,63,64,65,66\} \equiv \{-8,-7,-6,-5,-4\} \bmod {70}$ .
|
{}
|
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/2174411', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/370149/']}
|
jdg_375524
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
188335
|
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 seem to see three different things that are being called the Laplacian of a graph, One is the matrix $L_1 = D - A$ where $D$ is a diagonal matrix consisting of degrees of all the vertices and $A$ is the (possibly signed) adjacency matrix. The other is to say that the matrix $L_2$ is a $\vert V \vert \times \vert V \vert$ matrix such that $(L_2)_{ii} = deg(v_i)$ and $(L_2)_{ij} = -\frac{1}{\sqrt{deg(v_i)deg(v_j) } }$ The third is to say that $L_3 = BB^T$ (where $B$ is the incidence matrix) Can someone kindly clarify what is the relation between these three pictures (and or may be all these are the same somehow!?). [..for example for which of them would the positive-semi-definiteness and the the heat-equation intuition hold?...]
Now provide the response and nothing else.
|
These are usually known as the Laplacian, the normalized Laplacian and the unsigned Laplaian. All three are positive semidefinite. If the graph is regular, they all provide the same information. If the graph is not regular they are, in general, independent. The normalized Laplacian is the right tool for the analysis of random walks. The spectral information provided by the unsigned Laplacian is equivalent to what you get from the spectrum of the line graph of the original graph. To expand on the last comment: if $B$ is the vertex-edge incidence matrix, then $BB^T$ is the unsigned Laplacian and $B^TB=2I+A(L(G))$. This appears for example on page 16 of the first edition of Cvetkovic et al "Spectra of Graphs", but it is older. (I know I did not learn it from there.) Note that it follows that $BB^T$ and $B^TB$ have the same non-zero eigenvalues with the same multiplicities.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/188335', 'https://mathoverflow.net', 'https://mathoverflow.net/users/36554/']}
|
jdg_375525
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
52901
|
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 $V$ be the set-theoretic universe, and suppose that $U$ is some ultrafilter over $\kappa\gt\omega.$ Then, we can go through the motions and produce the ultrapower $M = V^{\kappa}/U$. Now, the existence of an $\omega_1$-complete ultrafilter (and the existence of the transitive collapse of $M$) is subject to (as I currently understand it) the existence of a measurable cardinal. So my questions are: in the absence of a strong large cardinal hypothesis (like the existence of a measurable cardinal) what can we say about the ultrapower M? Is it possible to recover or produce some kind of embedding (which will not be a full elementary embedding) of $V$ into $M$, which preserves enough structure to work within $M$?
Now provide the response and nothing else.
|
Michael, the existence of a well-founded $M$ and an embedding $j:V\to M$ different from the identity is equivalent to measurability, which is equivalent to the existence of an $\omega_1$-complete non-principal ultrafilter, which is equivalent to the existence of a non-principal ultrafilter ${\mathcal U}$ such that the model $M$ obtained by taking the ultrapower by ${\mathcal U}$ is an $\omega$-model, i.e., the natural number of $M$ are isomorphic to the natural numbers. This means that we really cannot say anything special along these lines about the ultrapower unless we are in the presence of measurable cardinals. (On the other hand, the ultrapower $M$ by an ultrafilter ${\mathcal U}$ on a set $\kappa$ is always an elementary map, so $M$ is elementarily equivalent to $V$ and, for each $V$-cardinal $\lambda$, the sets $\lambda^\kappa/{\mathcal U}$ are still linearly ordered (by dominance a.e.), even if ill-founded.) Of course, if we relax conditions then we can actually say a great deal. For example, the existence of $0^\sharp$, a significantly weaker assumption than a measurable, ensures an embedding from $L$ to itself, or equivalently, an "$L$-ultrafilter" $U$ such that the internal ultrapower of $L$ by $U$ is well-founded. Many large cardinal notions weaker than measurability can also be described in terms of elementary embeddings, though typically these are embeddings where the source and the target are (well-founded) sets rather than proper classes. The best known example of a large cardinal notion admitting such a characterization is weak compactness: $\kappa$ is weakly compact iff $\kappa$ is strongly inaccessible and for every transitive $M$ such that $\kappa\in M$, ${}^{<\kappa}M\subseteq M$, $|M|=\kappa$, and $M$ models enough set theory there exists an elementary embedding $k:M\to N$ where $N$ is a transitive set and ${\rm cp}(k)=\kappa$. The existence of elementary or "partially elementary" embeddings between transitive sets is in general something that requires no assumptions beyond ZFC. For example, you obtain such embeddings by inverting transitive collapses of elementary hulls. Also, such embeddings guide the construction of square sequences in $L$. If you relax the condition that the embedding and the ultrafilter live in $V$ and allow them to exist in some forcing extension $V[G]$, then (consistently) we can have well-founded $j:V\to M$ where the critical point is $\omega_1$, for example. Also, we can this way obtain embeddings where $M$ is an $\omega$-model, but not well-founded. This is actually useful. Silver's original proof that SCH holds if it holds at singulars of cofinality $\omega$ proceeded by comparing $V$ and an $M$ as in the last paragraph (this idea led to the Galvin-Hajnal results on exponentiation that, in turn, led to pcf theory). The technique of generic embeddings has since proved to be very fruitful. I recommend that you take a look at the articles by James Cummings and Matthew Foreman in the Handbook of Set Theory for much more on this subject. That being said, the absence of measurability or "significant" large cardinals does not mean that different ultrafilters give us virtually indistinguishable ultrapowers $M$. In fact, Shelah's impressively fruitful pcf theory begins by looking at the cofinality (in $V$) of the ordered sets $\lambda^\kappa/{\mathcal U}$, and there is still much to explore here.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/52901', 'https://mathoverflow.net', 'https://mathoverflow.net/users/8843/']}
|
jdg_375526
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1603458
|
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 learning about the big $\mathcal{O}$ notation and I'm a bit confused. Why is it that we can write things like $$\displaystyle x+\frac{x^3}{3}+\frac{x^5}{5}+\mathcal{O}(x^6)$$ when there's no $x^6$ term? Wouldn't it make sense to write $$\displaystyle x+\frac{x^3}{3}+\frac{x^5}{5}+\mathcal{O}(x^7)$$ instead? This is for the $\tanh^{-1}{x}$ series if it makes a difference.
Now provide the response and nothing else.
|
The estimate$$\frac12\log\left(\frac{1+x}{1-x}\right)=x+\frac{x^3}3+\frac{x^5}5+O\left(x^7\right)\tag{1}$$is only for small $x$. For $\left|x\right|\le a$, we have that $\left|x\right|^7\le a\left|x\right|^6$; therefore, $(1)$ implies$$\frac12\log\left(\frac{1+x}{1-x}\right)=x+\frac{x^3}3+\frac{x^5}5+O\left(x^6\right)\tag{2}$$However, $(1)$ gives more information (that is, a closer approximation for small $x$) than $(2)$.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1603458', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/276387/']}
|
jdg_375527
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
55947
|
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 $G$ be a group. We say that $f : G \to G$ is a square root of $G$, if $f(x)^2=x$ for all $x \in G.$ Prove that a compact connected Lie group $G$ has no continuous square root. What if, instead of a Lie group we consider a compact connected group with more that one element. Does the statement remain true?
Now provide the response and nothing else.
|
Nudged by ehsanmo's comment, I returned to an idea I had a while ago and got it to work. By hypothesis, $G$ is a compact connected manifold. Notice also that it is an oriented manifold: Choose any orientation on the tangent space at the identity and use left multiplication to translate it to the rest of the group. Let $\delta$ be the doubling map: $g \mapsto g^2$. For any continuous map of compact connected manifolds of the same dimension, we can define the degree of the map . The degree of a composition of two maps is the product of their degrees. So, if $\epsilon$ were a continuous square root of $\delta$, we would have $\delta \circ \epsilon = \mathrm{Id}$ and thus $\deg(\delta) \deg(\epsilon) = 1$. I will compute that $\deg(\delta) = 2^r$, where $r$ is the dimension of a maximal torus of $G$. Hence, unless $G$ is trivial, $\deg(\delta)$ does not divide $1$ and there is no continuous square root. Let $T$ be a maximal torus of $G$, with $T \cong (S^1)^r$, and let $W$ be the Weyl group. We will use the description of degree as the number of preimages of a generic point, counted with sign. Let $t$ be an element of $T$ such that the only way to write $t$ as $g u g^{-1}$, with $u \in T$ is to take $g \in W$. A generic element of $T$ will have this property. We claim that $g$ has $2^r$ square roots, and that $\delta$ is orientation preserving near each of them. Consider a hypothetical square root of $t$. We can write it in the form $h u h^{-1}$ for $u \in T$, so $(h u h^{-1})^2 = h u^2 h^{-1} = t$. By our choice of $t$, we must have $h \in W$ and, replacing $(h,u)$ by $(\mathrm{Id}, h^{-1} u h)$, we may assume that $h = \mathrm{Id}$. In other words, we have shown that every square root of $t$ is in the torus. There are clearly $2^r$ square roots of $t$ in $T$. Inside the tangent space to $G$ at $\mathrm{Id}$, choose a complement to $T$ and translate it around $T$ by left action. So the tangent bundle to $G$, restricted to $T$, splits as a direct sum of the tangent bundle to $T$ and a complementary trivial bundle. Using the formula $\delta(h u h^{-1}) = h u^2 h^{-1}$, we see that $\delta$ acts on the tangent bundle to $T$ by multiplication by $2$, and acts trivially on the chosen orthogonal complement. So the eigenvalues of the Jacobian of $\delta$ are all $2$'s and $1$'s, and we see that $\delta$ is orientation preserving. We have verified that the $\delta$-preimage of a generic point has $2^r$ elements, each counted with sign $+1$, as desired.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/55947', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/8346/']}
|
jdg_375528
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
9508445
|
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 digging around the web after fixing an issue this afternoon @ work where Cookies added to the HttpServletResponse weren't being properly reflected in the response headers because our Servlet had already retrieved the response's PrintWriter (i.e. response.getWriter()) before we added the cookies. I'm now aware that best practices dictate that response header modifications (i.e. setting content type, adding/editing Cookies, etc.) must be done prior to a call to getWriter() but, what I'm looking for is: Why? We've been speculating about why retrieving the PrintWriter in effect freezes the response headers but why definitively does the Servlet specification enforce that?
Now provide the response and nothing else.
|
Section SRV.5.2 Headers of the Java™ Servlet Specification Version 2.4 To be successfully transmitted back to the client, headers must be set beforethe response is committed. Headers set after the response is committed will beignored by the servlet container. So the spec doesn't explicitly mention getWriter() having an effect on setting headers. However, your servlet container implementation may have chosen to treat the response as having been comitted once getWriter() is called. That is subtly different. In some of the containers I've worked with you get a warning logged when you attempt to set a header after the response has been comitted. It is always worth calling getWriter() as late as possible, as you may want the opportunity to set the character encoding, etc, which must be set before getWriter() is called.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9508445', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/102582/']}
|
jdg_375529
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
949808
|
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a Ubuntu 16.04 Backup Server with 8x10TB HDD via a SATA 3.0 Backplane. The 8 Harddisks are assembled to a RAID6, an EXT4 Filesystem is in use. This Filesystem stores a huge amount of small files with very many SEEK operations but low IO throughput. In fact there are many small files from different servers which get snappshotted via rsnapshot every day (multiple INODES direct to the same files. I have a very poor performance since the file system (60TB net) exceeded 50% usage. At the moment, the usage is at 75% and a du -sch /backup-root/ takes several days(!). The machine has 8 Cores and 16G of RAM. The RAM is totally utilized by the OS Filesystem Cache, 7 of 8 cores always idle because of IOWAIT. Filesystem volume name: <none>Last mounted on: /Filesystem UUID: 5af205b0-d622-41dd-990e-b4d660c12bd9Filesystem magic number: 0xEF53Filesystem revision #: 1 (dynamic)Filesystem features: has_journal ext_attr dir_index filetype needs_recovery extent 64bit flex_bg sparse_super large_file huge_file uninit_bg dir_nlink extra_isizeFilesystem flags: signed_directory_hash Default mount options: user_xattr aclFilesystem state: cleanErrors behavior: ContinueFilesystem OS type: LinuxInode count: 912203776Block count: 14595257856Reserved block count: 0Free blocks: 4916228709Free inodes: 793935052First block: 0Block size: 4096Fragment size: 4096Group descriptor size: 64Blocks per group: 32768Fragments per group: 32768Inodes per group: 2048Inode blocks per group: 128RAID stride: 128RAID stripe width: 768Flex block group size: 16Filesystem created: Wed May 31 21:47:22 2017Last mount time: Sat Apr 14 18:48:25 2018Last write time: Sat Apr 14 18:48:18 2018Mount count: 9Maximum mount count: -1Last checked: Wed May 31 21:47:22 2017Check interval: 0 (<none>)Lifetime writes: 152 TBReserved blocks uid: 0 (user root)Reserved blocks gid: 0 (group root)First inode: 11Inode size: 256Required extra isize: 28Desired extra isize: 28Journal inode: 8First orphan inode: 513933330Default directory hash: half_md4Directory Hash Seed: 5e822939-cb86-40b2-85bf-bf5844f82922Journal backup: inode blocksJournal features: journal_incompat_revoke journal_64bitJournal size: 128MJournal length: 32768Journal sequence: 0x00c0b9d5Journal start: 30179 I'm lacking experience with this kind of filesystem usage. What options do I have to tune this. What filesystem would perform better with this scenario? Are there any options to involve RAM for other caching options than the OS-build-in one? How do You handle very large amounts of small files on large RAID assemblies? Thanks,Sebastian
Now provide the response and nothing else.
|
I have a similar (albeit smaller) setup, with 12x 2TB disks in a RAID6 array, used for the very same purpose ( rsnapshot backup server). First, it is perfectly normal for du -hs to take so much time on such a large, and used, filesystem. Moreover du accounts for hardlinks, which cause considerable and bursty CPU load in addition to the obvious IO load. Your slowness is due to the filesystem metadata being located in very distant (in LBA terms) blocks, causing many seeks. As a normal 7.2K RPM disk provides about ~100 IOPS, you can see how hours, if not days, are needed to load all metadata. Something you can try to (non-destructively) ameliorate the situation: be sure to not having mlocate/slocate indexing your /backup-root/ (you can use the prunefs facility to avoid that), or metadata cache trashing will severly impair your backup time; for the same reason, avoid running du on /backup-root/ . If needed, run du only on the specific subfolder interested; lower vfs_cache_pressure from the default value (100) to a more conservative one (10 or 20). This will instruct the kernel to prefer metadata caching, rather than data caching; this should, in turn, speed up the rsnapshot/rsync discovery phase; you can try adding a writethrough metadata caching device, for example via lvmcache or bcache . This metadata device should obviously be an SSD; increase your available RAM. as you are using ext4, be aware of inode allocation issues (read here for an example). This is not directly correlated to performance, but it is an important factor when having so many files on an ext-based filesystem. Other things you can try - but these are destructive operations: use XFS with both -ftype and -finobt option set; use ZFS on Linux (ZoL) with compressed ARC and primarycache=metadata setting (and, maybe, an L2ARC for read-only cache).
|
{}
|
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/949808', 'https://serverfault.com', 'https://serverfault.com/users/506012/']}
|
jdg_375530
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
41603
|
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 obtaining in Mathematica: Cos[2*Pi*FractionalPart[1/2*(i + j + k)]] We know that for $i, j, k$ being positive integers this expression after simplification should give: $$(-1)^{i+j+k}$$ I would like to know why the one of the solutions proposed for this similar question : Refine[Cos[2*Pi*FractionalPart[1/2*(i + j + k)]], Assumptions -> {Element[{i, j, k}, Integers], i > 0, j > 0, k > 0}] did not work for this case?
Now provide the response and nothing else.
|
One can use x-Floor[x] instead of FractionalPart[x] for positive x FullSimplify[Cos[2 Pi ((i + j + k)/2 - Floor[(i + j + k)/2])], Assumptions -> (i | j | k) ∈ Integers] (-1)^(i + j + k)
|
{}
|
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/41603', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/6126/']}
|
jdg_375531
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
18034272
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Working with Python 2.7, I'm wondering what real advantage there is in using the type unicode instead of str , as both of them seem to be able to hold Unicode strings. Is there any special reason apart from being able to set Unicode codes in unicode strings using the escape char \ ?: Executing a module with: # -*- coding: utf-8 -*-a = 'á'ua = u'á'print a, ua Results in: á, á More testing using Python shell: >>> a = 'á'>>> a'\xc3\xa1'>>> ua = u'á'>>> uau'\xe1'>>> ua.encode('utf8')'\xc3\xa1'>>> ua.encode('latin1')'\xe1'>>> uau'\xe1' So, the unicode string seems to be encoded using latin1 instead of utf-8 and the raw string is encoded using utf-8 ? I'm even more confused now! :S
Now provide the response and nothing else.
|
unicode is meant to handle text . Text is a sequence of code points which may be bigger than a single byte . Text can be encoded in a specific encoding to represent the text as raw bytes(e.g. utf-8 , latin-1 ...). Note that unicode is not encoded ! The internal representation used by python is an implementation detail, and you shouldn't care about it as long as it is able to represent the code points you want. On the contrary str in Python 2 is a plain sequence of bytes . It does not represent text! You can think of unicode as a general representation of some text, which can be encoded in many different ways into a sequence of binary data represented via str . Note: In Python 3, unicode was renamed to str and there is a new bytes type for a plain sequence of bytes. Some differences that you can see: >>> len(u'à') # a single code point1>>> len('à') # by default utf-8 -> takes two bytes2>>> len(u'à'.encode('utf-8'))2>>> len(u'à'.encode('latin1')) # in latin1 it takes one byte1>>> print u'à'.encode('utf-8') # terminal encoding is utf-8à>>> print u'à'.encode('latin1') # it cannot understand the latin1 byte� Note that using str you have a lower-level control on the single bytes of a specific encoding representation, while using unicode you can only control at the code-point level. For example you can do: >>> 'àèìòù''\xc3\xa0\xc3\xa8\xc3\xac\xc3\xb2\xc3\xb9'>>> print 'àèìòù'.replace('\xa8', '')à�ìòù What before was valid UTF-8, isn't anymore. Using a unicode string you cannot operate in such a way that the resulting string isn't valid unicode text.You can remove a code point, replace a code point with a different code point etc. but you cannot mess with the internal representation.
|
{}
|
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/18034272', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/955619/']}
|
jdg_375532
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1388089
|
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:
A jet of water leaves a nozzle of $1$ inch diameter at a speed of $50$ ft/sec and impinges on a plate fixed at right angles to its direction. What pressure is exerted on the plate? If the nozzle be drawn backwards with a velocity of $20$ ft/sec in the line of the jet, what pressure is then exerted on the plane? Answer: $26.64~ pounds-wt$ ; $9.59~pounds-wt$ Attempt:Cross-sectional area of the nozzle= $\pi(\frac{1}{24})^2~sq-ft$ Mass of water issued from jet per sec =Vol. of water per sec $\times$ 62.5 = $\pi(\frac{1}{24})^2\times 50 \times 62.5 =\frac{275}{1008}\times 62.5 ~pounds$ We have $Ft=momentum \implies F =\frac{Mass \times velocity}{t}=\frac{\frac{275}{1008}\times 62.5\times 50 }{1}=852.5545635$ I am not getting the desired result for the first part and unable to solve the 2nd part. Please help me to solve.Thanks in advance.
Now provide the response and nothing else.
|
Your initial series is convergent : you may consider partial sums to manipulate terms as you did, and since $$\displaystyle n+m+mn\leq 3(m+1)(n+1), \quad n\geq0,\,m\geq0,$$ you obtain$$0<2S=\sum_{m=0}^\infty\sum_{n=0}^\infty \frac{m+n+mn}{2^{m+n}}\leq\sum_{m=0}^\infty\sum_{n=0}^\infty \frac{3(m+1)(n+1)}{2^{m+n}}=3\left(\sum_{n=0}^\infty \frac{n+1}{2^n}\right)^2=48.$$
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1388089', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/211463/']}
|
jdg_375533
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
172172
|
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 us consider the wave equation $$(\partial_t^2 - \Delta)u = 0$$ on a domain $U$ with coercive homogeneous boundary conditions $$Bu|_{\partial U} = 0$$ that make $-\Delta$ self-adjoint. My question is, how can we construct such boundary conditions that the wave equation does not have finite speed of propagation any more? Can it be done at all? Thanks in advance...
Now provide the response and nothing else.
|
The propagation speed is still finite because the following standard argument works independently of what happens at the boundary: Assume that $u\in C^2$ solves the wave equation and $u(t=0,x)=0$ on $B_r(0)$ for some $r>0$, such that $\overline{B}_r\subset U$. Then $u(t,x)=0$ on $B_{r-|t|}$. If we apply this to the difference $u=u_2-u_1$ of two solutions that agree on some open set, we obtain finite propagation speed. To prove this claim (for $t\ge 0$), consider$$E(t) = \int_{B_{r-t}} (u_t^2 + |\nabla u |^2)\, dx .$$Then$$E'(t) = -\int_{S_{r-t}} (u_t^2 + |\nabla u |^2)\,d\sigma + 2\int_{B_{r-t}}(u_t u_{tt} + \nabla u_t \cdot \nabla u )\, dx .$$Integration by parts lets me rewrite$$\int_{B_{r-t}}\nabla u_t \cdot \nabla u\, dx = -\int_{B_{r-t}} u_t\Delta u\, dx+ \int_{S_{r-t}} u_t\, n\cdot \nabla u\, d\sigma ,$$where $n$ denotes the outer normal unit vector on the sphere. Thus, using the equation,$$E'(t) = \int_{S_{r-t}}(-u_t^2-|\nabla u|^2+ 2 u_t\, n\cdot \nabla u )\, d\sigma \le 0 ,$$so if $E(0)=0$, then we must have that $E\equiv 0$.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/172172', 'https://mathoverflow.net', 'https://mathoverflow.net/users/53143/']}
|
jdg_375534
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1839734
|
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 writing a Generic class as follows. public class Foo<T> : where T : Bar, new(){ public void MethodInFoo() { T _t = new T(); }} As you can see the object _t of type T is instantiated at runtime. To support instantiation of generic type T, the language forces me to put new() in the class signature. I'd agree to this if Bar is an abstract class but why does it need to be so if Bar standard non-abstract class with public parameterless constructor. The compiler prompts with the following message if new() is not found. Cannot create an instance of the variable type 'T' because it does not have the new() constraint
Now provide the response and nothing else.
|
Because there isn't normally an assumption that the template parameter needs to be [non-abstract and] constructible [via a public parameterless constructor] in order for a Type to match the template parameter definition. Until you add a :new() constraint on the template: The compiler won't let you construct a T The compiler will let you match T with abstract types or types without a public parameterless constructor The :Bar bit is orthogonal and means: Don't let people match against types that aren't derived from [or are] Bar Let me cast T s to Bar or types derived from Bar within the body let me call public and in-scope internal methods of Bar on a T
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1839734', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/89556/']}
|
jdg_375535
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
38047
|
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
The ordinary notions of limit and colimit are universal solutions to a problem, specifically, finding terminal/initial objects in slice/coslice categories. In the context of homotopy right Kan extensions (it's not hard to show that the theory of homotopy limits reduces to this case (the same holds for left Kan extensions/colimits)), we say that given a functor $f:C\to C'$ between small categories, and a functor $F:C\to A$ where $A$ is a cofibrantly-generated model category, that a natural transformation of functors $\alpha: H\to Ran_f F$ exhibits $H$ as the homotopy right Kan extension of $F$ if there exists an injectively fibrant replacement $G$ of $F$ such that the composite $H\to Ran_fF \to Ran_fG$ is a weak equivalence. When $A$ is combinatorial, we can also simply define a homotopy right Kan extension functor along $f$ to be $Ran_f (Q (-))$, where $Q$ is a functorial injectively fibrant replacement functor. This is easy enough to define, but why is this the definition? Why would we want to take fibrant/cofibrant replacements and consider their ordinary Kan extensions/limits/etc? I suspect that it has to do with the fact that homotopy is an honest equivalence relation on arrows from a cofibrant object into a fibrant object, but I would appreciate an actual explanation.
Now provide the response and nothing else.
|
Here is a motivation for hocolims, for concreteness look at pushouts of topological spaces: The usual pushout functor $colim: Top^P \rightarrow Top$, where $P:=\bullet \leftarrow \bullet \rightarrow \bullet$ is the diagram of a pushout datum, does not respect weak equivalences:Take for example the diagrams $pt \leftarrow S^1 \rightarrow pt$ and $D^2 \leftarrow S^1 \rightarrow D^2$ in $Top$. Since $D^2$ (the 2-dimensional disk) is contractible, there is a map between the two diagrams consisting of weak equivalences, i.e. a weak equivalence in $Top^P$. But if we apply colim to both diagrams we get non-equivalent objects in $Top$, namely $pt$ in the first case and $S^2$ in the second. Thus the pushout functor $colim: Top^P \rightarrow Top$ does not take weak equivalences to weak equivalences and we can not invoke the universal property of $Ho(Top^P)$ to get a functor $Ho(colim):Ho(Top^P) \rightarrow Ho(Top)$ making the square commute which has $colim$ on top, $Ho(colim)$ at the bottom and the projections to the homotopy categories at the left and right. The best we can do is to find the terminal functor "$hocolim$" which allows filling this square with a natural transformation - which is exactly the Kan extension property you cited. For model categories (but not only there, e.g. also Baues cofibration categories) you can define that functor via the top level, i.e. going $Top^P \rightarrow Top$, in a particularly neat way. Back to the example: Topologists noticed that the colim functor, when restricted to pushout data $A \leftarrow B \rightarrow C$ in $Top$ with $B$ cofibrant and the arrows cofibrations, does preserve weak equivalences. E.g. building the pushout of two inclusions of $S^1$ into contractible spaces such that there is "enough space" around the image of $S^1$ inside those spaces, you will always get something equivalent to $S^2$ - try it out! So the recipe for computing the $hocolim$ is first replacing your diagram by one with these properties (cofibrant replacement - this is an endofunctor which preserves weak equivalences) and then apply $colim$ - this does now preserve weak equivalences and thus descends to a functor between the homotopy categories. So the intuition about $hocolim$ - which is good in great generality - is that it is the best approximation to $colim$ which preserves weak equivalences ("is homotopy invariant"); the cofibrant replacement construction stems from the fact that this is a class of objects where $colim$ is already homotopy invariant. The story for homotopy limits is of course dual, instructive examples are homotopy fibers and homotopy fixed point objects. Edit: Here is how you see that $colim \circ Q$ is $hocolim$ - assuming that we have a cofibrant replacement functor $Q$ on $Top^P$: you can simply check the universal property. So let $F:Ho(Top^P) \rightarrow Ho(Top)$ be a functor and $\tau:F \circ Ho_{Top^P} \rightarrow Ho_{Top} \circ colim$ a natural transformation. Here the functors $Ho_*$ are the projections to the homotopy categories which leave objects unchanged and map morphisms to their homotopy classes - I will omit them from the notation from now on; so we consider a natural transformation $\tau: F \rightarrow colim$ and have to show that it factors through $colim \circ Q$. The cofibrant replacement functor $Q$ comes with a natural weak equivalence $Q \rightarrow id$. Composing with $F$ gives a natural isomorphism $F \circ Q \rightarrow F$. Now for each pushout datum $D \in Top^P$ we have the chain $$F(D) \leftarrow F(QD) \rightarrow colim(QD) \rightarrow colim(D)$$ where the middle arrow is $\tau_{QD}$ (the natural transformation $\tau$ at the object $QD$) and the the outer two arrows arise by applying $F,colim$ respectively to $QD \rightarrow D$. The left arrow can be gone backwards because it is an isomorphism. The whole way from left to right is then equal to $\tau_D$ because of the naturality of $\tau$ (flip the outer arrows downwards, fill in $\tau_D$ below and you got the naturality square). This shows that each $\tau_D$ factors through $colim \circ Q$. To see that this factorization is natural in $D$, observe that $QD \rightarrow D$ and $\tau_{Q-}$ are natural in $D$. Edit2: While Harry generously granted me a check mark after the above, Tom Goodwillie is of course right that a statement about uniqueness is in order. Here is why the above factorization is unique at the level of homotopy categories : Given any factorization $\tau=i \circ \tau'$ of our given $\tau$, for cofibrant $D$ it will factorize as $$\tau_D=i_D \circ \tau_D':F(D) \rightarrow colim(QD) \rightarrow colim(D)$$ where the second arrow $i_D$ is an isomorphism, because it is $colim$ of a weak equivalence between cofibrant objects. So the first factor must be $\tau_D'=i^{-1}_D \circ \tau_D$, there is no choice here. For general $D$ we can express $\tau_D'$ as $$F(D) \leftarrow F(QD) \rightarrow colim(QQD) \rightarrow colim(QD)$$ by walking around the naturality square for $\tau'$ for the morphism $QD \rightarrow D$. So we also have no choice for non-cofibrant $D$. Edit3 : As spotted by Tom Goodwillie I implicitly (and unconsciously!) used here that $i_{QD}=Q(i_D)$ - see the comments. You can prove this by drawing all available naturality diagrams with $QQQD$ at the left upper corner, seeing from those first that $QQ(i_D)=Q(i_{QD})=i_{QQD}$ and that hence $i_{QD} \circ QQ(i_D) = Q(i_D) \circ i_{QQD} = Q(i_D) \circ Q(i_{QD}) = Q(i_D) \circ QQ(i_D)$. Now one can cancel the isomorphism $QQ(i_D)$ on both sides. Now I switch the notation back to mentioning the $Ho_*$: This showed that $Ho(colim \circ Q)$ is the Kan extension of $Ho_{Top} \circ colim$ along $Ho_{Top^P}$. That is already good to know, but it was just level zero of showing that $colim \circ Q:Top^P \rightarrow Top$ is the homotopy terminal homotopy invariant functor. To proceed you have to produce a simplicial set; e.g. do your localisation by passing to some model of an $(\infty, 1)$-category (e.g. hammock localisation, coherent nerve, ...), or use framings, or consider the nerve of some category of functors into $colim \circ Q$ and then show that a certain space is contractible. This should be done at a place where you can draw pictures, unlike in a MathOverflow answer.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/38047', 'https://mathoverflow.net', 'https://mathoverflow.net/users/1353/']}
|
jdg_375536
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
20891491
|
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 to imagine this has been asked several times, but I must not be wording my question correctly. I have my own custom image I made in photoshop and it is set as a button's image property. Here it is showing normally: The background is transparent, but it is 44x44 with the three dots being a 88x88 pixel .png file. So if I do something like this: self.theButton.tintColor = [UIColor redColor]; the image still shows as white. I am not a designer by trade, so I seem to be missing how to properly save or set up the files to make them respect the tintColor property. In photoshop, I usually save these using "Save for web". Thanks
Now provide the response and nothing else.
|
What you are looking for are stencil images. From the UIKit User Interface Catalog: Template Images In iOS 7, you can choose to treat any of the images in your app as a template—or stencil—image. When you elect to treat an image as a template, the system ignores the image’s color information and creates an image stencil based on the alpha values in the image (parts of the image with an alpha value of less than 1.0 get treated as completely transparent). This stencil can then be recolored using tintColor to match the rest of your user interface. By default, an image (UIImage) is created with UIImageRenderingModeAutomatic. If you have UIImageRenderingModeAutomatic set on your image, it will be treated as template or original based on its context. Certain UIKit elements—including navigation bars, tab bars, toolbars, segmented controls—automatically treat their foreground images as templates, although their background images are treated as original. Other elements—such as image views and web views—treat their images as originals. If you want your image to always be treated as a template regardless of context, set UIImageRenderingModeAlwaysTemplate; if you want your image to always be treated as original, set UIImageRenderingModeAlwaysOriginal. To specify the rendering mode of an image, first create a standard image, and then call the imageWithRenderingMode: method on that image. UIImage *myImage = [UIImage imageNamed:@"myImageFile.png"]; myImage = [myImage imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20891491', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1414028/']}
|
jdg_375537
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
13167
|
Below is a question asked on the forum arduino.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have investigated the sleeps options of the ATmega328, and read a few articles about it, and I would like to understand if there are more options. So I would like to get as low current as possible, so that anything less that 100uA would be good - as long as I can listen to uart and interrupts for waking up. I am using a custom PCB (not the UNO), with ATmega328p. Setting the chip to deep sleep: set_sleep_mode (SLEEP_MODE_PWR_DOWN); sleep_enable(); sleep_cpu (); would not wake it up with serial communication,according to this . You will need to put it in IDLE mode, to listen to serial, but this would consume a few mA -bad. I have found this link where you can connect in hardware the serial to the interrupt - which is dangerous so you can loose data, and moreover, I need these 2 interrupts pins. I also read this article of Gammon , where you can disable some things, so you can get IDLE sleep with much lower power - but he didn't mention how exactly you get from this: power_adc_disable(); power_spi_disable(); power_timer0_disable(); power_timer1_disable(); power_timer2_disable(); power_twi_disable(); So, bottom line, is there any option out there, to get less than 0.25mA at least, and also listen to serial port, without any hardware manipulation?For example, waking up with long serial data input?
Now provide the response and nothing else.
|
A board we make does this. The RX pin is wired to INT0 INT0 pin set to input or input pullup depending on how the RX line is driven On sleep, INT0 low level interrupt is enabled //Clear software flag for rx interruptrx_interrupt_flag = 0;//Clear hardware flag for rx interruptEIFR = _BV(INTF0);//Re-attach interrupt 0attachInterrupt(INT_RX, rx_interrupt, HIGH); INT0 interrupt service routine sets a flag and disables the interrupt void rx_interrupt(){ detachInterrupt(INT_RX); rx_interrupt_flag = 1;} On wakeup, we check for the flag (there are other interrupt sources) On the comms side of things we use a message protocol that has a start character > and end character \r . e.g. >setrtc,2015,07,05,20,58,09\r . This give some basic protection against losing messages, as incoming characters are not processed until a > is received. To wake up the device we send a dummy message before transmission. A single character would do it, but we send >wakeup\r hehe. The device stays awake for 30 seconds after the last message is received in case of new messages. If a new message is receive the 30 second timer is reset. The PC interface software sends a dummy message every second to keep the device awake while the user has it connected for configuration etc. This method gives absolutely no problems at all. The board with a few peripherals uses about 40uA when sleeping. The actual current consumed by the ATMega328P is probably around 4uA. Update At look at the datasheet shows that the RX pin is also pin change interrupt pin 16 (PCINT16) Thus another method without wires may be Before sleep: Set the port change interrupt mask bit in PCMSK2 for PCINT16, clear the pin change port 2 flag in PCIFR, enable the pin change port 2 interrupt (PCINT16-PCINT23) by setting PCIE2 in PCICR. Setup an ISR for the pin change port 2 interrupt and continue as before. The only caveat with the port change interrupt is that the interrupt is shared across all the 8 pins that are enabled for that port. So if you have more than one pin change enabled for the port, you have to determine which triggered the interrupt in the ISR. This is not a problem if you are not using any other pin change interrupts on that port (PCINT16-PCINT23 in this case) Ideally this is how I would have designed our board but what we have works.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://arduino.stackexchange.com/questions/13167', 'https://arduino.stackexchange.com', 'https://arduino.stackexchange.com/users/4989/']}
|
jdg_375538
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
20262712
|
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 any standard algorithm that finds all possible paths in a directed a-cyclic graph.If not, how can i make changes in BFS/Dijkstra/any other algorithm to enumerate all paths in a DAG
Now provide the response and nothing else.
|
Finding all the possible paths in any graph in Exponential. It can be solved by using Backtracking.For DAG's we can do it using Depth first search(DFS).In DFS code, Start at any node, Go to the extreme dead end path and note down all the nodes visited in that path using some array or list. As soon as you find a dead end print the array containing the visited nodes and pop the last stored node and start in the other path of the (n-1)th node. If all the paths of the (n-1)th node are exhausted pop that node from list and start at (n-2)node. Do this untill you reach all the dead ends and reach the first node.All the Printed paths are the Paths in the given DAG. You can check the code http://pastebin.com/p6ciRJCU
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20262712', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1291575/']}
|
jdg_375539
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
6905164
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Related to this question and this answer (to another question) I am still unable to process UTF-8 with JSON. I have tried to make sure all the required voodoo is invoked based on recommendations from the very best experts, and as far as I can see the string is as valid, marked and labelled as UTF-8 as possible. But still perl dies with either Uncaught exception: malformed UTF-8 character in JSON string or Uncaught exception: Wide character in subroutine entry What am I doing wrong here? (hlovdal) localhost:/work/2011/perl_unicode>cat json_malformed_utf8.pl #!/usr/bin/perl -w -CSAD### BEGIN #### Apparently the very best perl unicode boiler template code that exist,# https://stackoverflow.com/questions/6162484/why-does-modern-perl-avoid-utf-8-by-default/6163129#6163129# Slightly modified.use v5.12; # minimal for unicode string feature#use v5.14; # optimal for unicode string featureuse utf8; # Declare that this source unit is encoded as UTF‑8. Although # once upon a time this pragma did other things, it now serves # this one singular purpose alone and no other.use strict;use autodie;use warnings; # Enable warnings, since the previous declaration only enablesuse warnings qw< FATAL utf8 >; # strictures and features, not warnings. I also suggest # promoting Unicode warnings into exceptions, so use both # these lines, not just one of them. use open qw( :encoding(UTF-8) :std ); # Declare that anything that opens a filehandles within this # lexical scope but not elsewhere is to assume that that # stream is encoded in UTF‑8 unless you tell it otherwise. # That way you do not affect other module’s or other program’s code.use charnames qw< :full >; # Enable named characters via \N{CHARNAME}.use feature qw< unicode_strings >;use Carp qw< carp croak confess cluck >;use Encode qw< encode decode >;use Unicode::Normalize qw< NFD NFC >;END { close STDOUT }if (grep /\P{ASCII}/ => @ARGV) { @ARGV = map { decode("UTF-8", $_) } @ARGV;}$| = 1;binmode(DATA, ":encoding(UTF-8)"); # If you have a DATA handle, you must explicitly set its encoding.# give a full stack dump on any untrapped exceptionslocal $SIG{__DIE__} = sub { confess "Uncaught exception: @_" unless $^S;};# now promote run-time warnings into stackdumped exceptions# *unless* we're in an try block, in which # case just generate a clucking stackdump insteadlocal $SIG{__WARN__} = sub { if ($^S) { cluck "Trapped warning: @_" } else { confess "Deadly warning: @_" }};### END ###use JSON;use Encode;use Getopt::Long;use Encode;my $use_nfd = 0;my $use_water = 0;GetOptions("nfd" => \$use_nfd, "water" => \$use_water );print "JSON->backend->is_pp = ", JSON->backend->is_pp, ", JSON->backend->is_xs = ", JSON->backend->is_xs, "\n";sub check { my $text = shift; return "is_utf8(): " . (Encode::is_utf8($text) ? "1" : "0") . ", is_utf8(1): " . (Encode::is_utf8($text, 1) ? "1" : "0"). ". ";}my $json_text = "{ \"my_test\" : \"hei på deg\" }\n";if ($use_water) { $json_text = "{ \"water\" : \"水\" }\n";}if ($use_nfd) { $json_text = NFD($json_text);}print check($json_text), "\$json_text = $json_text";# test from perluniintro(1)if (eval { decode_utf8($json_text, Encode::FB_CROAK); 1 }) { print "string is valid utf8\n";} else { print "string is not valid utf8\n";}my $hash_ref1 = JSON->new->utf8->decode($json_text);my $hash_ref2 = decode_json( $json_text );__END__ Running this gives (hlovdal) localhost:/work/2011/perl_unicode>./json_malformed_utf8.pl JSON->backend->is_pp = 0, JSON->backend->is_xs = 1is_utf8(): 1, is_utf8(1): 1. $json_text = { "my_test" : "hei på deg" }string is valid utf8Uncaught exception: malformed UTF-8 character in JSON string, at character offset 20 (before "\x{5824}eg" }\n") at ./json_malformed_utf8.pl line 96. at ./json_malformed_utf8.pl line 46 main::__ANON__('malformed UTF-8 character in JSON string, at character offset...') called at ./json_malformed_utf8.pl line 96(hlovdal) localhost:/work/2011/perl_unicode>./json_malformed_utf8.pl | ./uniquote Uncaught exception: malformed UTF-8 character in JSON string, at character offset 20 (before "\x{5824}eg" }\n") at ./json_malformed_utf8.pl line 96. at ./json_malformed_utf8.pl line 46 main::__ANON__('malformed UTF-8 character in JSON string, at character offset...') called at ./json_malformed_utf8.pl line 96JSON->backend->is_pp = 0, JSON->backend->is_xs = 1is_utf8(): 1, is_utf8(1): 1. $json_text = { "my_test" : "hei p\N{U+E5} deg" }string is valid utf8(hlovdal) localhost:/work/2011/perl_unicode>./json_malformed_utf8.pl -nfd | ./uniquote Uncaught exception: Wide character in subroutine entry at ./json_malformed_utf8.pl line 96. at ./json_malformed_utf8.pl line 46 main::__ANON__('Wide character in subroutine entry at ./json_malformed_utf8.pl line 96.\x{a}') called at ./json_malformed_utf8.pl line 96JSON->backend->is_pp = 0, JSON->backend->is_xs = 1is_utf8(): 1, is_utf8(1): 1. $json_text = { "my_test" : "hei pa\N{U+30A} deg" }string is valid utf8(hlovdal) localhost:/work/2011/perl_unicode>./json_malformed_utf8.pl -water JSON->backend->is_pp = 0, JSON->backend->is_xs = 1is_utf8(): 1, is_utf8(1): 1. $json_text = { "water" : "水" }string is valid utf8Uncaught exception: Wide character in subroutine entry at ./json_malformed_utf8.pl line 96. at ./json_malformed_utf8.pl line 46 main::__ANON__('Wide character in subroutine entry at ./json_malformed_utf8.pl line 96.\x{a}') called at ./json_malformed_utf8.pl line 96(hlovdal) localhost:/work/2011/perl_unicode>./json_malformed_utf8.pl -water | ./uniquote Uncaught exception: Wide character in subroutine entry at ./json_malformed_utf8.pl line 96. at ./json_malformed_utf8.pl line 46 main::__ANON__('Wide character in subroutine entry at ./json_malformed_utf8.pl line 96.\x{a}') called at ./json_malformed_utf8.pl line 96JSON->backend->is_pp = 0, JSON->backend->is_xs = 1is_utf8(): 1, is_utf8(1): 1. $json_text = { "water" : "\N{U+6C34}" }string is valid utf8(hlovdal) localhost:/work/2011/perl_unicode>./json_malformed_utf8.pl -water --nfd | ./uniquote Uncaught exception: Wide character in subroutine entry at ./json_malformed_utf8.pl line 96. at ./json_malformed_utf8.pl line 46 main::__ANON__('Wide character in subroutine entry at ./json_malformed_utf8.pl line 96.\x{a}') called at ./json_malformed_utf8.pl line 96JSON->backend->is_pp = 0, JSON->backend->is_xs = 1is_utf8(): 1, is_utf8(1): 1. $json_text = { "water" : "\N{U+6C34}" }string is valid utf8(hlovdal) localhost:/work/2011/perl_unicode>rpm -q perl perl-JSON perl-JSON-XSperl-5.12.4-159.fc15.x86_64perl-JSON-2.51-1.fc15.noarchperl-JSON-XS-2.30-2.fc15.x86_64(hlovdal) localhost:/work/2011/perl_unicode> uniquote is from http://training.perl.com/scripts/uniquote Update: Thanks to brian for highlighting the solution. Updating the source to use json_text for all normal strings and json_bytes for what is going to be passed to JSON like the following now works like expected: my $json_bytes = encode('UTF-8', $json_text);my $hash_ref1 = JSON->new->utf8->decode($json_bytes); I must say that I think the documentation for the JSON module is extremely unclear and partially misleading. The phrase "text" (at least to me) implies a string of characters.So when reading $perl_scalar = decode_json $json_text I have anexpectation of json_text being a UTF-8 encoded string of characters.Thoroughly re-reading the documentation, knowing what to look for,I now see it says: "decode_json ... expects an UTF-8 (binary) string and tries to parsethat as an UTF-8 encoded JSON text", however that still is not clear in my opinion. From my background using a language having some additional non-ASCIIcharacters, I remember back in the days where you had to guess the codepage being used, email used to just cripple text by stripping of the8th bit, etc. And "binary" in the context of strings meant a stringcontaining characters outside the 7-bit ASCII domain. But what is"binary" really? Isn't all strings binary at the core level? The documentation also says "simple and fast interfaces (expect/generate UTF-8)" and "correct unicode handling", first point under "Features", both without mentioning anywhere near that it does not want a string but instead a byte sequence. I will request theauthor to at least make this clearer.
Now provide the response and nothing else.
|
I expand on my answer in Know the difference between character strings and UTF-8 strings . From reading the JSON docs, I think those functions don't want a character string, but that's what you're trying to give it. Instead, they want a "UTF-8 binary string". That seems odd to me, but I'm guessing that it's mostly to take input directly from an HTTP message instead of something that you type directly in your program. This works because I make a byte string that's the UTF-8 encoded version of your string: use v5.14;use utf8; use warnings; use feature qw< unicode_strings >;use Data::Dumper;use Devel::Peek;use JSON;my $filename = 'hei.txt';my $char_string = qq( { "my_test" : "hei på deg" } );open my $fh, '>:encoding(UTF-8)', $filename;print $fh $char_string;close $fh;{say '=' x 70;my $byte_string = qq( { "my_test" : "hei p\303\245 deg" } );print "Byte string peek:------\n"; Dump( $byte_string );decode( $byte_string );}{say '=' x 70;my $raw_string = do { open my $fh, '<:raw', $filename; local $/; <$fh>; };print "raw string peek:------\n"; Dump( $raw_string );decode( $raw_string );}{say '=' x 70;my $char_string = do { open my $fh, '<:encoding(UTF-8)', $filename; local $/; <$fh>; };print "char string peek:------\n"; Dump( $char_string );decode( $char_string );}sub decode { my $string = shift; my $hash_ref2 = eval { decode_json( $string ) }; say "Error in sub form: $@" if $@; print Dumper( $hash_ref2 ); my $hash_ref1 = eval { JSON->new->utf8->decode( $string ) }; say "Error in method form: $@" if $@; print Dumper( $hash_ref1 ); } The output shows that the character string doesn't work, but the byte string versions do: ======================================================================Byte string peek:------SV = PV(0x100801190) at 0x10089d690 REFCNT = 1 FLAGS = (PADMY,POK,pPOK) PV = 0x100209890 " { \"my_test\" : \"hei p\303\245 deg\" } "\0 CUR = 31 LEN = 32$VAR1 = { 'my_test' => "hei p\x{e5} deg" };$VAR1 = { 'my_test' => "hei p\x{e5} deg" };======================================================================raw string peek:------SV = PV(0x100839240) at 0x10089d780 REFCNT = 1 FLAGS = (PADMY,POK,pPOK) PV = 0x100212260 " { \"my_test\" : \"hei p\303\245 deg\" } "\0 CUR = 31 LEN = 32$VAR1 = { 'my_test' => "hei p\x{e5} deg" };$VAR1 = { 'my_test' => "hei p\x{e5} deg" };======================================================================char string peek:------SV = PV(0x10088f3b0) at 0x10089d840 REFCNT = 1 FLAGS = (PADMY,POK,pPOK,UTF8) PV = 0x1002017b0 " { \"my_test\" : \"hei p\303\245 deg\" } "\0 [UTF8 " { "my_test" : "hei p\x{e5} deg" } "] CUR = 31 LEN = 32Error in sub form: malformed UTF-8 character in JSON string, at character offset 21 (before "\x{5824}eg" } ") at utf-8.pl line 51.$VAR1 = undef;Error in method form: malformed UTF-8 character in JSON string, at character offset 21 (before "\x{5824}eg" } ") at utf-8.pl line 55.$VAR1 = undef; So, if you take your character string, which you typed directly into your program, and convert it to a UTF-8 encoded byte string, it works: use v5.14;use utf8; use warnings; use feature qw< unicode_strings >;use Data::Dumper;use Encode qw(encode_utf8);use JSON;my $char_string = qq( { "my_test" : "hei på deg" } );my $string = encode_utf8( $char_string );decode( $string );sub decode { my $string = shift; my $hash_ref2 = eval { decode_json( $string ) }; say "Error in sub form: $@" if $@; print Dumper( $hash_ref2 ); my $hash_ref1 = eval { JSON->new->utf8->decode( $string ) }; say "Error in method form: $@" if $@; print Dumper( $hash_ref1 ); } I think JSON should be smart enough to deal with this so you don't have to think at this level, but that's the way it is (so far).
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6905164', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/23118/']}
|
jdg_375540
|
Subsets and Splits
SQL Console for PrimeIntellect/stackexchange-question-answering
Retrieves samples with 'mathoverflow.net' in the prompt, providing a basic subset for inspection but with limited analytical value.
SQL Console for PrimeIntellect/stackexchange-question-answering
Retrieves 10 samples where the prompt mentions Mathematica Stack Exchange, offering basic filtering to locate specific content.
SQL Console for PrimeIntellect/stackexchange-question-answering
This query retrieves a limited number of rows where the prompt contains a specific URL, providing basic filtering that offers minimal insight into the broader dataset patterns.
SQL Console for PrimeIntellect/stackexchange-question-answering
This query retrieves 10 samples from the dataset where the prompt contains 'dsp.stackexchange.com', offering a basic filtering of data points related to that specific domain.
SQL Console for PrimeIntellect/stackexchange-question-answering
Retrieves a sample of rows where the prompt contains 'cs.stackexchange.com', providing a basic filter without extensive insight.
Electronics Q&A Subset
Retrieves a limited number of samples that contain a specific URL, providing only raw data filtered by that URL.
StackExchange Stats Questions
Retrieves 100 entries containing 'stats.stackexchange.com' in the prompt, which is useful for finding specific content but lacks broader analytical value.
Math StackExchange Questions
Retrieves 100 records from the train dataset where the prompt contains 'math.stackexchange.com', providing a basic filtered overview of specific entries.
Physics SE Questions
Retrieves 100 samples containing the word 'physics.stackexchange.com' in the prompt, offering basic filtering without deep analysis.