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
|
69843615
|
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 package.json file react-router-dom dependencies added. App component wrapped by BrowswerRouter , but when I wrap route by switch it says the following error Switch' is not exported from 'react-router-dom'. I deleted the package.json.lock ,node modules, installed npm again and npm install @babel/core --save. Still not working. I successfully wasted 6 hour for this. Can you please help me to fix this? why it's not importing? Index.js import {BrowserRouter} from 'react-router-dom';ReactDOM.render( <BrowserRouter> <App /> </BrowserRouter>, document.getElementById('root')); App.js: import logo from './logo.svg';import './App.css';import React from 'react';import {Switch,Route,Link} from 'react-router-dom';import Home from './Home';class App extends React.Component { componentDidMount(){ alert('mounting'); } componentDidUpdate(){ alert('updated'); } render(){ return ( <div className="App"> <div> <Link to="/">Home</Link> </div> <hr /> <Switch> <Route exact path="/"> <Home/> </Route> </Switch> </div> ); }}export default App;import React from 'react'; const Home = () => { return <h1>Home</h1>; }; export default Home; package.json "dependencies": { "@babel/core": "^7.16.0", "@testing-library/jest-dom": "^5.11.4", "@testing-library/react": "^11.1.0", "@testing-library/user-event": "^12.1.10", "react": "^17.0.2", "react-dom": "^17.0.2", "react-router": "^6.0.0", "react-router-dom": "^6.0.0", "react-scripts": "4.0.3", "web-vitals": "^1.0.1" },
Now provide the response and nothing else.
|
Using Routes instead of Switch in react-router v6 You are using react-router-dom version 6, which replaced Switch with the Routes component import { BrowserRouter, Routes, // instead of "Switch" Route,} from "react-router-dom";// ... <BrowserRouter> <Routes> <Route path="/" element={<Home />} /> </Routes> </BrowserRouter> Note that you now also pass your component as the element prop instead of using children.
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/69843615', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8467488/']}
|
jdg_379041
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1036364
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I understand what livelock is, but I was wondering if anyone had a good code-based example of it? And by code-based, I do not mean "two people trying to get past each other in a corridor". If I read that again, I'll lose my lunch.
Now provide the response and nothing else.
|
Here's a very simple Java example of livelock where a husband and wife are trying to eat soup, but only have one spoon between them. Each spouse is too polite, and will pass the spoon if the other has not yet eaten. public class Livelock { static class Spoon { private Diner owner; public Spoon(Diner d) { owner = d; } public Diner getOwner() { return owner; } public synchronized void setOwner(Diner d) { owner = d; } public synchronized void use() { System.out.printf("%s has eaten!", owner.name); } } static class Diner { private String name; private boolean isHungry; public Diner(String n) { name = n; isHungry = true; } public String getName() { return name; } public boolean isHungry() { return isHungry; } public void eatWith(Spoon spoon, Diner spouse) { while (isHungry) { // Don't have the spoon, so wait patiently for spouse. if (spoon.owner != this) { try { Thread.sleep(1); } catch(InterruptedException e) { continue; } continue; } // If spouse is hungry, insist upon passing the spoon. if (spouse.isHungry()) { System.out.printf( "%s: You eat first my darling %s!%n", name, spouse.getName()); spoon.setOwner(spouse); continue; } // Spouse wasn't hungry, so finally eat spoon.use(); isHungry = false; System.out.printf( "%s: I am stuffed, my darling %s!%n", name, spouse.getName()); spoon.setOwner(spouse); } } } public static void main(String[] args) { final Diner husband = new Diner("Bob"); final Diner wife = new Diner("Alice"); final Spoon s = new Spoon(husband); new Thread(new Runnable() { public void run() { husband.eatWith(s, wife); } }).start(); new Thread(new Runnable() { public void run() { wife.eatWith(s, husband); } }).start(); }} Run the program and you'll get: Bob: You eat first my darling Alice!Alice: You eat first my darling Bob!Bob: You eat first my darling Alice!Alice: You eat first my darling Bob!Bob: You eat first my darling Alice!Alice: You eat first my darling Bob!... This will go on forever if uninterrupted. This is a livelock because both Alice and Bob are repeatedly asking each other to go first in an infinite loop (hence live ). In a deadlock situation, both Alice and Bob would simply be frozen waiting on each other to go first — they won't be doing anything except wait (hence dead ).
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/1036364', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7671/']}
|
jdg_379042
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
64872
|
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Why does each individual photon have such a low amount of energy? I am hit by photons all day and I find it amazing that I am not vaporized. Am I simply too physically big for the photons to harm me much, or perhaps the Earth's magnetic field filters out enough harmful causes such as gamma rays?
Now provide the response and nothing else.
|
Individual photons are very small and don't have much energy. If you put a lot of them together in one place you can hurt somebody - by simply supplying enough power to melt an object (ask any spy on a table underneath a laser beam). There is another very odd feature of photons . Although lots of them can provide a lot of energy and heat an object, it takes an individual photon of enough energy to break a chemical bond. So while a single high-energy ultraviolet photon can break a molecule in your skin and cause damage, a billion lower energy visible photons hitting the same point can't break that single bond. Even though they together carry much more energy, it is the energy that is delivered in a single photon that matters in chemistry. Fortunately the Earth's atmosphere shields us from the photons with enough energy to break most chemical bonds.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://physics.stackexchange.com/questions/64872', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/24579/']}
|
jdg_379043
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
30778382
|
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 employee salary table that contains : public partial class S_EmployeeSalary { public int SalaryId { get; set; } public int TypeId { get; set; } public int UserId { get; set; } public double Salary { get; set; } public Nullable<double> ExtraSalary { get; set; } public Nullable<double> Insurance { get; set; } public Nullable<double> Sanctions { get; set; } public System.DateTime SalaryDate { get; set; } public virtual C_UserItems C_UserItems { get; set; } } and i have a button when user click on it, it created a copy from last month records automatically to just update records of new month that created: public ActionResult CreateNewRows(int typeId){ IQueryable<S_EmployeeSalary> moduleItems = db.S_EmployeeSalary .Include(x => x.C_UserItems) .Where(x => x.TypeId == typeId && DbFunctions.DiffDays(x.SalaryDate, DateTime.Now) > 30 && DbFunctions.DiffDays(x.SalaryDate, DateTime.Now) < 30); foreach (var item in moduleItems) { S_EmployeeSalary entity = new S_EmployeeSalary { TypeId = typeId, UserId = item.UserId, Salary = item.Salary, ExtraSalary = item.ExtraSalary, Insurance = item.Insurance, Sanctions = item.Sanctions, SalaryDate = DateTime.Now }; db.S_EmployeeSalary.Add(entity); } db.SaveChanges();} my question is how can i just specify last month records only to select it, i tried DbFunctions.DiffDays but it didnt work well, is there anyone can help me for new idea ?note its employees salary , so i need last month not last 30 days
Now provide the response and nothing else.
|
Depending if you want the last month or last 30 days (question is unclear) This is for the previous month: var startOfTthisMonth = new DateTime(DateTime.Today.Year, DateTime.Today.Month, 1); var firstDay = startOfTthisMonth.AddMonths(-1);var lastDay = startOfTthisMonth.AddDays(-1);IQueryable<S_EmployeeSalary> moduleItems = db.S_EmployeeSalary .Include(x => x.C_UserItems) .Where(x => x.TypeId == typeId && x.SalaryDate >= firstDay && x.SalaryDate <= lastDay); This is for the previous 30 days: var firstDay = DateTime.Today.AddDays(-30);IQueryable<S_EmployeeSalary> moduleItems = db.S_EmployeeSalary .Include(x => x.C_UserItems) .Where(x => x.TypeId == typeId && x.SalaryDate >= firstDay);
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/30778382', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3300821/']}
|
jdg_379044
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
520422
|
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:
As part of a larger problem I need to show that $i$ is not contained in the field extension $\mathbb Q(\sqrt[3]{2},\zeta)$, where $\zeta$ is the third root of unity. I understand that the third root of unity is equal to $${-1}/{2} + i\sqrt{3}/2.$$I'm unsure how to procure a contradiction now though. Do I have to consider the degree? How would I do that? Thanks
Now provide the response and nothing else.
|
Both $K=\mathbb{Q}(\sqrt[3]{2},\zeta)$ and $L=\mathbb{Q}(\sqrt[3]{2},\sqrt{3})$ have degree $6$ over $\mathbb{Q}$. But the latter is obviously real, so $K\neq L$, and in particular $\sqrt{3}\notin K$. Now, if $i\in K$, can we show that $\sqrt{3}\in K$ for a contradiction?
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/520422', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/99776/']}
|
jdg_379045
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
23014684
|
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 use docker on OSX with boot2docker . I want to get an Ssh connection from my terminal into a running container. But I can't do this :( I think it's because Docker is running in a virtual machine.
Now provide the response and nothing else.
|
There are several things you must do to enable ssh'ing to a container running in a VM: install and run sshd in your container ( example ). sshd is not there by default because containers typically run only one process, though they can run as many as you like. EXPOSE a port as part of creating the image, typically 22, so that when you run the container, the daemon connects to the EXPOSE 'd port inside the container and something can be exposed on the outside of the container. When you run the container, you need to decide how to map that port. You can let Docker do it automatically or be explicit. I'd suggest being explicit: docker run -p 42222:22 ... which maps port 42222 on the VM to port 22 in the container. Add a portmap to the VM to expose the port to your host. e.g. when your VM is not running, you can add a mapping like this: VBoxManage modifyvm "boot2docker-vm" --natpf1 "containerssh,tcp,,42222,,42222" Then from your host, you should be able to ssh to port 42222 on the host to reach the container's ssh daemon. Here's what happens when I perform the above steps: $ VBoxManage modifyvm "boot2docker-vm" --natpf1 "containerssh,tcp,,42222,,42222"$ ./boot2docker start[2014-04-11 12:07:35] Starting boot2docker-vm...[2014-04-11 12:07:55] Started.$ docker run -d -p 42222:22 dhrp/sshdUnable to find image 'dhrp/sshd' (tag: latest) locallyPulling repository dhrp/sshd2bbfe079a942: Download complete c8a2228805bc: Download complete 8dbd9e392a96: Download complete 11d214c1b26a: Download complete 27cf78414709: Download complete b750fe79269d: Download complete cf7e766468fc: Download complete 082189640622: Download complete fa822d12ee30: Download complete 1522e919ec9f: Download complete fa594d99163a: Download complete 1bd442970c79: Download complete 0fda9de88c63: Download complete 86e22a5fdce6: Download complete 79d05cb13124: Download complete ac72e4b531bc: Download complete 26e4b94e5a13b4bb924ef57548bb17ba03444ca003128092b5fbe344110f2e4c$ docker psCONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES26e4b94e5a13 dhrp/sshd:latest /usr/sbin/sshd -D 6 seconds ago Up 3 seconds 0.0.0.0:42222->22/tcp loving_einstein $ ssh root@localhost -p 42222The authenticity of host '[localhost]:42222 ([127.0.0.1]:42222)' can't be established.RSA key fingerprint is ....Are you sure you want to continue connecting (yes/no)? yesWarning: Permanently added '[localhost]:42222' (RSA) to the list of known hosts.root@localhost's password: screencastWelcome to Ubuntu 12.04 LTS (GNU/Linux 3.12.1-tinycore64 x86_64) * Documentation: https://help.ubuntu.com/The programs included with the Ubuntu system are free software;the exact distribution terms for each program are described in theindividual files in /usr/share/doc/*/copyright.Ubuntu comes with ABSOLUTELY NO WARRANTY, to the extent permitted byapplicable law.root@26e4b94e5a13:~# exitlogout So that shows ssh->localhost 42222->VM port 42222->container port 22.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/23014684', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1679753/']}
|
jdg_379046
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
226315
|
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 an sh file that I would like to be able to open from the terminal at any time. I would like to type "studio" into the terminal, and have android studio open I recall using ln -s to do this, but I have forgotten and have already wasted much time searching the web. Also, in which directory is the created symbolic link kept in? Here is the syntax from my effort, command not found ricardo@debian:~$ ln -s /opt/android-studio/bin/studio.sh studioricardo@debian:~$ studiobash: studio: command not found
Now provide the response and nothing else.
|
The command you ran created a symbolic link in the current directory. Judging by the prompt, the current directory is your home directory. Creating symbolic links to executable programs in your home directory is not particularly useful. When you type the name of a program, the shell looks for it in the directories listed in the PATH environment variable . To see the value of this variable, run echo $PATH . The directories are separated by a colon ( : ). A typical path is /home/ricardo/bin:/usr/local/bin:/usr/bin:/bin but there's a lot of variation out there. You need to create this symbolic link in one of the directories listed in $PATH . If you want to make the command available to all users, create the link in /usr/local/bin : sudo ln -s /opt/android-studio/bin/studio.sh /usr/local/bin/studio If you want to make the command available only to you (which is the only possibility if you don't have administrator privileges), create the link in ~/bin (the bin subdirectory of your home directory). ln -s /opt/android-studio/bin/studio.sh ~/bin/studio If your distribution doesn't put /home/ricardo/bin in your PATH (where /home/ricardo is your home directory), create it first with mkdir ~/bin , and add it to your PATH by adding the following line to ~/.profile (create the file if it doesn't exist): PATH=~/bin:$PATH The .profile file is read when you log in. You can read it in the current terminal by running . ~/.profile (this only applies to programs started from that terminal).
|
{}
|
{'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/226315', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/128695/']}
|
jdg_379047
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4295799
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Thanks to some help from people here, I was able to get my code for Tasmanian camels puzzle working. However, it is horribly slow (I think. I'm not sure because this is my first program in Python). The example run in the bottom of the code takes a long time to be solved in my machine: dumrat@dumrat:~/programming/python$ time python camels.py[['F', 'F', 'F', 'G', 'B', 'B', 'B'], ['F', 'F', 'G', 'F', 'B', 'B', 'B'], ['F', 'F', 'B', 'F', 'G', 'B', 'B'], ['F', 'F', 'B', 'F', 'B', 'G', 'B'], ['F', 'F', 'B', 'G', 'B', 'F', 'B'], ['F', 'G', 'B', 'F', 'B', 'F', 'B'], ['G', 'F', 'B', 'F', 'B', 'F', 'B'], ['B', 'F', 'G', 'F', 'B', 'F', 'B'], ['B', 'F', 'B', 'F', 'G', 'F', 'B'], ['B', 'F', 'B', 'F', 'B', 'F', 'G'], ['B', 'F', 'B', 'F', 'B', 'G', 'F'], ['B', 'F', 'B', 'G', 'B', 'F', 'F'], ['B', 'G', 'B', 'F', 'B', 'F', 'F'], ['B', 'B', 'G', 'F', 'B', 'F', 'F'], ['B', 'B', 'B', 'F', 'G', 'F', 'F']]real 0m20.883suser 0m20.549ssys 0m0.020s Here's the code: import QueuefCamel = 'F'bCamel = 'B'gap = 'G'def solution(formation): return len([i for i in formation[formation.index(fCamel) + 1:] if i == bCamel]) == 0def heuristic(formation): fCamels, score = 0, 0 for i in formation: if i == fCamel: fCamels += 1; elif i == bCamel: score += fCamels; else: pass return scoredef getneighbors (formation): igap = formation.index(gap) res = [] # AB_CD --> A_BCD | ABC_D | B_ACD | ABD_C def genn(i,j): temp = list(formation) temp[i], temp[j] = temp[j], temp[i] res.append(temp) if(igap > 0): genn(igap, igap-1) if(igap > 1): genn(igap, igap-2) if igap < len(formation) - 1: genn(igap, igap+1) if igap < len(formation) - 2: genn(igap, igap+2) return resclass node: def __init__(self, a, g, p): self.arrangement = a self.g = g self.parent = pdef astar (formation, heuristicf, solutionf, genneighbors): openlist = Queue.PriorityQueue() openlist.put((heuristicf(formation), node(formation, 0, None))) closedlist = [] while 1: try: f, current = openlist.get() except IndexError: current = None if current is None: print "No solution found" return None; if solutionf(current.arrangement): path = [] cp = current while cp != None: path.append(cp.arrangement) cp = cp.parent path.reverse() return path #arr = current.arrangement closedlist.append(current) neighbors = genneighbors(current.arrangement) for neighbor in neighbors: if neighbor in closedlist: pass else: openlist.put((current.g + heuristicf(neighbor), node(neighbor, current.g + 1, current))) #sorted(openlist, cmp = lambda x, y : x.f > y.f)def solve(formation): return astar(formation, heuristic, solution, getneighbors)print solve([fCamel, fCamel, fCamel, gap, bCamel, bCamel, bCamel])#print solve([fCamel, fCamel, fCamel, fCamel, gap, bCamel, bCamel, bCamel, bCamel]) That is just for 3 camels each. I wanted to do this for 4 at least. That test case is still running (It's been about 5 minutes now :(). I'll update this if and when it finishes. What should I do to improve this code? (Mostly performance-wise, but any other suggestions are welcome also).
Now provide the response and nothing else.
|
I've been tripped up by this before too. The bottleneck here is actually if neighbor in closedlist . The in statement is so easy to use, you forget that it's linear search, and when you're doing linear searches on lists, it can add up fast. What you can do is convert closedlist into a set object. This keeps hashes of its items so the in operator is much more efficient than for lists. However, lists aren't hashable items, so you will have to change your configurations into tuples instead of lists. If the order of closedlist is crucial to the algorithm, you could use a set for the in operator and keep an parallel list around for your results. I tried a simple implementation of this including aaronasterling's namedtuple trick and it performed in 0.2 sec for your first example and 2.1 sec for your second, but I haven't tried verifying the results for the second longer one.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4295799', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/466694/']}
|
jdg_379048
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
45139805
|
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 just faced a little PHP snippet from 3v4l: https://3v4l.org/jmrZB echo 1...1; //10.1 And I'm afraid I have no idea how to explain its results. Why is this considered valid at all?
Now provide the response and nothing else.
|
The dot ( . ) has two roles in PHP: As decimal digit, when it is part of a real number, e.g. 1.1 . Both the integral part and the decimal part are optional on real numbers but not on the same time . This means both 1. and .1 are valid real numbers in PHP but . is not a number. As the string concatenation operator . This operator connects two string sub-expressions into a larger expression. The value of the larger expression is the concatenation of the string values of the sub-expressions. The sub-expressions that are not strings are converted to strings before concatenation. E.g. 1 . 1 is the same as '1' . '1' and its value is the string '11' . The expression 1...1 is parsed as 1. . .1 . According to those said above, 1. and .1 are real numbers ( 1.0 and 0.1 ) and the middle dot ( . ) is the string concatenation operator. When converts numbers to strings, PHP uses the minimum amount of characters required for this operation. If a real number has only integral part then it represents the number as integer, without decimal point and decimals. This is why 1. . .1 is the same as '1' . '0.1' and the final value of the expression is 10.1 . Why is 1...1 parsed this way? The parser reads the expression from left to right. 1 tells it a number starts there. 1. is a valid real number but 1.. is not. It keeps 1. as a number then the next dot is the concatenation operator. The next . , being followed by a digit, is the beginning of another real number ( .1 ). All in all, 1...1 is the same as 1. . .1 .
|
{}
|
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/45139805', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2018304/']}
|
jdg_379049
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1161624
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
What is the difference between doing use My::Module and require My::Module ?
Now provide the response and nothing else.
|
The use function: use ModuleName; is equivalent to the following code using the require function: BEGIN { require ModuleName; ModuleName->import;} The BEGIN block causes this code to run as soon as the parser sees it. The require loads the module or die s trying. And then the import function of the module is called. The import function may do all sorts of things, but it is common for it to load functions into the namespace that use d it (often with the Exporter module). It is important to note that import will not be called in this case: use ModuleName (); In that case, it is equivalent to BEGIN { require ModuleName;}
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1161624', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/58109/']}
|
jdg_379050
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
44002128
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am implementing a spark application, of which below is a sample snippet(Not the exact same code): val rdd1 = sc.textfile(HDFS_PATH)val rdd2 = rdd1.map(func)rdd2.persist(StorageLevel.MEMORY_AND_DISK)println(rdd2.count) On checking the performance of this code from the Spark Application Master UI, I see an entry for the count action, but not for the persist . The DAG for this count action also has a node for the 'map' transformation (line 2 of the above code). Is it safe to conclude that the map transformation is executed when count (in the last line) is encountered, and not when persist is encountered? Also, at what point is rdd2 actually persisted?I understand that only two types of operations can be called on RDDs - transformations and actions. If the RDD is persisted lazily when the count action is called, would persist be considered a transformation or an action or neither?
Now provide the response and nothing else.
|
Dataset's cache and persist operators are lazy and don't have any effect until you call an action (and wait till the caching has finished which is the extra price for having a better performance later on). From Spark's official documentation RDD Persistence (with the sentence in bold mine): One of the most important capabilities in Spark is persisting (or caching) a dataset in memory across operations. When you persist an RDD, each node stores any partitions of it that it computes in memory and reuses them in other actions on that dataset (or datasets derived from it). This allows future actions to be much faster (often by more than 10x). Caching is a key tool for iterative algorithms and fast interactive use. You can mark an RDD to be persisted using the persist() or cache() methods on it. The first time it is computed in an action, it will be kept in memory on the nodes . Spark’s cache is fault-tolerant – if any partition of an RDD is lost, it will automatically be recomputed using the transformations that originally created it. That's exactly the reason why some people (and Spark SQL itself!) do the following trick: rdd2.persist(StorageLevel.MEMORY_AND_DISK).count to trigger the caching. count operator is fairly cheap so the net effect is that the caching is executed almost immediately after the line (there might be a small delay before the caching has completed as it executes asynchronously). The benefits of this count after persist are as follows: No action (but the count itself) will "suffer" the extra time for caching The time between this line and the place where the cached rdd2 is used could be enough to fully complete the caching and hence the time would be used better (without extra "slowdown" for caching) So when you asked: would persist be considered a transformation or an action or neither? I'd say it's neither and consider it an optimization hint (that may or may not be executed or taken into account ever ). Use web UI's Storage tab to see what Datasets (as their underlying RDDs) have already been persisted. You can also see cache or persist operators' output using explain (or simply QueryExecution.optimizedPlan ). val q1 = spark.range(10).groupBy('id % 5).agg(count("*") as "count").cachescala> q1.explain== Physical Plan ==*(1) ColumnarToRow+- InMemoryTableScan [(id % 5)#120L, count#119L] +- InMemoryRelation [(id % 5)#120L, count#119L], StorageLevel(disk, memory, deserialized, 1 replicas) +- *(2) HashAggregate(keys=[(id#0L % 5)#8L], functions=[count(1)]) +- Exchange hashpartitioning((id#0L % 5)#8L, 200), true, [id=#13] +- *(1) HashAggregate(keys=[(id#0L % 5) AS (id#0L % 5)#8L], functions=[partial_count(1)]) +- *(1) Range (0, 10, step=1, splits=16)scala> println(q1.queryExecution.optimizedPlan.numberedTreeString)00 InMemoryRelation [(id % 5)#5L, count#4L], StorageLevel(disk, memory, deserialized, 1 replicas)01 +- *(2) HashAggregate(keys=[(id#0L % 5)#8L], functions=[count(1)], output=[(id % 5)#5L, count#4L])02 +- Exchange hashpartitioning((id#0L % 5)#8L, 200), true, [id=#13]03 +- *(1) HashAggregate(keys=[(id#0L % 5) AS (id#0L % 5)#8L], functions=[partial_count(1)], output=[(id#0L % 5)#8L, count#10L])04 +- *(1) Range (0, 10, step=1, splits=16) Please note that the count above is a standard function not an action and no caching happens. It's just a coincidence that count is the name of a standard function and an Dataset action. You can cache a table using pure SQL (this is eager!) // That registers range5 to contain the output of range(5) functionspark.sql("CACHE TABLE range5 AS SELECT * FROM range(5)")val q2 = spark.sql("SELECT * FROM range5")scala> q2.explain== Physical Plan ==*(1) ColumnarToRow+- Scan In-memory table `range5` [id#51L] +- InMemoryRelation [id#51L], StorageLevel(disk, memory, deserialized, 1 replicas) +- *(1) Range (0, 5, step=1, splits=16) InMemoryTableScan physical operator (with InMemoryRelation logical plan) is how you can make sure that the query is cached in-memory and hence reused. Moreover, Spark SQL itself uses the same pattern to trigger DataFrame caching for SQL's CACHE TABLE query (which, unlike RDD caching, is by default eager): if (!isLazy) { // Performs eager caching sparkSession.table(tableIdent).count()} That means that depending on the operators you may have different result as far as caching is concerned. cache and persist operators are lazy by default while SQL's CACHE TABLE is eager.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/44002128', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2487397/']}
|
jdg_379051
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
44624110
|
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 find the nearest point to a location using geodjango. I tried using the following code: LocationInfo.objects.filter(coordinates__distance_lte=(user_location, D(km=2))) But It only works if the location is within the specified distance ( D(km=2) in this case). I need to find the point nearest to the user without using any limit during query.
Now provide the response and nothing else.
|
Let's assume that your LocationInfo has it's geometry field named position : For Django version >= 1.9: You can use the Distance() function: from django.contrib.gis.db.models.functions import DistanceLocationInfo.objects.annotate( distance=Distance('position', user_location)).order_by('distance').first() Which will return the nearest object to the user_location For Django 1.6 <= version < 1.9: You can use the .distance() method: LocationInfo.objects.distance(user_location).order_by('distance').first() For Django version < 1.6: The .first() method does not exist so you have to get the first of the ordered queryset as follows: LocationInfo.objects.distance(user_location).order_by('distance')[:1].get()
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/44624110', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8041633/']}
|
jdg_379052
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1310813
|
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:
In encryption process (aes encryption), and also in Galois field, a prime number is always used to perform the modulo operation. So I wanted to know the reason for using only prime numbers for modulo operations ?
Now provide the response and nothing else.
|
The nice things about primes is that when looking at the numbers modulo a prime, you can always "divide" by anything non-zero. In particular, if you want to solve the equation$$ax \equiv b \pmod p$$where $a \not \equiv 0$, and $b$ is any number, there exists some $(1/a)$, so that$$(1/a)ax \equiv (1/a)b$$or in other words,$$x \equiv b/a$$In mathematical terms, the numbers modulo a prime form a field , whereas the numbers modulo a composite number only form a ring . To see how this doesn't work for composites, note that$$2x \equiv 1 \pmod 6$$has no solution, which is to say that $2$ has no multiplicative inverse.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1310813', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/245344/']}
|
jdg_379053
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
16907825
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How can i implement a sublime-like fuzzy search on select2? Example, typing "sta jav sub" would match "Stackoverflow javascript sublime like"
Now provide the response and nothing else.
|
select2 allows you to implement your own "matcher" functions ( as seen on their docs ), using that and some regexp you can do something like: $("#element").select2({ matcher: function(term, text, opt) { //We call to uppercase to do a case insensitive match //We replace every group of whitespace characters with a .+ //matching any number of characters return text.toUpperCase().match(term.toUpperCase().replace(/\s+/g, '.+')); }}); A matcher function is invoked against every select2 list element when filtering / searching the list, you could implement any kind of custom search using that.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16907825', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/23020/']}
|
jdg_379054
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
35927
|
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 am confused about the concept of confidence interval. Specifically, assume there is a Gaussian variable $X \sim N(\mu, \sigma)$ with $\sigma$ known, and I am interested in the lower-bound $\mu_L$ of the mean with $95\%$ confidence level. I will do the experiment for $5$ times, and observe $X_1$, $X_2$, $X_3$, $X_4$, $X_5$. Option 1: I treat each sample separately, and I can compute $\mu_L = X_i - \sigma z$ for each $X_i$.And then I guess there is some way (I don't know how) to compute the actual lower bound from these 5 $\mu_L$'s. Option 2: On the other hand, if I take $T = (X_1+X_2+X_3+X_4+X_5)/5$, I can compute $\mu_L = T - \sigma/\sqrt{5}z$. (assuming $T$ is normal, we can use t-stat too.) Is there any method other than option 2 to compute a lower-bound based on the $5$ samples? And for option 1, is there a way to compute the lower-bound based on the 5 lower-bounds computed?
Now provide the response and nothing else.
|
This is a great question because it explores the possibility of alternative procedures and asks us to think about why and how one procedure might be superior to another. The short answer is that there are infinitely many ways we might devise a procedure to obtain a lower confidence limit for the mean, but some of these are better and some are worse (in a sense that is meaningful and well-defined). Option 2 is an excellent procedure, because a person using it would need to collect less than half as much data as a person using Option 1 in order to obtain results of comparable quality. Half as much data typically means half the budget and half the time, so we're talking about a substantial and economically important difference. This supplies a concrete demonstration of the value of statistical theory. Rather than rehash the theory, of which many excellent textbook accounts exist, let's quickly explore three lower confidence limit (LCL) procedures for $n$ independent normal variates of known standard deviation. I chose three natural and promising ones suggested by the question. Each of them is determined by a desired confidence level $1-\alpha$: Option 1a, the "min" procedure . The lower confidence limit is set equal to $t_{\min} = \min(X_1, X_2, \ldots, X_n) - k^{\min}_{\alpha, n, \sigma} \sigma$. The value of the number $k^{\min}_{\alpha, n, \sigma}$ is determined so that the chance that $t_{\min}$ will exceed the true mean $\mu$ is just $\alpha$; that is, $\Pr(t_{\min} \gt \mu) = \alpha$. Option 1b, the "max" procedure . The lower confidence limit is set equal to $t_{\max} = \max(X_1, X_2, \ldots, X_n) - k^{\max}_{\alpha, n, \sigma} \sigma$. The value of the number $k^{\max}_{\alpha, n, \sigma}$ is determined so that the chance that $t_{\max}$ will exceed the true mean $\mu$ is just $\alpha$; that is, $\Pr(t_{\max} \gt \mu) = \alpha$. Option 2, the "mean" procedure . The lower confidence limit is set equal to $t_\text{mean} = \text{mean}(X_1, X_2, \ldots, X_n) - k^\text{mean}_{\alpha, n, \sigma} \sigma$. The value of the number $k^\text{mean}_{\alpha, n, \sigma}$ is determined so that the chance that $t_\text{mean}$ will exceed the true mean $\mu$ is just $\alpha$; that is, $\Pr(t_\text{mean} \gt \mu) = \alpha$. As is well known, $k^\text{mean}_{\alpha, n, \sigma} = z_\alpha/\sqrt{n}$ where $\Phi(z_\alpha) = 1-\alpha$; $\Phi$ is the cumulative probability function of the standard Normal distribution. This is the formula cited in the question. A mathematical shorthand is $k^\text{mean}_{\alpha, n, \sigma} = \Phi^{-1}(1-\alpha)/\sqrt{n}.$ The formulas for the min and max procedures are less well known but easy to determine: $k^\text{min}_{\alpha,n,\sigma} = \Phi^{-1}(1-\alpha^{1/n})$. $k^\text{max}_{\alpha, n, \sigma} = \Phi^{-1}((1-\alpha)^{1/n})$. By means of a simulation, we can see that all three formulas work. The following R code conducts the experiment n.trials separate times and reports all three LCLs for each trial: simulate <- function(n.trials=100, alpha=.05, n=5) { z.min <- qnorm(1-alpha^(1/n)) z.mean <- qnorm(1-alpha) / sqrt(n) z.max <- qnorm((1-alpha)^(1/n)) f <- function() { x <- rnorm(n); c(max=max(x) - z.max, min=min(x) - z.min, mean=mean(x) - z.mean) } replicate(n.trials, f())} (The code does not bother to work with general normal distributions: because we are free to choose the units of measurement and the zero of the measurement scale, it suffices to study the case $\mu=0$, $\sigma=1$. That is why none of the formulas for the various $k^*_{\alpha,n,\sigma}$ actually depend on $\sigma$.) 10,000 trials will provide sufficient accuracy. Let's run the simulation and calculate the frequency with which each procedure fails to produce a confidence limit less than the true mean: set.seed(17)sim <- simulate(10000, alpha=.05, n=5)apply(sim > 0, 1, mean) The output is max min mean 0.0515 0.0527 0.0520 These frequencies are close enough to the stipulated value of $\alpha=.05$ that we can be satisfied all three procedures work as advertised: each one of them produces a 95% confidence lower confidence limit for the mean. (If you're concerned that these frequencies differ slightly from $.05$, you can run more trials. With a million trials, they come even closer to $.05$: $(0.050547, 0.049877, 0.050274)$.) However, one thing we would like about any LCL procedure is that not only should it be correct the intended proportion of time, but it should tend to be close to correct. For instance, imagine a (hypothetical) statistician who, by virtue of a deep religious sensibility, can consult the Delphic oracle (of Apollo) instead of collecting the data $X_1, X_2, \ldots, X_n$ and doing an LCL computation. When she asks the god for a 95% LCL, the god will just divine the true mean and tell that to her--after all, he's perfect. But, because the god does not wish to share his abilities fully with mankind (which must remain fallible), 5% of the time he will give an LCL that is $100\sigma$ too high. This Delphic procedure is also a 95% LCL--but it would be a scary one to use in practice due to the risk of it producing a truly horrible bound. We can assess how accurate our three LCL procedures tend to be. A good way is to look at their sampling distributions: equivalently, histograms of many simulated values will do as well. Here they are. First though, the code to produce them: dx <- -min(sim)/12breaks <- seq(from=min(sim), to=max(sim)+dx, by=dx)par(mfcol=c(1,3))tmp <- sapply(c("min", "max", "mean"), function(s) { hist(sim[s,], breaks=breaks, col="#70C0E0", main=paste("Histogram of", s, "procedure"), yaxt="n", ylab="", xlab="LCL"); hist(sim[s, sim[s,] > 0], breaks=breaks, col="Red", add=TRUE)}) They are shown on identical x axes (but slightly different vertical axes). What we are interested in are The red portions to the right of $0$--whose areas represent the frequency with which the procedures fail to underestimate the mean--are all about equal to the desired amount, $\alpha=.05$. (We had already confirmed that numerically.) The spreads of the simulation results. Evidently, the rightmost histogram is narrower than the other two: it describes a procedure that indeed underestimates the mean (equal to $0$) fully $95$% of the time, but even when it does, that underestimate is almost always within $2 \sigma$ of the true mean. The other two histograms have a propensity to underestimate the true mean by a little more, out to about $3\sigma$ too low. Also, when they overestimate the true mean, they tend to overestimate it by more than the rightmost procedure. These qualities make them inferior to the rightmost histogram. The rightmost histogram describes Option 2, the conventional LCL procedure. One measure of these spreads is the standard deviation of the simulation results: > apply(sim, 1, sd) max min mean 0.673834 0.677219 0.453829 These numbers tell us that the max and min procedures have equal spreads (of about $0.68$) and the usual, mean , procedure has only about two-thirds their spread (of about $0.45$). This confirms the evidence of our eyes. The squares of the standard deviations are the variances, equal to $0.45$, $0.45$, and $0.20$, respectively. The variances can be related to the amount of data : if one analyst recommends the max (or min ) procedure, then in order to achieve the narrow spread exhibited by the usual procedure, their client would have to obtain $0.45/0.21$ times as much data--over twice as much. In other words, by using Option 1, you would be paying more than twice as much for your information than by using Option 2.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/35927', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/12898/']}
|
jdg_379055
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
27150465
|
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 built the Geolocation API into my webapp and all browsers are working fine. Except Safari 8 and 7.1. The browser keeps asking for permission after allowing or not allowing it and ends up in an infinite loop making the browser (tab) unusable. It's easily reproducible by just going to http://html5demos.com/geo in Safari. Is there any fix for this or is this just a bug in Safari?I searched but couldn't find anything related.
Now provide the response and nothing else.
|
Our team saw this too. At first we thought we might have been stuck inside some kind of loop that the other browsers ignored, so we instrumented the code and confirmed that the call was only happening once. We suspended JavaScript by forcing a breakpoint and the alerts kept coming (and coming, and coming...). At this point we were pretty sure the issue was not in our code. On a whim I placed the call to the GeoLocation API inside a setTimeout (to allow the call stack to empty) and the problem went away. No idea why that would fix the issue. . . Edit Per request, I put up an example @ https://jsfiddle.net/r8hst2zp/1/
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/27150465', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/127550/']}
|
jdg_379056
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
749756
|
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 could prove it hit and trial method. But I was thinking to come up with a general and a more 'mathematically' correct method, but I did not reach anywhere. Thanks a lot for any help.
Now provide the response and nothing else.
|
Suppose to the contrary that the difference is a perfect square. Note that the difference is odd, so we would have$$(2m+1)^2-4(2n+1)=(2q+1)^2.$$This can be rewritten as $$4(2n+1)=4(m^2+m)-4(q^2+q).\tag{1}$$Note that both $m^2+m$ and $q^2+q$ are always even, so the right-hand side of (1) is divisible by $8$. But the left-hand side is not, and we have reached a contradiction.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/749756', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/142473/']}
|
jdg_379057
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
5692624
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I want to create an artificial neural network (in PyBrain) that follows the following layout: However, I cannot find the proper way to achieve this. The only option that I see in the documentation is the way to create fully connected layers, which is not what I want: I want some of my input nodes to be connected to the second hidden layer and not to the first one.
Now provide the response and nothing else.
|
The solution is to use the connection type of your choice, but with slicing parameters: inSliceFrom , inSliceTo , outSliceFrom and outSliceTo . I agree the documentation should mention this, so far it's only in the Connection class' comments. Here is example code for your case: #create network and modulesnet = FeedForwardNetwork()inp = LinearLayer(9)h1 = SigmoidLayer(2)h2 = TanhLayer(2)outp = LinearLayer(1)# add modulesnet.addOutputModule(outp)net.addInputModule(inp)net.addModule(h1)net.addModule(h2)# create connectionsnet.addConnection(FullConnection(inp, h1, inSliceTo=6))net.addConnection(FullConnection(inp, h2, inSliceFrom=6))net.addConnection(FullConnection(h1, h2))net.addConnection(FullConnection(h2, outp))# finish upnet.sortModules()
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5692624', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/17523/']}
|
jdg_379058
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
14357945
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Please help me on, How can we make AngularJS compile the code generated by directive ? You can even find the same code here, http://jsbin.com/obuqip/4/edit HTML <div ng-controller="myController"> {{names[0]}} {{names[1]}} <br/> <hello-world my-username="names[0]"></hello-world> <br/> <hello-world my-username="names[1]"></hello-world> <br/><button ng-click="clicked()">Click Me</button></div> Javascript var components= angular.module('components', []);components.controller("myController", function ($scope) { var counter = 1; $scope.names = ["Number0","lorem","Epsum"]; $scope.clicked = function() { $scope.names[0] = "Number" + counter++; }; });// **Here is the directive code**components.directive('helloWorld', function() { var directiveObj = { link:function(scope, element, attrs) { var strTemplate, strUserT = attrs.myUsername || ""; console.log(strUserT); if(strUserT) { strTemplate = "<DIV> Hello" + "{{" + strUserT +"}} </DIV>" ; } else { strTemplate = "<DIV>Sorry, No user to greet!</DIV>" ; } element.replaceWith(strTemplate); }, restrict: 'E' }; return directiveObj;});
Now provide the response and nothing else.
|
Here's a version that doesn't use a compile function nor a link function: myApp.directive('helloWorld', function () { return { restrict: 'E', replace: true, scope: { myUsername: '@' }, template: '<span><div ng-show="myUsername">Hello {{myUsername}}</div>' + '<div ng-hide="myUsername">Sorry, No user to greet!</div></span>', };}); Note that the template is wrapped in a <span> because a template needs to have one root element. (Without the <span>, it would have two <div> root elements.) The HTML needs to be modified slightly, to interpolate: <hello-world my-username="{{names[0]}}"></hello-world> Fiddle .
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14357945', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/148869/']}
|
jdg_379059
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
17588767
|
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 use iptraf to monitor the network traffic in linux, and the shell command is(make iptraf running in background): iptraf -s eth0 -f -B -L ./traffic.dat if I want to get the result, I have to stop iptraf first, so I use the shell command: kill -SIGUSR2 $pid however, I could not stop iptraf if I move these shell commands into a bash script file(net.sh), and I get an error: kill: SIGUSR2: invalid signal specification I use 'kill -l' in the script file(net.sh), and I find there is no parameter which name is SIGUSR2. and I would get nothing if I use USR2 or -9. the complete script file is: iptraf -s eth0 -f -B -L ./temp.txt pid=`ps -ef | grep iptraf | grep -v grep | awk '{print $2}'` kill -USR2 $pid cat temp.txt I get nothing after these commands. what shoud I do if I want to get the result?
Now provide the response and nothing else.
|
SIGUSR2 is architecture depended and can have a value out of 31 , 12 or 17 . This is described in man 7 signal . You'll have to find out which value is appropriate for your system. Usually this is done by having a look into: /usr/include/asm/signal.h On my system - Ubuntu 12.04 AMD 64 - it has a value of 12 : #define SIGUSR2 12 Once you know the proper numeric value for SIGUSR2 on your system, you can send this signal using: kill -SIGNO PID# In this casekill -12 PID
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17588767', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2369515/']}
|
jdg_379060
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2300583
|
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 sorry if this is a duplicate. I have no idea on what kind of "name" i should give to this, and therefore i have no idea on how to search on the internet for help on understanding it. If it happens that this is a duplicate, i would be grateful if you could link me to where there are any solutions for this. I need to prove for an exercise on my analysis book that the following sequence$${\cfrac{1}{1+\cfrac{1}{5}}},\quad{\cfrac{1}{1+\cfrac{1}{5+\cfrac{1}{1+\cfrac{1}{5}}}}},\dotsc$$ is monotone and converges to ${\frac{-5+\sqrt{45}}{2}}$ I imagine that once i get on how to determine it's limit, it will be easy to prove that it is in fact monotone. I have no idea on how to approach it though. Any tips?
Now provide the response and nothing else.
|
Let $a_0=0$ and $a_{n+1}=\cfrac1{1+\cfrac1{5+a_n}}$. Prove by induction: 1) $a_n<\dfrac{-5+\sqrt{45}}2$ 2) $a_{n+1}>a_n$ i.e. monotone So that it converges and that it must converge to some $a'$ such that: $$a'=\cfrac1{1+\cfrac1{5+a'}}$$ (feel free to ask if you need more tips on any steps below, hover on the below tips to see major steps) Induction step on proving 1) \begin{align}&a_0<\cfrac{-5+\sqrt{45}}2\\&a_{n+1}=\cfrac1{1+\cfrac1{5+a_n}}<\cfrac1{1+\cfrac1{5+\cfrac{-5+\sqrt{45}}2}}=\cfrac{-5+\sqrt{45}}2\end{align} Induction on 2) \begin{align}&a_1>a_0\\&a_{n+1}=\cfrac1{1+\cfrac1{5+a_n}}>\cfrac1{1+\cfrac1{5+a_{n-1}}}=a_n\end{align}
|
{}
|
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/2300583', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/450157/']}
|
jdg_379061
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
17498320
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am using PowerShell v3 and the Windows PowerShell ISE. I have the following function that works fine: function Get-XmlNode([xml]$XmlDocument, [string]$NodePath, [string]$NamespaceURI = "", [string]$NodeSeparatorCharacter = '.'){ # If a Namespace URI was not given, use the Xml document's default namespace. if ([string]::IsNullOrEmpty($NamespaceURI)) { $NamespaceURI = $XmlDocument.DocumentElement.NamespaceURI } # In order for SelectSingleNode() to actually work, we need to use the fully qualified node path along with an Xml Namespace Manager, so set them up. [System.Xml.XmlNamespaceManager]$xmlNsManager = New-Object System.Xml.XmlNamespaceManager($XmlDocument.NameTable) $xmlNsManager.AddNamespace("ns", $NamespaceURI) [string]$fullyQualifiedNodePath = Get-FullyQualifiedXmlNodePath -NodePath $NodePath -NodeSeparatorCharacter $NodeSeparatorCharacter # Try and get the node, then return it. Returns $null if the node was not found. $node = $XmlDocument.SelectSingleNode($fullyQualifiedNodePath, $xmlNsManager) return $node} Now, I will be creating a few similar functions, so I want to break the first 3 lines out into a new function so that I don't have to copy-paste them everywhere, so I have done this: function Get-XmlNamespaceManager([xml]$XmlDocument, [string]$NamespaceURI = ""){ # If a Namespace URI was not given, use the Xml document's default namespace. if ([string]::IsNullOrEmpty($NamespaceURI)) { $NamespaceURI = $XmlDocument.DocumentElement.NamespaceURI } # In order for SelectSingleNode() to actually work, we need to use the fully qualified node path along with an Xml Namespace Manager, so set them up. [System.Xml.XmlNamespaceManager]$xmlNsManager = New-Object System.Xml.XmlNamespaceManager($XmlDocument.NameTable) $xmlNsManager.AddNamespace("ns", $NamespaceURI) return $xmlNsManager}function Get-XmlNode([xml]$XmlDocument, [string]$NodePath, [string]$NamespaceURI = "", [string]$NodeSeparatorCharacter = '.'){ [System.Xml.XmlNamespaceManager]$xmlNsManager = Get-XmlNamespaceManager -XmlDocument $XmlDocument -NamespaceURI $NamespaceURI [string]$fullyQualifiedNodePath = Get-FullyQualifiedXmlNodePath -NodePath $NodePath -NodeSeparatorCharacter $NodeSeparatorCharacter # Try and get the node, then return it. Returns $null if the node was not found. $node = $XmlDocument.SelectSingleNode($fullyQualifiedNodePath, $xmlNsManager) return $node} The problem is that when "return $xmlNsManager" executes the following error is thrown: Cannot convert the "System.Object[]" value of type "System.Object[]" to type "System.Xml.XmlNamespaceManager". So even though I have explicitly cast my $xmlNsManager variables to be of type System.Xml.XmlNamespaceManager, when it gets returned from the Get-XmlNamespaceManager function PowerShell is converting it to an Object array. If I don't explicitly cast the value returned from the Get-XmlNamespaceManager function to System.Xml.XmlNamespaceManager, then the following error is thrown from the .SelectSingleNode() function because the wrong data type is being passed into the function's 2nd parameter. Cannot find an overload for "SelectSingleNode" and the argument count: "2". So for some reason PowerShell is not maintaining the data type of the return variable. I would really like to get this working from a function so that I don't have to copy-paste those 3 lines all over the place. Any suggestions are appreciated. Thanks.
Now provide the response and nothing else.
|
What's happening is PowerShell is converting your namespace manager object to a string array. I think it has to do with PowerShell's nature of "unrolling" collections when sending objects down the pipeline. I think PowerShell will do this for any type implementing IEnumerable (has a GetEnumerator method). As a work around you can use the comma trick to prevent this behavior and send the object as a whole collection. function Get-XmlNamespaceManager([xml]$XmlDocument, [string]$NamespaceURI = ""){ ... $xmlNsManager.AddNamespace("ns", $NamespaceURI) return ,$xmlNsManager}
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/17498320', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/602585/']}
|
jdg_379062
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
14178264
|
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 initialize a std::array as follows, the compiler gives me a warning about missing braces std::array<int, 4> a = {1, 2, 3, 4}; This fixes the problem: std::array<int, 4> a = {{1, 2, 3, 4}}; This is the warning message: missing braces around initializer for 'std::array<int, 4u>::value_type [4] {aka int [4]}' [-Wmissing-braces] Is this just a bug in my version of gcc, or is it done intentionally? If so, why?
Now provide the response and nothing else.
|
This is the bare implementation of std::array : template<typename T, std::size_t N>struct array { T __array_impl[N];}; It's an aggregate struct whose only data member is a traditional array, such that the inner {} is used to initialize the inner array. Brace elision is allowed in certain cases with aggregate initialization (but usually not recommended) and so only one brace can be used in this case. See here: C++ vector of arrays
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/14178264', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1392142/']}
|
jdg_379063
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
586312
|
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:
From Baby Rudin, I see that for $inf$ he chose $a_{n+1}$ to be $\frac{1}{8}$ and $a_n$ to be $1$ because that's the smallest ratio. For $sup$ he chose $\frac{1}{8}$ to be $a_n$. Can someone verify this? I also do not know how the third limit is reached.
Now provide the response and nothing else.
|
You have $$a_n=\begin{cases}4^{-n/2+1},&\ n \text{ even},\\2^{-n},&\ n \text{ odd}\end{cases}$$So, when $n$ is even $$\frac{a_{n+1}}{a_n}=\frac{2^{-n-1}}{4^{-n/2+1}}=\frac{2^{-n-1}}{2^{-n+2}}=\frac18.$$When $n$ is odd,$$\frac{a_{n+1}}{a_n}=\frac{4^{-(n+1)/2+1}}{2^{-n}}=\frac{2^{-n+1}}{2^{-n}}=2.$$That shows that values for the $\liminf$ and $\limsup$. Similarly, when $n$ is even,$$(a_n)^{1/n}=(4^{-n/2+1})^{1/n}=4^{-1/2+1/n}=\frac12\times4^{1/n}\to\frac12.$$For $n$ odd,$$(a_n)^{1/n}=(2^{-n})^{1/n}=2^{-1}=\frac12.$$So $\lim_n(a_n)^{1/n}=\frac12$.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/586312', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/91377/']}
|
jdg_379064
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1419966
|
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 a JDBC application I need to issue a few ALTER SESSION commands. I do not want to put those into the application code itself. Is there a way to specify defaults for the session parameters for the database schema that the application uses (on the database side) ?
Now provide the response and nothing else.
|
most session parameters are defined by the client application. If you want to override the client settings you could create a DATABASE TRIGGER . For example, this will create a LOGON trigger on the BAR schema: CREATE OR REPLACE TRIGGER bar.foo AFTER LOGON ON DATABASE WHEN (USER = 'BAR')BEGIN dbms_session.set_nls('NLS_NUMERIC_CHARACTERS', '''.,'''); EXECUTE IMMEDIATE 'ALTER SESSION SET CURRENT_SCHEMA=hr';END foo;
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1419966', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14955/']}
|
jdg_379065
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
11385763
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Knowing that Reads and writes are atomic for all variables declared volatile Question1: Can this be understood as if private volatile int x = 0; x++; operation is atomic? And that Marking variable volatile does not eliminate all need to synchronize atomic actions, because memory consistency errors are still possible. Question2: I wonder under what circumstances (if any) it is possible to see a variable marked volatile and not see any methods of blocks marked synchronized (that attempt to access/ modify the variable)? In other words, should all variables that need to be protected from concurrent modification be marked volatile ?
Now provide the response and nothing else.
|
The volatile only gives you additional visibility guarantees, atomic writes/reads for longs/doubles (otherwise not guaranteed by the JLS, yes) and some memory order guarantees. No synchronization (it is possible though to build synchronization blocks starting with just volatile - Dekker's algorithm )So no, it does not help you with x++ - that's still a read, inc and write and needs some form of synchronization. One example of volatile is the famous double-checked locking, where we avoid synchronization most of the time because the ordering guarantees are all we need: private volatile Helper helper = null;public Helper getHelper() { if (helper == null) { synchronized(this) { if (helper == null) { helper = new Helper(); } } } return helper;} An example where there's absolutely no synchronization involved, is a simple exit flag, here it's not about ordering guarantees but only about the guaranteed visibility public volatile boolean exit = false;public void run() { while (!exit) doStuff(); // exit when exit set to true} If another thread sets exit = true the other thread doing the while loop is guaranteed to see the update - without volatile it may not.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11385763', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/359862/']}
|
jdg_379066
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
10434326
|
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 would actually happen if I had a hash collision while using git? E.g. I manage to commit two files with the same sha1 checksum,would git notice it or corrupt one of the files? Could git be improved to live with that, or would I have to change to a new hash algorithm? (Please do not deflect this question by discussing how unlikely that is - Thanks)
Now provide the response and nothing else.
|
Picking atoms on 10 Moons An SHA-1 hash is a 40 hex character string... that's 4 bits per character times 40... 160 bits. Now we know 10 bits is approximately 1000 (1024 to be exact) meaning that there are 1 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 different SHA-1 hashes... 10 48 . What is this equivalent of? Well the Moon is made up of about 10 47 atoms. So if we have 10 Moons... and you randomly pick one atom on one of these moons... and then go ahead and pick a random atom on them again... then the likelihood that you'll pick the same atom twice, is the likelihood that two given git commits will have the same SHA-1 hash. Expanding on this we can ask the question... How many commits do you need in a repository before you should start worrying about collisions? This relates to so called "Birthday attacks", which in turn refers to the "Birthday Paradox" or "Birthday Problem", which states that when you pick randomly from a given set, you need surprisingly few picks before you are more likely than not to have picked something twice. But "surprisingly few" is a very relative term here. Wikipedia has a table on the probability of Birthday Paradox collisions . There is no entry for a 40 character hash. But an interpolation of the entries for 32 and 48 characters lands us in the range of 5*10 22 git commits for a 0.1% probability of a collision. That is fifty thousand billion billion different commits, or fifty Zettacommits , before you have reached even a 0.1% chance that you have a collision. The byte sum of the hashes alone for these commits would be more data than all the data generated on Earth for a year, which is to say you would need to churn out code faster than YouTube streams out video. Good luck with that. :D The point of this is that unless someone is deliberately causing a collision, the probability of one happening at random is so staggeringly small you can ignore this issue "But when a collision does occur, then what actually happens?" Ok, suppose the improbable does happen, or suppose someone managed to tailor a deliberate SHA-1 hash collision . What happens then? In that case there is an excellent answer where someone experimented on it . I will quote from that answer: If a blob already exists with the same hash, you will not get any warnings at all. Everything seems to be ok, but when you push, someone clones, or you revert, you will lose the latest version (in line with what is explained above). If a tree object already exists and you make a blob with the same hash: Everything will seem normal, until you either try to push or someone clones your repository. Then you will see that the repo is corrupt. If a commit object already exists and you make a blob with the same hash: same as #2 - corrupt If a blob already exists and you make a commit object with the same hash, it will fail when updating the "ref". If a blob already exists and you make a tree object with the same hash. It will fail when creating the commit. If a tree object already exists and you make a commit object with the same hash, it will fail when updating the "ref". If a tree object already exists and you make a tree object with the same hash, everything will seem ok. But when you commit, all of the repository will reference the wrong tree. If a commit object already exists and you make a commit object with the same hash, everything will seem ok. But when you commit, the commit will never be created, and the HEAD pointer will be moved to an old commit. If a commit object already exists and you make a tree object with the same hash, it will fail when creating the commit. As you can see some cases are not good. Especially cases #2 and #3 mess up your repository. However, it does seem that the fault stays within that repository, and the attack or bizarre improbability does not propagate to other repositories. Also, it seems that the issue of deliberate collisions is being recognised as a real threat, and so for instance GitHub is taking measures to prevent it .
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/10434326', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/20555/']}
|
jdg_379067
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
8647224
|
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 keep the properties set in :hover , when you are at the address of the clicked button? To clarify let's say I have a button that turns red when I click it and it redirects to mysite.com/buttonPage.html. On buttonPage.html can I keep the button red?
Now provide the response and nothing else.
|
(1) Your <script> tag should be placed before the closing </body> tag. Your JavaScript is trying to manipulate HTML elements that haven't been loaded into the DOM yet. (2) Your assignment of HTML content looks jumbled. (3) Be consistent with the case in your element ID, i.e. 'DIV2' vs 'Div2' (4) User lower case for 'document' object (credit: ThatOtherPerson) <body><div id="DIV1"> // Some content goes here.</div><div id="DIV2"></div><script type="text/javascript"> var MyDiv1 = document.getElementById('DIV1'); var MyDiv2 = document.getElementById('DIV2'); MyDiv2.innerHTML = MyDiv1.innerHTML;</script></body>
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/8647224', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1052137/']}
|
jdg_379068
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
842
|
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:
In logic, a semantics is said to be compact iff if every finite subset of a set of sentences has a model, then so to does the entire set. Most logic texts either don't explain the terminology, or allude to the topological property of compactness. I see an analogy as, given a topological space X and a subset of it S, S is compact iff for every open cover of S, there is a finite subcover of S. But, it doesn't seem strong enough to justify the terminology. Is there more to the choice of the terminology in logic than this analogy?
Now provide the response and nothing else.
|
The Compactness Theorem is equivalent to the compactness of the Stone space of the Lindenbaum–Tarski algebra of the first-order language $L$ . (This is also the space of $0$ -types over the empty theory.) A point in the Stone space $S_L$ is a complete theory $T$ in the language $L$ . That is, $T$ is a set of sentences of $L$ which is closed under logical deduction and contains exactly one of $\sigma$ or $\lnot\sigma$ for every sentence $\sigma$ of the language. The topology on the set of types has for basis the open sets $U(\sigma) = \{T:\sigma\in T\}$ for every sentence $\sigma$ of $L$ . Note that these are all clopen sets since $U(\lnot\sigma)$ is complementary to $U(\sigma)$ . To see how the Compactness Theorem implies the compactness of $S_L$ , suppose the basic open sets $U(\sigma_i)$ , $i\in I$ , form a cover of $S_L$ . This means that every complete theory $T$ contains at least one of the sentences $\sigma_i$ . I claim that this cover has a finite subcover. If not, then the set $\{\lnot\sigma_i:i\in I\}$ is finitely consistent. By the Compactness Theorem, the set consistent and hence (by Zorn's Lemma) is contained in a maximally consistent set $T$ . This theory $T$ is a point of the Stone space which is not contained in any $U(\sigma_i)$ , which contradicts our hypothesis that the $U(\sigma_i)$ , $i\in I$ , form a cover of the space. To see how the compactness of $S_L$ implies the Compactness Theorem, suppose that $\{\sigma_i:i\in I\}$ is an inconsistent set of sentences in $L$ . Then $U(\lnot\sigma_i),i\in I$ forms a cover of $S_L$ . This cover has a finite subcover, which corresponds to a finite inconsistent subset of $\{\sigma_i:i\in I\}$ . Therefore, every inconsistent set has a finite inconsistent subset, which is the contrapositive of the Compactness Theorem.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://math.stackexchange.com/questions/842', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/277/']}
|
jdg_379069
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
141926
|
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:
trying to do a pattern matching on a list, I want to find the two members that are negatives of each other, i.e.: {0.,1.5,-1.5,4.2} I tried: listOfNumbers/. {x___, PatternSequence[z__, -z__], y___} :> {z} And every similar case, but I am missing something. Any ideas?
Now provide the response and nothing else.
|
Position[MovingAverage[mylist, 2], 0.] Example: mylist = {4, 6.8, 7.3, -7.3, 14, 22, π};Position[MovingAverage[mylist, 2], 0.] {{3}} You can then select from mylist element 3 (and subsequent one). Or: mylist[[Position[MovingAverage[mylist, 2], 0][[1]]]] {7} It even works with functions that must be evaluated: mylist = {4, 6.8, -2, Limit[4 x^2/(2 x^2 + 1), x -> \[Infinity]], -7.3, 14, 22, π};
|
{}
|
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/141926', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/44023/']}
|
jdg_379070
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1462402
|
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 know that surprisingly enough, $i^i=\frac1{e^{\frac\pi2}}$. But what about finding the value of ${i^i}^{i\cdots}$? Is it possible? My attempt : Let $${i^i}^{i\cdots}=x$$$$i^x=x$$Or $$\left(\cos\frac{\pi}{2}+i\sin\frac{\pi}{2}\right)^x=x$$$$e^{\frac{\pi}{2}ix}=x$$But can we take the $\log$ of both sides? Even if we take, $$\frac{\pi}{2}ix=\log x$$Now how to solve this equation? Edit : OKay, as pointed by @JackD'Aurizio, that we have to first check whether the given sequence converges or not. But I have no idea for how to check that? (Please answer in elementary terms)
Now provide the response and nothing else.
|
Here is a treatment of the problem that does not make use of the $W$-function. For $z\in{\mathbb C}$ we choose the following definition of $i^z\>$: $$i^z:=\exp\bigl(z\>{\rm Log}(i)\bigr)=e^{i\pi z/2}\ .$$ We then have to analyze the sequence $(z_n)_{n\geq0}$ defined by $$z_0:=1,\qquad z_{n+1}:=e^{i\pi z_n/2}\quad(n\geq0)\ .$$ The first terms of the sequence are $1$, $i$, $e^{-\pi/2}\doteq 0.207$, all in the set $A:=\overline\Omega$, where $$\Omega:=\{z=x+iy\in{\mathbb C}\>|\>|z|<1, \ x>0,\ y>0\}\ .$$ The well known properties of the exponential map show that the function $$f(z):=e^{i\pi z/2}=e^{-\pi y/2}\cdot e^{i\pi x/2}$$ maps $A$ bijectively onto the domain $B$ shaded red in the following figure, and it maps $\Omega$ onto the interior of $B$, which is a proper subset of $\Omega$. As $B\subset A$, by Brouwer's fixed point theorem $f\restriction A$ has at least one fixed point $z_*\in A$. Since no point of $\partial A$ stays fixed it follows that $z_*\in \Omega$. The Riemann mapping theorem allows to conjugate $f\restriction\Omega$ with a map $g:\>D\to D$, the unit disk of the $w$-plane, that keeps $0$ fixed. Since $g(D)\subsetneq D$ Schwarz' Lemma then guarantees $|g(w)|<|w|$ for all $w\in \dot D$. This implies that there can be no other fixed point, and more: The sequence $(w_n)_{n\geq0}$ will converge to $0$ (the assumption $\inf_{n\geq0} |w_n|=:\rho>0$ would lead to a contradiction). We therefore can conclude that $\lim_{n\to\infty} z_n=z_*$. Note that $$\bigl|f'(z_*)\bigr|=\bigl|g'(0)\bigr|<1$$ shows that $z_*$ is indeed attractive. I computed the first $200$ points $z_n$ and obtained the estimate $z_*\doteq 0.438283 + 0.360592\> i$. At the fixed point one has $\bigl|f'(z_*)\bigr|\doteq0.89$. This reveals that the convergence is not particularly fast.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1462402', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/217555/']}
|
jdg_379071
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
117146
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm trying to show that for every real number $r$, there exists a sequence of rational numbers $\{q_{n}\}$ such that $q_{n} \rightarrow r$. Could I get some comments on my proof? I know that between 2 reals $r, b$ there exists a rational number $m$ such that $r < m < b$.So I can write $r < q_{1} < b$ ; Now check if $q_{1} = r$ or not. If it does I'm done, and if not, I consider the interval $(a, q_{1})$. $r < q_{2} < q_{1}$ check if $q_{2} = r$ or not. If it does I'm done, and if not, I consider the interval $(a, q_{3})$ If I continue in this manner, I see that $|r - q_{n+1}| < |r - q_{n}|$. So whether $r$ is rational or irrational, I'm making my the size of the interval $(r, q_{n})$ closer to 0 and as $n \rightarrow \infty$. And so given any $\epsilon > 0$, I know that $|q_{n} - r| < \epsilon$. Revision Let $\{q_{n} \}$ be a sequence of rational numbers and $q_{n} \rightarrow r$ where $r \in \mathbb{R}$. If $r$ is rational, then let every element of $q_{n} = r$. But if $r$ is irrational, then consider the interval $(r, b)$ where $b \in \mathbb{R}$. Since we can always find a rational number between two reals, consider $r < q_{1} < b$. Now pick $q_{2}$ such that $q_{2}$ is the midpoint of $r$ and $q_{1}$. So we get that $r < q_{2} < q_{1}$. Then repeat the process so that $r < q_{n} < q_{n-1}$. Note that $|r - q_{n}| = \frac{1}{2}|r - q_{n-1}|$. As we take more values for $q_{n}$, it is clear that $|q_{n} - r| \rightarrow 0$. So given any $\epsilon > 0$, $|q_{n} - r| < \epsilon$.
Now provide the response and nothing else.
|
You have the right idea but you are handwaving. You are not telling exactly how you will pick the rationals, and how their limit is $r$. Also $|r - q_{n+1}| \lt |r - q_n|$ does mean $q_n \to r$. For instance, $\left|-1 - \frac{1}{n+1}\right| \lt \left|-1 - \frac{1}{n}\right|$, but $\frac{1}{n} \to 0$, and not $-1$. Also, you don't have to check if $q_i = r$, as you pick $r \lt q_i$. (Also, the above writeup contains a possible hint, try to find it :-)) Since you are almost there (based on your Revision) (but note: you still are handwaving and don't have a "proper" proof yet..) Here is the hint I was referring to: Since there is at least one rational in $(r, r+\frac{1}{n})$. Pick one and call it $q_n$. What is the limit of $q_n$? A different proof: Consider the set $S = \{q: q \ge r, q \in \mathbb{Q}\}$. Show that $\inf S = r$ and show that that implies there is a sequence $q_n \in S$ whose limit is $r$.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/117146', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/26139/']}
|
jdg_379072
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
22454258
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have an app, that allowing the end user to enter his desired slug. What I am looking for is a regex that check if the slug is valid. In general, as valid a mean a string that start and ends with a latin leter, divided by dashes but not more than one dashes. More specific, the following is correct: one-two-three The following are not: one---two-thee--one-two-threeone-two-three- So with the following regex I am somewhow ok, but how can I check if in the middle of the string there are no more than two dashes ? ^[a-z][a-z][a-z]$ Is there a better way to write this regex, in order to meet my validation creteria ?
Now provide the response and nothing else.
|
http://regexpal.com/ can be a great webpage for checking your regexes as you write them. A handy tool :). Having a look at yours, should it accept capital letters/numbers? If so maybe this will help : /^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$/ This will only match sequences of one or more sequences of alphanumeric characters separated by a single -. If you do not want to allow single words (e.g. just hello), replace the * multiplier with + to allow only one or more repetitions of the last group. Here's a link to a live sample from the same thread to demonstrate. Changing around the A-Za-z0-9 inside the squares will allow you to only accept capitals,non-capitals or numbers as is appropriate to you. Good luck and let me know if you have any more questions ! :)
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/22454258', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/366664/']}
|
jdg_379073
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1261
|
Below is a question asked on the forum unix.meta.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Sometimes I come across superfluous uses of cat , e.g.: $ cat file | grep pattern instead of: $ grep pattern file or: $ cat file | somecommand options instead of: $ somecommand options < file or: $ <file somecommand options I tend to directly edit those cases and remove the useless uses of cat . What do you think, is that a best practice for the Unix & Linux stackexchange, or should other actions (e.g. adding a comment) be preferred? On what is useless The above examples and link are about useless-uses-of-cat - why useless? Basically because an unnecessary call of cat is made, i.e. a fork() and a /exec() system call are wasted. It is useless because concatenating just one thing results in that one thing (input = output, the indentity function). Note that the context still matters. For a class of useless-uses-of cat the concatenation of one file is a necessity but not sufficient. Useful examples: a command line where cat foo | is used as an example to provide a non-seekable input is a useful use of cat a command line where cat is used to output a proprietary source (e.g. MVS datasets on ceratin IBM systems) a command like ( cmd1; cat midpart; cmd2; cat bottom; ) > completeoutput Usually, it should not be difficult to spot useless-uses-of-cat because of the context.
Now provide the response and nothing else.
|
If you don't mind a dissenting opinion from a junior member here, I'd like to say: please don't. Although it may be useless on its own, cat somefile is a nice stand-in for dosomething --write-to stdout . So, to take a simple case, let's pretend someone asks the question, "How do I only show the non-blank lines in myfile.conf?" The answer grep -v ^$ < myfile.conf might be more pleasing to read than cat myfile.conf | grep -v ^$ , but it's not as helpful to the person with the similar question, "How do I only show the non-blank lines in the output from my application?" The UUOC answer, though, let's them just copy the | grep -v ^$ part and paste it onto their command line after the command invocation, see that it works, give you an upvote, and close their browser and get back to work. Of course this becomes a lot more useful when you start doing something more complex, such as chaining commands together. In a script, as I'm debugging it and trying to understand how each command affects the stream, I might start out with: foo --bar > file1.txtcat file1.txt | sort -r > file2.txtcat file2.txt | uniq -c and now I can examine the intermediate files, and, once I'm convinced that the right thing is happening each time, put everything together easily with just copy-and-paste or removing the excess junk: foo --bar | sort -r | uniq -c Hardly the most interesting example, of course. But being able to just replace cat somefile with something-interesting is a simple thing to do when you're still trying to understand how the stuff after your UUOC is going to behave. Stack Exchange sites are here to (among other things) help people learn, and being a little more verbose helps accomplish that.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://unix.meta.stackexchange.com/questions/1261', 'https://unix.meta.stackexchange.com', 'https://unix.meta.stackexchange.com/users/1131/']}
|
jdg_379074
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
11617
|
Below is a question asked on the forum cstheory.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Edit: there is now a follow-up question related to this post. Definitions Let $c$ and $k$ be integers. We use the notation $[i] = \{1,2,...,i\}$. A $c \times c$ matrix $M = (m_{i,j})$ is said to be a $c$-to-$k$ colouring matrix if the following holds: we have $m_{i,j} \in [k]$ for all $i, j \in [c]$, for all $i,j,\ell \in [c]$ with $i \ne j$ and $j \ne \ell$ we have $m_{i,j} \ne m_{j,\ell}$. We write $c \leadsto k$ if there exists a $c$-to-$k$ colouring matrix. Note that the diagonal elements are irrelevant; we are only interested in the non-diagonal elements of $M$. The following alternative perspective may be helpful. Let $R(M,\ell) = \{ m_{\ell,i} : i \ne \ell \}$ be the set of non-diagonal elements in row $\ell$, and similarly let $C(M,\ell) = \{ m_{i,\ell} : i \ne \ell \}$ be the set of non-diagonal elements in column $\ell$. Now $M$ is a $c$-to-$k$ colouring matrix iff $$R(M,\ell) \subseteq [k], \quad C(M,\ell) \subseteq [k], \quad R(M,\ell) \cap C(M,\ell) = \emptyset$$ for all $\ell \in [c]$. That is, row $\ell$ and column $\ell$ must consist of distinct elements (except, of course, at the diagonal). It may or may not be helpful to try to interpret $M$ as a special kind of hash function from $[c]^2$ to $[k]$. Examples Here is a $6$-to-$4$ colouring matrix: $$\begin{bmatrix}-&2&2&1&1&1\\3&-&3&1&1&1\\4&4&-&1&1&1\\3&2&2&-&3&2\\4&2&2&4&-&2\\3&4&3&4&3&-\end{bmatrix}.$$ In general, it is known that for any $n \ge 2$ we have $${2n \choose n} \leadsto 2n.$$ For example, $20 \leadsto 6$ and $6 \leadsto 4$. To see this, we can use the following construction (e.g., Naor & Stockmeyer 1995). Let $c = {2n \choose n}$ and let $k = 2n$. Let $f$ be a bijection from $[c]$ to the set of all $n$-subsets of $[2n]$, that is, $f(i) \subseteq [2n]$ and $|f(i)| = n$ for all $i$. For each $i,j \in [c]$ with $i \ne j$, choose arbitrarily $$m_{i,j} \in f(i) \setminus f(j).$$ Note that $f(j) \setminus f(i) \ne \emptyset$. It is straightforward to verify that the construction is indeed a colouring matrix; in particular, we have $R(M,\ell) = f(\ell)$ and $C(M,\ell) = [k] \setminus f(\ell)$. Question Is the above construction optimal? Put otherwise, do we have $${2n \choose n} + 1 \leadsto 2n$$ for any $n \ge 2$? It is well-known that the above construction is asymptotically tight; necessarily $k = \Omega(\log c)$. This follows, e.g., from Linial's (1992) result or from a straightforward application of Ramsey theory. But to me it is not clear whether the construction is also tight up to constants. Some numerical experiments suggest that the above construction might be optimal. Motivation The question is related to the existence of fast distributed algorithms for graph colouring. For example, assume that we are given a directed tree (all edges oriented towards a root node), and assume that we are given a proper $c$-colouring of the tree. Now there is a distributed algorithm that computes a proper $k$ colouring of the tree in $1$ synchronous communication round if and only if $c \leadsto k$.
Now provide the response and nothing else.
|
The construction is optimal in the sense that $\binom{2n}{n}+1 \leadsto n$ cannot hold. Indeed, it is easy to see that c -to- k coloring matrix exists if and only if there are c subsets A 1 , …, A c of the set {1, …, k } such that no distinct i and j satisfy A i ⊆ A j . (For the “only if” direction, take A i = R ( M , i ) for a c -to- k coloring matrix M . For the “if” direction, set m ij ∈ A i ∖ A j .) A family of sets none of which contains another is called a Sperner family , and it is Sperner’s theorem that the maximum number of sets in a Sperner family on the universe of size k is $\binom{k}{\lfloor k/2\rfloor}$. This implies that $c \leadsto k \iff c \le \binom{k}{\lfloor k/2\rfloor}$.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://cstheory.stackexchange.com/questions/11617', 'https://cstheory.stackexchange.com', 'https://cstheory.stackexchange.com/users/74/']}
|
jdg_379075
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
30309038
|
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 following program: #include <iostream>#include <stdexcept>#include <string>using namespace std;class MyError : public runtime_error{ public: MyError(string mess = ""); ~MyError(void); }; MyError::MyError(string mess) : runtime_error(mess) { cout << "MyError::MyError()\n"; } MyError::~MyError(void) { cout << "MyError::~MyError\n"; }int main(void){ try { throw MyError("hi"); } catch (MyError& exc) { cout << exc.what() << endl; } cout << "goodbye\n"; return 0;} Which prints the following: MyError::MyError()MyError::~MyErrorhiMyError::~MyErrorgoodbye Why is the destructor of the exception ( ~MyError() ) called twice? I assumed that throw creates a new object, but I do not understand why the class destructor is called.
Now provide the response and nothing else.
|
If you instrument the exception's copy or move constructor, you'll find it's called once before the handler. There's a temporary exception object into which the thrown expression is copied/moved, and it is this exception object to which the reference in the handler will bind. C++14 15.1/3+ So the execution resulting from your code looks something like this (pseudo-C++): // throw MyError("hi"); expands to:auto tmp1 = MyError("hi");auto exceptionObject = std::move(tmp1);tmp1.~MyError();goto catch;// catch expands to:MyError& exc = exceptionObject;cout << exc.what() << endl;// } of catch handler expands to:exceptionObject.~MyError();// normal code follows:cout << "goodbye\n";
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/30309038', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3776194/']}
|
jdg_379076
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
17130348
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
#include <stdio.h>int main(){ struct bitfield { unsigned a:5; unsigned c:5; unsigned b:6; } bit; char *ptr; struct bitfield bit1={1,3,3}; ptr=&bit1; ptr++; printf("%d",*ptr); return 0;} Output to this question is 12. How is it coming? Can anyone please explain it?I tried my best to explain it.
Now provide the response and nothing else.
|
Explanation to this question is fairly SIMPLE : Binary value of 1 is 00001 (as "a" have 5 bitfield)Binary value of 3 is 00011 (as "c" have 5 bitfield)Binary value of 3 is 000011 (as "b" have 6 bitfield) Memory Layout can be visualized as this : First 5 Bits are occupied by a and have value 00001. Then 5 bits are occupied by b having value 00011 and last 6 bits by c having value 000011. So, at starting pointer ptr is at memory location 1000, and now when you did ptr++ . Since sizeof(char) is 1, ptr will move by 1 memory location. So ptr moves to memory location 1001. Hence *ptr will give you the value stored at memory location 1001,and Hence the answer will be the 12
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17130348', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
|
jdg_379077
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
61278
|
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 method do you use when you want to get performance data about specific code paths?
Now provide the response and nothing else.
|
This method has several limitations, but I still find it very useful. I'll list the limitations (I know of) up front and let whoever wants to use it do so at their own risk. The original version I posted over-reported time spent in recursive calls (as pointed out in the comments to the answer). It's not thread safe, it wasn't thread safe before I added the code to ignore recursion and it's even less thread safe now. Although it's very efficient if it's called many times (millions), it will have a measurable effect on the outcome so that scopes you measure will take longer than those you don't. I use this class when the problem at hand doesn't justify profiling all my code or I get some data from a profiler that I want to verify. Basically it sums up the time you spent in a specific block and at the end of the program outputs it to the debug stream (viewable with DbgView ), including how many times the code was executed (and the average time spent of course)). #pragma once#include <tchar.h>#include <windows.h>#include <sstream>#include <boost/noncopyable.hpp>namespace scope_timer { class time_collector : boost::noncopyable { __int64 total; LARGE_INTEGER start; size_t times; const TCHAR* name; double cpu_frequency() { // cache the CPU frequency, which doesn't change. static double ret = 0; // store as double so devision later on is floating point and not truncating if (ret == 0) { LARGE_INTEGER freq; QueryPerformanceFrequency(&freq); ret = static_cast<double>(freq.QuadPart); } return ret; } bool in_use; public: time_collector(const TCHAR* n) : times(0) , name(n) , total(0) , start(LARGE_INTEGER()) , in_use(false) { } ~time_collector() { std::basic_ostringstream<TCHAR> msg; msg << _T("scope_timer> ") << name << _T(" called: "); double seconds = total / cpu_frequency(); double average = seconds / times; msg << times << _T(" times total time: ") << seconds << _T(" seconds ") << _T(" (avg ") << average <<_T(")\n"); OutputDebugString(msg.str().c_str()); } void add_time(__int64 ticks) { total += ticks; ++times; in_use = false; } bool aquire() { if (in_use) return false; in_use = true; return true; } }; class one_time : boost::noncopyable { LARGE_INTEGER start; time_collector* collector; public: one_time(time_collector& tc) { if (tc.aquire()) { collector = &tc; QueryPerformanceCounter(&start); } else collector = 0; } ~one_time() { if (collector) { LARGE_INTEGER end; QueryPerformanceCounter(&end); collector->add_time(end.QuadPart - start.QuadPart); } } };}// Usage TIME_THIS_SCOPE(XX); where XX is a C variable name (can begin with a number)#define TIME_THIS_SCOPE(name) \ static scope_timer::time_collector st_time_collector_##name(_T(#name)); \ scope_timer::one_time st_one_time_##name(st_time_collector_##name)
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/61278', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3848/']}
|
jdg_379078
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
646549
|
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 have encountered this topology.As you can see, there is a constant 3.5V voltage source connected to the non-inverting op-amp input.It's clear that this is an inverting op-amp ampifier but I couldn't figure out what exactly the R7 resistor is.Does this topology have a specific purpose (especially R7 resistor)?
Now provide the response and nothing else.
|
The challenge It is always a big challenge to understand a circuit that is new to you. Let's then try to do it with the OP's "topology"... Analyzing the circuit I suggest that we analyze their circuit from left to right (as input signals flow). First we see two input sources - one is constant (3.5 V) and the other is adjustable. Non-inverting amplifier We can drive the non-inverting input of the op-amp through the first voltage source; then the circuit name would be "non-inverting amplifier". Inverting amplifier With the same success, we can drive the inverting input of the op-amp through the second voltage source; then the circuit name would be "inverting amplifier". Differential amplifier We can even drive both op-amp inputs through both sources; then the circuit name would be "differential amplifier". Indeed, it is quite imperfect since the two input gains are not equalized. Reference voltage source Once set, the "adjustable voltage source" becomes a "constant voltage source" like the other; so both can be considered as input sources. Thus both input voltages are constant and the op-amp output voltage is also constant; so the name of this circuit can be "buffered reference voltage source". The role of bias voltage The non-inverting configuration is more suitable for such an application because it is "self-biased". Let's consider the need of another (bias) voltage source here, in this inverting cobfiguration... The op-amp is supplied only by one (7 V) voltage source. So the output voltage can be positive between 0 V and 7 V. To obtain it, the second (adjustable) voltage applied (through R3) to the inverting input has to be lower than the first (3.5 V) voltage applied directly to the non-inverting input. So this is the role of the first (3.5 V) voltage source - to "lift" ("bias") the voltage applied to the non-inverting input above the adjustable voltage. If the non-inverting input was directly grounded, the adjustable voltage has to be negative (undesired). Let's see what the "biasing" means here. We have actually added another voltage source in series and opposite to the input source so that their voltages subtract. The voltage sources are connected in series (regarding the op-amp differential input) and both they are grounded. In other cases (e.g., AC common emitter ampifier stage), a floating bias voltage (across a charged capacitor) is added to the voltage of the grounded input source. So the biasing is adding a positive or negative constant voltage to the input voltage. The role of resistors ... R7 In my opinion, the resistor R7 is connected between the two input voltage sources for the case when the 3.5 V voltage source is disconnected. Then the op-amp will be saturated (maybe undesired). With this "protecting resistor", all voltages (including the output one) will be equal to the adjustable voltage. There is no such a problem with disconnecting the adjustable voltage source since the inverting amplifier will become a follower. ... R8 and R10 This network acts as a load consisting of two resistors in series... but what the hell this is (still) I can't figure out. It practically does nothing because one of the resistors is too high (100 k). Perhaps the idea is to be able to short R10 in order to study the circuit behavior under heavy (330 ohm) load... ... R3 and R6 Since a good situation has been created here that stimulates and not suppresses original thoughts (rarely found in SE EE), I will allow myself to "philosophize" a little on this simple network of the two resistors R3 and R6 in series. I think this will be helpful for the OP (I know it from personal experience since the late 70s when I was frantically trying to figure out what the hell these resistors were). R3-R6 network is a simple voltage summer that adds (subtracts) the circuit input and output voltages. It can be considered as a 2-input voltage divider. The op-amp adjusts its output voltage to make the difference (the summer output voltage) zero. As a result, the proportion between voltages (circuit gain) is the same as between the resistors... and it depends only on the latter. It seems a little difficult to understand but it is actually all around us and we all operate according to this principle known by the trivial name "negative feedback". Generalization We saw a few powerful ideas here that we can add to our "collection of circuit principles": Biasing: To match the input voltage to the input range of a device (amplifier, ADC, etc.), add an appropriate (in sign and value) constant voltage to the input voltage. Voltage self-switching: To change the voltage of a real source driving a high-resistance load, connect an "ideal" source in parallel. NFB inverting: Subtract the output from the input voltage in a parallel manner (through resistors) to obtain an inverted copy of the input voltage. NFB inverting amplification: Subtract a part of the output from the input voltage to obtain an inverted and amplified copy of the input voltage. NFB following: Use the result of parallel subtraction as an exact copy of the input voltage. See also How to Understand Circuits is a story from my Circuit Idea wikibook that reveals the philosophy of understanding. Two other stories reveal the philosophy of explaining and inventing circuits. What is the idea behind the op-amp instrumentation amplifier? is my Codidact story about the philosophy behind the related differential and instrumentation amplifier.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/646549', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/248057/']}
|
jdg_379079
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
7790561
|
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 field: <input type='number' /> I'd like to punch in 0.50 without it “correcting it” to 0.5 , so it would display 0.50 .
Now provide the response and nothing else.
|
I've had a little play around with this and looked at the spec. It says that it must be a valid floating point number. There's one sentence in the definition of a valid floating point number it gives which caught my attention: The best representation of the number n as a floating point number is the string obtained from applying the JavaScript operator ToString to n. This means that the format will always be consistent with assessing what the number is, then using JavaScript's toString on that number. So no trailing 0s then. So, you're going to have to resort to JavaScript. This isn't straightforward because document.getElementById('numInput').value = '0.50'; still gets corrected to 0.5 , so the validation isn't triggered at onchange where the default action can be prevented, it's triggered internally. This is the best solution I could come up with... it's a bit of a hack, and will need a bit of tweaking for robustness, but hopefully it'll do what you want: var numInput = document.getElementById('numInput');numInput.addEventListener('keypress', function () { this.setAttribute('type', 'text');});numInput.addEventListener('click', function () { this.setAttribute('type', 'number');}); So if the user wants to enter the number by typing, it switches the input type to text, but when they click it, it converts it back to a number. If you always want the trailing 0s no matter what the user types, then you could do it something like this: var numInput = document.getElementById('numInput');numInput.addEventListener('blur', function () { if (this.value === '') { return; } this.setAttribute('type', 'text'); if (this.value.indexOf('.') === -1) { this.value = this.value + '.00'; } while (this.value.indexOf('.') > this.value.length - 3) { this.value = this.value + '0'; }});numInput.addEventListener('focus', function () { this.setAttribute('type', 'number');}); Edit: I think the second solution is more inline with what the user might expect, but it means that if the user types 0.5 it will be coerced to 0.50 , so it depends if that's what you want.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7790561', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/950147/']}
|
jdg_379080
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
636997
|
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 an HP DL380 G5 server and a PCI-E card that I need to use in the server. The problem: the PCI-E card requires additional power from a 4-pin floppy connector, and the HP DL380 G5's PSU has no floppy connector cables (in fact, the PSU plugs directly into the motherboard and has no connector cables whatsoever). Is there any other way I can provide power to the PCI-E card? Are there adapters that allow me to draw power from a USB connector or one of the many proprietary connectors on the motherbord? Can I buy another PCI card with a floppy connector that I can use to drive my PCI-E card? My googling has given me a bunch of USB to Molex adapter cables, but no USB to floppy connector adapters. I know the ideal solution would be to buy a different sound card or somehow find a server with a 4-pin floppy connector, but we're a low-budget college student operation and I'd rather do some MacGyvering than to spend more from our (non-existent) budget.
Now provide the response and nothing else.
|
Edit: For what you need, I'd really suggest trying a different sound card. But if you want to see MacGyver ... I've needed to provide auxiliary power in various HP ProLiant 2U chassis configurations. I'm sorry you're working with an older G5 HP, but you have some options. Pull power from internal or external USB. Splice power from the PSU connection. There should be a 4-pin or 10-pin Molex connector intended for the drive backplane bay and CD-ROM cage. You can tap that. If you're really desperate, you can tap power from a SAS drive slot. pulling power from a DL380 G6 drive cage power header pulling from SATA CD-ROM motherboard header HP ProLiant drive backplane running power to the PCIe cage Unusable drive bay
|
{}
|
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/636997', 'https://serverfault.com', 'https://serverfault.com/users/193456/']}
|
jdg_379081
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
161845
|
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:
In trying to learn Mathematica by solving problems as I study Abstract Algebra, I was trying to solve the following very simple problem. Given a set {x1, x2, ... , xN} , find all possible products of all the elements in this set using parentheses. So, for the set {x1,x2, x3} , the answer will be { (x1 . x2) . x3, x1 . (x2 . x3) } I create the list as follows : listx[n_]:= Table[Subscript[x,i], {i, n}] How do I compute the possible products with parentheses ?
Now provide the response and nothing else.
|
For each n , you obtain the new list of possibilities by multiplying each possibility for n-1 once from the left and once from the right (modulo renaming of elements). I use m[x,y] to represent the parentheses. listx = n \[Function] Thread[Subscript[x, Range[n]]];step = a \[Function] With[{n = Max[Cases[a, _Integer, \[Infinity]]]}, Join[ Map[b \[Function] m[Subscript[x, 1], b], a /. Thread[Range[1, n] -> Range[2, n + 1]]], Map[b \[Function] m[b, Subscript[x, n + 1]], a] ] ];possibilities = n \[Function] Nest[step, {m @@ listx[2]}, n - 2];possibilities[3] possibilities[4] Edit kglr pointed me to an error in the implementation above. The code below uses a similar strategy by composing new possibilities from old ones, but now in an exhaustive way. ClearAll[f];f[1] = {Subscript[x, 1]};f[2] = {m[Subscript[x, 1],Subscript[x, 2]]};f[n_] := f[n] = Flatten[Table[ Outer[m, f[i], f[n - i] /. Thread[Range[1, n - i] -> Range[i + 1, n]]], {i, 1, n - 1}] ]f[4] // Column // TeXForm $\begin{array}{l} > m\left(x_1,m\left(x_2,m\left(x_3,x_4\right)\right)\right) \\ > m\left(x_1,m\left(m\left(x_2,x_3\right),x_4\right)\right) \\ > m\left(m\left(x_1,x_2\right),m\left(x_3,x_4\right)\right) \\ > m\left(m\left(x_1,m\left(x_2,x_3\right)\right),x_4\right) \\ > m\left(m\left(m\left(x_1,x_2\right),x_3\right),x_4\right) \end{array}$ Surprisingly, this is also a bit quicker than using Groupings . (And it produces the same results (up to reordering)).
|
{}
|
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/161845', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/8370/']}
|
jdg_379082
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
186237
|
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 think it might help to think of the following definition of a Ramanujan graph - a graph whose non-trivial eigenvalues are such that their magnitude is bounded above by the spectral radius of its universal cover. By "non-trivial eigenvalues" I mean all the eigenvalues except the highest and the smallest. A universal cover of a graph is the infinite tree such that every connected lift of the graph is a quotient of the tree. The spectral radius of a graph would be the norm of its adjacency matrix. It would be helpful if people can give any pointers along these directions..
Now provide the response and nothing else.
|
In fact, the original motivation behind Lubotzky--Phillips--Sarnak's construction of Ramanujan graphs was in analogy with modular curves $Y(N)=\mathbb H^2/\Gamma(N)$ for the principal congruence subgroups $\Gamma(N)\subseteq\operatorname{PSL}(2,\mathbb Z)$. So the answer is yes, there is a continuous analogue, but in fact it came first! Let me give a few more details. The spectrum of the Laplacian $\Delta$ on hyperbolic space $\mathbb H^2$ consists of $[\frac 14,\infty)$. Selberg proved that the smallest positive eigenvalue of the Laplacian on $Y(N)$ satisfies $\lambda_1(Y(N))\geq\frac 3{16}$, and conjectured that $\lambda_1(Y(N))\geq\frac 14$. Note that $\frac 14$ is exactly the inf of the spectrum of $\Delta$ on the universal cover $\mathbb H^2$. You can read more about this in an article by Sarnak . As far as I understand things, Lubotzky--Phillips--Sarnak's examples of Ramanujan graphs are discrete analogues of modular curves.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/186237', 'https://mathoverflow.net', 'https://mathoverflow.net/users/38852/']}
|
jdg_379083
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
391159
|
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:
A long time ago when starting learning programming I remember a teacher saying that compiler do not care about whitespace and they are useful to make code readable for human beings. It made perfect sense back then, but I only knew some Pascal and C++. Many years later, after diving in many other languages I began wondering what is the rational of having programming languages that rely on indentation / white space, as there are quite a few disadvantages: Stange errors like this one (unindent does not match any oute indentation level) Minifying still requires extra whitespace - example Many other reasons as indicated in this Quora post : lack of white space indentation across operating systems / text editors whitespace might be introduced while doing code merge possible errors while copy-pasting all modern IDEs automatically indent code Question: Why do we still have programming languages that rely on indentation / white space?
Now provide the response and nothing else.
|
What do you mean, "still"? Whitespace-delimiting is an advanced feature. Lisp, Algol, Pascal, C etc. etc. were delimited by BEGIN..END or by bracket characters. The focus in early programming languages was to get the computer to do what we wanted at all . It mattered little if the formatting looked clunky. But then programming became a huge success story, and programs, modules, and entire systems became huge and unwieldy. Eventually we realized that making the code look good for human readers was just as important as making it understandable for computers, because no one would be able to maintain old code otherwise. Mirroring logical structure (nesting) with indentation turned out to be a very good way of achieving this. Proper indenting became a standard rule of clean code. Eventually people realised that the indentation could be used to inform both programmers and computers: with proper indenting - which every style guide already said you should be using anyway - you could in fact omit Pascal's BEGIN..END, or Lisp's wastelands of parentheses, or C/Java's brackets, and readability would be even better. This last point is controversial, but historically, whitespace delimitation is the endpoint of a development, not a remnant.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://softwareengineering.stackexchange.com/questions/391159', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/207359/']}
|
jdg_379084
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
8258480
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Does java.util.UUID generates special characters? What are the type of each character (eg- Uppercase, lower case, digits) generated by UUID.
Now provide the response and nothing else.
|
tl;dr You asked: Does java.util.UUID generates special characters? No. A UUID is actually a 128-bit value , not text. A UUID’s textual representation is canonically a string of hex digits (0-9, a-f, A-F) plus hyphens. You asked: What are the type of each character (eg- Uppercase, lower case, digits) generated by UUID. As required by the UUID spec, any a-to-f characters in the hex string representing a UUID value must be in all lowercase . But violations abound. UUID ≠ text To clarify, a UUID is actually a 128-bit value , not text, not digits. You could think of them as 128-bit unsigned integers. But they are not actually numbers, as certain bit positions have semantics, specific meanings. Which bits have which meanings varies by variant and by version of UUID. Hex string Humans don't do well reading and writing 128 bits as 128 1 and 0 characters. When a UUID needs to be written for human consumption, we use a base-16 Hexadecimal (digits 0 - 9 and letters a - f ) string. We use 32 hex characters grouped with 4 hyphens to represent those 128 bits in a total of 36 characters. For example: 550e8400-e29b-41d4-a716-446655440000 No "Special" Characters As for "special characters" mentioned in the Question, you will only see these 23 possible characters in a hex-string representation of a UUID: abcdefABCDEF1234567890- Lowercase Required By Spec The latest international spec dated 2008-08 states (emphasis mine): 6.5.4 Software generating the hexadecimal representation of a UUID shall not use upper case letters.NOTE – It is recommended that the hexadecimal representation used in all human-readable formats be restricted to lower-case letters. Software processing this representation is, however, required to accept both upper and lower case letters as specified in 6.5.2. Violations Common However, Microsoft, Apple, and others commonly violate the lowercase rule. At one point Microsoft released software that generated mixed case (using both upper- and lowercase), apparently an unintended feature. So do as the spec says: Use lowercase for output. Tolerate either lowercase or uppercase for input. The Java documentation for the UUID class’ toString method documents in BNF that uppercase is allowed when generating a string, in contradiction to the UUID standard specification. However the actual behavior of the class and its toString method in the Oracle implementation for Java 8 is correct, using lowercase for output but tolerating either uppercase or lowercase for input. Input in either lower-/uppercase: UUID uuidFromLowercase = UUID.fromString ( "897b7f44-1f31-4c95-80cb-bbb43e4dcf05" ); UUID uuidFromUppercase = UUID.fromString ( "897B7F44-1F31-4C95-80CB-BBB43E4DCF05" ); Output to lowercase only: System.out.println ( "uuidFromLowercase.toString(): " + uuidFromLowercase );System.out.println ( "uuidFromUppercase.toString(): " + uuidFromUppercase ); uuidFromLowercase.toString(): 897b7f44-1f31-4c95-80cb-bbb43e4dcf05 uuidFromUppercase.toString(): 897b7f44-1f31-4c95-80cb-bbb43e4dcf05 See this code run live in IdeOne.com . Nil value When the UUID is not yet known, you can use a special UUID consisting of all zeros. 00000000-0000-0000-0000-000000000000 Example Values You can see some examples of UUID values by using any of the many web sites that generate values. For example: https://www.uuidgenerator.net/ Or use a command-line tool. Nearly every operating system comes bundled with such a tool. On macOS , launch Terminal.app and type uuidgen .
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/8258480', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/300097/']}
|
jdg_379085
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
18274534
|
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 Java EE application which should start a synchronization process with an external system once after its deployment. How could I implement this requirement?
Now provide the response and nothing else.
|
Below are listed a couple of popular methods for getting lifecycle callbacks in JavaEE apps. Create a javax.servlet.ServletContextListener implementation If you have a web component to your .ear file (embedded .war) or your deployment is a .war by itself you can add a ServletContextListener to your web.xml and get a callback when the server starts or is shutting down. Example: package com.stackoverflow.questionimport javax.servlet.ServletContextListener;import javax.servlet.ServletContextEvent;public class MyServletContextListener implements ServletContextListener{ @Override public void contextInitialized(ServletContextEvent contextEvent) { /* Do Startup stuff. */ } @Override public void contextDestroyed(ServletContextEvent contextEvent) { /* Do Shutdown stuff. */ }} and then add this configuration to your web.xml deployment descriptor. $WAR_ROOT/WEB-INF/web.xml . <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee"> <listener> <listener-class>com.stackoverflow.question.MyServletContextListener</listener-class> </listener></web-app> Create an EJB 3.1 @Startup Bean This method uses an EJB 3.1 singleton to get a startup and shutdown callback from the server. import javax.annotation.PostConstruct;import javax.annotation.PreDestroy;import javax.ejb.Startup;import javax.ejb.Singleton;@Singleton@Startuppublic class LifecycleBean { @PostConstruct public void init() { /* Startup stuff here. */ } @PreDestroy public void destroy() { /* Shutdown stuff here */ }}
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18274534', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/844177/']}
|
jdg_379086
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
63537
|
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
Our source code is our most prized asset. I would like to have it: secured from proliferation by in-house developers but they also need unrestricted access to the code to do their job right. So I'm not sure this is even possible. regularly backed up to secure location , but would it be safe to upload it to a cloud storage such as box.net? Any recommendations on strategies?Or am I paranoid?
Now provide the response and nothing else.
|
Securing things from the actions of your people is more a human issue than a technology one unfortunately, so I'll leave that for others to answer (humans are not my forté - machines: yes, cats: sometimes, humans: no!). If you are sending your code to any external service you either have to make sure it is securely encrypted before it is sent, or that you have fully vetted the external service, preferably both. Running your own backup servers will be safer (you have more direct control) but more complex (you have to do everything yourself). As your backup servers will probably be running in colo space that you don't have physical control of you might want to set the data on encrypted filesystems that do not auto-mount on boot (have them require manual intervention, to send over the key(s), if the servers need restarting) - having the keys on the server so it can auto-mount the encrypted volumes is like having an expensive safe with the combination written on a post-it note near by. Either way, you should have offline backups as well as online ones - i.e. discs/tapes offsite and not connected. That way if you are thoroughly hacked and all your core servers, local backups and hosted online backups are wrecked you should still have the offline backups to roll back to. One way to mitigate the problem of a hacker breaking into your main servers and using them to break into your backup servers (which happened to a relatively high profile web service a few months ago) I suggest having an intermediate service that both the live and backup servers connect to. That way you can arrange for neither the live or backup servers to have access to each other, and the intermediate server doesn't need to log in to either live or backup. The live sites would log into the intermediate server to push the most recent data and some time after the backup servers would login to pull it to themselves. This doesn't remove the recommendation of having offline offsite backups too, though it reduces your chance of needing to use them in anger. One extra option for hosting your external backups: if you are on very good terms with another local non-competing business you could perhaps host each other's backups. You might still encrypt your backups for true paranoia though (not in case the other business goes bad, though that could happen, but to cover for the possibility that they get hacked or burgled themselves). And one extra point that is all too often neglected: make sure you have a procedure in place for testing the backups . You don't want to find they stopped working for some reason weeks ago on the day that you need to restore something from them. There are a numbber of ways to test your backups, the best one to go for depends on the nature and size of data you are storing and the format it is stored in. For instance, I have a copy of my mail server running in a VM that thinks it is the live server but is not seen from the outside world. Three times a week a script stops it, restores the most recent backup to it, and restarts it, any errors being mailed to me. Then as part of my regular house keeping I login to this backup VM to check everything looks OK (it is running, recent changes are present, a random sample of old data looks OK too, ...). You should still occasionally manually test the backups, but automated tests are sometimes a godsend - they might flag a minor problem before it becomes a major one. It is difficult to be too paranoid when looking after your source code. It is your core asset, your business may be worth nothing without it, so you need to guard it from outside malicious forces (including natural forces!) very carefully.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/63537', 'https://serverfault.com', 'https://serverfault.com/users/17904/']}
|
jdg_379087
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
54327
|
Below is a question asked on the forum skeptics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I read from several places that Bertrand Russell spent many pages in Principia Mathematica to prove 1 + 1 = 2, e.g. here said "it takes over 360 pages to prove definitively that 1 + 1 = 2 ", while here said 162 pages. I do not believe that is the case, however, as I don't see why you'd need to prove 1+1=2 in the first place. But Wikipedia's article for Principia Mathematica mentions: "From this proposition it will follow, when arithmetical addition hasbeen defined, that 1 + 1 = 2." – Volume I, 1st edition, p. 379 So did Bertrand Russell actually spend 360 pages proving that 1 + 1 = 2? What did Bertrand Russell want to accomplish by doing that?
Now provide the response and nothing else.
|
If you have only studied mathematics at school, the way it works at university/academic level can be quite alien. By looking at the original Principia Mathematica , by Alfred Whitehead AND Bertrand Russell (e.g. this large PDF ), we can confirm the claim. It isn't until page 359 that the concept of "2" is introduced (as a "cardinal couple" - it isn't until later that they show that this is equivalent to the cardinal number, 2, that we are familiar with.) On page 362 there is the quoted claim that Proposition 54.43 provides the basis for 1 + 1 = 2 It is worth noting: Whitehead & Russell don't spend 360-odd pages just adding two numbers together, like you were taught in school. They spend the treatise defining what was hoped to be a complete and consistent basis for all of mathematics. That means they weren't just proving that 1+1=2 (under their system of mathematics) but also defined (amongst a lot of other propositions) what "1", "2", "+" and "=" meant. They based this on a minimum set of "axioms" or assumptions. They tried to avoid allowing paradoxes and contradictions [before Kurt Gödel came along and proved that to be impossible.]
|
{}
|
{'log_upvote_score': 7, 'links': ['https://skeptics.stackexchange.com/questions/54327', 'https://skeptics.stackexchange.com', 'https://skeptics.stackexchange.com/users/66003/']}
|
jdg_379088
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
264441
|
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:
Do electromagnetic waves like light and gravitational waves (due to moon for instance) affect on mechanical waves like sound? Can sound change the path of light?
Now provide the response and nothing else.
|
Any physical phenomenon is potentially capable to cause some change to any other phenomenon, more or less directly. If it was not the case, the physical world could be divided into completely independent realms; there would not be the one single world we call Nature. Practically though, many if not most of the actually existing interactions between systems can be ignored, or just treated as perturbations in models taking into account only the most important ones. This is because interactions happen in a wide range of order of magnitudes. For example you would not usually include electromagnetic interactions between Moon and Earth when modelling their respective motion, although it certainly does play some part in the actual interplay of the two bodies (both having a magnetic field). If you do not ignore negligible effects, well even nocturnal urban lighting does play a part by sending photons to the Moon, pushing it away from Earth! As a side note, the fact that some interactions are so much less intense than others is very useful: it allows us to use them as measuring devices. As shown in another answer, we can use Schlieren photography as a straightforward way to display air density because indeed the path of light is altered by compression waves, but only marginally so. If the dependence of electromagnetic waves on air density was more intense, it would be more complicated to decorrelate both effects.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/264441', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/111951/']}
|
jdg_379089
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
55826791
|
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 followed the steps mentioned in Using PowerShell Behind a Proxy to configure my proxy server. netsh winhttp set proxy "[IP]:[Port]"$Wcl = New-Object System.Net.WebClient$Creds = Get-Credential$Wcl.Proxy.Credentials = $Creds A dialog popped up to collect my credential on the third line. Then I tried to install NuGet: PS C:\Users\Administrator> Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -ForceWARNING: Unable to download from URI 'https://go.microsoft.com/fwlink/ ?LinkID=627338&clcid=0x409' to ''.WARNING: Unable to download the list of available providers. Check your internet connection.Install-PackageProvider : No match was found for the specified search criteriafor the provider 'NuGet'. The package provider requires 'PackageManagement' and'Provider' tags. Please check if the specified package has the tags.At line:1 char:1+ Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidArgument: (Microsoft.Power...PackageProvider:InstallPackageProvider) [Install-PackageProvider], Exception + FullyQualifiedErrorId : NoMatchFoundForProvider,Microsoft.PowerShell.PackageManagement.Cmdlets.InstallPackageProvider The error message seems to indicate my PowerShell cannot connect to internet, but when I tried this command: PS C:\Users\Administrator> Invoke-WebRequest "https://go.microsoft.com/fwlink/?LinkID=627338&clcid=0x409"StatusCode : 200StatusDescription : OKContent : <?xml version="1.0" encoding="utf-8"?> <SoftwareIdentity xmlns="http://standards.iso.org/iso/19770/-2/2015/schema.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:discovery="http://p...RawContent : HTTP/1.1 200 OK Content-MD5: 01uMBNqAHedJsS1dqKC5oA== Vary: Accept-Encoding X-Cache: HIT x-ms-blob-type: BlockBlob x-ms-lease-status: unlocked x-ms-request-id: 1b7af5a7-901e-0003-5d94-f5cc950000...Forms : {}Headers : {[Content-MD5, 01uMBNqAHedJsS1dqKC5oA==], [Vary, Accept-Encoding], [X-Cache, HIT], [x-ms-blob-type, BlockBlob]...}Images : {}InputFields : {}Links : {}ParsedHtml : System.__ComObjectRawContentLength : 1847 It seems it can connect to the Internet after all. What did I do wrong? How do I install NuGet? EDIT: I tried Ocaso Protal's suggestion: PS C:\Users\Administrator> Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force -proxy [ProxyServer:Port] -proxycredential $CredsWARNING: Unable to download from URI 'https://go.microsoft.com/fwlink/?LinkID=627338&clcid=0x409' to ''.WARNING: Unable to download the list of available providers. Check your internet connection.Install-PackageProvider : No match was found for the specified search criteria for the provider 'NuGet'. The packageprovider requires 'PackageManagement' and 'Provider' tags. Please check if the specified package has the tags.At line:1 char:1+ Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force ...+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidArgument: (Microsoft.Power...PackageProvider:InstallPackageProvider) [Install-Pac kageProvider], Exception + FullyQualifiedErrorId : NoMatchFoundForProvider,Microsoft.PowerShell.PackageManagement.Cmdlets.InstallPackagePro viderPS C:\Users\Administrator> $CredsUserName Password-------- --------[My UserName] System.Security.SecureString It seems to have no effect.
Now provide the response and nothing else.
|
could be TLS security related (ref: https://rnelson0.com/2018/05/17/powershell-in-a-post-tls1-1-world/ ) Try this command first: [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 then try to do the update. Note: the command only affects the current session and does not persist. You may also check what version of TLS for client is set on computer. Looks like TLS 1.0 for client is required. (ref: https://powershell.org/forums/topic/wmf-5-1-upgrade-broken-repositories/ ) Michael
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/55826791', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2205845/']}
|
jdg_379090
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
116786
|
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:
Burning wood emits smoke and black. Provided more oxygen or whatever required, can wood be practically burnt fully like petroleum gasses that emits a blue flame and little smoke and little black.
Now provide the response and nothing else.
|
Burning wood is three processes: Gasification - under heat and little oxygen, the wood is turned into combustible gases (mostly Carbon Monoxide, Hydrogen and gaseous tar) and charcoal combustion of charcoal combustion of gasses The optimum conditions for these are not exactly the same (I'll dig out my thesis to look up the particulars). A good stove will have one area where char burns and the gasification happens. Then, additional air is added to the (combustible) exhaust to burn it more or less completely. An additional complication is that thegaseous tar tends to (partly) polymerize in the flame and form soot that usually does not burn - the yellow in the flame you see is glowing soot. So, in summary, burning wood completely is sometimes possible but hard, but good approximations exist.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/116786', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/48843/']}
|
jdg_379091
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
17431207
|
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 this class: /** * */package com.xerox.tclg.ejuror.ui.client;import com.extjs.gxt.ui.client.Style.HorizontalAlignment;import com.extjs.gxt.ui.client.event.ButtonEvent;import com.extjs.gxt.ui.client.event.Events;import com.extjs.gxt.ui.client.event.FormEvent;import com.extjs.gxt.ui.client.event.Listener;import com.extjs.gxt.ui.client.event.SelectionListener;import com.extjs.gxt.ui.client.widget.LayoutContainer;import com.extjs.gxt.ui.client.widget.MessageBox;import com.extjs.gxt.ui.client.widget.button.Button;import com.extjs.gxt.ui.client.widget.button.ButtonBar;import com.extjs.gxt.ui.client.widget.form.FileUploadField;import com.extjs.gxt.ui.client.widget.form.FormPanel;import com.extjs.gxt.ui.client.widget.form.FormPanel.Encoding;import com.extjs.gxt.ui.client.widget.form.FormPanel.Method;import com.extjs.gxt.ui.client.widget.form.LabelField;import com.extjs.gxt.ui.client.widget.form.TextField;import com.extjs.gxt.ui.client.widget.layout.TableData;import com.extjs.gxt.ui.client.widget.layout.TableLayout;import com.google.gwt.core.client.GWT;import com.google.gwt.user.client.rpc.AsyncCallback;import com.google.gwt.user.client.ui.Image;import com.xerox.tclg.ejuror.ui.client.service.PersonViewService;import com.xerox.tclg.ejuror.ui.client.service.PersonViewServiceAsync;import com.xerox.tclg.ejuror.ui.client.workbench.StyleHelper;/** * Form for uploading images to the main server * @author Xerox Services */public class UploadForm extends MessageEnabledContainer { //instance variables private String description; private String cancel; private String file; private MessageResource messageResource; private String ok; private PersonViewServiceAsync personViewService = (PersonViewServiceAsync) GWT.create(PersonViewService.class); //UI components private Button btnOk; private Button btnCancel; private ButtonBar buttonBar; private LabelField lblTitle; private FormPanel form; private LayoutContainer header; private LayoutContainer layMain; private TextField<String> textDescription; private FileUploadField uploadFile; /** * Create a disclaimer page that will show disclaimers and return the results in a callback * @param icon * @param header1 * @param header2 * @param disclaimerText * @param buttonFlags */ public UploadForm() { String selectFile; String title; messageResource = ImageViewer.getImageViewer(); if(isDesignTime()){ cancel = "Cancel"; description = "Short Description<BR/>(e.g. Doctor's Letter)"; file = "File"; ok = "Ok"; selectFile = "Select a File to Upload"; title = "Upload a File"; } else{ cancel = messageResource.getString(Messages.MSGKEY_CANCEL); description = "Short Description<BR/>(e.g. Doctor's Letter)"; file = "File"; ok = messageResource.getString(Messages.MSGKEY_OK); selectFile = "Select a File to Upload"; title = "Upload a File"; } addStyleName("white-screen"); setWidth(MainLayout.FORM_WIDTH); setLayout(new TableLayout()); header = new LayoutContainer(); TableLayout tl_header = new TableLayout(2); tl_header.setCellSpacing(5); header.setLayout(tl_header); Image imageUpload = new Image(EjurorBundle.BUNDLE.uploadIcon()); header.add(imageUpload); String str = StyleHelper.formatHeader(title); lblTitle = new LabelField(str); header.add(lblTitle); layMain = new LayoutContainer(); TableLayout tl_layMain = new TableLayout(); tl_layMain.setCellPadding(5); layMain.setLayout(tl_layMain); layMain.add(header); form = new FormPanel(); form.setHeading(selectFile); layMain.add(form); buildUploadForm(); buildButtonBar(); FooterContainer footer = new FooterContainer("50"); TableData td_footer = new TableData(); td_footer.setWidth("100%"); layMain.add(footer, td_footer); footer.setSize("740", ""); add(layMain); loadUrl(); } /** * */ private void buildButtonBar() {// buttonBar = new ButtonBar();// buttonBar.setAlignment(HorizontalAlignment.RIGHT);// buttonBar.setHeight(MainLayout.BUTTON_BAR_HEIGHT);// form.add(buttonBar); btnOk = new Button(ok); btnOk.setSize(MainLayout.BUTTON_WIDTH, MainLayout.BUTTON_HEIGHT); btnOk.addSelectionListener(new SelectionListener<ButtonEvent>() { @Override public void componentSelected(ButtonEvent be) { if(form.isValid()){ upload(); } else{ MessageBox.info("Validation Error", "You must enter all required fields.", null); } } });// buttonBar.add(btnOk); form.add(btnOk); btnCancel = new Button(cancel); btnCancel.setSize(MainLayout.BUTTON_WIDTH, MainLayout.BUTTON_HEIGHT); btnCancel.addSelectionListener(new SelectionListener<ButtonEvent>() { @Override public void componentSelected(ButtonEvent be) { exit(); } });// buttonBar.add(btnCancel); form.add(btnCancel); } /** * */ private void buildUploadForm() { form.setFrame(true); form.setEncoding(Encoding.MULTIPART); form.setMethod(Method.POST); form.setButtonAlign(HorizontalAlignment.CENTER); form.setWidth(MainLayout.CONTENT_WIDTH); form.addListener(Events.Submit, new Listener<FormEvent>() { public void handleEvent(FormEvent fe) { System.out.println(fe.getResultHtml()); }; }); String desc = StyleHelper.formatPrompt(description); textDescription = new TextField<String>(); textDescription.setAllowBlank(false); textDescription.setFieldLabel(desc); form.add(textDescription); String fileLabel = StyleHelper.formatPrompt(file); uploadFile = new FileUploadField(); uploadFile.setAllowBlank(false); uploadFile.setFieldLabel(fileLabel); form.add(uploadFile); } /** * Jump back to the landing page */ protected void exit(){ ImageViewer.getImageViewer().showLanding(); } /** * */ protected void upload(){ form.submit(); exit(); } /** * Load the URL from the person service */ private void loadUrl() { personViewService.buildUploadUrl(new AsyncCallback<String>() { @Override public void onFailure(Throwable caught) { System.err.println("Unable to construct URL"); caught.printStackTrace(); MainLayout.showError(caught.getMessage()); } @Override public void onSuccess(String url) { form.setAction(url); } }); } /** * GWT-Designer will change to return true during design time * * @return */ private static final boolean isDesignTime() { return false; }} As you can see the URL is built dynamically. The problem is that when I run this, and click the OK button, the servlet never gets called. If I look at the rendered HTML and copy the URL that in the action, and then paste that into my browser, it calls the servlet, so the URL is OK. I have also verified that submit is being called. Can anyone point me in the right direction? I'm following this example: http://extjs-public.googlecode.com/svn/gxt/release/samples/examples/www/com.extjs.gxt.samples.Examples/forms/fileupload.html
Now provide the response and nothing else.
|
You can't use like in a Linq join. In fact, you can't use like in Linq at all, only conventional string methods like StartsWith , EndsWith , or Contains . You'd have to do something like this: var query = from f in db.form from n in db.name.Where(x => f.nameField.Contains(x.firstName)) ...
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17431207', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/967330/']}
|
jdg_379092
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
44480134
|
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 Visual Studio 2017, when I want to create an ASP.NET Core Web Application from scratch using either one of these standard .NET Core project templates: Console App (.NET Core) Class Library (.NET Core) These project templates; obviously would not include the wwwroot folder. So, when I add the folder to my project it will look like (and behave like) a standard folder: When you create it using the ASP.NET Core Web Application project template, the wwwroot folder looks like this: Question - Appearance (Icon) How do you change the icon of the wwwroot folder to look like the one found in the ASP.NET Core Web Application project template? Additional Question - Behavior (Copying Files to Output Directory) In the standard .NET Core project, I would have to add this to my .csproj file: <ItemGroup> <Content Include="wwwroot\**" CopyToOutputDirectory="PreserveNewest" /></ItemGroup> so that it copies all my files from the wwwroot folder to the output directory similar to the ASP.NET Core Web Application project. I looked in the ASP.NET Core Web Application's .csproj file and didn't see anything like that. I'm assuming the answer to the main question will also provide the answer for this one, as the project templates are obviously different. I can't seem to find the resources online to help me manually edit this myself. Thanks in advance.
Now provide the response and nothing else.
|
After reading this page that announced the new tooling in Visual Studio 2017, I found out that it was in fact possible. I noticed that the ASP.NET Core Web Application project uses a different value under the Project node in the .csproj file. <Project Sdk="Microsoft.NET.Sdk.Web"> Whereas the standard project templates used Microsoft.NET.Sdk like this: <Project Sdk="Microsoft.NET.Sdk"> ← ← ← ← //change this to Microsoft.NET.Sdk.Web <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>netcoreapp1.1</TargetFramework> </PropertyGroup></Project> Once I changed the value to Microsoft.NET.Sdk.Web and saved the csproj file, the project upgraded itself, and the wwwroot folder was added to my project automatically (but excluded) , like this: Then I included it into the project and now: Great! I hope this answer helps others.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/44480134', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3645638/']}
|
jdg_379093
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
35230317
|
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 migrating an application running with Hibernate 3 to Hibernate 5. I have a strange error: ERROR: relation hibernate_sequence does not exist We are using *.hbm.xml mapping files and everything was working fine until I changed the Hibernate version. I mean we have a pretty straight forward mapping with ID column and DB sequence generator and still Hibernate wasn't able to pick the correct config. <hibernate-mapping> <class name="com.boyan.MyClass" table="my_class"> <id name="id" type="long"> <column name="id" /> <generator class="sequence"> <param name="sequence">my_class_seq</param> </generator> </id>... </class></hibernate-mapping>
Now provide the response and nothing else.
|
I started digging in the Hibernate code and saw that SequenceGenerator is deprecated and the new versions use SequenceStyleGenerator . I was very confused when I noticed that in the new version the property telling which is the sequence name is changed from sequence to sequence_name . So finally when I changed: <param name="sequence">my_class_seq</param> to: <param name="sequence_name">my_class_seq</param> everything worked.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/35230317', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1005599/']}
|
jdg_379094
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
569185
|
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
The standard way of describing neutrino oscillations seems to be that the mass eigenstates differ from the flavour eigenstates, which leads to an oscillation of neutrino flavour over time. However, every other change in the Standard Model seems to be mediated by a gauge boson, so I was wondering why neutrino oscillations were somehow the exception to this, changing flavour all on their own without any other interactions. Have physicists ruled out the possibility of a gauge boson being absorbed/emitted in the process of neutrino oscillation causing the neutrino to change flavour, and if so, how? (Or, is there an even simpler theoretical reason why this is unlikely to be the case?) Or are there theories out there which propose an extension to the Standard Model with some kind of a mediating gauge boson for neutrino oscillations?
Now provide the response and nothing else.
|
The reason that no other Standard Model particles oscillate into each other is that they are defined not to. An "oscillation" is another name for an interaction in which one particle goes in and one particle goes out. In the standard model (after electroweak symmetry breaking) any fermion of a particular type (neutrino, electron, up, down) can oscillate into a fermion of the same type and a different generation. For each such oscillation there's a coefficient which governs the rate at which it takes place. These coefficients appear quasirandom and we have no idea where they come from. The coefficients for a particular fermion type can be written in a 3×3 matrix. That matrix can be diagonalized by changing the basis for the fermion fields, in the abstract 3-dimensional space of flavors. For all fermions except the neutrinos, that's what we do: we simply define the three particles to be the three stable modes of oscillation. With the neutrinos, partly for historical reasons (we didn't know there was an oscillation matrix for them) and partly for practical reasons (it's the only way we observe them experimentally), we chose the basis instead to diagonalize a different matrix, the one governing the weak interaction with the electron-type fermions. An electron/mu/tau neutrino can only interact with an electron/muon/tauon respectively, by definition. The non-oscillating neutrinos (the mass eigenstates) are unimaginatively named 1, 2, and 3. If you take those as your three neutrinos then the leptons are just like the quarks: none of them oscillate, but they do change generation in weak interactions. The reason solar neutrinos arrive in all three generations is not that they change generation en route, but rather that some of them change generation on emission in the sun and some change generation on absorption in our detectors. Although it sounds like a completely different explanation, it's the same physics in different words. Before electroweak symmetry breaking, the "oscillation" of fermions is actually a three-way interaction with the Higgs field, so it is mediated by a boson, though it isn't a gauge boson.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/569185', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/271157/']}
|
jdg_379095
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
274626
|
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 c++ what is object slicing and when does it occur?
Now provide the response and nothing else.
|
"Slicing" is where you assign an object of a derived class to an instance of a base class, thereby losing part of the information - some of it is "sliced" away. For example, class A { int foo;};class B : public A { int bar;}; So an object of type B has two data members, foo and bar . Then if you were to write this: B b;A a = b; Then the information in b about member bar is lost in a .
|
{}
|
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/274626', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/35737/']}
|
jdg_379096
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
18524784
|
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 exactly is a CakePHP behavior? Where and how should I use it?
Now provide the response and nothing else.
|
Behaviors in CakePHP are living on the model side of the framework. Since we all prefer to create a reusable and dry logic, behaviors are provided by CakePHP to get away from 'ugly' and extra code. Behaviors "change" the way models behaves, enforcing it to "act as" something. You can think of them, that they are for models, what components are for controllers and helpers are for views. Behaviors help you make your code more abstract, not to mention that they can be shared across different models. When you force a model to behave as something or as some things, you just use functions of that behavior(s). Of course later you can take away or perhaps temporarily force a model to forget about this or that behavior. There lots of other stuff that you can ask models about behaviors, for example check if model behaves like this or that, if not to behave. Generally, you tell a model to behave using public $actAs = array(); statement, but you can do it by $this->ModelName->Behaviors->load('BehaviorName') too. You use them in models of course. Unless you implement your own behaviors rather than use tons of them available at the bakery, you load them and use them as if models already supported such kinds of functions.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18524784', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1533709/']}
|
jdg_379097
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
165748
|
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 was trying to find the maximum of a function and where it maximises. I found that FindMaximum will give the result. Now I need to save the maximum value and x value(using replace rule) in two different variables. I have a Table like this: T1 = { 0.686151, x -> 1.54793, 0.686075, x -> 1.55549, 0.687346, x -> 1.54975, 0.689603, x -> 1.52983, 0.692579, x -> 1.49448, 0.696075, x -> 1.44192, 0.699942, x -> 1.36952, 0.704069, x -> 1.27328, 0.708369, x -> 1.14652, 0.712778, x -> 0.976704, 0.717245, x -> 0.733626, 0.721731, x -> 0.256813, 0.726028, x -> 1.84992*10^-9, 0.729878, x -> 1.01046*10^-9, 0.733336, x -> 4.23067*10^-7, 0.736454, x -> 1.1326*10^-8, 0.739275, x -> 5.37651*10^-10, 0.741835, x -> 9.37745*10^-6, 0.744167, x -> 3.23782*10^-6, 0.746296, x -> 1.28956*10^-6, 0.748245, x -> 5.7631*10^-7, 0.750034, x -> 2.82576*10^-7, 0.75168, x -> 1.49276*10^-7, 0.753197, x -> 8.37318*10^-8, 0.754599, x -> 4.92927*10^-8, 0.755898, x -> 3.01754*10^-8, 0.757103, x -> 1.90688*10^-8, 0.758222, x -> 1.23672*10^-8, 0.759265, x -> 8.19418*10^-9, 0.760237, x -> 5.52643*10^-9, 0.761145, x -> 3.78294*10^-9, 0.761994, x -> 2.62213*10^-9, 0.76279, x -> 1.83701*10^-9, 0.763537, x -> 1.29881*10^-9, 0.764238, x -> 9.25594*10^-10, 0.764898, x -> 6.64199*10^-10}; and I need this: T2 = {{0.686151}, {0.686075}, {0.687346}, {0.689603}, {0.692579}, \{0.696075}, {0.699942}, {0.704069}, {0.708369}, {0.712778}, \{0.717245}, {0.721731}, {0.726028}, {0.729878}, {0.733336}, \{0.736454}, {0.739275}, {0.741835}, {0.744167}, {0.746296}, \{0.748245}, {0.750034}, {0.75168}, {0.753197}, {0.754599}, \{0.755898}, {0.757103}, {0.758222}, {0.759265}, {0.760237}, \{0.761145}, {0.761994}, {0.76279}, {0.763537}, {0.764238}, {0.764898}};T3 = { x -> 1.54793, x -> 1.55549, x -> 1.54975, x -> 1.52983, x -> 1.49448,x -> 1.44192, x -> 1.36952, x -> 1.27328, x -> 1.14652, x -> 0.976704, x -> 0.733626, x -> 0.256813, x -> 1.84992*10^-9, x -> 1.01046*10^-9, x -> 4.23067*10^-7, x -> 1.1326*10^-8, x -> 5.37651*10^-10, x -> 9.37745*10^-6, 0.744167, x -> 3.23782*10^-6, 0.746296, x -> 1.28956*10^-6, x -> 5.7631*10^-7, x -> 2.82576*10^-7 x -> 1.49276*10^-7, x -> 8.37318*10^-8, x -> 4.92927*10^-8, x -> 3.01754*10^-8, x -> 1.90688*10^-8, x -> 1.23672*10^-8, x -> 8.19418*10^-9, x -> 5.52643*10^-9, x -> 3.78294*10^-9, x -> 2.62213*10^-9, x -> 1.83701*10^-9, x -> 1.29881*10^-9, x -> 9.25594*10^-10, x -> 6.64199*10^-10}; Please help me out Thanks in advance
Now provide the response and nothing else.
|
T1 = {0.686151,x->1.54793,0.686075,x->1.55549,0.687346,x->1.54975,0.689603,x->1.52983,0.692579,x->1.49448,0.696075,x->1.44192,0.699942,x->1.36952,0.704069,x->1.27328,0.708369,x->1.14652,0.712778,x->0.976704,0.717245,x->0.733626,0.721731,x->0.256813,0.726028,x->1.84992*10^-9,0.729878,x->1.01046*10^-9,0.733336,x->4.23067*10^-7,0.736454,x->1.1326*10^-8,0.739275,x->5.37651*10^-10,0.741835,x->9.37745*10^-6,0.744167,x->3.23782*10^-6,0.746296,x->1.28956*10^-6,0.748245,x->5.7631*10^-7,0.750034,x->2.82576*10^-7,0.75168,x->1.49276*10^-7,0.753197,x->8.37318*10^-8,0.754599,x->4.92927*10^-8,0.755898,x->3.01754*10^-8,0.757103,x->1.90688*10^-8,0.758222,x->1.23672*10^-8,0.759265,x->8.19418*10^-9,0.760237,x->5.52643*10^-9,0.761145,x->3.78294*10^-9,0.761994,x->2.62213*10^-9,0.76279,x->1.83701*10^-9,0.763537,x->1.29881*10^-9,0.764238,x->9.25594*10^-10,0.764898,x->6.64199*10^-10}; Then {T2, T3} = GatherBy[T1, Head] Or alternatively pos = Drop[Position[T1, Rule, {2}], 0, -1];T2 = Delete[T1, pos];T3 = Extract[T1, pos];
|
{}
|
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/165748', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/45795/']}
|
jdg_379098
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
62651
|
Below is a question asked on the forum networkengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
How many stack cables would be needed if we want to stack two 3850 switches :We have one 3850 switch and planning to add one more. So my guess is only one Power & One data stack cable would be fine. Or please let me know if it is mandatory to loop the cable with two Power & two data stack cable?
Now provide the response and nothing else.
|
How many stack cables would be needed if we want to stack two 3850 switches : We have one 3850 switch and planning to add one more. So my guess is only one Power & One data stack cable would be fine. Or please let me know if it is mandatory to loop the cable with two Power & two data stack cable? Minimum (and improperly), one stacking cable (data). However this is a bad idea as any issue with this cable will split your stack into standalone devices. Minimum and properly, two stacking cables (data). Providing the loop is the proper (and documented) way to stack these switches. If one cable gets damaged or needs to be disconnected for some reason, the stack remains a stack. The power stacking cables are purely optional, but add flexibility which can be useful and cost saving depending on the deployment. This allows the switches to "share" their power supplies with each other. Again, the loop is the correct way to utilize this feature. Let's say that your power needs on each switch is about 400W. With the power stacking cables and a single 1100W power supply in each switch, you can have fully redundant power. Or you could skip the power stacking cables and put two smaller power supplies in each switch, which means you have four power cables to plug into outlets (if you can't use power strips --policy or regulation reasons-- this may exceed your available electrical outlets). The actual implementation on power (and if you need the power stack cables) is going to highly depend on your situation and the potential future needs of your deployment. For example, if you know that there will be a VoIP rollout next year and you will need more power for PoE phones, you may want to leave the additional power supply slot available to add more power at that time.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://networkengineering.stackexchange.com/questions/62651', 'https://networkengineering.stackexchange.com', 'https://networkengineering.stackexchange.com/users/19899/']}
|
jdg_379099
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
228672
|
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have watched the active record classes in our project grow into large, do-it-all classes. When you need anything about a user, for example, you should go to the Person class. While this makes perfect sense when you consider the domain, in reality, the Person class is a mishmash of lots and lots of functionality, which do get modified sometimes as the domain becomes clearer, which means both SRP and OCP are violated. Is this one of the things that comes with the Active Record pattern, or are we doing it wrong?
Now provide the response and nothing else.
|
The typical use of AR violates these principles. Many developers dump every possible piece of functionality into their models making them fat and cumbersome. The fact that AR makes database interactions an afterthought aids in the misuse. What you could do is make use of the repository pattern. Use it to separate your data persistence code from the business logic thus hiding away the details of AR. Then separate your use cases into single responsibility classes. Recently this has been dubbed DCI and it's starting to gain some traction. This will keep your models uber-light and use cases will become more clearly articulated in real classes. Learning to make use of DCI takes some practice but there are a growing number of resources out there and really, once you grok the concept, you shouldn't have much trouble using it. (Don't worry if you make some initial mistakes.) By taking this tack you wouldn't be tightly bound to AR. You could very easily create interfaces that use the filesystem or any sort of persistence. By making your persistence layer more of an afterthought, you'll have improved your architecture dramatically.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/228672', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/109596/']}
|
jdg_379100
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
14667005
|
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 reading up on virtual environment, and it seems like an extremely useful tool, but now I'm questioning how I've set up my entire python environment thus far. Right now, all of the modules and packages that I have installed are residing in this directory: /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages But the virtualenv docs seem to suggest that such universal system installs are a bad thing. If that's the case, then what should I do with my current modules and how should I install future modules? For instance, I recently installed flask from my user directory with this command: pip install flask It now resides in site-packages. Should I have done something different? I'm having trouble with the documentation, which seems to suggest that I need to go into a project directory, set up a virtual environment, and install all of the modules that I need using virtualenv. Is this the case? Is there any way to make things less cumbersome? It seems like installing potentially dozens of packages for every single project directory would be a little much. Or is it the case that I only need to create virtual environments for projects that use older versions of modules than the ones I have installed in the system directory? If that's the case, however, then what's up with the virtualenv mantra that seems to discourage all system installs?
Now provide the response and nothing else.
|
If you've already installed virtualenv like this: pip install virtualenv You'll then want to setup a particular virtualenv folder: virtualenv [your project folder name] This will create that project folder with a few important subdirectories. You'll activate your virtualenv first before installing anything new, the newly installed modules will be available to you only when 'sourced' into your virtualenv. From your project folder type: source bin/activate You then will see your virtualenv name in parenthesis on each terminal line. This indicates you are 'sourced' in. NOW install stuff with pip or easy_install. pip install flask virtualenv basically sets your path to look in [venv folder]/bin for executables instead of /usr/local/bin or whatever. So you can copy files straight into your virtual env bin folder. (MongoDB files for instance just come in a zip/tar file, you can just untar them into your venv bin folder and you will have access to that particular version of MongoDB when 'sourced' in.) Try for yourself, run this command from your virtual and then default environment to see how it changes. echo $PATH && echo $PYTHONPATH To exit out of your virtualenv: deactivate Typing this will get you back to your default environment. If you haven't read this yet, it's a pretty good resource. https://python-guide.readthedocs.org/en/latest/dev/virtualenvs/
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14667005', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1427661/']}
|
jdg_379101
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
9271747
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
As you can see the image below, there is "A", "B", "C", "D" and "E" on the website, and the user may only can see the A, B, and a little parts of D in their browser. They need to require to scroll down the browser or some users may have a bigger screen, or a longer window on their browser that allow they can even see the element C. Ok, my question is, is this possible to let me know what the user seeing on their browser using javascript? In this element, is "A", "B" and "D".
Now provide the response and nothing else.
|
Try it :) http://jsfiddle.net/Aj2fU/5/ $('input').click(function(){ // check for visible divs with class 'check' $('.check').each(function(){ var pos = $(this).offset(), wX = $(window).scrollLeft(), wY = $(window).scrollTop(), wH = $(window).height(), wW = $(window).width(), oH = $(this).outerHeight(), oW = $(this).outerWidth(); // check the edges // left, top and right, bottom are in the viewport if (pos.left >= wX && pos.top >= wY && oW + pos.left <= wX + wW && oH + pos.top <= wY + wH ) alert('Div #' + $(this).attr('id') + ' is fully visible'); else // partially visible if (((pos.left <= wX && pos.left + oW > wX) || (pos.left >= wX && pos.left <= wX + wW)) && ((pos.top <= wY && pos.top + oH > wY) || (pos.top >= wY && pos.top <= wY + wH))) alert('Div #' + $(this).attr('id') + ' is partially visible'); else // not visible alert('Div #' + $(this).attr('id') + ' is not visible'); }); }); Updated to work with very wide divs. Basically it checks whether the left, top and right, bottom edges of the divs are both in the visible part of the screen, partially or outside of the viewport.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9271747', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/148978/']}
|
jdg_379102
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
7366237
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Consider this code: public class DummyClass { public List<? extends Number> dummyMethod() { return new ArrayList<Integer>(); }} public class DummyClassTest { public void testMockitoWithGenerics() { DummyClass dummyClass = Mockito.mock(DummyClass.class); List<? extends Number> someList = new ArrayList<Integer>(); Mockito.when(dummyClass.dummyMethod()).thenReturn(someList); //Compiler complains about this }} The compiler complains about the line that's trying to stub the behavior for dummyMethod() . Any pointers on how one goes about stubbing methods that return a type with bounded wild-cards?
Now provide the response and nothing else.
|
You can also use the non-type safe method doReturn for this purpose, @Testpublic void testMockitoWithGenerics(){ DummyClass dummyClass = Mockito.mock(DummyClass.class); List<? extends Number> someList = new ArrayList<Integer>(); Mockito.doReturn(someList).when(dummyClass).dummyMethod(); Assert.assertEquals(someList, dummyClass.dummyMethod());} as discussed on Mockito's google group. While this is simpler than thenAnswer , again note that it is not type safe. If you're concerned about type safety, millhouse's answer is correct. Additional Details To be clear, here's the observed compiler error, The method thenReturn(List<capture#1-of ? extends Number>) in the type OngoingStubbing<List<capture#1-of ? extends Number>> is not applicable for the arguments (List<capture#2-of ? extends Number>) I believe the compiler has assigned the first wildcard type during the when call and then cannot confirm that the second wildcard type in the thenReturn call is the same. It looks like thenAnswer doesn't run into this issue because it accepts a wildcard type while thenReturn takes a non-wildcard type, which must be captured. From Mockito's OngoingStubbing , OngoingStubbing<T> thenAnswer(Answer<?> answer);OngoingStubbing<T> thenReturn(T value);
|
{}
|
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/7366237', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/245997/']}
|
jdg_379103
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
59809495
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Whenever I try to install TensorFlow with pip on Python 3.8, I get the error that TensorFlow is not found. I have realized later on that it is not supported by Python 3.8. How can I install TensorFlow on Python 3.8?
Now provide the response and nothing else.
|
As of May 7, 2020, according to Tensorflow's Installation page with pip , Python 3.8 is now supported. Python 3.8 support requires TensorFlow 2.2 or later. You should be able to install it normally via pip. Prior to May 2020: As you mentioned, it is currently not supported by Python 3.8, but is by Python 3.7. You want to have virtualenv installed. You also need Python 3.7.Then you can just start a virtualenv with -p python3.7 and install it using pip like you did before: virtualenv --system-site-packages -p python3.7 DEST_DIRsource ./DEST_DIR/bin/activatepip install --upgrade pippip install --upgrade tensorflow
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/59809495', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
|
jdg_379104
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
97249
|
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 have read from multiple sources that it might be better to have a password composed of several random words since this is easier to remember than a random sequence of characters. For example this article from Thomas Baekdal . I even see this xkcd comic quite often. Now, I read this article about a new tool called brainflayer, currently target Bitcoin wallets, that can guess 130000 passwords a second. This makes Bitcoin brainwallets useless. I wonder if a similar tool could be used against all passwords and are passwords such as "this is fun" really as safe as Thomas Baekdal claims?
Now provide the response and nothing else.
|
I wrote brainflayer and gave a talk about it at DEFCON. Neither Thomas Baekdal's article nor XKCD's comic apply well to modern offline attacks. I read Thomas's article and his FAQ about it, and it may have been marginally reasonable when he wrote it, it no longer is. A key point is that password cracking attacks have gotten much better since then. Q: If I cannot write "this is fun" because of the spaces, can I not just write "thisisfun"? A: Absolutely not! The reason why "this is fun" is 10 times more secure, is simply because it is much longer (11 characters). By removing the spaces, you reduce the length and the complexity substantially. The spaces are effectively special characters, which in itself makes the password much more secure. Use "this-is-fun" instead. Password crackers don't try long brute force attacks much - it's all about cracking ROI. A smart cracker will try word combinations with various delimiters, so using spaces, hyphens, underscores or nothing all ends up providing about the same security. Today's cracking methods use wordlists - which can include phrases - and large corpuses of previously compromised passwords along with popularity. This is combined with rule-based permutation and statistical models. Ars Technica posted a great article detailing modern techniques mid-2013, and attacks only get better. I am also of the (possibly controversial) opinion that it is pointless to talk about guesses per second for offline attacks. A much better way of thinking about it is guesses per dollar . If you want to be pedantic you could add a one-time guesses per second per dollar cost, but the operational cost will tend to dominate. Brainflayer's upper bound on operational cost is 560M guesses per dollar, based on EC2 spot instance benchmarks - with zero one-time cost. It's possible to make these costs many orders of magnitude higher with a "harder" hash function like bcrypt , scrypt , PBKDF2 or, once it is finalized, Argon2 .
|
{}
|
{'log_upvote_score': 7, 'links': ['https://security.stackexchange.com/questions/97249', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/83825/']}
|
jdg_379105
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
509240
|
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'd like to work through some basic logic circuits with some youngsters and wanted to build them up from scratch (transistors), not logic gates if possible. We've done the basics: buffer, NOT, AND, OR, NAND, XOR just using NPN mosfets and resistors. We've even been able to get to D-latches. As an example, the AND gates we're playing with have been build like this: simulate this circuit – Schematic created using CircuitLab The problem is that as the circuits have grown in complexity, with transistor emitters feeding into other transistor bases, I've only been able to get things to work by very carefully balancing resistor values to make sure transistors are triggered when they should be. I would like to be able to build modular logic gates, which are identical and can just be plugged into one another without needing to carefully calculate resistor values. Another restrictions is that we currently have 200 BC547ATA NPN transistors and a big bunch of resistors, so if its achievable without buying any more components, that would be ideal.
Now provide the response and nothing else.
|
If all you have is NPNs and resistors, you'll want to use some form of RTL . Here, the basic logic element is the NOR gate. The one-transistor gate uses fewer transistors (obviously), but the multi-transistor gate is more robust in several ways. And there's a teaching opportunity here, to show how the NOR gate is a "universal" logic element — all other functions can be created by combinations of NOR gates (including the degenerate 1-input NOR gate, or inverter). Even large systems have been built this way. The original Cray-1's logic was entirely implemented using 4- and 5-input ECL NOR gates! One implementation strategy would be to build up individual 3-, 4- or 5-input gates on single-inline modules like these: ( source ) These are easy to plug into a breadboard socket, allowing the students to focus on the logic they're building. If you need a large number of them, have a custom PCB made. And if you're really ambitious, you could plug them into a universal wirewrap card for larger projects and a more permanent implenentation.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/509240', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/228635/']}
|
jdg_379106
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
342749
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
What is the difference between minimum and infimum? I have a great confusion about this.
Now provide the response and nothing else.
|
The minimum is attained, the infimum isn't necessarily. Example. Let $f(x) = \frac{1}{x}$. Then $f$ has no minimum value on the interval $(0,\infty)$. The minimum is the smallest element in the set. That is$$\min\{f(x)\mid x\in (0,\infty)\}$$doesn't exist because there is not smallest number in the set. Another example is the minimum of the set $S = (0,1) = \{x\mid 0<x<1\}$. Here again there isn't a smallest number$$\min\{x\mid 0<x<1\}$$doesn't exist. The infimum of a set $S$ is defined as the greatest number that is less than or equal to all elements of S ( from Wikipedia ). The infimum is also sometimes called the greatest lower bound. It is a fact that every non empty set (bounded below) of real numbers has an infimum. But, as we saw, not every real set has a minimum. So in the example$$\inf\{f(x)\mid x\in (0,\infty)\} = 0.$$ Note that the infimum and the minimum can be the same. Consider for example $S = \{1,2,3,\dots\}$. Then the infimum and minimum is both $1$. Consider this other example. If $f$ is a continuous function on a closed interval $[a,b]$, then it is a fact that $f$ attains a minimum over that interval. So here again$$\inf\{f(x)\mid x\in [a,b]\} = \min\{f(x)\mid x\in [a,b]\}.$$
|
{}
|
{'log_upvote_score': 8, 'links': ['https://math.stackexchange.com/questions/342749', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/63618/']}
|
jdg_379107
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
68336
|
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 am told by our server admins, that our server has no DNS resolutions because they are under tight PCI DSS regulations for outbound data. I don't quite understand this because the server is used to host a website which all can access from the URL, but when I logon via Remote Desktop onto the server, I can't use the internet from the server i.e it can serve data but can't send outbound data. How is this possible? How can it have access to the internet by sending http data to and fro, but can't resolve DNS names?
Now provide the response and nothing else.
|
Generally in this situation the firewall is configured to do a couple things: Only allow inbound connections on specific service ports (HTTP and HTTPS). Only allow outbound connections that are related to inbound connections (ie. the response to clients' HTTP requests). In many cases the DNS requests are explicitly blocked. This prevents the server from making its own connections to other IP addresses, including preventing connections to DNS servers for the purpose of DNS lookup. This is one way of stopping malicious code on the server from transferring data elsewhere and from downloading other data. It also stops server administrators from being able to 'browse the web' on the server, which they definitely shouldn't be doing anyway.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/68336', 'https://serverfault.com', 'https://serverfault.com/users/-1/']}
|
jdg_379108
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
294877
|
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 want to turn on vlan tagging on my main cisco catalyst 3560 so that frames leaving the switch are tagged (and visible on my layer 2 managed switches on the far side of my network) but at the same time I also want to accept both tagged and untagged frames until I can better map the network. I do have other brands of switches that I'll be getting to work with the vlans defined on this 3650 (etherwan and 3COM/HP) so 802.1Q tagging is what I'm going with and, eventually, I need to be able to have the vlans span (?) from the primary switch to the others. Can someone help me get started with the IOS foo to accomplish some of this? I have VLANs configured but I don't see any tagging in the frames.
Now provide the response and nothing else.
|
Once you've identified your exact requirements above: Each VLAN needs to be created before traffic will pass: Switch(config)# vlan [number]Switch(config-vlan)# name [name] For each trunk (>1 vlan) port, config as follows. Let's say 1000 is native (untagged) VLAN and 2000-2100 and 3000 are carried: Switch(config)# int gi0/1Switch(config-interface)# switchport mode trunkSwitch(config-interface)# switchport trunk allowed vlan 1000,2000-2100,3000Switch(config-interface)# switchport trunk native vlan 1000 For each access (1 vlan, untagged) port, config as follows: Switch(config)# int gi0/2Switch(config-interface)# switchport mode accessSwitch(config-interface)# switchport access vlan 1000 You can also specify and interface range: Switch(config)# int range gi0/1 - 10, gi1/1 And shorten commands if the keywords are still unique: Switch(config-interface)# sw tr na vl 1000
|
{}
|
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/294877', 'https://serverfault.com', 'https://serverfault.com/users/61070/']}
|
jdg_379109
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
13179093
|
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 many models which I use to obtain data and generate a report. The report doesn't need to be stored, i.e. it's not an active record. But certainly there's like 80 lines of code which generate the data for the report. Where should I put those lines? They are currently in the controller but since controller should be thin, I'm not sure if that's the best place.
Now provide the response and nothing else.
|
I would create a directory in app called reports , and put all of my reports in there. Everything in the app directory in rails can be found as long as the filename and class follow the normal convention. For example, if you have the following in app/reports/example_report.rb : class ExampleReport def initialize ... endend You will be able to use it from your controllers as such: class SomethingController < ApplicationController def something example = ExampleReport.new ... endend Reports that rely on models are considered part of your application's domain, which is why I recommend the app directory. The ease of adding subdirectories in app means that you can maintain a logical separation of the different roles in your application. It shouldn't be hard to guess where the implementation for something is. Controllers are in app/controllers , models are in app/models , so it follows that reports are in app/reports . And for example, if you were to add generic service classes to your app, they could go in app/services . In contrast, they do not belong in lib, because they cannot function in a generic fashion. To further this point, only code that you could envision being used in any rails project belongs in the lib directory.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13179093', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1614737/']}
|
jdg_379110
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
24785689
|
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 code that was originally written for an English language market where the decimal separator is "." so it's expecting numeric values as strings to use "." as the separator. But we now have users in other places, e.g., places in Europe where the decimal separator is ",". So, in the context of my software (really just the current thread) I want to override the decimal separator for the current language to be "." even if it defaults to something else. I tried String sep = "."; NumberFormatInfo nfi1 = NumberFormatInfo.CurrentInfo; nfi1.NumberDecimalSeparator = sep; But I get an " Instance is read-only " exception on the third line. Apparently NumberFormatInfo is not writable. So how DO you set the current language's decimal separator to something other than its default?
Now provide the response and nothing else.
|
You need to create a new culture and you can use the current culture as a template and only change the separator. Then you must set the current culture to your newly created one as you cannot change the property within current culture directly. string CultureName = Thread.CurrentThread.CurrentCulture.Name;CultureInfo ci = new CultureInfo(CultureName);if (ci.NumberFormat.NumberDecimalSeparator != "."){ // Forcing use of decimal separator for numerical values ci.NumberFormat.NumberDecimalSeparator = "."; Thread.CurrentThread.CurrentCulture = ci; }
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/24785689', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/316117/']}
|
jdg_379111
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
6127187
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
When I try to compile the following function I get the error. string& foo(){return "Hello World";}Error:1 IntelliSense: a reference of type "std::string &" (not const-qualified) cannot be initialized with a value of type "const char [12]"
Now provide the response and nothing else.
|
There are two problems with your code. First, "Hello World!" is a char const[13] , not an std::string . So the compiler has to(implicitly) convert it to an std::string . The result of aconversion is a temporary (rvalue in C++-speak), and you cannotinitialize a reference to a non-const with a temporary. The second isthat even if you could (or you declared the function to return areference to const), you're returning a reference to something whichwill immediately go out of scope (and thus be destructed); any use ofthe resulting reference will result in undefined behavior. The real question is: why the reference? Unless you're actuallyreferring to something in an object with a longer lifetime, with theintent that the client code modify it (usually not a good idea, butthere are notable exceptions, like operator[] of a vector), you shouldreturn by value.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/6127187', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/703061/']}
|
jdg_379112
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
13340216
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm looking for an example of a Microsoft Word Document generated by HTML.It should contain a header, footer and a watermark.
Now provide the response and nothing else.
|
This is some example, hope it helps others that are trying to generate ms word .doc file with HTML. <html xmlns:v="urn:schemas-microsoft-com:vml"xmlns:o="urn:schemas-microsoft-com:office:office"xmlns:w="urn:schemas-microsoft-com:office:word"xmlns:m="http://schemas.microsoft.com/office/2004/12/omml"xmlns="http://www.w3.org/TR/REC-html40"><head><meta http-equiv=Content-Type content="text/html; charset=utf-8"><title></title><style>v\:* {behavior:url(#default#VML);}o\:* {behavior:url(#default#VML);}w\:* {behavior:url(#default#VML);}.shape {behavior:url(#default#VML);}</style><style>@page{ mso-page-orientation: landscape; size:29.7cm 21cm; margin:1cm 1cm 1cm 1cm;}@page Section1 { mso-header-margin:.5in; mso-footer-margin:.5in; mso-header: h1; mso-footer: f1; }div.Section1 { page:Section1; }table#hrdftrtbl{ margin:0in 0in 0in 900in; width:1px; height:1px; overflow:hidden;}p.MsoFooter, li.MsoFooter, div.MsoFooter{ margin:0in; margin-bottom:.0001pt; mso-pagination:widow-orphan; tab-stops:center 3.0in right 6.0in; font-size:12.0pt;}</style><xml><w:WordDocument><w:View>Print</w:View><w:Zoom>100</w:Zoom><w:DoNotOptimizeForBrowser/></w:WordDocument></xml></head><body><div class="Section1"> <p> </p><br/> <table id='hrdftrtbl' border='0' cellspacing='0' cellpadding='0'> <tr><td> <div style='mso-element:header' id=h1 > <!-- HEADER-tags --> <p class=MsoHeader >HEADER</p> <!-- end HEADER-tags --> </div> </td> <td> <div style='mso-element:footer' id=f1><span style='position:relative;z-index:-1'> <!-- FOOTER-tags --> FOOTER <span style='mso-no-proof:yes'><!--[if gte vml 1]><v:shapetype id="_x0000_t75" coordsize="21600,21600" o:spt="75" o:preferrelative="t" path="m@4@5l@4@11@9@11@9@5xe" filled="f" stroked="f"> <v:formulas> <v:f eqn="if lineDrawn pixelLineWidth 0"/> <v:f eqn="sum @0 1 0"/> <v:f eqn="sum 0 0 @1"/> <v:f eqn="prod @2 1 2"/> <v:f eqn="prod @3 21600 pixelWidth"/> <v:f eqn="prod @3 21600 pixelHeight"/> <v:f eqn="sum @0 0 1"/> <v:f eqn="prod @6 1 2"/> <v:f eqn="prod @7 21600 pixelWidth"/> <v:f eqn="sum @8 21600 0"/> <v:f eqn="prod @7 21600 pixelHeight"/> <v:f eqn="sum @10 21600 0"/> </v:formulas> <v:path o:extrusionok="f" gradientshapeok="t" o:connecttype="rect"/> <o:lock v:ext="edit" aspectratio="t"/> </v:shapetype><v:shape id="Picture_x0020_1" o:spid="_x0000_s3073" type="#_x0000_t75" alt="VHB" style='position:absolute; margin-right:0pt;margin-top:-400pt; z-index:-1; visibility:visible;mso-wrap-style:square;mso-wrap-distance-left:9pt; mso-wrap-distance-top:0;mso-wrap-distance-right:9pt; mso-wrap-distance-bottom:0;mso-position-horizontal:absolute; mso-position-horizontal-relative:text;mso-position-vertical:absolute; mso-position-vertical-relative:text'> <v:imagedata src="https://www.google.bg/logos/2012/Rodin-2012-homepage.png"/> </v:shape><![endif]--></span> <p class=MsoFooter> <span style='mso-tab-count:2'></span> Page <span style='mso-field-code: PAGE'><span style='mso-no-proof:yes'></span> from <span style='mso-field-code: NUMPAGES'></span> <!-- end FOOTER-tags --> </span> </p> </div> <div style='mso-element:header' id='fh1'> <p class='MsoHeader'><span lang='EN-US' style='mso-ansi-language:EN-US'> <o:p></o:p></span></p> </div> <div style='mso-element:footer' id='ff1'> <p class='MsoFooter'><span lang='EN-US' style='mso-ansi-language:EN-US'> <o:p></o:p></span></p> </div> </td></tr> </table></div></body></html> You can adjust the watermark picture by setting width, height, margin-top, margin-right on the element v:shape id="Picture_x0020_1" : inline style.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/13340216', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1171803/']}
|
jdg_379113
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
25828303
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
i am trying to create a time array, something like: 1:001:151:301:452:002:15... here is my code, what it does is that it starts the time from current time upwoards: var timeArray = [];var d = new Date();var h = d.getHours();var m = d.getMinutes();for (var i = h; i <= 24; i++) { for (var j = m; j <= 59; j++) { if (j % 15 === 0) { j = j === 0 ? '00' : j; if (i >= 12) { timeArray.push((i - 12) + ':' + j + ' PM'); } else { timeArray.push(i + ':' + j + ' AM'); } } }} the problem is that is m is over 46 , like var m = 50; , then the array goes empty because j % 15 doesn't get 0 no more. an ideas how to fix this? thanks
Now provide the response and nothing else.
|
If what you want is an array ["1:00", "1:15", ...] then why not just build that? It has nothing to do with "hours" and "minutes", only with "getting some obviously sequential numbers" right: cost arr = [];for (let i=0; i < 24; i++) { for (let j=0; j < 4; j++) { arr.push(`${i}:${j === 0 ? `00` : 15*j}`); }} Done. Find your current time nearest a 15 minute block: const d = new Date(), h = d.getHours(), m = 15 * Math.floor(d.getMinutes() / 15), stamp = `${h}:${m === 0 ? `00` : m}`; And just reorder the timeslots: const pos = arr.indexOf(stamp);let timelist = [];if (pos > -1) { timelist = [ ...arr.slice(pos), ...arr.slice(0,pos) ];}
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/25828303', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/642022/']}
|
jdg_379114
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4215464
|
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 using Subclipse to manage SVN projects in Eclipse 3.4.2. However, while installing a buggy plugin, Eclipse became so sluggishly unusable that I had to kill the process and restart. Unfortunately, even though I removed the buggy plugin, this appears to have destroyed Subclipse's links to all my SVN projects. The projects themselves are still there, but the "Team" context menu only shows "Apply Patch", and no SVN icon overlays are being displayed. Is there anyway to fix this, or do I have to delete and recreate all my projects?
Now provide the response and nothing else.
|
If your project has the .svn directories (only the Eclipse integration 'has gone missing') you could try Team -> Share Project. In my workspace, Subclipse noticed the presence of the SVN folders and created the appropriate connection. Edit: if you do not have the Share Project menu maybe the Eclipse installation 'got screwed'. If you do not have the Share Project menu in a newly created project and you do not see the SVN preferences under Preferences --> Team then you should re-install the Subclipse plugin. If you do not have the Share Project menu only the projects you previously shared with SVN, than you should delete and recreate all your projects (in the delete do not delete the project contents and after the delete select File -> Import -> Existing projects into Workspace).
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/4215464', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/247542/']}
|
jdg_379115
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
22559891
|
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 know if it's possible to change the data type for a column. For instance, the json data passed to the grid are strings, but I would like slickgrid to consider it as integers or floats to be able to sort it correctly. var data = [{"NOM": "Saguenay - Lac-Saint-Jean", "CODE": "02", "id": "0", "integer": "1"},] I would like the 'integer' column to be an int not a string, without changing the data itself. Thank you for your help.
Now provide the response and nothing else.
|
As I mentioned in my comment, you are looking at the wrong place (no offense); there is no need to change datatype as actually this will not fix your problem with sort, since the SlickGrid default sort is string sort. But you could use custom sort to fix your problem. So here is the solution: Define sort function and use them as needed. Here is a list of custom sort functions you could create: function sorterStringCompare(a, b) { var x = a[sortcol], y = b[sortcol]; return sortdir * (x === y ? 0 : (x > y ? 1 : -1));}function sorterNumeric(a, b) { var x = (isNaN(a[sortcol]) || a[sortcol] === "" || a[sortcol] === null) ? -99e+10 : parseFloat(a[sortcol]); var y = (isNaN(b[sortcol]) || b[sortcol] === "" || b[sortcol] === null) ? -99e+10 : parseFloat(b[sortcol]); return sortdir * (x === y ? 0 : (x > y ? 1 : -1));}function sorterRating(a, b) { var xrow = a[sortcol], yrow = b[sortcol]; var x = xrow[3], y = yrow[3]; return sortdir * (x === y ? 0 : (x > y ? 1 : -1));}function sorterDateIso(a, b) { var regex_a = new RegExp("^((19[1-9][1-9])|([2][01][0-9]))\\d-([0]\\d|[1][0-2])-([0-2]\\d|[3][0-1])(\\s([0]\\d|[1][0-2])(\\:[0-5]\\d){1,2}(\\:[0-5]\\d){1,2})?$", "gi"); var regex_b = new RegExp("^((19[1-9][1-9])|([2][01][0-9]))\\d-([0]\\d|[1][0-2])-([0-2]\\d|[3][0-1])(\\s([0]\\d|[1][0-2])(\\:[0-5]\\d){1,2}(\\:[0-5]\\d){1,2})?$", "gi"); if (regex_a.test(a[sortcol]) && regex_b.test(b[sortcol])) { var date_a = new Date(a[sortcol]); var date_b = new Date(b[sortcol]); var diff = date_a.getTime() - date_b.getTime(); return sortdir * (diff === 0 ? 0 : (date_a > date_b ? 1 : -1)); } else { var x = a[sortcol], y = b[sortcol]; return sortdir * (x === y ? 0 : (x > y ? 1 : -1)); }} and then in your columns definition you would use whichever custom filter you need, in your case the sorterNumeric() is what you're looking for...so your columns definition would look like the following (custom filter are at the end): var columns = [ {id:"column1", name:"column1", field: "Column String", width:40, sortable:true, sorter:sorterStringCompare}, {id:"column2", name:"column2", field: "Column integer", width:40, sortable:true, sorter:sorterNumeric}, {id:"column3", name:"column3", field: "Column rating", width:40, sortable:true, sorter:sorterRating} ]; Saguenay...? Quebecois? :) EDIT I forgot to add the piece of code that attach the new sorter property to the onSort event (of course without it then it won't work), make sure you have same object name for grid and dataView , correct to whatever your variables naming are (if need be), here is the code: grid.onSort.subscribe(function (e, args) { var cols = args.sortCols; dataView.sort(function (dataRow1, dataRow2) { for (var i = 0, l = cols.length; i < l; i++) { sortdir = cols[i].sortAsc ? 1 : -1; sortcol = cols[i].sortCol.field; var result = cols[i].sortCol.sorter(dataRow1, dataRow2); // sorter property from column definition comes in play here if (result != 0) { return result; } } return 0; }); args.grid.invalidateAllRows(); args.grid.render();}); You could also put your code directly into the last onSort.subscribe but I suggest having the sorter into a separate function since it is cleaner (which is the code I sent).
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/22559891', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1914034/']}
|
jdg_379116
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
955442
|
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:
Are these two definitions equivalent, even though the first one has an extra term: If we consider the series $\sum_{n=1}^{\infty}x_{n}$ and the formal definition of a Cauchy property defined in terms of the values $x_{n}$ as being: For arbitrary $\epsilon > 0$ there exists a positive integer $N$ such that if $m > n > N$ we have $$|x_{n}+x_{n+1}+...+x_{m}| < \epsilon$$ is this equivalent to For arbitrary $\epsilon > 0$ there exists a positive integer $N$ such that if $m > n > N$ we have $$|s_{n}-s_{m}| < \epsilon$$ where $|s_{n}-s_{m}| = |\sum_{k=m+1}^{n}x_{k}|$ are partial sums. Are these equivalent and which one is the standard definition for the cauchy property of series in terms of $x_{n}$?
Now provide the response and nothing else.
|
First of all, using the Taylor series for $e^z$ we have$$\frac{e^z-1}{z} = 1 + \frac{z}{2} + \frac{z^2}{6} + \frac{z^3}{24} + \cdots.$$Multiplying this by the power series for $z/(e^z-1)$ and comparing coefficients (the product should be $1$) we get$$\begin{align*}1 &= B_0 \\0 &= B_1 + 1/2 \\0 &= (2B_2) + (1/2) B_1 + (1/6) B_0 \\0 &= (6B_3) + (1/2) (2B_2) + (1/6) B_1 + (1/24) B_0\end{align*}$$and so on. Therefore $B_0 = 1$, $B_1 = -1/2$, $B_2 = 1/6$, $B_3 = -1/30$, and so on. If you look at the function$$ f(z) = \frac{z}{e^z-1} + \frac{z}{2} $$then you find out that$$\begin{align*}f(-z) = \frac{-z}{e^{-z}-1} - \frac{z}{2} =\frac{ze^z}{e^z-1} - \frac{z}{2} =\frac{z}{e^z-1} + z - \frac{z}{2} = f(z).\end{align*}$$Therefore $f(z)$ is even and all the odd coefficients in its power series vanish. This shows that apart from $B_1 = -1/2$, all other odd-indexed Bernoulli numbers vanish. Why do we need them, then? They're just the sequence whose exponential generating series is $z/(e^z-1)$.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/955442', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
|
jdg_379117
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
214879
|
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:
In a git repository, I have set up my .gitmodules file to reference a github repository: [submodule "src/repo"] path = src/repo url = repourl when I 'git status' on this repo, it shows: On branch masterYour branch is up-to-date with 'origin/master'.Changes not staged for commit: (use "git add <file>..." to update what will be committed) (use "git checkout -- <file>..." to discard changes in working directory)modified: src/repo (new commits) If I cd into src/repo and git status on repo, it says that there is nothing to commit. Why is my top-level git repo complaining?
Now provide the response and nothing else.
|
It's because Git records which commit (not a branch or a tag, exactly one commit represented in SHA-1 hash) should be checked out for each submodule. If you change something in submodule dir, Git will detect it and urge you to commit those changes in the top-level repoisitory. Run git diff in the top-level repository to show what has actually changed Git thinks. If you've already made some commits in your submodule (thus "clean" in submodule), it reports submodule's hash change. $ git diffdiff --git a/src/repo b/src/repoindex b0c86e2..a893d84 160000--- a/src/repo+++ b/src/repo@@ -1 +1 @@-Subproject commit b0c86e28675c9591df51eedc928f991ca42f5fea+Subproject commit a893d84d323cf411eadf19569d90779610b10280 Otherwise it shows -dirty hash change which you cannot stage or commit in the top-level repository. git status also claims submodule has untracked/modified content. $ git diffdiff --git a/src/repo b/src/repo--- a/src/repo+++ b/src/repo@@ -1 +1 @@-Subproject commit b0c86e28675c9591df51eedc928f991ca42f5fea+Subproject commit b0c86e28675c9591df51eedc928f991ca42f5fea-dirty$ git statusOn branch masterChanges not staged for commit: (use "git add <file>..." to update what will be committed) (use "git checkout -- <file>..." to discard changes in working directory) (commit or discard the untracked or modified content in submodules) modified: src/repo (untracked content)no changes added to commit (use "git add" and/or "git commit -a") To update which commit records should be checked out for the submodule, you need to git commit the submodule in addition to committing the changes in the submodule: git add src/repo
|
{}
|
{'log_upvote_score': 7, 'links': ['https://unix.stackexchange.com/questions/214879', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/122721/']}
|
jdg_379118
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
54897646
|
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 convert the Torchvision MNIST train and test datasets into NumPy arrays but can't find documentation to actually perform the conversion. My goal would be to take an entire dataset and convert it into a single NumPy array, preferably without iterating through the entire dataset. I've looked at How do I turn a Pytorch Dataloader into a numpy array to display image data with matplotlib? but it doesn't address my issue. So my question is, utilizing torch.utils.data.DataLoader , how would I go about converting the datasets (train/test) into two NumPy arrays such that all of the examples are present? Note: I've left the batch size as the default of 1 for now; I could set it to 60,000 for train and 10,000 for test, but I'd prefer to not use magic numbers of that sort. Thank you.
Now provide the response and nothing else.
|
If I understand you correctly, you want to get the whole train dataset of MNIST images (in total 60000 images, each image of size 1x28x28 array with 1 for color channel) as a numpy array of size (60000, 1, 28, 28)? from torchvision import datasets, transformsfrom torch.utils.data import DataLoader# Transform to normalized Tensors transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))])train_dataset = datasets.MNIST('./MNIST/', train=True, transform=transform, download=True)# test_dataset = datasets.MNIST('./MNIST/', train=False, transform=transform, download=True)train_loader = DataLoader(train_dataset, batch_size=len(train_dataset))# test_loader = DataLoader(test_dataset, batch_size=len(test_dataset))train_dataset_array = next(iter(train_loader))[0].numpy()# test_dataset_array = next(iter(test_loader))[0].numpy() This is the result: >>> train_dataset_arrayarray([[[[-0.42421296, -0.42421296, -0.42421296, ..., -0.42421296, -0.42421296, -0.42421296], [-0.42421296, -0.42421296, -0.42421296, ..., -0.42421296, -0.42421296, -0.42421296], [-0.42421296, -0.42421296, -0.42421296, ..., -0.42421296, -0.42421296, -0.42421296], ..., [-0.42421296, -0.42421296, -0.42421296, ..., -0.42421296, -0.42421296, -0.42421296], [-0.42421296, -0.42421296, -0.42421296, ..., -0.42421296, -0.42421296, -0.42421296], [-0.42421296, -0.42421296, -0.42421296, ..., -0.42421296, -0.42421296, -0.42421296]]], [[[-0.42421296, -0.42421296, -0.42421296, ..., -0.42421296, -0.42421296, -0.42421296], [-0.42421296, -0.42421296, -0.42421296, ..., -0.42421296, -0.42421296, -0.42421296], [-0.42421296, -0.42421296, -0.42421296, ..., -0.42421296, -0.42421296, -0.42421296], ..., [-0.42421296, -0.42421296, -0.42421296, ..., -0.42421296, -0.42421296, -0.42421296], [-0.42421296, -0.42421296, -0.42421296, ..., -0.42421296, -0.42421296, -0.42421296], [-0.42421296, -0.42421296, -0.42421296, ..., -0.42421296, -0.42421296, -0.42421296]]], [[[-0.42421296, -0.42421296, -0.42421296, ..., -0.42421296, -0.42421296, -0.42421296], [-0.42421296, -0.42421296, -0.42421296, ..., -0.42421296, -0.42421296, -0.42421296], [-0.42421296, -0.42421296, -0.42421296, ..., -0.42421296, -0.42421296, -0.42421296], ..., [-0.42421296, -0.42421296, -0.42421296, ..., -0.42421296, -0.42421296, -0.42421296], [-0.42421296, -0.42421296, -0.42421296, ..., -0.42421296, -0.42421296, -0.42421296], [-0.42421296, -0.42421296, -0.42421296, ..., -0.42421296, -0.42421296, -0.42421296]]], ..., [[[-0.42421296, -0.42421296, -0.42421296, ..., -0.42421296, -0.42421296, -0.42421296], [-0.42421296, -0.42421296, -0.42421296, ..., -0.42421296, -0.42421296, -0.42421296], [-0.42421296, -0.42421296, -0.42421296, ..., -0.42421296, -0.42421296, -0.42421296], ..., [-0.42421296, -0.42421296, -0.42421296, ..., -0.42421296, -0.42421296, -0.42421296], [-0.42421296, -0.42421296, -0.42421296, ..., -0.42421296, -0.42421296, -0.42421296], [-0.42421296, -0.42421296, -0.42421296, ..., -0.42421296, -0.42421296, -0.42421296]]], [[[-0.42421296, -0.42421296, -0.42421296, ..., -0.42421296, -0.42421296, -0.42421296], [-0.42421296, -0.42421296, -0.42421296, ..., -0.42421296, -0.42421296, -0.42421296], [-0.42421296, -0.42421296, -0.42421296, ..., -0.42421296, -0.42421296, -0.42421296], ..., [-0.42421296, -0.42421296, -0.42421296, ..., -0.42421296, -0.42421296, -0.42421296], [-0.42421296, -0.42421296, -0.42421296, ..., -0.42421296, -0.42421296, -0.42421296], [-0.42421296, -0.42421296, -0.42421296, ..., -0.42421296, -0.42421296, -0.42421296]]], [[[-0.42421296, -0.42421296, -0.42421296, ..., -0.42421296, -0.42421296, -0.42421296], [-0.42421296, -0.42421296, -0.42421296, ..., -0.42421296, -0.42421296, -0.42421296], [-0.42421296, -0.42421296, -0.42421296, ..., -0.42421296, -0.42421296, -0.42421296], ..., [-0.42421296, -0.42421296, -0.42421296, ..., -0.42421296, -0.42421296, -0.42421296], [-0.42421296, -0.42421296, -0.42421296, ..., -0.42421296, -0.42421296, -0.42421296], [-0.42421296, -0.42421296, -0.42421296, ..., -0.42421296, -0.42421296, -0.42421296]]]], dtype=float32) Edit : You can also get the labels by next(iter(train_loader))[1].numpy() . Alternatively you can use train_dataset.data.numpy() and train_dataset.targets.numpy() , but note that the data will not be transformed by transform as is done when using the dataloader.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/54897646', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4309985/']}
|
jdg_379119
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
36171208
|
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 create a UDF to be used in pyspark python which uses a java object for its internal calculations. If it were a simple python I would do something like: def f(x): return 7fudf = pyspark.sql.functions.udf(f,pyspark.sql.types.IntegerType()) and call it using: df = sqlContext.range(0,5)df2 = df.withColumn("a",fudf(df.id)).show() However, the implementation of the function I need is in java and not in python. I need to wrap it somehow so I can call it in a similar way from python. My first try was to do implement the java object, then wrap it in python in pyspark and convert that to UDF. That failed with serialization error. Java code: package com.test1.test2;public class TestClass1 { Integer internalVal; public TestClass1(Integer val1) { internalVal = val1; } public Integer do_something(Integer val) { return internalVal; } } pyspark code: from py4j.java_gateway import java_importfrom pyspark.sql.functions import udffrom pyspark.sql.types import IntegerTypejava_import(sc._gateway.jvm, "com.test1.test2.TestClass1")a = sc._gateway.jvm.com.test1.test2.TestClass1(7)audf = udf(a,IntegerType()) error: ---------------------------------------------------------------------------Py4JError Traceback (most recent call last)<ipython-input-2-9756772ab14f> in <module>() 4 java_import(sc._gateway.jvm, "com.test1.test2.TestClass1") 5 a = sc._gateway.jvm.com.test1.test2.TestClass1(7)----> 6 audf = udf(a,IntegerType())/usr/local/spark/python/pyspark/sql/functions.py in udf(f, returnType) 1595 [Row(slen=5), Row(slen=3)] 1596 """-> 1597 return UserDefinedFunction(f, returnType) 1598 1599 blacklist = ['map', 'since', 'ignore_unicode_prefix']/usr/local/spark/python/pyspark/sql/functions.py in __init__(self, func, returnType, name) 1556 self.returnType = returnType 1557 self._broadcast = None-> 1558 self._judf = self._create_judf(name) 1559 1560 def _create_judf(self, name):/usr/local/spark/python/pyspark/sql/functions.py in _create_judf(self, name) 1565 command = (func, None, ser, ser) 1566 sc = SparkContext.getOrCreate()-> 1567 pickled_command, broadcast_vars, env, includes = _prepare_for_python_RDD(sc, command, self) 1568 ctx = SQLContext.getOrCreate(sc) 1569 jdt = ctx._ssql_ctx.parseDataType(self.returnType.json())/usr/local/spark/python/pyspark/rdd.py in _prepare_for_python_RDD(sc, command, obj) 2297 # the serialized command will be compressed by broadcast 2298 ser = CloudPickleSerializer()-> 2299 pickled_command = ser.dumps(command) 2300 if len(pickled_command) > (1 << 20): # 1M 2301 # The broadcast will have same life cycle as created PythonRDD/usr/local/spark/python/pyspark/serializers.py in dumps(self, obj) 426 427 def dumps(self, obj):--> 428 return cloudpickle.dumps(obj, 2) 429 430 /usr/local/spark/python/pyspark/cloudpickle.py in dumps(obj, protocol) 644 645 cp = CloudPickler(file,protocol)--> 646 cp.dump(obj) 647 648 return file.getvalue()/usr/local/spark/python/pyspark/cloudpickle.py in dump(self, obj) 105 self.inject_addons() 106 try:--> 107 return Pickler.dump(self, obj) 108 except RuntimeError as e: 109 if 'recursion' in e.args[0]:/home/mendea3/anaconda2/lib/python2.7/pickle.pyc in dump(self, obj) 222 if self.proto >= 2: 223 self.write(PROTO + chr(self.proto))--> 224 self.save(obj) 225 self.write(STOP) 226 /home/mendea3/anaconda2/lib/python2.7/pickle.pyc in save(self, obj) 284 f = self.dispatch.get(t) 285 if f:--> 286 f(self, obj) # Call unbound method with explicit self 287 return 288 /home/mendea3/anaconda2/lib/python2.7/pickle.pyc in save_tuple(self, obj) 566 write(MARK) 567 for element in obj:--> 568 save(element) 569 570 if id(obj) in memo:/home/mendea3/anaconda2/lib/python2.7/pickle.pyc in save(self, obj) 284 f = self.dispatch.get(t) 285 if f:--> 286 f(self, obj) # Call unbound method with explicit self 287 return 288 /usr/local/spark/python/pyspark/cloudpickle.py in save_function(self, obj, name) 191 if islambda(obj) or obj.__code__.co_filename == '<stdin>' or themodule is None: 192 #print("save global", islambda(obj), obj.__code__.co_filename, modname, themodule)--> 193 self.save_function_tuple(obj) 194 return 195 else:/usr/local/spark/python/pyspark/cloudpickle.py in save_function_tuple(self, func) 234 # create a skeleton function object and memoize it 235 save(_make_skel_func)--> 236 save((code, closure, base_globals)) 237 write(pickle.REDUCE) 238 self.memoize(func)/home/mendea3/anaconda2/lib/python2.7/pickle.pyc in save(self, obj) 284 f = self.dispatch.get(t) 285 if f:--> 286 f(self, obj) # Call unbound method with explicit self 287 return 288 /home/mendea3/anaconda2/lib/python2.7/pickle.pyc in save_tuple(self, obj) 552 if n <= 3 and proto >= 2: 553 for element in obj:--> 554 save(element) 555 # Subtle. Same as in the big comment below. 556 if id(obj) in memo:/home/mendea3/anaconda2/lib/python2.7/pickle.pyc in save(self, obj) 284 f = self.dispatch.get(t) 285 if f:--> 286 f(self, obj) # Call unbound method with explicit self 287 return 288 /home/mendea3/anaconda2/lib/python2.7/pickle.pyc in save_list(self, obj) 604 605 self.memoize(obj)--> 606 self._batch_appends(iter(obj)) 607 608 dispatch[ListType] = save_list/home/mendea3/anaconda2/lib/python2.7/pickle.pyc in _batch_appends(self, items) 637 write(MARK) 638 for x in tmp:--> 639 save(x) 640 write(APPENDS) 641 elif n:/home/mendea3/anaconda2/lib/python2.7/pickle.pyc in save(self, obj) 304 reduce = getattr(obj, "__reduce_ex__", None) 305 if reduce:--> 306 rv = reduce(self.proto) 307 else: 308 reduce = getattr(obj, "__reduce__", None)/usr/local/spark/python/lib/py4j-0.9-src.zip/py4j/java_gateway.py in __call__(self, *args) 811 answer = self.gateway_client.send_command(command) 812 return_value = get_return_value(--> 813 answer, self.gateway_client, self.target_id, self.name) 814 815 for temp_arg in temp_args:/usr/local/spark/python/pyspark/sql/utils.py in deco(*a, **kw) 43 def deco(*a, **kw): 44 try:---> 45 return f(*a, **kw) 46 except py4j.protocol.Py4JJavaError as e: 47 s = e.java_exception.toString()/usr/local/spark/python/lib/py4j-0.9-src.zip/py4j/protocol.py in get_return_value(answer, gateway_client, target_id, name) 310 raise Py4JError( 311 "An error occurred while calling {0}{1}{2}. Trace:\n{3}\n".--> 312 format(target_id, ".", name, value)) 313 else: 314 raise Py4JError(Py4JError: An error occurred while calling o18.__getnewargs__. Trace:py4j.Py4JException: Method __getnewargs__([]) does not exist at py4j.reflection.ReflectionEngine.getMethod(ReflectionEngine.java:335) at py4j.reflection.ReflectionEngine.getMethod(ReflectionEngine.java:344) at py4j.Gateway.invoke(Gateway.java:252) at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:133) at py4j.commands.CallCommand.execute(CallCommand.java:79) at py4j.GatewayConnection.run(GatewayConnection.java:209) at java.lang.Thread.run(Thread.java:745) EDIT : I also tried to make the java class serializable but to no avail. My second attempt was to define the UDF in java to begin with but that failed as I am not sure how to correctly wrap it: java code: package com.test1.test2; import org.apache.spark.sql.api.java.UDF1;public class TestClassUdf implements UDF1<Integer, Integer> { Integer retval; public TestClassUdf(Integer val) { retval = val; } @Override public Integer call(Integer arg0) throws Exception { return retval; } } but how would I use it?I tried: from py4j.java_gateway import java_importjava_import(sc._gateway.jvm, "com.test1.test2.TestClassUdf")a = sc._gateway.jvm.com.test1.test2.TestClassUdf(7)dfint = sqlContext.range(0,15)df = dfint.withColumn("a",a(dfint.id)) but I get: ---------------------------------------------------------------------------TypeError Traceback (most recent call last)<ipython-input-5-514811090b5f> in <module>() 3 a = sc._gateway.jvm.com.test1.test2.TestClassUdf(7) 4 dfint = sqlContext.range(0,15)----> 5 df = dfint.withColumn("a",a(dfint.id))TypeError: 'JavaObject' object is not callable and I tried to use a.call instead of a: df = dfint.withColumn("a",a.call(dfint.id)) but got: --------------------------------------------------------------------------- TypeError Traceback (most recent call last) in () 3 a = sc._gateway.jvm.com.test1.test2.TestClassUdf(7) 4 dfint = sqlContext.range(0,15) ----> 5 df = dfint.withColumn("a",a.call(dfint.id)) /usr/local/spark/python/lib/py4j-0.9-src.zip/py4j/java_gateway.py in __call__(self, *args) 796 def __call__(self, *args): 797 if self.converters is not None and len(self.converters) > 0:--> 798 (new_args, temp_args) = self._get_args(args) 799 else: 800 new_args = args/usr/local/spark/python/lib/py4j-0.9-src.zip/py4j/java_gateway.py in _get_args(self, args) 783 for converter in self.gateway_client.converters: 784 if converter.can_convert(arg):--> 785 temp_arg = converter.convert(arg, self.gateway_client) 786 temp_args.append(temp_arg) 787 new_args.append(temp_arg)/usr/local/spark/python/lib/py4j-0.9-src.zip/py4j/java_collections.py in convert(self, object, gateway_client) 510 HashMap = JavaClass("java.util.HashMap", gateway_client) 511 java_map = HashMap()--> 512 for key in object.keys(): 513 java_map[key] = object[key] 514 return java_mapTypeError: 'Column' object is not callable Any help would be appriciated.
Now provide the response and nothing else.
|
I got this working with the help of another question (and answer) of your own about UDAFs. Spark provides a udf() method for wrapping Scala FunctionN , so we can wrap the Java function in Scala and use that. Your Java method needs to be static or on a class that implements Serializable . package com.exampleimport org.apache.spark.sql.UserDefinedFunctionimport org.apache.spark.sql.functions.udfclass MyUdf extends Serializable { def getUdf: UserDefinedFunction = udf(() => MyJavaClass.MyJavaMethod())} Usage in PySpark: def my_udf(): from pyspark.sql.column import Column, _to_java_column, _to_seq pcls = "com.example.MyUdf" jc = sc._jvm.java.lang.Thread.currentThread() \ .getContextClassLoader().loadClass(pcls).newInstance().getUdf().apply return Column(jc(_to_seq(sc, [], _to_java_column)))rdd1 = sc.parallelize([{'c1': 'a'}, {'c1': 'b'}, {'c1': 'c'}])df1 = rdd1.toDF()df2 = df1.withColumn('mycol', my_udf()) As with the UDAF in your other question and answer, we can pass columns into it with return Column(jc(_to_seq(sc, ["col1", "col2"], _to_java_column)))
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/36171208', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1547734/']}
|
jdg_379120
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
14698228
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
The behaviour of MemoryCache.AddOrGetExisting is described as: Adds a cache entry into the cache using the specified key and a value and an absolute expiration value. And that it returns: If a cache entry with the same key exists, the existing cache entry; otherwise, null. What is the purpose of a method with these semantics? What is an example of this?
Now provide the response and nothing else.
|
There are often situations where you only want to create a cache entry if a matching entry doesn't already exist (that is, you don't want to overwrite an existing value). AddOrGetExisting allows you to do this atomically. Without AddOrGetExisting it would be impossible to perform the get-test-set in an atomic, thread-safe manner. For example: Thread 1 Thread 2 -------- -------- // check whether there's an existing entry for "foo" // the call returns null because there's no match Get("foo") // check whether there's an existing entry for "foo" // the call returns null because there's no match Get("foo") // set value for key "foo" // assumes, rightly, that there's no existing entry Set("foo", "first thread rulez") // set value for key "foo" // assumes, wrongly, that there's no existing entry // overwrites the value just set by thread 1 Set("foo", "second thread rulez") (See also the Interlocked.CompareExchange method, which enables a more sophisticated equivalent at the variable level, and also the wikipedia entries on test-and-set and compare-and-swap .)
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/14698228', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1575281/']}
|
jdg_379121
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1046343
|
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 are infinitely many primes of the form $8k + 3$ I have seen proofs for $4k+1$ and $8k+1$ and $4k+3$ but struggling with this one please help The suggestion given is to consider a number of the form $N^2+2$ how did one decide this is the one to work with.
Now provide the response and nothing else.
|
Method $1$ using Dirichlet's Theorem http://en.wikipedia.org/wiki/Dirichlet%27s_theorem_on_arithmetic_progressions Dirichlet asserts that whenever $(a, b) = 1$ and a not zero the sequence $an + b$ contains infinitely many primes. $(8,3)=1$ so there are infinitely many primes of the form $8k+3$ Method $2$ By the hint from lhf Let primes of the form $8k+3$ be finite and denoted by $p_1, \dots, p_n$ Let $N=p_1 p_2\cdots p_n$. consider $M=N^2+2$. Clearly none of the $p_i$ divide $M$. Let $q$ be a prime factor of $M$ so $N^2\equiv-2\pmod q$. By quadratic Residue principles we can say $\left(\frac{-2}q\right)$ which is same as $\left(\frac2q\right)*\left(\frac{-1}q\right)$by using formula for these two we can say $q\equiv1\pmod2$ and $q^2\equiv1\pmod8$ so we can try for $q\equiv1,3,5,7\pmod8$ the conditions are satisfied for only 1 and 3. we can say the $q\equiv1\pmod8$ implies $q$ must be of the form $8k+1$ $q\equiv3\pmod8$ implies $q$ must be of the form $8k+3$. we know each $p_i\equiv3\pmod8$ $N=p_1 p_2\cdots p_n\equiv3^n\pmod8$ $N^2\equiv3^{2n}\equiv(3^2)^n\equiv9^n\equiv1\pmod8$ as $M=N^2+2$ $M\equiv3\pmod8$ we know all the divisors ($q$) of $M$ must be of the form $8k+1$ or $8k+3$ let $M=r_1 r_2\cdots r_t$ where all $r_i$ are of the form $8k+1$ and all $r_i\equiv1\pmod8$ so $M\equiv1\pmod8$ which is a contradiction as we have asserted previously that $M\equiv3\pmod8$ so M cannot have all divisors in the form of $8k+1$ it should have at least one divisor of the form $8k+3$. Let this divisor be $Q$. since $Q$ divides $M$ but its not one of the $p_i$ its contradiction hence we should have infinite primes of the form $8k+3$
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1046343', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/70964/']}
|
jdg_379122
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
35172956
|
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 table contains the details like with two fields: ID DisplayName1 Editor1 Reviewer7 EIC7 Editor7 Reviewer7 Editor19 EIC19 Editor19 Reviewer I want get the unique details with DisplayName like 1 Editor,Reviewer 7 EIC,Editor,Reviewer Don't get duplicate value with ID 7 How to combine DisplayName Details? How to write the Query?
Now provide the response and nothing else.
|
In SQL-Server you can do it in the following: QUERY SELECT id, displayname = STUFF((SELECT DISTINCT ', ' + displayname FROM #t b WHERE b.id = a.id FOR XML PATH('')), 1, 2, '')FROM #t aGROUP BY id TEST DATA create table #t (id int,displayname nvarchar(max))insert into #t values (1 ,'Editor'),(1 ,'Reviewer'),(7 ,'EIC'),(7 ,'Editor'),(7 ,'Reviewer'),(7 ,'Editor'),(19,'EIC'),(19,'Editor'),(19,'Reviewer') OUTPUT id displayname1 Editor, Reviewer7 Editor, EIC, Reviewer19 Editor, EIC, Reviewer
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/35172956', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2164986/']}
|
jdg_379123
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2628565
|
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 since Steve Jobs said Flash sucks and implied that HTML5 can do everything Flash can without the need for a Plugin, I keep hearing those exact words from a lot of People. I would really like to have a Chart somewhere (similar to http://en.wikipedia.org/wiki/Comparison_of_layout_engines_%28HTML5%29#Form_elements_and_attributes ) that I can just show to those people. Showing all the little things that Flash can do right now, that HTML5/Ajax/CSS is not yet even thinking about. But of course also the things that HTML5 does better. I would like to see details compared like audio playback, realtime audio processing, byte level access, bitmap data manipulation, webcam access, binary sockets, stuff in the works such as P2P technology (adobe stratus) and all the stuff I don't know about myself. Ideally with examples of what can be accomplished with, lets say Binary Sockets (such as a POP3 client) because otherwise it won't mean a lot to non-programmers since they will just say "well we can do without Binary Sockets". And ideally with some current benchmarks and some examples of websites that use this technology. I've searched the web and am surprised not to find anything. So is there such a comparison somewhere? Or does anybody want to create this and post it to Wikipedia? ;-)
Now provide the response and nothing else.
|
There are already many questions asked on SO for comparisons between HTML5 and Flash. HTML5 by itself isn't powerful enough (being a markup language), but people commonly refer to the whole stack that is HTML5, Javascript, CSS3 and more when referring to HTML5. This is not the tabular comparison that you were looking for, but it gets some points across. To start with, HTML5 is a standard and will take time to reach completion. Browser implementation varies as of today although Chrome, Safari, and Firefox are really active in terms of what has already been implemented. Now the biggest difference between Flash and HTML5 is the sandbox. Flash being a browser plugin has access to all low level functionality that HTML5 does not due to the browser's security restrictions. It's much more easier to lift a restriction in Flash with a simple update to the plugin, but a lot more difficult to update the spec once it has been finalized and implemented, being the reason why it is taking so long. That said, HTML5 is bridging that gap to get as close as possible to what Flash does. Audio/Video playback In HTML5, full programmatic access is provided for audio and video playback. The issue of supported codec is still lurking wide open and being debated over. Real-time audio/video processing For real-time audio and video processing, things are not looking bad for HTML5. Checkout this demo for a sample of real-time audio visualization. Another demo for real-time motion-detection is available. Websockets (with server sent events) and P2P support HTML5 has WebSockets that allows creating a full-duplex connection to a server, thus reducing the need for Reverse Ajax/Comet techniques. This will be very helpful for games, chat, stocks and many other types of application that require real-time data. WebSockets are not raw sockets, and will only connect to servers that implement the WebSocket protocol. So direct access to your IMAP account, for example, won't not possible. One major shortcoming with WebSockets as they stand today is the lack of P2P support. It would have been much more useful had it supported connections to other clients. This might change in the future but as of today there is no P2P support. UI HTML lacked the UI side of things mainly due to a lack of a canvas like Flash. SVG was there but it wasn't the easiest thing to use in the world. IDE support for these is still minimal, but it should improve with time. A canvas puts HTML5 at par with Flash, at least on the UI side of things. Devices - Webcam/Microphone/.. A HTML5 Device spec is targeted towards providing access to devices such as a webcam, microphone, etc. Interestingly enough, there is also a mention of P2P support on this link. It's still an editors draft but looks like we will finally have P2P before HTML6. More details on the capture API (video/audio) are available here . A full list of things being worked on the device end specifically are listed here . This has been forked off the HTML5 spec and is under a separate working group afaik. Offline storage, Geo-Location, Parallel processing among other things Mobile support for HTML5 is also looking good with Mobile Safari on the iPhone and Android. For some cool demos, checkout these links: http://linuxers.org/article/some-cool-html5-demos http://html5demos.com/ http://people.mozilla.com/~prouget/demos/ http://htmlfive.appspot.com/ http://9elements.com/io/projects/html5/canvas/ http://ajaxian.com/archives/html5-demos Two more awesome links thanks to @iddqd http://apirocks.com/html5/html5.html#slide http://html5readiness.com
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2628565', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/252814/']}
|
jdg_379124
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
28388204
|
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 started to discovered Mockito library and there is a question for which I didn't find the proper answer. If I have for example such method in my UserDAO class that saves user in database: public class UserDAO{... public void create(User user) { Connection connection = null; PreparedStatement pstmt = null; ResultSet generatedKeys = null; try { connection = getConnection(); pstmt = connection.prepareStatement(INSERT_USER, PreparedStatement.RETURN_GENERATED_KEYS); int counter = 1; pstmt.setString(counter++, user.getFirstName()); pstmt.setString(counter++, user.getLastName()); pstmt.setString(counter++, user.getEmail()); pstmt.setString(counter++, user.getPassword()); pstmt.setString(counter++, user.getRole()); pstmt.setString(counter, user.getLang()); pstmt.execute(); connection.commit(); generatedKeys = pstmt.getGeneratedKeys(); if (generatedKeys.next()) { user.setId(generatedKeys.getInt(Fields.GENERATED_KEY)); } } catch (SQLException e) { rollback(connection); LOG.error("Can not create a user", e); } finally { close(connection); close(pstmt); close(generatedKeys); } } ....} How should I test it ? If I want to test for example a DAO class then I need to create a DataSource mock, Connection mock, ResultSet mock etc ? And so not to test the database itself ? But what if I want to also test the behavior of dao and database ? Would you please produce some code samples, links that could be helpful and show best approaches of doing it ?
Now provide the response and nothing else.
|
Here is a good start using Mockito to test your UserDAO. This code uses a good amount of the Mockito features, so you can see how to use them. Let me know if you have questions. import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import javax.sql.DataSource;import org.junit.After;import org.junit.AfterClass;import org.junit.Before;import org.junit.BeforeClass;import org.junit.Test;import static org.junit.Assert.*;import org.junit.runner.RunWith;import static org.mockito.Matchers.anyInt;import static org.mockito.Matchers.anyString;import org.mockito.Mock;import static org.mockito.Mockito.doNothing;import static org.mockito.Mockito.times;import static org.mockito.Mockito.verify;import static org.mockito.Mockito.when;import org.mockito.runners.MockitoJUnitRunner;@RunWith(MockitoJUnitRunner.class)public class TestUserDAO { @Mock DataSource mockDataSource; @Mock Connection mockConn; @Mock PreparedStatement mockPreparedStmnt; @Mock ResultSet mockResultSet; int userId = 100; public TestUserDAO() { } @BeforeClass public static void setUpClass() throws Exception { } @AfterClass public static void tearDownClass() { } @Before public void setUp() throws SQLException { when(mockDataSource.getConnection()).thenReturn(mockConn); when(mockDataSource.getConnection(anyString(), anyString())).thenReturn(mockConn); doNothing().when(mockConn).commit(); when(mockConn.prepareStatement(anyString(), anyInt())).thenReturn(mockPreparedStmnt); doNothing().when(mockPreparedStmnt).setString(anyInt(), anyString()); when(mockPreparedStmnt.execute()).thenReturn(Boolean.TRUE); when(mockPreparedStmnt.getGeneratedKeys()).thenReturn(mockResultSet); when(mockResultSet.next()).thenReturn(Boolean.TRUE, Boolean.FALSE); when(mockResultSet.getInt(Fields.GENERATED_KEYS)).thenReturn(userId); } @After public void tearDown() { } @Test public void testCreateWithNoExceptions() throws SQLException { UserDAO instance = new UserDAO(mockDataSource); instance.create(new User()); //verify and assert verify(mockConn, times(1)).prepareStatement(anyString(), anyInt()); verify(mockPreparedStmnt, times(6)).setString(anyInt(), anyString()); verify(mockPreparedStmnt, times(1)).execute(); verify(mockConn, times(1)).commit(); verify(mockResultSet, times(2)).next(); verify(mockResultSet, times(1)).getInt(Fields.GENERATED_KEYS); } @Test(expected = SQLException.class) public void testCreateWithPreparedStmntException() throws SQLException { //mock when(mockConn.prepareStatement(anyString(), anyInt())).thenThrow(new SQLException()); try { UserDAO instance = new UserDAO(mockDataSource); instance.create(new User()); } catch (SQLException se) { //verify and assert verify(mockConn, times(1)).prepareStatement(anyString(), anyInt()); verify(mockPreparedStmnt, times(0)).setString(anyInt(), anyString()); verify(mockPreparedStmnt, times(0)).execute(); verify(mockConn, times(0)).commit(); verify(mockResultSet, times(0)).next(); verify(mockResultSet, times(0)).getInt(Fields.GENERATED_KEYS); throw se; } }}
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/28388204', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3424394/']}
|
jdg_379125
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
296
|
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:
In high school I was taught energy was conserved. Then I learned that nuclear reactions allow energy to be converted into mass. Then I also heard that apparently energy can spontaneously appear in quantum mechanics. So, are there any other caveats with the conservation of energy?
Now provide the response and nothing else.
|
The topic of "Energy Conservation" really depends on the particular "theory", paradigm, that you're considering — and it can vary quite a lot. A good hammer to use to hit this nail is Noether's Theorem : see, e.g., how it's applied in Classical Mechanics . The same principle can be applied to all other theories in Physics, from Thermodynamics and Statistical Mechanics all the way up to General Relativity and Quantum Field Theory (and Gauge Theories). Thus, the lesson to learn is that Energy is only conserved if there's translational time symmetry in the problem. Which brings us to General Relativity: in several interesting cases in GR, it's simply impossible to properly define a "time" direction! Technically speaking, this would imply a certain global property (called " global hyperbolicity ") which not all 4-dimensional spacetimes have. So, in general, Energy is not conserved in GR. As for quantum effects, Energy is conserved in Quantum Field Theory (which is a superset of Quantum Mechanics, so to speak): although it's true that there can be fluctuations, these are bounded by the "uncertainty principle", and do not affect the application of Noether's Theorem in QFT. So, the bottom line is that, even though energy is not conserved always, we can always understand what this non-conservation mean via Noether's Theorem. ;-)
|
{}
|
{'log_upvote_score': 6, 'links': ['https://physics.stackexchange.com/questions/296', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/119/']}
|
jdg_379126
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
549070
|
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am following Cross-Compiled Linux From Scratch - Embedded. In section 3.3 "Setting Up the Environment" , PS1 is declared in .bash_profile . When I log in as su - clfs , both .bash_profile and .bashrc get executed. When I log in as su clfs , only .bashrc gets executed. In both cases, PS1 never updates the terminal. When I put PS1 in .bashrc , it does update the terminal. The CLFS book has put it in .bash_profile : cat > ~/.bash_profile << "EOF"exec env -i HOME=${HOME} TERM=${TERM} PS1='\u:\w\$ ' /bin/bashEOF What is the suitable location for PS1?
Now provide the response and nothing else.
|
The PS1 shell variable should be set in ~/.bashrc for the bash shell as that is the initialisation file that is read for interactive shell sessions. Note that this variable is a shell variable , not an environment variable (it does not make sense to let child processes inherit its value, and it's only the current shell that uses it). It therefore does not need to be exported with export . Related: What is the purpose of .bashrc and how does it work? You shouldn't need to start bash from any of the shell's startup files. Starting a particular shell from ~/.profile (or the corresponding file related to your login shell) may possibly be warranted if the system that you're running on does not allow you to change your login shell. Care should be taken to not start the other shell if that is the shell already executing the file though, or you may end up in an infinite loop of sorts. The exec code that you add to your ~/.bash_profile should never be needed. I suppose it's a way of getting ~/.bashrc to be parsed (it starts an interactive shell, and interactive bash shells read ~/.bashrc ). A better way of doing that would be to have one of the files source the other, for example using this in ~/.bash_profile : if [[ -f $HOME/.bashrc ]]; then source "$HOME/.bashrc"fi Then set PS1 in ~/.bashrc (there should be no need to touch HOME or TERM ). The other thing that the command does is to clean out all other environment variables using env -i . Unless you have very specific reasons to do this, you should not do that from your ordinary shell startup files.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/549070', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/211284/']}
|
jdg_379127
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
8488565
|
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 Play! if you call this: void method(){User u = User();u.name = "bob";u.save();while(true){/* endless loop */}} Nothing will actually be saved into the db (The Play! class needs to get the hand back to flush the saves.) How do I have to proceed in order to either force a flush or to make it automatically flush at save ?
Now provide the response and nothing else.
|
The reason why your changes are not visible in the database, is that the transaction is not yet commited and so other transactions can't see your changes (at least in a good database like PostgreSQL, Oracle, MSSQL, DB2).To make your changes seen, you'll have to commit your transaction before it enters the infinite loop, like this: void method(){ User u = User(); u.name = "bob"; u.save(); JPA.em().flush(); JPA.em().getTransaction().commit(); while(true){/* endless loop */}} If you want to access your database inside the infinite loop or after it (if you have a break condition), you'll have to begin a new transaction or you'll get exceptions from hibernate. Do this like this void method(){ User u = User(); u.name = "bob"; u.save(); JPA.em().flush(); JPA.em().getTransaction().commit(); while(true){ // do some stuff /* TRANSACTIONAL BLOCK BEGINS */ JPA.em().getTransaction().begin(); try{ // do some stuff // fetching, updating, deleting, whatever JPA.em().getTransaction().commit(); } catch (Exception e) { // if an error occurs, rollback the transaction JPA.em().getTransaction().rollback(); } /* TRANSACTIONAL BLOCK ENDS */ // do some other stuff } // copy the TRANSACTIONAL BLOCK from above, if you want to do stuff after the "infinite loop" as well.} It's important that you either commit or rollback the transaction in the loop, if you start it there, as else you'll run into problems with too many open transactions soon.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8488565', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/532695/']}
|
jdg_379128
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
10377593
|
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 plotting some functions that have several discontinuities. Each function is given as a list. I want to connect points with lines only where the function is continuous. Here is a simplified example of what plot is doing. x=linspace(0,1,100) y=zeros(100)y[x<0.5] = x[x<0.5]y[x>=0.5] = 1 + x[x>=0.5]plot(x, y, '-o') There is a discontinuity at x=0.5, but plot connects all points with lines regardless. My functions are different of course. They typically have several discontinuities in different places. The criterion for the discontinuity is simple. Say, if the function jumps by more than 0.5, I assume it is discontinuous at that point. Is there an option in plot to tell it to drop the connecting lines between the points where the function is discontinuous? I recall being able to do that easily with gnuplot.
Now provide the response and nothing else.
|
use nan to break the line into multiple segments: import numpy as npfrom pylab import *x=linspace(0,1,100) y=zeros(100)y[x<0.5] = x[x<0.5]y[x>=0.5] = 1 + x[x>=0.5]pos = np.where(np.abs(np.diff(y)) >= 0.5)[0]x[pos] = np.nany[pos] = np.nanplot(x, y, '-o') Edit: to insert nan at discontinuities: pos = np.where(np.abs(np.diff(y)) >= 0.5)[0]+1x = np.insert(x, pos, np.nan)y = np.insert(y, pos, np.nan)
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/10377593', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/622489/']}
|
jdg_379129
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
11672676
|
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 Hadoop when do reduce tasks start? Do they start after a certain percentage (threshold) of mappers complete? If so, is this threshold fixed? What kind of threshold is typically used?
Now provide the response and nothing else.
|
The reduce phase has 3 steps: shuffle, sort, reduce. Shuffle is where the data is collected by the reducer from each mapper. This can happen while mappers are generating data since it is only a data transfer. On the other hand, sort and reduce can only start once all the mappers are done. You can tell which one MapReduce is doing by looking at the reducer completion percentage: 0-33% means its doing shuffle, 34-66% is sort, 67%-100% is reduce. This is why your reducers will sometimes seem "stuck" at 33%-- it's waiting for mappers to finish. Reducers start shuffling based on a threshold of percentage of mappers that have finished. You can change the parameter to get reducers to start sooner or later. Why is starting the reducers early a good thing? Because it spreads out the data transfer from the mappers to the reducers over time, which is a good thing if your network is the bottleneck. Why is starting the reducers early a bad thing? Because they "hog up" reduce slots while only copying data and waiting for mappers to finish. Another job that starts later that will actually use the reduce slots now can't use them. You can customize when the reducers startup by changing the default value of mapred.reduce.slowstart.completed.maps in mapred-site.xml . A value of 1.00 will wait for all the mappers to finish before starting the reducers. A value of 0.0 will start the reducers right away. A value of 0.5 will start the reducers when half of the mappers are complete. You can also change mapred.reduce.slowstart.completed.maps on a job-by-job basis. In new versions of Hadoop (at least 2.4.1) the parameter is called is mapreduce.job.reduce.slowstart.completedmaps (thanks user yegor256). Typically, I like to keep mapred.reduce.slowstart.completed.maps above 0.9 if the system ever has multiple jobs running at once. This way the job doesn't hog up reducers when they aren't doing anything but copying data. If you only ever have one job running at a time, doing 0.1 would probably be appropriate.
|
{}
|
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/11672676', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1486882/']}
|
jdg_379130
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
748628
|
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 reading a book about abstract algebra, but I'm having trouble solving this excercise: "Show that $(\mathbb{Q}^*,\cdot)$ and $(\mathbb{R}^*,\cdot)$ aren't cyclic" Where $(\mathbb{Q}^*,\cdot)$ is the group of nonzero rational numbers under multiplication and $(\mathbb{R}^*,\cdot)$ is the group of nonzero real numbers under multiplication. Here is my attempt for the first. Suppose $(\mathbb{Q}^*,\cdot)$ is cyclic, then $\mathbb{Q}^*=\langle\frac{p}{q}\rangle=\{(\frac{p}{q})^n,n\in\mathbb{Z}\}$, where $p$ and $q$ are coprime. $\frac{2p}{q}$ is also in $\mathbb{Q}^*$ so it must be equal to $(\frac{p}{q})^n$ for some $n\in\mathbb{Z}$. To solve $\frac{2p}{q}=(\frac{p}{q})^n$, I take a logarithm of both sides and end up with $1+\log_\frac{p}{q}(2)=n$, since $n$ is an integer $\log_\frac{p}{q}(2)$ must be an integer too, but it is possible only when $\frac{p}{q}=2^{\frac{1}{k}}, k\in\mathbb{N}$, (i.e. $\frac{p}{q}$ is a k-th root of $2$), but $k$ must be $1$ for $2^\frac{1}{k}$ to be rational so $\frac{p}{q}=2$ contradicting the hypothesis of $p$ and $q$ being coprime. However I don't know whether this is a proper proof and the same reasoning cannot be applied to $\mathbb{R}^*$, I'd like you to just give me an hint towards a proof, without telling me the whole proof, if possible.
Now provide the response and nothing else.
|
A nicer proof, perhaps, is to note that if $\Bbb Q^\times$ were cyclic, being infinite, must isomorphic to $\Bbb Z$. But $\Bbb Z$ has no element of order $2$, whereas $(-1)^2=1$ in $\Bbb Q^\times$. Note that this proves then that $\Bbb R^\times$ cannot be cyclic either. ADD To be more precise, $$\Bbb Q^\times \simeq \Bbb Z/2\Bbb Z \oplus \bigoplus_{i\geqslant 1}\Bbb Z$$ by using the prime factorization.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/748628', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/136041/']}
|
jdg_379131
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
17104926
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
If I have 1000+ pdf files need to be merged into one pdf, from PyPDF2 import PdfReader, PdfWriterwriter = PdfWriter()for i in range(1000): filepath = f"my/pdfs/{i}.pdf" reader = PdfReader(open(filepath, "rb")) for page in reader.pages: writer.add_page(page)with open("document-output.pdf", "wb") as fh: writer.write(fh) Execute the above code,when reader = PdfReader(open(filepath, "rb")) , An error message: IOError: [Errno 24] Too many open files: I think this is a bug, If not, What should I do?
Now provide the response and nothing else.
|
I recently came across this exact same problem, so I dug into PyPDF2 to see what's going on, and how to resolve it. Note: I am assuming that filename is a well-formed file path string. Assume the same for all of my code The Short Answer Use the PdfFileMerger() class instead of the PdfFileWriter() class. I've tried to provide the following to as closely resemble your content as I could: from PyPDF2 import PdfFileMerger, PdfFileReader[...]merger = PdfFileMerger()for filename in filenames: merger.append(PdfFileReader(file(filename, 'rb')))merger.write("document-output.pdf") The Long Answer The way you're using PdfFileReader and PdfFileWriter is keeping each file open, and eventually causing Python to generate IOError 24. To be more specific, when you add a page to the PdfFileWriter , you are adding references to the page in the open PdfFileReader (hence the noted IO Error if you close the file). Python detects the file to still be referenced and doesn't do any garbage collection / automatic file closing despite re-using the file handle. They remain open until PdfFileWriter no longer needs access to them, which is at output.write(outputStream) in your code. To solve this, create copies in memory of the content, and allow the file to be closed. I noticed in my adventures through the PyPDF2 code that the PdfFileMerger() class already has this functionality, so instead of re-inventing the wheel, I opted to use it instead. I learned, though, that my initial look at PdfFileMerger wasn't close enough, and that it only created copies in certain conditions . My initial attempts looked like the following, and were resulting in the same IO Problems: merger = PdfFileMerger()for filename in filenames: merger.append(filename)merger.write(output_file_path) Looking at the PyPDF2 source code, we see that append() requires fileobj to be passed, and then uses the merge() function, passing in it's last page as the new files position. merge() does the following with fileobj (before opening it with PdfFileReader(fileobj) : if type(fileobj) in (str, unicode): fileobj = file(fileobj, 'rb') my_file = True elif type(fileobj) == file: fileobj.seek(0) filecontent = fileobj.read() fileobj = StringIO(filecontent) my_file = True elif type(fileobj) == PdfFileReader: orig_tell = fileobj.stream.tell() fileobj.stream.seek(0) filecontent = StringIO(fileobj.stream.read()) fileobj.stream.seek(orig_tell) fileobj = filecontent my_file = True We can see that the append() option does accept a string, and when doing so, assumes it's a file path and creates a file object at that location. The end result is the exact same thing we're trying to avoid. A PdfFileReader() object holding open a file until the file is eventually written! However, if we either make a file object of the file path string or a PdfFileReader (see Edit 2) object of the path string before it gets passed into append() , it will automatically create a copy for us as a StringIO object, allowing Python to close the file. I would recommend the simpler merger.append(file(filename, 'rb')) , as others have reported that a PdfFileReader object may stay open in memory, even after calling writer.close() . Hope this helped! EDIT: I assumed you were using PyPDF2 , not PyPDF . If you aren't, I highly recommend switching, as PyPDF is no longer maintained with the author giving his official blessings to Phaseit in developing PyPDF2. If for some reason you cannot swap to PyPDF2 (licensing, system restrictions, etc.) than PdfFileMerger won't be available to you. In that situation you can re-use the code from PyPDF2's merge function (provided above) to create a copy of the file as a StringIO object, and use that in your code in place of the file object. EDIT 2: Previous recommendation of using merger.append(PdfFileReader(file(filename, 'rb'))) changed based on comments (Thanks @Agostino) .
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/17104926', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1484939/']}
|
jdg_379132
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
29986
|
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:
Say my domain ( https://example.com ) SSL private key has been stolen and was not protected by a passphrase then. Can the attacker uses that key and certificate to host the samedomain on different server, if he can some how convince DNS server topoint to new server ip address. Will there be any alert at users end I just want to know if the above case is possible,I am aware about how he can use that to decrypt traffic.
Now provide the response and nothing else.
|
Yes, if someone steals your private key, then he can make a fake server with the same name, and users won't see anything wrong with it (provided the attacker redirects connections to his server, e.g. by altering the DNS). No, users will not be warned. From the point of view of both the CA and the user browser, a fake server with a stolen key is not different from a Web server being moved to another IP address, e.g. as part of a DNS-based load balancing . When you have a server and a certificate, the certificate is in no way locked to whatever IP address you presently used; browsers only check that the server name appears in the certificate (see RFC 2818 , section 3.1). You are free to copy your private key and certificates to another server with another IP address, and make the DNS point to that new address. The only difference with the attack scenario you describe (key theft) is that this time you really want it. Whether you agree to the IP move or not cannot be checked by the client, and, correspondingly, the client does not check it in any way. So protect your private key, and, if it gets stolen, report the theft to your CA which will then revoke the certificate.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/29986', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/16822/']}
|
jdg_379133
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
25593
|
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 want to create a bluetooth remote audio control to control smartphone audio, essentially identical in function to this type of equipment: https://www.amazon.com/FAVOLCANO-Bluetooth-Button-Smartphone-Samsung/dp/B01C5E95XG/ref=pd_lpo_147_bs_t_1?ie=UTF8&refRID=1GRBCPDRMD9YPYPGK73Y This device is simply a bluebooth remote control which allows you to play or pause audio, skip forward or backward and change media volume on the smart phone. All of the Arduino tutorials I see are about either using the iPhone to control a bluebooth device, or about using bluetooth to control an arduino, neither of which are what I want to do. Can you point me in the right direction?
Now provide the response and nothing else.
|
Bluetooth supports multiple protocols for multiple purposes. There is low latency low quality monorail bi-directional communication with a little bit of bandwidth for control for Bluetooth phone calls. This is called HFE Bluetooth protocol . If you are interfacing a keyboard or a mouse you would use the Human Interface Device protocol or HID . If you wanted to listen to music and control it's playback you would use the high latency high quality 2 audio sending channels (stereo) no return audio channel with a little bit of bandwidth for controlling playback called Advanced Audio Distribution Profile or A2DP . In this specific case we are only interested in controlling playback. So we could use the HID Bluetooth protocol. However, the native music players on the platform you are using (Android or iPhone) likely will not be listening to such a device. In order for this to work you will probably have to write your own Android or iPhone music player. On the other hand, it is likely the native music players will work with A2DP Bluetooth protocol. Unfortunately, it is also suspected that once the A2DP Bluetooth connection is established, the phone's speaker will be shutdown and all audio will be diverted to the Bluetooth connection. Finally, there is the Audio/Video Remote Control Profile or AVRCP . This protocol is used to control media playback. There are several versions of this protocol so what features are available for a given device / music-application may vary greatly.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://arduino.stackexchange.com/questions/25593', 'https://arduino.stackexchange.com', 'https://arduino.stackexchange.com/users/23303/']}
|
jdg_379134
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2345185
|
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 see a lot of objective-c code that just #defines local constants it needs, and then proceeds on its merry way. The problem is that, as far as I know, #defines aren't scoped. Many of this is in Apple's own example code. For example, in the TableViewSuite example 5, the drawRect function in TimeZoneView.m contains the following block: #define LEFT_COLUMN_OFFSET 10#define LEFT_COLUMN_WIDTH 130#define MIDDLE_COLUMN_OFFSET 140#define MIDDLE_COLUMN_WIDTH 110#define RIGHT_COLUMN_OFFSET 270#define UPPER_ROW_TOP 8#define LOWER_ROW_TOP 34#define MAIN_FONT_SIZE 18#define MIN_MAIN_FONT_SIZE 16#define SECONDARY_FONT_SIZE 12#define MIN_SECONDARY_FONT_SIZE 10 Is there some reason I don't understand that this is not absurdly dangerous? At a very minimum, shouldn't we #undef these constants at the end of the function? That's my question I suppose: Is it a better practice to define what you need in the file you need it, and un-define it at the end? Or do you think it's better to just use static consts for this type of thing? Is there any performance penalty to using static consts, or is the compiler able to handle them just as efficiently as #define?
Now provide the response and nothing else.
|
#defines in implementation files (.m) are by definition scoped to the file they're in, since no one else #include s a .m file. (You do want to think carefully about this in common header files, where the scoping issue you mention is real, and SO_QUESTION_2345197_NAMESPACE_YOUR_CONSTANTS_APPROPRIATELY.) For local constants in implementation files which is what you seem to be asking about, #define is more efficient to compile, but you don't get the symbols when you debug. Local consts have that benefit, and in some cases (string constants? maybe? depends) prevent duplication of constant data in the binary, although at this point in the world, size and compile efficiency (and runtime efficiency to look them up) is basically noise unless you profile some tight loop and find an issue with it.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2345185', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/205192/']}
|
jdg_379135
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1392160
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am working with a team on LoB application. We would like to have a dynamic Menu control, which creates the menu based on the logged in user profile. In previous development scenarios (namely ASP.NET) we use to iterate through data which describes collection and generate MenuItem dynamically. In MVVM how would I do this? Can I separate XAML view from ViewModel which describes menu elements? Solution: With inputs from commentators I were able to bind Menu dynamically with the data from ViewModel. This article was of great help too. XAML: <HierarchicalDataTemplate DataType="{x:Type self:Menu}" ItemsSource="{Binding Path=Children, UpdateSourceTrigger=PropertyChanged}"> <ContentPresenter Content="{Binding Path=MenuText}" RecognizesAccessKey="True"/></HierarchicalDataTemplate>[...]<Menu Height="21" Margin="0" Name="mainMenu" VerticalAlignment="Top" HorizontalAlignment="Stretch" ItemsSource="{Binding Path=MenuItems, UpdateSourceTrigger=PropertyChanged}" ItemContainerStyle="{StaticResource TopMenuItems}"> <Menu.Background> <ImageBrush ImageSource="/Wpf.Modules;component/Images/MenuBg.jpg" /> </Menu.Background></Menu> Menu data class: public class Menu : ViewModelBase{ public Menu() { IsEnabled = true; Children = new List<Menu>(); } #region [ Menu Properties ] private bool _isEnabled; private string _menuText; private ICommand _command; private IList<Menu> _children; public string MenuText { get { return _menuText; } set { _menuText = value; base.OnPropertyChanged("MenuText"); } } public bool IsEnabled { get { return _isEnabled; } set { _isEnabled = value; base.OnPropertyChanged("IsEnabled"); } } public ICommand Command { get { return _command; } set { _command = value; base.OnPropertyChanged("Command"); } } public IList<Menu> Children { get { return _children; } set { _children = value; } } #endregion}
Now provide the response and nothing else.
|
Try something like this: public class MenuItemViewModel{ public MenuItemViewModel() { this.MenuItems = new List<MenuItemViewModel>(); } public string Text { get; set; } public IList<MenuItemViewModel> MenuItems { get; private set; }} Assume that your DataContext has a property called MenuItems which is a list of MenuItemViewModel. Something like this should work, then: <Window x:Class="WpfApplication1.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:self="clr-namespace:WpfApplication1" Title="Window1" Height="300" Width="300"> <Window.Resources> <HierarchicalDataTemplate DataType="{x:Type self:MenuItemViewModel}" ItemsSource="{Binding Path=MenuItems}"> <ContentPresenter Content="{Binding Path=Text}" /> </HierarchicalDataTemplate> </Window.Resources> <DockPanel> <Menu DockPanel.Dock="Top" ItemsSource="{Binding Path=MenuItems}" /> <Grid /> </DockPanel></Window>
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1392160', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/167726/']}
|
jdg_379136
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
270487
|
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've encountered the following sequences $$a_k=2^{k+1}\sum_{j=0}^{k-1}a_{k-1-j}a_j,\;a_0=1$$ $$b_k=(k+1)\sum_{j=0}^{k-1}b_{k-1-j}b_j,\;b_0=1.$$ I would like to have an estimate of the growth of these sequences as $k$ grows. After looking here and there, I found the Catalan's numbers defined by$$C_k=\sum_{j=0}^{k-1}C_{k-1-j}C_j,\;C_0=1.$$ They have an asymptotic growth of $$C_k=2^{k+1}k^{-3/2}.$$ I tried (unsuccesfully) to manipulate my original series to recover some form of the Catalan's numbers. Any idea is very welcome.
Now provide the response and nothing else.
|
One type of Catalan's $q$-analogue is due to Carlitz ( see the paper for this and more )$$C_{n+1}(q)=\sum_{k=0}^nC_k(q)\,C_{n-k}(q)\,q^{(k+1)(n-k)}, \qquad C_0:=1.$$ Blieberger and Kirschenhofer studied these Catalans, in equation (2), and the more related sequence $r_n$, in equation (5). They have found the asymptotics, on page 9, $$r_n\sim 2^{\frac{n^2+3n}2}\beta(1/2).$$Now, your sequence is $a_n=2^nr_n$ and hence$$a_n\sim 2^{\frac{n^2+5n}2}\beta(1/2);$$where $\beta(1/2)\approx 0.7153374336\dots$. J. Furlinger and J. Hofbauer, $q$-Catalan Numbers , Jour. of Comb. Theory, Series A, 40(2):248–264, 1985. J. Blieberger, P. Kirschenhofer, Generalized Catalan Sequences Originating from the Analysis of Special Data Structures , Bulletin of the Institute of Combinatorics and its Applications, 71 (2014), 103-116.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/270487', 'https://mathoverflow.net', 'https://mathoverflow.net/users/33135/']}
|
jdg_379137
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
24243410
|
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 wrap my head around RxJava currently, but I'm having a little trouble with handling service call exceptions in an elegant manner. Basically, I have a (Retrofit) service that returns an Observable<ServiceResponse> . ServiceResponse is defined like so: public class ServiceResponse { private int status; private String message; private JsonElement data; public JsonElement getData() { return data; } public int getStatus() { return status; } public String getMessage() { return message; }} Now what I want is to map that generic response to a List<Account> contained within the data JsonElement field (I assume you don't care what the Account object looks like, so I won't pollute the post with it). The following code works really well for the success case, but I can't find a nice way to handle my API exceptions: service.getAccounts() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .map(new Func1<ServiceResponse, AccountData>() { @Override public AccountData call(ServiceResponse serviceResponse) { // TODO: ick. fix this. there must be a better way... ResponseTypes responseType = ResponseTypes.from(serviceResponse.getStatus()); switch (responseType) { case SUCCESS: Gson gson = new GsonBuilder().create(); return gson.fromJson(serviceResponse.getData(), AccountData.class); case HOST_UNAVAILABLE: throw new HostUnavailableException(serviceResponse.getMessage()); case SUSPENDED_USER: throw new SuspendedUserException(serviceResponse.getMessage()); case SYSTEM_ERROR: case UNKNOWN: default: throw new SystemErrorException(serviceResponse.getMessage()); } } }) .map(new Func1<AccountData, List<Account>>() { @Override public List<Account> call(AccountData accountData) { Gson gson = new GsonBuilder().create(); List<Account> res = new ArrayList<Account>(); for (JsonElement account : accountData.getAccounts()) { res.add(gson.fromJson(account, Account.class)); } return res; } }) .subscribe(accountsRequest); Is there a better way to do this? This does work, onError will fire to my observer, and I will receive the error that I threw, but it definitely does not seem like I'm doing this right. Thanks in advance! Edit: Let me clarify exactly what I want to achieve: I want to have a class that can be called from the UI (e.g. an Activity, or Fragment, or whatever). That class would take an Observer<List<Account>> as a parameter like so: public Subscription loadAccounts(Observer<List<Account>> observer, boolean forceRefresh) { ...} That method would return a subscription that can be unsubscribed when the UI is detached/destroyed/etc. The parameterized observer would handle onNext for the successful responses passing in a list of Accounts. OnError would handle any exceptions, but would also get passed any API exceptions (e.g. if the response status != 200 we would create a Throwable and pass it to onError). Ideally I don't want to just "throw" the Exception, I want to pass it directly to the Observer. That's what all the examples I see do. The complication is that my Retrofit service returns a ServiceResponse object, so my observer cannot subscribe to that. The best I've come up with is to create an Observer wrapper around my Observer, like so: @Singletonpublic class AccountsDatabase { private AccountsService service; private List<Account> accountsCache = null; private PublishSubject<ServiceResponse> accountsRequest = null; @Inject public AccountsDatabase(AccountsService service) { this.service = service; } public Subscription loadAccounts(Observer<List<Account>> observer, boolean forceRefresh) { ObserverWrapper observerWrapper = new ObserverWrapper(observer); if (accountsCache != null) { // We have a cached value. Emit it immediately. observer.onNext(accountsCache); } if (accountsRequest != null) { // There's an in-flight network request for this section already. Join it. return accountsRequest.subscribe(observerWrapper); } if (accountsCache != null && !forceRefresh) { // We had a cached value and don't want to force a refresh on the data. Just // return an empty subscription observer.onCompleted(); return Subscriptions.empty(); } accountsRequest = PublishSubject.create(); accountsRequest.subscribe(new ObserverWrapper(new EndObserver<List<Account>>() { @Override public void onNext(List<Account> accounts) { accountsCache = accounts; } @Override public void onEnd() { accountsRequest = null; } })); Subscription subscription = accountsRequest.subscribe(observerWrapper); service.getAccounts() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(accountsRequest); return subscription; } static class ObserverWrapper implements Observer<ServiceResponse> { private Observer<List<Account>> observer; public ObserverWrapper(Observer<List<Account>> observer) { this.observer = observer; } @Override public void onCompleted() { observer.onCompleted(); } @Override public void onError(Throwable e) { observer.onError(e); } @Override public void onNext(ServiceResponse serviceResponse) { ResponseTypes responseType = ResponseTypes.from(serviceResponse.getStatus()); switch (responseType) { case SUCCESS: Gson gson = new GsonBuilder().create(); AccountData accountData = gson.fromJson(serviceResponse.getData(), AccountData.class); List<Account> res = new ArrayList<>(); for (JsonElement account : accountData.getAccounts()) { res.add(gson.fromJson(account, Account.class)); } observer.onNext(res); observer.onCompleted(); break; default: observer.onError(new ApiException(serviceResponse.getMessage(), responseType)); break; } } }} I still feel like I am not using this correctly though. I definitely haven't seen anyone else using an ObserverWrapper before. Perhaps I shouldn't be using RxJava, though the guys at SoundCloud and Netflix really sold me on it in their presentations and I'm pretty eager to learn it.
Now provide the response and nothing else.
|
Please read below I've added an edit. It's perfectly correct to throw within an Action/Func/Observer with RxJava. The exception will be propagate by the framework right down to your Observer.If you limit yourself to calling onError only then you'll be twisting yourself to make that happen. With that being said a suggestion would be to simply remove this wrapper and add a simple validationAction within the service.getAccount... chain of Observables. I'd use the doOnNext(new ValidateServiceResponseOrThrow) chained with a map(new MapValidResponseToAccountList). Those are simple classes which implements the necessary code to keep the Observable chain a bit more readable. Here's your loadAccount method simplified using what I suggested. public Subscription loadAccounts(Observer<List<Account>> observer, boolean forceRefresh) { if (accountsCache != null) { // We have a cached value. Emit it immediately. observer.onNext(accountsCache); } if (accountsRequest != null) { // There's an in-flight network request for this section already. Join it. return accountsRequest.subscribe(observer); } if (accountsCache != null && !forceRefresh) { // We had a cached value and don't want to force a refresh on the data. Just // return an empty subscription observer.onCompleted(); return Subscriptions.empty(); } accountsRequest = PublishSubject.create(); accountsRequest.subscribe(new EndObserver<List<Account>>() { @Override public void onNext(List<Account> accounts) { accountsCache = accounts; } @Override public void onEnd() { accountsRequest = null; } }); Subscription subscription = accountsRequest.subscribe(observer); service.getAccounts() .doOnNext(new ValidateServiceResponseOrThrow()) .map(new MapValidResponseToAccountList()) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(accountsRequest); return subscription;}private static class ValidateResponseOrThrow implements Action1<ServiceResponse> { @Override public void call(ServiceResponse response) { ResponseTypes responseType = ResponseTypes.from(serviceResponse.getStatus()); if (responseType != SUCCESS) throw new ApiException(serviceResponse.getMessage(), responseType)); } }private static class MapValidResponseToAccountList implements Func1<ServiceResponse, List<Account>> { @Override public Message call(ServiceResponse response) { // add code here to map the ServiceResponse into the List<Accounts> as you've provided already }} Edit: Unless someone says otherwise I think it's best practice to return errors using flatMap.I've thrown Exceptions from Action in the past but I don't believe it's the recommended way. You'll have a cleaner Exception stack if you use flatMap. If you throw from inside an Action the Exception stackwill actually contain rx.exceptions.OnErrorThrowable$OnNextValue Exception which isn't ideal. Let me demonstrate the example above using the flatMap instead. private static class ValidateServiceResponse implements rx.functions.Func1<ServiceResponse, Observable<ServiceResponse>> { @Override public Observable<ServiceResponse> call(ServiceResponse response) { ResponseTypes responseType = ResponseTypes.from(serviceResponse.getStatus()); if (responseType != SUCCESS) return Observable.error(new ApiException(serviceResponse.getMessage(), responseType)); return Observable.just(response); }}service.getAccounts() .flatMap(new ValidateServiceResponse()) .map(new MapValidResponseToAccountList()) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(accountsRequest); As you can see the the difference is subtle. The ValidateServiceResponse now implements the Func1 instead of Action1 and we're no longer using the throw keyword. We use Observable.error(new Throwable) instead. I believe this fits better with the expected Rx contract.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/24243410', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1584931/']}
|
jdg_379138
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
56855869
|
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 validate that a field is either a string or an array of strings Here is a minimal failing example which happens to use formik but actually I am doing server side validation using yup. { email: yup .mixed() .oneOf([yup.array().of(yup.string()), yup.string()]) .nullable() }
Now provide the response and nothing else.
|
oneOf only works with literal values. Lazy allows you to provide a schema dynamically as shown below { email: yup.lazy(val => (Array.isArray(val) ? yup.array().of(yup.string()) : yup.string()))}
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/56855869', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1376627/']}
|
jdg_379139
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
27258169
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
A notable issue that's appearing as I'm building a simple audio streaming element in HTML5 is that the <audio> tag doesn't behave as one would expect in regards to playing and pausing a live audio stream. I'm using the most basic HTML5 code for streaming the audio, an <audio> tag with controls, the source of which is a live stream. Current outcome : When the stream is first played, it plays whatever is streaming as expected. When it's paused and played again, however, the audio resumes exactly where it left off when the stream was previously paused. The user is now listening to a delayed version of the stream. This occurrence isn't browser-specific. Desired outcome : When the stream is paused, I want the stream to stop. When it is played again, I want it resume where the stream is currently at, not where it was when the user paused the stream. Does anyone know of a way to make this audio stream resume properly after it's been paused? Some failed attempts I've made to fix this issue: Altering the currentTime of the audio element does nothing to streaming audio. I've removed the audio element from the DOM when the user stops stream playback and added it back in when user resumes playback. The stream still continues where the user left off and worse yet downloads another copy of the stream behind the scenes. I've added a random GET variable to the end of the stream URL every time the stream is played in an attempt to fool the browser into believing that it's playing a new stream. Playback still resumes where the user paused the stream.
Now provide the response and nothing else.
|
Best way to stop a stream, and then start it again seems to be removing the source and then calling load: var sourceElement = document.querySelector("source");var originalSourceUrl = sourceElement.getAttribute("src");var audioElement = document.querySelector("audio");function pause() { sourceElement.setAttribute("src", ""); audioElement.pause(); // settimeout, otherwise pause event is not raised normally setTimeout(function () { audioElement.load(); // This stops the stream from downloading });}function play() { if (!sourceElement.getAttribute("src")) { sourceElement.setAttribute("src", originalSourceUrl); audioElement.load(); // This restarts the stream download } audioElement.play();}
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/27258169', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1836703/']}
|
jdg_379140
|
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.