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
23260042
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Good day. I have a question I couldn't solve it, I'm using Cakephp and $.ajax . The data from $.ajax can be passed in to my database. But the problem is I cant redirect to another page when successful. I had tried the if($save){ echo something} and is working, just the $this->redirect part. The Cakephp code as below: public function testingadd() { $this->layout=null; $name = $_GET['name']; $email = $_GET['email']; $phone = $_GET['phone']; $this->Newlead->create(); $this->Newlead->set("name",$name); $this->Newlead->set("email",$email); $this->Newlead->set("phone",$phone); $save = $this->Newlead->save(); if($save) { $this->redirect('/Newlead/thankyou'); } } Ajax code as below: $("#btn-submit").click(function () { var obj = new Object(); obj.n = $("#inputName").val(); obj.e = $("#inputEmail").val(); obj.c = $("#inputMobile").val(); $.ajax({ type: 'POST', url: '/Newleads/testingadd.json', data: { 'name' : obj.n, 'email' : obj.e, 'phone' : obj.c }, dataType: "jsonp", timeout:1000, jsonp:'jsonp' });}); Is there any more code need to be added to any files in Cakephp such as routes.php , PagesController.php or any? I'm still new to this. Please help. Now provide the response and nothing else.
As the other answers mentioned, you can't prevent duplicate messages coming through from SQS. Most of the time your messages will be handed to one of your consumers once, but you will run into duplicates at some stage. I don't think there is an easy answer to this question, because it entails coming up with a proper architecture that can cope with duplicates, meaning it's idempotent in nature. If all the workers in your distributed architecture were idempotent, it would be easy, because you wouldn't need to worry about duplicates. But in reality, that sort of environment does not exist, somewhere along the way something will not be able to handle it. I am currently working on a project where it's required of me to solve this, and come up with an approach to handle it. I thought it might benefit others to share my thinking here. And it might be a good place to get some feedback on my thinking. Fact store It's a pretty good idea to develop services so that they collect facts which can theoretically be replayed to reproduce the same state in all the affected downstream systems. For example, let's say you are building a message broker for a stock trading platform. ( I have actually worked on a project like this before, it was horrible, but also a good learning experience. ) Now let's say that that trades come in, and there are 3 systems interested in it: An old school mainframe which needs to stay updated A system that collates all the trades and share it with partners on a FTP server The service that records the trade, and reallocates shares to the new owner It's a bit convoluted, I know, but the idea is that one message (fact) coming in, has various distributed downstream effects. Now let's imagine that we maintain a fact store, a recording of all the trades coming into our broker. And that all 3 downstream service owners calls us to tell us that they have lost all of their data from the last 3 days. The FTP download is 3 days behind, the mainframe is 3 days behind, and all the trades are 3 days behind. Because we have the fact store, we could theoretically replay all these messages from a certain time to a certain time. In our example that would be from 3 days ago until now. And the downstream services could be caught up. This example might seem a bit over the top, but I'm trying to convey something very particular: the facts are the important things to keep track of, because that's where we are going to use in our architecture to battle duplicates. How the Fact store helps us with duplicate messages Provided you implement your fact store on a persistence tier that gives you the CA parts of the CAP theorem , consistency and availability, you can do the following: As soon as a message is received from a queue, you check in your fact store whether you've already seen this message before, and if you have, whether it's locked at the moment, and in a pending state. In my case, I will be using MongoDB to implement my fact store, as I am very comfortable with it, but various other DB technologies should be able to handle this. If the fact does not exist yet, it gets inserted into the fact store, with a pending state, and a lock expiration time. This should be done using atomic operations, because you do not want this to happen twice! This is where you ensure your service's idempotence . Happy case - happens most of the time When the Fact store comes back to your service telling it that the fact did not exist, and that a lock was created, the service attempts to do it's work. Once it's done, it deletes the SQS message , and marks the fact as completed. Duplicate message So that's what happens when a message comes through and it's not a duplicate. But let's look at when a duplicate message comes in. The service picks it up, and asks the fact store to record it with a lock. The fact store tells it that it already exists, and that it's locked. The service ignores the message and skips over it! Once the message processing is done, by the other worker, it will delete this message from the queue, and we won't see it again. Disaster case - happens rarely So what happens when a service records the fact for the first time in the store, then get a lock for a certain period, but falls over? Well SQS will present a message to you again, if it was picked up, but not deleted within a certain period after it was served from the queue. Thats why we code up our fact store such that a service maintains a lock for a limited time. Because if it falls over, we want SQS to present the message to the service, or another instance thereof at a later time, allowing that service to assume that the fact should be incorporated into state (executed) again.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/23260042', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3496855/']}
jdg_87341
stackexchange
llm_judgeable_groundtruth_similarity
5303472
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 MSDN says ConcurrentDictionary<TKey, TValue> Class Represents a thread-safe collection of key-value pairs that can be accessed by multiple threads concurrently. But as I know, System.Collections.Concurrent classes are designed for PLINQ. I have Dictionary<Key,Value> which keeps on-line clients in the server, and I make it thread safe by locking object when I have access to it. Can I safely replace Dictionary<TKey,TValue> by ConcurrentDictionary<TKey,TValue> in my case? will the performance increased after replacement? Here in Part 5 Joseph Albahari mentioned that it designed for Parallel programming The concurrent collections are tuned for parallel programming. The conventional collections outperform them in all but highly concurrent scenarios. A thread-safe collection doesn’t guarantee that the code using it will be thread-safe. If you enumerate over a concurrent collection while another thread is modifying it, no exception is thrown. Instead, you get a mixture of old and new content. There’s no concurrent version of List. The concurrent stack, queue, and bag classes are implemented internally with linked lists. This makes them less memory-efficient than the nonconcurrent Stack and Queue classes, but better for concurrent access because linked lists are conducive to lock-free or low-lock implementations. (This is because inserting a node into a linked list requires updating just a couple of references, while inserting an element into a List-like structure may require moving thousands of existing elements.) Now provide the response and nothing else.
Without knowing more about what you're doing within the lock, then it's impossible to say. For instance, if all of your dictionary access looks like this: lock(lockObject){ foo = dict[key];}... // elsewherelock(lockObject){ dict[key] = foo;} Then you'll be fine switching it out (though you likely won't see any difference in performance, so if it ain't broke, don't fix it). However, if you're doing anything fancy within the lock block where you interact with the dictionary, then you'll have to make sure that the dictionary provides a single function that can accomplish what you're doing within the lock block, otherwise you'll end up with code that is functionally different from what you had before. The biggest thing to remember is that the dictionary only guarantees that concurrent calls to the dictionary are executed in a serial fashion; it can't handle cases where you have a single action in your code that interacts with the dictionary multiple times. Cases like that, when not accounted for by the ConcurrentDictionary , require your own concurrency control. Thankfully, the ConcurrentDictionary provides some helper functions for more common multi-step operations like AddOrUpdate or GetOrAdd , but they can't cover every circumstance. If you find yourself having to work to shoehorn your logic into these functions, it may be better to handle your own concurrency.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5303472', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/87053/']}
jdg_87342
stackexchange
llm_judgeable_groundtruth_similarity
31019157
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: All classes inherit from java.lang.Object , although extends Object is (generally) not written out anywhere. How is this possible? Now provide the response and nothing else.
if you don't explicitly write extends Object the compiler does it for you. So knowing that a class can only extend one super class, the compiler will look at the hierarchy and extend the highest super class to Object . So every class will directly or indirectly inherit the Object class. The Object class however is a special case because it doesn't extend anything. Lastly if you were to compile a simple class and decompile it, you will see the compiler inserts extends java.lang.Object (or the bytecode equivalent) into the class
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/31019157', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_87343
stackexchange
llm_judgeable_groundtruth_similarity
94340
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: Is there a way to trace back who was using a public dynamic IP address previously? Would it be possible to find out the MAC address of the host using the IP address at a given time? (e.g., can you interrogate gateways to find this historical data?) Or is it as good as gone once the IP address has been reassigned? Now provide the response and nothing else.
Internet service providers do typically keep a detailed record of which dynamic IP address is assigned to which customer at any given time. However, in general they will only give out this information to law enforcement if they receive a court order, to protect privacy. As for MAC address, the ISP probably also knows the MAC address of the home router used at that IP address (assuming this is a residential Internet connection). However, most likely they will not know the MAC addresses of any devices behind that router, as MAC addresses are only visible within the same LAN. These MAC addresses may or may not be logged by the home router, depending on brand/configuration.
{}
{'log_upvote_score': 5, 'links': ['https://security.stackexchange.com/questions/94340', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/43059/']}
jdg_87344
stackexchange
llm_judgeable_groundtruth_similarity
16544001
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Suppose I define a variable like this var today = Date();console.log(today.getMonth()); // Throw Error while other class like Error class call their methods without new operator. function factorial(x) { if(x <= 1) throw Error("x must not be negative"); return x*factorial(x-1);} Also wrapper objects (number, boolean, string) can call their methods without new operator.So, Is this the only class which require new operator or any object creation technique before calling their methods. Edit: As Date() is a string type, so it should be call their methods without creating objects. Because string type behave as if they are objects. So why not? Edit 2 : I think this is the only core function which cannot be same as new Date() like other functions ( Array(), String(), Error() etc). So, it's also the hidden feature of this language or ECMAScript mistake. Now provide the response and nothing else.
ECMAScript Language Specification According to the ECMAScript specification (on which Javascript is based): When Date is called as a function rather than as a constructor, it returns a String representing the current time (UTC). NOTE The function call Date(…) is not equivalent to the object creation expression new Date(…) with the same arguments. Reference: http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.2 Calling Constructor vs Calling Function You need the new because you are creating a new Date object. Calling simply Date() , means calling a function that returns the Date() as a string. See: http://www.javascripture.com/Date Date() : StringReturns a string representation of the current date and time. In the case of other types such as Array or Error, the functions are factory functions that create a new object and return them. See: http://www.javascripture.com/Error http://www.javascripture.com/Array Error(message : String) : ErrorCreates a new Error with the specified message that describes the error. new Error(message : String) : ErrorSame as Error(message)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16544001', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2092405/']}
jdg_87345
stackexchange
llm_judgeable_groundtruth_similarity
51965
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Let $\mathbb{H}$ be the skew-field of quaternions. I'm aware of the Theorem 1. A function $f:\mathbb{H}\to\mathbb{H}$ which is $\mathbb{H}$-differentiable on the left (i.e. the usual limit $h^{-1}\cdot (f(x+h)-f(x))$, for $h\to 0$, exists for every $x\in \mathbb{H}$) is a quaternionic affine function on the right (i.e. of the form $x\mapsto x\cdot \alpha + v$). This means that there are no interesting smooth quaternionic funcions, hence no interesting "quaternionic-smooth manifolds" (which is not the same as the quaternionic-Kahler or hyperkahler structures you encounter in differential geometry and complex analytic geometry). I think I can also recall the Theorem 2. If a function $f:\mathbb{H}\to\mathbb{H}$ is locally $\mathbb{H}$-analytic (i.e. it can be locally developped in power series, for the suitable noncommutative notion of "power series"), than it corresponds to a real-analytic function $f:\mathbb{R}^4\to \mathbb{R}^4$, and any real-analytic funcion $f:\mathbb{R}^4\to \mathbb{R}^4$ can be obtained in this way. That says that $\mathbb{H}$-analytic functions are essentially the same as quadruples of real-analytic functions of 4 variables. Hence there is no "quaternionic-analytic geometry" distinguishable from $4n$-dimentional real-analytic geometry.I think the same happens with quaternionic (noncommutative) polynomials: they're just 4-tuples of real polynomials in 4 variables. But, is it reasonable that the zero locus on $\mathbb{H}^n$ of a "noncommutative polynomial" with $\mathbb{H}$-coefficients doesn't have any further mathematical structure than it's real-algebraic variety structure? It would be nice to be able to see things such as $\mathbb{HP}^1$ as a "quaternionic curve ", and to speak of a point " $\mathrm{Spec}(\mathbb{H})$ " (whatever it means) if it possible... Is there a theory of "quaternionic algebraic geometry", maybe as a branch or particular case of some noncommutative (algebraic) geometry theory? Of course, if such a theory has some sense, it cannot be the "obvious analog" of complex algebraic or analytic geometry, as theorems 1. and 2. above show. Now provide the response and nothing else.
The answer is yes!(at least if quaternionic holomorphic geometry counts) "Qauternionic holomorphic geometry" provides a very elegant description of surfaces in 3- and 4-dimensional space. The first paper in this field is more or less Franz Pedit and Ulrich Pinkall, Quaternionic Analysis on Riemann Surfaces and Differential Geometry, in: Proocedings of the international con- gress of mathematicians, Berlin 1998, II Documenta Mathematica, Journal der Deutschen Mathematiker-Vereinigung, Extra Volume ICM 1998, 389-400. Click me A good introduction to "Quaternionic holomorphic geometry" is given by Francis E. Burstall, Dirk Ferus, Katrin Leschke, Franz Pedit and Ulrich Pinkall, Conformal geometry of surfaces in S4 and quaternions, Lecture Notes in Mathematics 1772, Springer-Verlag, Berlin, 2002. http://arxiv.org/abs/math/0002075 and Dirk Ferus, Katrin Leschke, Franz Pedit and Ulrich Pinkall, Quaternionic Holomorphic Geometry: Plucker Formula, Dirac Eigenvalue Esitmates and Energy Estimates of Harmonic 2-Tori, Inventiones Mathematicae 146 (2001),no. 3, 507-593 arxiv.org/abs/math/0012238v1 But just to clarify things: "Of course, if such a theory has some sense, it cannot be the "obvious analog" of complex algebraic or analytic geometry, as theorems 1. and 2. above show." This isn't really true, because the quaternionic holomorphic geometry developed in the papers above, is a kind of generalization of complex geometry, i.e. if you look how a "quaternionic holomorphic structure" is defined, you see that it is a kind of $\overline{\partial}$-Operator with some extra data (a so called Hopf field). If you need more references, there are plenty available (just type "quaternionic holomorphic geometry" into google)
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/51965', 'https://mathoverflow.net', 'https://mathoverflow.net/users/4721/']}
jdg_87346
stackexchange
llm_judgeable_groundtruth_similarity
41705559
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have the following TypeScript interface: interface SelectProps { options: Option[]; value: string[]; onChange: (value: string[]) => void;} I want to add boolean called isMultiple that will change the types of the other properties. When isMultiple=true enforce value:string[] enforce onChange: (value: string[]) => void; When isMultiple=false enforce value:string enforce onChange: (value: string) => void; Is it possible to dynamically set the type of other properties based on the value of one property? Now provide the response and nothing else.
It's a bit late but I hope it helps others like it helped me. Discriminated unions, also known as tagged unions or algebraic data types can be used to solve this problem. interface MultipleSelectProps { isMultiple: true; options: string[]; value: string[]; onChange: (value: string[]) => void;}interface SingleSelectProps { isMultiple: false; options: string[]; value: string; onChange: (value: string) => void;}type SelectProps = MultipleSelectProps | SingleSelectProps; Usage example: function Select(props: SelectProps) { if (props.isMultiple) { const { value, onChange } = props; onChange(value); } else if (props.isMultiple === false) { const { value, onChange } = props; onChange(value); }} Note: When isMultiple is undefined or null it is not possible to infer the specific type of SelectProps . In these cases is necessary to do a strict comparison isMultiple === false . Source: https://blog.mariusschulz.com/2016/11/03/typescript-2-0-tagged-union-types
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/41705559', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/266535/']}
jdg_87347
stackexchange
llm_judgeable_groundtruth_similarity
57878
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: How many NAT mapping rules (that is, mappings between internal, private IP:PORT, and externally mapped IP:PORT) can a common NAT box support? Is there a limit in such number (that is, how many rules can be 'active' at the same time) ? Now provide the response and nothing else.
Two factors impact the maximum possible number of NAT mappings for a single device: the type of NAT and the amount of memory available for the NAT table: As for the type of NAT, let's consider a full-cone NAT, to see how this affects the number of possible mappings: every internal ip:port pair is mapped to an external ip:port pair. Let's now assume that the NAT has only one external IP address available, the maximum number of possible mappings is limited by the possible number of external ports, which is 2^16. As for the amount of memory available for the NAT table, we have to separate two distinct classes of NATs: "hardware" and "software" NATs. I consider purpose-built devices such as home routers or professional network equipment to be hardware NATs, whereas stock PCs running a general-purpose OS along with some NAT software makes a software NAT. Whereas software NATs are obviously limited by the amount of memory the host machine has, hardware NATs have memory for NAT mappings built-in, which is typically not expandable, unless you are dealing with carrier-grade equipment. The size of this fixed memory then forms the limit on how much NAT mappings can be held alive concurrently. For typical home-router devices, NAT table sizes are in the range of 2^10 to 2^14 entries. I think that should give you a pretty good idea of the dimensions limiting NAT mappings in practice. Obviously there are various other factors along this dimension, like process size limits for user-space software NATs, or policies limiting the maximum number of mappings per single host, etc.
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/57878', 'https://serverfault.com', 'https://serverfault.com/users/18016/']}
jdg_87348
stackexchange
llm_judgeable_groundtruth_similarity
43993560
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 react-router v4 and redux-saga. I'm attempting to make an API call when a page loads. When I visit /detailpage/slug/ , my application seems to get stuck in a loop and makes endless calls to my API endpoint. Here's how my application is setup. Assume my imports are correct. index.js const history = createHistory()const sagaMiddleware = createSagaMiddleware()const middleware = [routerMiddleware(history), sagaMiddleware]const store = createStore( combineReducers({ aReducer }), applyMiddleware(...middleware))injectTapEventPlugin();sagaMiddleware.run(rootSaga)ReactDOM.render( <Provider store={store}> <ConnectedRouter history={history}> <Switch> <Route path="/" exact component={HomePage} /> <Route path="/detailpage/:slug" component={Detail} /> <Route path="/page" component={Page} /> </Switch> </ConnectedRouter> </Provider>, document.getElementById('root')); reducers/index.js const aReducer = (state={}, action) => { switch(action.type) { case 'SHOW_DETAIL': console.log('Reducers: reducer called') return Object.assign({}, state, { name: 'adfsdf' }) default: return state; }}export default aReducer; actions/index.js export const showDetailInfo = () => { console.log('action called') return { type: 'SHOW_DETAIL' }} saga.js export function* fetchDetailsAsync() { try { console.log('fetching detail info') const response = yield call(fetch, 'http://localhost:8000/object/1/', { method: 'GET', headers: { 'Authorization': 'Token xxxxxxxxxxxx' }}) console.log(response); yield put({type: 'SHOW_DETAIL', response: response.data}) } catch (e) { console.log('error') }}// watcher sagaexport function* fetchDetails() { console.log('watcher saga') yield takeEvery('SHOW_DETAIL', fetchDetailsAsync)}export default function* rootSaga() { console.log('root saga') yield [ fetchDetails() ]} containers/Detail.js const mapStateToProps = (state) => { return { name: 'Test' }}const mapDispatchToProps = (dispatch, ownProps) => { console.log('mapDispatchToProps') return { showDetailInfo: (payload) => { console.log('dispatching'); dispatch({ type: 'SHOW_DETAIL' }) } }}const Detail = connect( mapStateToProps, mapDispatchToProps)(DetailPage)export default Detail; components/DetailPage.js class DetailPage extends React.Component { componentWillMount() { this.props.showDetailInfo(); } render() { return ( <Layout> <h3>DetailPage</h3> <p>{ this.props.name }</p> </Layout> ) }}DetailPage.PropTypes = { showDetailInfo: PropTypes.func.isRequired, name: PropTypes.string.isRequired}export default DetailPage; I've spent a few days troubleshooting, trying various ideas including testing different lifecycle methods, removing the routerMiddleware from applyMiddleware. I thought that my component was updating after every API call, but console.log from any of the lifecycle methods indicates that it's not. Being new to react ecosystem, there are a lot of moving parts here and it's challenging for me to troubleshoot. Now provide the response and nothing else.
Of course, you explicitly set the infinite loop the next lines: yield put({type: 'SHOW_DETAIL', response: response.data})// ...yield takeEvery('SHOW_DETAIL', fetchDetailsAsync) The saga doesn't do any magic things for you, and only is a preliminary layer of a subscription and generation on actions and executions coroutines. SOLUTION: You shall use different names for actions which you catch from React components, and actions which are used for optimistical and real up-dating of a status. Use yield takeEvery('SHOW_DETAIL_REQUEST', fetchDetailsAsync) and name your action in this manner. Use yield put({type: 'SHOW_DETAIL_SUCCESS', response: response.data}) in success response and name your reducer in this manner More than that, you can use 'SHOW_DETAIL_FAILURE' for failed saga request. All names above are common-used case.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/43993560', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/890961/']}
jdg_87349
stackexchange
llm_judgeable_groundtruth_similarity
1825720
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 interested in measuring a specific point in time down to the nanosecond using C++ in Windows. Is this possible? If it isn't, is it possible to get the specific time in microseconds at least?. Any library should do, unless I suppose it's possible with managed code.thanks Now provide the response and nothing else.
If you have a threaded application running on a multicore computer QueryPerformanceCounter can (and will) return different values depending on which core the code is executing on. See this MSDN article. ( rdtsc has the same problem) This is not just a theoretical problem; we ran into it with our application and had to conclude that the only reliable time source is timeGetTime which only has ms precision (which fortunately was sufficient in our case). We also tried fixating the thread affinity for our threads to guarantee that each thread always got a consistent value from QueryPerformanceCounter , this worked but it absolutely killed the performance in the application. To sum things up there isn't a reliable timer on windows that can be used to time thing with micro second precision (at least not when running on a multicore computer).
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1825720', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/222054/']}
jdg_87350
stackexchange
llm_judgeable_groundtruth_similarity
219718
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: The usual reinforcement learning task is that an agent starts from a start position with the ultimate aim to reach a goal. More often than not, RL algorithms involve planning and learning optimal policies to reach this goal and rewards are only awarded when the goal is attained. Sometimes, there is a penalty for each time step when the goal is not reached. Now, I am interested in a reinforcement learning task with a start and goal, but with one additional requirement: there are some subgoals that need to be achieved. The subgoals will have to be achieved first (and perhaps in a certain order) before the actual goal will be achieved. I want to ask: If this is a totally new field/area, or a modification of the existing RL that I know. What added conditions can be put in place to include the "subgoals" as specified? Please send some references. Now provide the response and nothing else.
Sure, standard MDPs can hack that. You just need to carefully define the state space so that it includes all possible states, and ensure that the transition function reflects that order. Consider a simple, square grid with length three on each side. The agent begins at the bottom left. The reward for the top-right—where the Master Sword resides—is some positive constant; other rewards are uniformly $0$. There's little to this problem. You can be in any of nine states, and can transition to each state from any of its adjacent states. You can index them by an integer, or row and column. Row and column is intuitive: You can quickly tell from the row and column indices of two states whether a move between the two is legal. So, we'll define each state as a tuple $(i,j)$. Value iteration, or any planning algorithm, would make short work of it. Let's add the possibility that the top-right is not a terminal state, and that the agent can move about after retrieving the sword. Changing the state space is easy enough: States are now $(i,j,m)$, $m$ being a boolean indicating whether the sword has been retrieved. (If it helps, you can think of this as two grids, one corresponding to having the sword, one not.) Our transition function also needs an upgrade, since our agent will never drop the sword. (It's very precious.) Easy enough: $T(s,a,s') = 0$ for any $s = (i_0,j_0,1), s' = (i_1,j_1,0)$. Now, say that in each square in the diagonal from the top-left to bottom-right are the pendants of Courage, Power and Wisdom, respectively, and that the agent must collect these, in order, prior to retrieving the Master Sword. The new states are $(i,j,n)$, $n$ being the number of artifacts (pendants & sword) retrieved. You can visualize this state space as a stack of grids; gathering the next pendant or sword is loosely like 'moving up' a level. (We're up to 45 states total.) Your transition function should again account for this, returning $0$ for any transition that would represent giving up an artifact. Value iteration would propagate value out and down from the Master Sword. If unordered gathering is allowed, we'll need more states still. Before, having the Pendant of Power implied having the Pendant of Courage. Since that's no longer the case, we'll need a boolean for each pendant and the Master Sword; states are now $(i,j,c,p,w,m)$ tuples, with any state with $m=1$ having $c = p = w = 1$. Important point being, your state space is, intuitively, just a list of unique, exclusive conditions. This representation can capture order, once you put enough thought into your problem's full realm of possible states, and adjust your transition function accordingly.
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/219718', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/67413/']}
jdg_87351
stackexchange
llm_judgeable_groundtruth_similarity
386578
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 a board which has its microcontroller pins directly breaking out to a breakout header. I am fairly certain the board won't be in ESD safe environment when being tested. I decided to get fairly standard ESD diodes and placed it across all Digital pins. They have capacitance in the pF's so shouldn't cause any distortion there. My question is if it is okay to place ESD diodes on analog inputs to the micro. Is there any way i reduce acuracy of these inputs? I have been told in the past to avoid using ESD diodes on very high speed signals (in my case it was MIPI-DSI), as the very low capacitance can become significant. I am just wondering if there are other cases (analog inputs being one) where this concern should be taken? Thanks! Now provide the response and nothing else.
First I'd like to stress that all microcontroller chips already have on-chip ESD protection, without that they would become almost impossible to handle. But it is indeed a good idea to add extra protection to pins which can be touched from the outside and/or interface with other boards etc. You can just treat the Analog pins the same way as the Digital pins and add the same protection. Under normal operation the extra ESD devices will not conduct and therefore cannot harm the signal. You will not reduce accuracy at all. Again let me point out that the pins will already have ESD protection inside the chip. Typically that is a circuit like this: The 2 diodes on the left are additional external diodes, not how they are in parallel with 2 of the on-chip diodes. Only for very high frequency signals either analog or digital (like MIPI) ESD protection can influence the operation. But very often cables and PCB traces add more capacitance that the small ESD protection devices.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/386578', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/192778/']}
jdg_87352
stackexchange
llm_judgeable_groundtruth_similarity
4588542
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 NSArray which is populated with objects from an NSMutableArray. Most of these object have integer values like "1", "2", "3", "4", "5", sometimes there is a name like "home", "far left", or "far right". I am trying to sort this array in Objective C. using sortedArrayUsingSelector:@selector(compare:) works fine when I have less then 10 items in the array. but when it there are more I start getting "1", "10", "11", "12", "2", "3" type of stuff. Any help would be most appreciated. The code should not return anything. It just needs to sort and move on. Original Code: presetNamesSort = [[[NSMutableArray alloc]init]retain];presetNamesSort = [presetNames sortedArrayUsingSelector:@selector(compare:)]; Now provide the response and nothing else.
You can use NSArray 's -sortedArrayUsingComparator: method to get a sorted array using a custom block. I find this more convenient than -sortedArrayUsingSelector: , because you can declare the comparator inline, like so: NSArray *unsortedArray = [NSArray arrayWithObjects:@"Hello", @"4", @"Hi", @"5", @"2", @"10", @"1", nil];NSArray *sortedArray = [unsortedArray sortedArrayUsingComparator:^(NSString *str1, NSString *str2) { return [str1 compare:str2 options:NSNumericSearch];}]; This will return an array that looks like so: ( 1, 2, 4, 5, 10, Hello, Hi) In general, it's pretty nice to use blocks because they eliminate the need to create random selectors that run amuk in your code.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4588542', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/561799/']}
jdg_87353
stackexchange
llm_judgeable_groundtruth_similarity
446008
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Let $X,Y$ be isomorphic Banach spaces. The Banach-Mazur distance: $$d(X,Y)=\inf\{\|T\| \cdot \|T^{-1}\|: T:X\longrightarrow Y \ \text{is an isomorphism} \}$$ can be rewritten as: $$d(X,Y)=\inf\{\|T^{-1}\|: T:X\longrightarrow Y \ \text{is an isomorphism}, \|T\|=1\}$$ If $X,Y$ are finite dimensional spaces the infimum is reached. But if $X,Y$ are infinite dimensional spaces the infimum is reached ? Any hints would be appreciated. Now provide the response and nothing else.
Let's follow the hint given by Wojtaszczyk. Take $(p_n)$ and $(q_n)$ two disjoint sequences, dense in $[1,1.5]$ such that $p_1=1$. Take $X=\left(\sum \ell_{p_n}^5\right)_2$ and $Y =\left(\sum \ell_{q_n}^5\right)_2$. The Banach-Mazur distance is $1$ because for every $\epsilon>0$ the interval $[1,1.5]$ can be partitioned into subintervals of size $\epsilon$, each of which meets both sequences countably many times. Now, it seems to me that the reason $Y$ does not contain an isometric copy of $\ell_1^5$ is that $Y$ is strictly convex. (If I'm right then neither $1.5$ nor $5$ are of importance; $1.5$ could be any number in $(1,\infty)$ and $5$ could be an integer $\ge 2$.) Indeed, suppose that $(y_n)$ and $(z_n)$ are two nonzero elements of $Y$ such that $\|(y_n+z_n)\|_Y = \|(y_n)\|_Y+\|(z_n)\|_Y$, meaning that$$\sqrt{\sum \left\| y_n+z_n \right\|_{q_n}^2} = \sqrt{\sum \left\|y_n\right\|_{q_n}^2} + \sqrt{\sum \left\|z_n\right\|_{q_n}^2} \tag1$$By the triangle inequality and Minkowski inequality for $\ell^2$,$$\sqrt{\sum \left\| y_n+z_n \right\|_{q_n}^2}\le \sqrt{\sum (\left\| y_n\|_{q^n}+ \|z_n \right\|_{q_n})^2}\le \sqrt{\sum \left\|y_n\right\|_{q_n}^2} + \sqrt{\sum \left\|z_n\right\|_{q_n}^2} \tag{2}$$where equality must hold throughout by (1). Since $\ell_2$ is strictly convex, equality in the second half of (2) implies that there exists $\lambda> 0$ such that $ \|z_n\|_{q_n}=\lambda \|y_n\|_{q_n}$ for all $n$. Since each $\ell_{q_n}$ is also strictly convex, equality in the first half of (2) implies that $z_n=\lambda y_n$. Thus, $Y$ is strictly convex.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/446008', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/34276/']}
jdg_87354
stackexchange
llm_judgeable_groundtruth_similarity
48377731
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am looking for a node.js way to verify a client certificate in X509 format with a CA certificate which was given to me (none of those are created/managed by me, my software only has to verify what is beeing sent to it). I have found several modules for this job, however I am having issues with each of them: X509 is able to do it using x509.verify(cert, CABundlePath, cb) , however it needs to read the certificates from FS, and I am having them in memory already. This is cumbersome as it will be done with each web request which reaches my app. It seems like PKI.js is able to do it, however their examples don't work for me but complain about missing files, so I can't even try it out. I tried node-forge , but while I am unsure if I use it correctly (they don't have any API documentation) its throwing a forge.pki.BadCertificate error from forge.pki.verifyCertificateChain(caStore, [ cer ], cb) . When trying pem , using a simple pem.verifySigningChain(cer, [ ca ], cb) would throw some error complaining about loading a file from /var/... . Even if it would work, I would avoid using this lib as its relying on the openssl command line tool , which I would like to avoid Now I feel pretty stupid because I failed to get this simple task done with any of the above modules. Could someone point me to a simple solution which will allow me to verify the signature/validity of a X509 certificate using a given CA certificate? :s [edit] Basically I would need openssl verify -verbose -CAfile ca-crt.pem client1-crt.pem in Node.js but without dependencies to the openssl command line tool and without temporarily saving the certs to disk. [edit2] Would it be possible to just use https://nodejs.org/api/crypto.html#crypto_verify_verify_object_signature_signatureformat ? Now provide the response and nothing else.
I finally managed to do it using node-forge . Heres a working code example: let pki = require('node-forge').pki;let fs = require('fs');let caCert;let caStore;try { caCert = fs.readFileSync('path/to/ca-cert.pem').toString(); caStore = pki.createCaStore([ caCert ]);} catch (e) { log.error('Failed to load CA certificate (' + e + ')'); return....;}try { pki.verifyCertificateChain(caStore, [ cert ]);} catch (e) { return handleResponse(new Error('Failed to verify certificate (' + e.message || e + ')'));} Both certificates shall be given in base64 encoded PEM format/js string. verifyCertificateChain checks the certifitate validity ( notBefore / notAfter ) as well as verifies the given CA chain. I am not 100% sure if this is the best approach, or if this library is doing a good job, since their source code of verifyCertificateChain is full of #TODO s, so maybe this is not ready for production? But at least I have a somewhat working solution. Probably it would be better to create a node module which wraps the libssl c calls, but thats just a lot of effort for this small task.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/48377731', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/826955/']}
jdg_87355
stackexchange
llm_judgeable_groundtruth_similarity
49800188
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 problem with adding days (numbers) to date format columns in Spark. I know that there is a function date_add that takes two arguments - date column and integer: date_add(date startdate, tinyint/smallint/int days) I'd like to use a column value that is of type integer instead (not an integer itself). Say I have the following dataframe: val data = Seq( (0, "2016-01-1"), (1, "2016-02-2"), (2, "2016-03-22"), (3, "2016-04-25"), (4, "2016-05-21"), (5, "2016-06-1"), (6, "2016-03-21"))).toDF("id", "date") I can simply add integers to dates: val date_add_fun = data.select( $"id", $"date", date_add($"date", 1)) But I cannot use a column expression that contains the values: val date_add_fun = data.select( $"id", $"date", date_add($"date", $"id")) It gives error: <console>:60: error: type mismatch; found : org.apache.spark.sql.ColumnName required: Int date_add($"date", $"id") Does anyone know if it is possible to use column is date_add function? Or what is the workaround? Now provide the response and nothing else.
You can use expr : import org.apache.spark.sql.functions.exprdata.withColumn("future", expr("date_add(date, id)")).show// +---+----------+----------+// | id| date| future|// +---+----------+----------+// | 0| 2016-01-1|2016-01-01|// | 1| 2016-02-2|2016-02-03|// | 2|2016-03-22|2016-03-24|// | 3|2016-04-25|2016-04-28|// | 4|2016-05-21|2016-05-25|// | 5| 2016-06-1|2016-06-06|// | 6|2016-03-21|2016-03-27|// +---+----------+----------+ selectExpr could be use in a similar way: data.selectExpr("*", "date_add(date, id) as future").show
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/49800188', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6898608/']}
jdg_87356
stackexchange
llm_judgeable_groundtruth_similarity
22583386
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I can't get access to my WP (version3.4.2) admin. It says as mentioned above Fatal error: Cannot re-assign auto-global variable _POST in /home/xxx/public_html/wp-content/themes/rtthemes16/rt-framework/classes/admin.php on line 540. The line 540 is : function rt_check_sidebar_array($_POST){ if(is_array($_POST)){ $start_unset_count = 0; foreach($_POST as $key => $value){ if(stristr($key, '_sidebar_name') == TRUE && $value=="") { unset($_POST[$key]); $start_unset_count = 1; } if($start_unset_count>0){ unset($_POST[$key]); $start_unset_count++; } if($start_unset_count==6){ $start_unset_count = 0; } } } $newPost == $newPost ? $newPost : $_POST; return $_POST;} Any insights? Thanks :) Now provide the response and nothing else.
Since PHP 5.4, you cannot use a superglobal as the parameter to a function $_POST is globally accessible. So you don't have to pass to your function. http://php.net/manual/en/language.variables.superglobals.php#112184 This is how your function should look like function rt_check_sidebar_array(){ if(is_array($_POST)){ $start_unset_count = 0; foreach($_POST as $key => $value){ if(stristr($key, '_sidebar_name') == TRUE && $value=="") { unset($_POST[$key]); $start_unset_count = 1; } if($start_unset_count>0){ unset($_POST[$key]); $start_unset_count++; } if($start_unset_count==6){ $start_unset_count = 0; } } } $newPost == $newPost ? $newPost : $_POST; return $_POST;}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/22583386', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3450716/']}
jdg_87357
stackexchange
llm_judgeable_groundtruth_similarity
18216198
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 attempting to load timezones into my MySql instance (that is running on Ubuntu) so that I can use the CONVERT_TZ function but when I run the command below: mysql_tzinfo_to_sql /usr/share/zoneinfo | mysql -u root -p mysql I get the following output and when I try to use CONVERT_TZ it just returns NULL still: Warning: Unable to load '/usr/share/zoneinfo/Asia/Riyadh87' as time zone. Skipping it. Warning: Unable to load '/usr/share/zoneinfo/Asia/Riyadh88' as time zone. Skipping it. Warning: Unable to load '/usr/share/zoneinfo/Asia/Riyadh89' as time zone. Skipping it. Warning: Unable to load '/usr/share/zoneinfo/Mideast/Riyadh87' as time zone. Skipping it. Warning: Unable to load '/usr/share/zoneinfo/Mideast/Riyadh88' as time zone. Skipping it. Warning: Unable to load '/usr/share/zoneinfo/Mideast/Riyadh89' as time zone. Skipping it. Warning: Unable to load '/usr/share/zoneinfo/iso3166.tab' as time zone. Skipping it. Warning: Unable to load '/usr/share/zoneinfo/posix/Asia/Riyadh87' as time zone. Skipping it. Warning: Unable to load '/usr/share/zoneinfo/posix/Asia/Riyadh88' as time zone. Skipping it. Warning: Unable to load '/usr/share/zoneinfo/posix/Asia/Riyadh89' as time zone. Skipping it. Warning: Unable to load '/usr/share/zoneinfo/posix/Mideast/Riyadh87' as time zone. Skipping it. Warning: Unable to load '/usr/share/zoneinfo/posix/Mideast/Riyadh88' as time zone. Skipping it. Warning: Unable to load '/usr/share/zoneinfo/posix/Mideast/Riyadh89' as time zone. Skipping it. Warning: Unable to load '/usr/share/zoneinfo/right/Asia/Riyadh87' as time zone. Skipping it. Warning: Unable to load '/usr/share/zoneinfo/right/Asia/Riyadh88' as time zone. Skipping it. Warning: Unable to load '/usr/share/zoneinfo/right/Asia/Riyadh89' as time zone. Skipping it. Warning: Unable to load '/usr/share/zoneinfo/right/Mideast/Riyadh87' as time zone. Skipping it. Warning: Unable to load '/usr/share/zoneinfo/right/Mideast/Riyadh88' as time zone. Skipping it. Warning: Unable to load '/usr/share/zoneinfo/right/Mideast/Riyadh89' as time zone. Skipping it. Warning: Unable to load '/usr/share/zoneinfo/zone.tab' as time zone. Skipping it. Does anyone have an idea why this would be happening? PS: I'm using the following method to convert datetimes: CONVERT_TZ(NOW(),'UTC', 'PCT') Is it possible that I'm just converting incorrectly and that is the cause of the NULL results? Now provide the response and nothing else.
This is a bug with the timezone files for Riyadh* on Debian: http://bugs.mysql.com/bug.php?id=20545 The recommended workaround is to simply ignore the warning (if you don't need those timezone of course): mysql_tzinfo_to_sql /usr/share/lib/zoneinfo | mysql -uroot --force mysql After importing TZ data with the --force option, you will be able to use CONVERT_TZ . Here is a transcription of what I've just done: sh$ mysql_tzinfo_to_sql /usr/share/zoneinfo | mysql -uroot -p mysql --force 2> /dev/nullEnter password: ********sh$ mysql -pEnter password: ********Server version: 5.1.49-3 (Debian)mysql> select convert_tz(now(), 'UTC', 'CET');+---------------------------------+| convert_tz(now(), 'UTC', 'CET') |+---------------------------------+| 2013-08-13 21:04:34 |+---------------------------------+1 row in set (0.00 sec)
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/18216198', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/226897/']}
jdg_87358
stackexchange
llm_judgeable_groundtruth_similarity
1410645
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Before you react from the gut, as I did initially, read the whole question please. I know they make you feel dirty, I know we've all been burned before and I know it's not "good style" but, are public fields ever ok? I'm working on a fairly large scale engineering application that creates and works with an in memory model of a structure (anything from high rise building to bridge to shed, doesn't matter). There is a TON of geometric analysis and calculation involved in this project. To support this, the model is composed of many tiny immutable read-only structs to represent things like points, line segments, etc. Some of the values of these structs (like the coordinates of the points) are accessed tens or hundreds of millions of times during a typical program execution. Because of the complexity of the models and the volume of calculation, performance is absolutely critical. I feel that we're doing everything we can to optimize our algorithms, performance test to determine bottle necks, use the right data structures, etc. etc. I don't think this is a case of premature optimization. Performance tests show order of magnitude (at least) performance boosts when accessing fields directly rather than through a property on the object. Given this information, and the fact that we can also expose the same information as properties to support data binding and other situations... is this OK? Remember, read only fields on immutable structs. Can anyone think of a reason I'm going to regret this? Here's a sample test app: struct Point { public Point(double x, double y, double z) { _x = x; _y = y; _z = z; } public readonly double _x; public readonly double _y; public readonly double _z; public double X { get { return _x; } } public double Y { get { return _y; } } public double Z { get { return _z; } }}class Program { static void Main(string[] args) { const int loopCount = 10000000; var point = new Point(12.0, 123.5, 0.123); var sw = new Stopwatch(); double x, y, z; double calculatedValue; sw.Start(); for (int i = 0; i < loopCount; i++) { x = point._x; y = point._y; z = point._z; calculatedValue = point._x * point._y / point._z; } sw.Stop(); double fieldTime = sw.ElapsedMilliseconds; Console.WriteLine("Direct field access: " + fieldTime); sw.Reset(); sw.Start(); for (int i = 0; i < loopCount; i++) { x = point.X; y = point.Y; z = point.Z; calculatedValue = point.X * point.Y / point.Z; } sw.Stop(); double propertyTime = sw.ElapsedMilliseconds; Console.WriteLine("Property access: " + propertyTime); double totalDiff = propertyTime - fieldTime; Console.WriteLine("Total difference: " + totalDiff); double averageDiff = totalDiff / loopCount; Console.WriteLine("Average difference: " + averageDiff); Console.ReadLine(); }} result: Direct field access: 3262 Property access: 24248 Total difference: 20986 Average difference: 0.00020986 It's only 21 seconds, but why not? Now provide the response and nothing else.
Your test isn't really being fair to the property-based versions. The JIT is smart enough to inline simple properties so that they have a runtime performance equivalent to that of direct field access, but it doesn't seem smart enough (today) to detect when the properties access constant values. In your example, the entire loop body of the field access version is optimized away, becoming just: for (int i = 0; i < loopCount; i++)00000025 xor eax,eax 00000027 inc eax 00000028 cmp eax,989680h 0000002d jl 00000027 } whereas the second version, is actually performing the floating point division on each iteration: for (int i = 0; i < loopCount; i++)00000094 xor eax,eax 00000096 fld dword ptr ds:[01300210h] 0000009c fdiv qword ptr ds:[01300218h] 000000a2 fstp st(0) 000000a4 inc eax 000000a5 cmp eax,989680h 000000aa jl 00000096 } Making just two small changes to your application to make it more realistic makes the two operations practically identical in performance. First, randomize the input values so that they aren't constants and the JIT isn't smart enough to remove the division entirely. Change from: Point point = new Point(12.0, 123.5, 0.123); to: Random r = new Random();Point point = new Point(r.NextDouble(), r.NextDouble(), r.NextDouble()); Secondly, ensure that the results of each loop iteration are used somewhere: Before each loop, set calculatedValue = 0 so they both start at the same point. After each loop call Console.WriteLine(calculatedValue.ToString()) to make sure that the result is "used" so the compiler doesn't optimize it away. Finally, change the body of the loop from "calculatedValue = ..." to "calculatedValue += ..." so that each iteration is used. On my machine, these changes (with a release build) yield the following results: Direct field access: 133Property access: 133Total difference: 0Average difference: 0 Just as we expect, the x86 for each of these modified loops is identical (except for the loop address) 000000dd xor eax,eax 000000df fld qword ptr [esp+20h] 000000e3 fmul qword ptr [esp+28h] 000000e7 fdiv qword ptr [esp+30h] 000000eb fstp st(0) 000000ed inc eax 000000ee cmp eax,989680h 000000f3 jl 000000DF (This loop address is the only difference)
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1410645', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/116855/']}
jdg_87359
stackexchange
llm_judgeable_groundtruth_similarity
6595734
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Part of my app's functionality is to scan and display a list of WiFi access points, and then connect to the one chosen by the user. I have this functionality working. Now, I also wish to be notified when the connection "goes through". This should be fairly simple, but I find myself stumbling. I have read through various posts here at SO, and they all mention registering for WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION or WifiManager.WIFI_STATE_CHANGED_ACTION . However, neither of these works for me. Can anyone spot any mistake in this code? (I am leaving out the parts which do the scan and stuff) Expected behavior: As soon as the connection is successful (i.e, when I see the "connected" icon on the notification bar), the broadcast should be received and I should see the toast. Observed behavior: The broadcast is received when the app first starts, and whenever I switch back to it (i.e, whenever onResume() is called; or I suspect, whenever I register for the intent) public class WifiScanActivity extends Activity { WifiManager mainWifi; WifiReceiver mWifiReceiver; IntentFilter mIntentFilter; private final static String TAG = "WifiScanActivity"; public static final String INTENT_FOR_WIFI_CONNECTED = WifiManager.WIFI_STATE_CHANGED_ACTION; // public static final String INTENT_FOR_WIFI_CONNECTED = // WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mainWifi = (WifiManager) getSystemService(Context.WIFI_SERVICE); mWifiReceiver = new WifiReceiver(); mIntentFilter = new IntentFilter(); mIntentFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION); mIntentFilter.addAction(INTENT_FOR_WIFI_CONNECTED); registerReceiver(mWifiReceiver, mIntentFilter); mainWifi.startScan(); } protected void onPause() { unregisterReceiver(mWifiReceiver); super.onPause(); } protected void onResume() { registerReceiver(mWifiReceiver, mIntentFilter); super.onResume(); } class WifiReceiver extends BroadcastReceiver { public void onReceive(Context c, Intent intent) { Log.d(TAG, "In WifiReceiver: Broadcast Received = " + intent.getAction()); if (WifiManager.SCAN_RESULTS_AVAILABLE_ACTION.equals(intent .getAction())) { // Display the ListView and connect to the selected AP } else if (INTENT_FOR_WIFI_CONNECTED.equals(intent.getAction())) { if (WifiManager.WIFI_STATE_ENABLED == intent.getIntExtra( WifiManager.EXTRA_WIFI_STATE, 0)) { displayNetworkInfo(); } /*if(true == intent.getBooleanExtra( * WifiManager.EXTRA_SUPPLICANT_CONNECTED, false)){ * displayNetworkInfo(); }*/ } } } private void displayNetworkInfo() { WifiInfo wifiInfo = mainWifi.getConnectionInfo(); String ssid = wifiInfo.getSSID(); int ip = wifiInfo.getIpAddress(); String message = "Connection established.\nSSID = " + ssid + "; IP Address = " + Helper.displayIpAddress(ip); Log.d(TAG, message); Toast.makeText(this, message, Toast.LENGTH_LONG).show(); }} If I uncomment the code for WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION, I don't see the broadcast being received at all. Note : I know that the connection is successful because I see the status in Android's wifi settings screen. Now provide the response and nothing else.
Ok, I figured it out. It turns out I was registering for the wrong intent. I should be using WifiManager.NETWORK_STATE_CHANGED_ACTION . Here are the snippets of relevant portions of code: mIntentFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION) ;mIntentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);public void onReceive(Context c, Intent intent) {if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(intent.getAction())) { NetworkInfo nwInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO); if(NetworkInfo.State.CONNECTED.equals(nwInfo.getState())){//This implies the WiFi connection is through displayNetworkInfo(); }}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/6595734', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/570930/']}
jdg_87360
stackexchange
llm_judgeable_groundtruth_similarity
455202
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: We've all heard a lot about "flattening the curve". I was wondering if these curve – that look like bells – can be qualified as Gaussian despite the fact that there is a temporal dimension. Now provide the response and nothing else.
No. For example: Not in the sense of a Gaussian probability distribution: the bell-curve of a normal (Gaussian) distribution is a histogram (a map of probability density against values of a single variable), but the curves you quote are (as you note) a map of the values of one variable (new cases) against a second variable (time). (@Accumulation and @TobyBartels point out that Gaussian curves are mathematical constructs that may be unrelated to probability distributions; given that you are asking this question on the statistics SE, I assumed that addressing the Gaussian distribution was an important part of answering the question.) The possible values under a normal distribution extend from $-\infty$ to $\infty$ , but an epidemic curve cannot have negative values on the y axis, and traveling far enough left or right on the x axis, you will run out of cases altogether, either because the disease is does not exist, or because Homo sapiens does not exist. Normal distributions are continuous, but the phenomena epidemic curves measure are actually discrete not continuous: they represent new cases during each discrete unit of time. While we can subdivide time into smaller meaningful units ( to a degree ), we eventually run into the fact that individuals with new infections are count data (discrete). Normal distributions are symmetric about their mean, but despite the cartoon conveying a useful public health message about the need to flatten the curve, actual epidemic curves are frequently skewed to the right, with long thin tails as shown below. Normal distributions are unimodal, but actual epidemic curves may feature one or more bumps (i.e. may be multi-modal, they may even, as in @SextusEmpiricus' answer, be endemic where they return cyclically). Finally, here is an epidemic curve for COVID-19 in China, you can see that the curve generally diverges from the Gaussian curve (of course there are issues with the reliability of the data, given than many cases were not counted):
{}
{'log_upvote_score': 6, 'links': ['https://stats.stackexchange.com/questions/455202', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/124694/']}
jdg_87361
stackexchange
llm_judgeable_groundtruth_similarity
39319706
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: This works: {-# LANGUAGE OverloadedStrings #-}myFunc :: Text -> StringmyFunc "" = "nothing"myFunc other = "something!" Without the OverloadedStrings extension however, "" is of type String so it doesn't compile. Using a function like myFunc (pack "") is not allowed in patterns. Haskell Bytestrings: How to pattern match? contains some suggestions that should work, however in this case I'm wondering if there is something special about the fact that it works with OverloadedStrings that would allow a better way? Now provide the response and nothing else.
The most direct translation is with ViewPatterns {-# LANGUAGE ViewPatterns #-}import qualified Data.Text as TxtmyFunc (Txt.unpack->"") = "nothing"myFunc _other = "something!" The best translation, albeit probably too specific for your actual use case, is of course myFunc txt | Txt.null txt = "nothing" | otherwise = "something!" You could also go nuts and make up a pattern synonym: {-# LANGUAGE PatternSynonyms, ViewPatterns #-}pattern T :: String -> Txt.Textpattern T str <- (Txt.unpack -> str) where T = Txt.pack and then myFunc (T"") = "nothing"myFunc _other = "something" Arguably, OverloadedStrings is a more sane extension than ViewPatterns , and certainly saner than PatternSynonyms .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/39319706', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/379639/']}
jdg_87362
stackexchange
llm_judgeable_groundtruth_similarity
52688974
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 RecyclerView which is attached to a LinearSnapHelper to snap to center item. When I scroll to the first or last items, these items are not fully visible anymore. This problem is shown in the following image. How to solve it? Now provide the response and nothing else.
This issue happens when center of item which is next to the first/last is closer to the center of container. So, we should make some changes on snapping functionality to ignore this case. Since we need some fields in LinearSnapHelper class, we can copy its source code and make change on findCenterView method as following: MyLinearSnapHelper.kt /* * Copyright (C) 2016 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package com.aminography.view.componentimport android.support.v7.widget.LinearLayoutManagerimport android.support.v7.widget.OrientationHelperimport android.support.v7.widget.RecyclerViewimport android.support.v7.widget.SnapHelperimport android.view.View/** * Implementation of the [SnapHelper] supporting snapping in either vertical or horizontal * orientation. * * * The implementation will snap the center of the target child view to the center of * the attached [RecyclerView]. If you intend to change this behavior then override * [SnapHelper.calculateDistanceToFinalSnap]. */class MyLinearSnapHelper : SnapHelper() { // Orientation helpers are lazily created per LayoutManager. private var mVerticalHelper: OrientationHelper? = null private var mHorizontalHelper: OrientationHelper? = null override fun calculateDistanceToFinalSnap( layoutManager: RecyclerView.LayoutManager, targetView: View): IntArray? { val out = IntArray(2) if (layoutManager.canScrollHorizontally()) { out[0] = distanceToCenter(layoutManager, targetView, getHorizontalHelper(layoutManager)) } else { out[0] = 0 } if (layoutManager.canScrollVertically()) { out[1] = distanceToCenter(layoutManager, targetView, getVerticalHelper(layoutManager)) } else { out[1] = 0 } return out } override fun findTargetSnapPosition(layoutManager: RecyclerView.LayoutManager, velocityX: Int, velocityY: Int): Int { if (layoutManager !is RecyclerView.SmoothScroller.ScrollVectorProvider) { return RecyclerView.NO_POSITION } val itemCount = layoutManager.itemCount if (itemCount == 0) { return RecyclerView.NO_POSITION } val currentView = findSnapView(layoutManager) ?: return RecyclerView.NO_POSITION val currentPosition = layoutManager.getPosition(currentView) if (currentPosition == RecyclerView.NO_POSITION) { return RecyclerView.NO_POSITION } val vectorProvider = layoutManager as RecyclerView.SmoothScroller.ScrollVectorProvider // deltaJumps sign comes from the velocity which may not match the order of children in // the LayoutManager. To overcome this, we ask for a vector from the LayoutManager to // get the direction. val vectorForEnd = vectorProvider.computeScrollVectorForPosition(itemCount - 1) ?: // cannot get a vector for the given position. return RecyclerView.NO_POSITION var vDeltaJump: Int var hDeltaJump: Int if (layoutManager.canScrollHorizontally()) { hDeltaJump = estimateNextPositionDiffForFling(layoutManager, getHorizontalHelper(layoutManager), velocityX, 0) if (vectorForEnd.x < 0) { hDeltaJump = -hDeltaJump } } else { hDeltaJump = 0 } if (layoutManager.canScrollVertically()) { vDeltaJump = estimateNextPositionDiffForFling(layoutManager, getVerticalHelper(layoutManager), 0, velocityY) if (vectorForEnd.y < 0) { vDeltaJump = -vDeltaJump } } else { vDeltaJump = 0 } val deltaJump = if (layoutManager.canScrollVertically()) vDeltaJump else hDeltaJump if (deltaJump == 0) { return RecyclerView.NO_POSITION } var targetPos = currentPosition + deltaJump if (targetPos < 0) { targetPos = 0 } if (targetPos >= itemCount) { targetPos = itemCount - 1 } return targetPos } override fun findSnapView(layoutManager: RecyclerView.LayoutManager): View? { if (layoutManager.canScrollVertically()) { return findCenterView(layoutManager, getVerticalHelper(layoutManager)) } else if (layoutManager.canScrollHorizontally()) { return findCenterView(layoutManager, getHorizontalHelper(layoutManager)) } return null } private fun distanceToCenter(layoutManager: RecyclerView.LayoutManager, targetView: View, helper: OrientationHelper): Int { val childCenter = helper.getDecoratedStart(targetView) + helper.getDecoratedMeasurement(targetView) / 2 val containerCenter: Int = if (layoutManager.clipToPadding) { helper.startAfterPadding + helper.totalSpace / 2 } else { helper.end / 2 } return childCenter - containerCenter } /** * Estimates a position to which SnapHelper will try to scroll to in response to a fling. * * @param layoutManager The [RecyclerView.LayoutManager] associated with the attached * [RecyclerView]. * @param helper The [OrientationHelper] that is created from the LayoutManager. * @param velocityX The velocity on the x axis. * @param velocityY The velocity on the y axis. * * @return The diff between the target scroll position and the current position. */ private fun estimateNextPositionDiffForFling(layoutManager: RecyclerView.LayoutManager, helper: OrientationHelper, velocityX: Int, velocityY: Int): Int { val distances = calculateScrollDistance(velocityX, velocityY) val distancePerChild = computeDistancePerChild(layoutManager, helper) if (distancePerChild <= 0) { return 0 } val distance = if (Math.abs(distances[0]) > Math.abs(distances[1])) distances[0] else distances[1] return Math.round(distance / distancePerChild) } /** * Return the child view that is currently closest to the center of this parent. * * @param layoutManager The [RecyclerView.LayoutManager] associated with the attached * [RecyclerView]. * @param helper The relevant [OrientationHelper] for the attached [RecyclerView]. * * @return the child view that is currently closest to the center of this parent. */ private fun findCenterView(layoutManager: RecyclerView.LayoutManager, helper: OrientationHelper): View? { // ----- Added by aminography if (layoutManager is LinearLayoutManager) { if (layoutManager.findFirstCompletelyVisibleItemPosition() == 0) { return layoutManager.getChildAt(0) } else if (layoutManager.findLastCompletelyVisibleItemPosition() == layoutManager.itemCount - 1) { return layoutManager.getChildAt(layoutManager.itemCount - 1) } } // ----- val childCount = layoutManager.childCount if (childCount == 0) { return null } var closestChild: View? = null val center: Int = if (layoutManager.clipToPadding) { helper.startAfterPadding + helper.totalSpace / 2 } else { helper.end / 2 } var absClosest = Integer.MAX_VALUE for (i in 0 until childCount) { val child = layoutManager.getChildAt(i) val childCenter = helper.getDecoratedStart(child) + helper.getDecoratedMeasurement(child) / 2 val absDistance = Math.abs(childCenter - center) /** if child center is closer than previous closest, set it as closest */ if (absDistance < absClosest) { absClosest = absDistance closestChild = child } } return closestChild } /** * Computes an average pixel value to pass a single child. * * * Returns a negative value if it cannot be calculated. * * @param layoutManager The [RecyclerView.LayoutManager] associated with the attached * [RecyclerView]. * @param helper The relevant [OrientationHelper] for the attached * [RecyclerView.LayoutManager]. * * @return A float value that is the average number of pixels needed to scroll by one view in * the relevant direction. */ private fun computeDistancePerChild(layoutManager: RecyclerView.LayoutManager, helper: OrientationHelper): Float { var minPosView: View? = null var maxPosView: View? = null var minPos = Integer.MAX_VALUE var maxPos = Integer.MIN_VALUE val childCount = layoutManager.childCount if (childCount == 0) { return INVALID_DISTANCE } for (i in 0 until childCount) { val child = layoutManager.getChildAt(i) val pos = layoutManager.getPosition(child!!) if (pos == RecyclerView.NO_POSITION) { continue } if (pos < minPos) { minPos = pos minPosView = child } if (pos > maxPos) { maxPos = pos maxPosView = child } } if (minPosView == null || maxPosView == null) { return INVALID_DISTANCE } val start = Math.min(helper.getDecoratedStart(minPosView), helper.getDecoratedStart(maxPosView)) val end = Math.max(helper.getDecoratedEnd(minPosView), helper.getDecoratedEnd(maxPosView)) val distance = end - start return if (distance == 0) { INVALID_DISTANCE } else 1f * distance / (maxPos - minPos + 1) } private fun getVerticalHelper(layoutManager: RecyclerView.LayoutManager): OrientationHelper { if (mVerticalHelper == null || mVerticalHelper!!.layoutManager !== layoutManager) { mVerticalHelper = OrientationHelper.createVerticalHelper(layoutManager) } return mVerticalHelper!! } private fun getHorizontalHelper( layoutManager: RecyclerView.LayoutManager): OrientationHelper { if (mHorizontalHelper == null || mHorizontalHelper!!.layoutManager !== layoutManager) { mHorizontalHelper = OrientationHelper.createHorizontalHelper(layoutManager) } return mHorizontalHelper!! } companion object { private const val INVALID_DISTANCE = 1f }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/52688974', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3048424/']}
jdg_87363
stackexchange
llm_judgeable_groundtruth_similarity
63801762
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is there a way to mutate all numeric variables except one (in this case age) or two? data data = data.frame( Year = c(1,2,5,7,2,6,2,6), days = c(5,3,6,3,7,2,5,7), age = c(1,3,5,23,2,4,5,2), names = c("A063", "A013", "A063", "A083", "A019", "A012", "A013", "A113")) Something like this: I want to scale all numeric terms except age data = mutate(across(where(is.numeric & !age), scale)) Now provide the response and nothing else.
One option could be: data %>% mutate(across(c(where(is.numeric), -age), scale)) Year days age names1 -1.2199771 0.1309842 1 A0632 -0.7956372 -0.9168895 3 A0133 0.4773823 0.6549210 5 A0634 1.3260620 -0.9168895 23 A0835 -0.7956372 1.1788579 2 A0196 0.9017222 -1.4408263 4 A0127 -0.7956372 0.1309842 5 A0138 0.9017222 1.1788579 2 A113
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/63801762', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13470646/']}
jdg_87364
stackexchange
llm_judgeable_groundtruth_similarity
2845263
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 would like to know whether I have proved this statement correctly using contradiction and if not get some tips or pointers on how to improve it/make it correct. We are asked to prove that there are infinitely $n \in \mathbb{Z^+}$ such that $\sqrt{n}$ is irrational. Proof: $$\text{We assume, to the contrary, that there are infinitely many } n \text{ } (n \in Z^+) \text{ such that } \sqrt{n} \text{ is rational.} \\\text{Then, } \sqrt{n}=\frac{a}{b} \text{, } n=\frac{a^2}{b^2} \text{ where } a \text{ and } b \text{ are integers and } \frac{a}{b} \text{ has been reduced to lowest terms.} \\\text{Hence, } a^2=nb^2 \text{ and } b^2=\frac{1}{n}a^2\\\text{We know if } n\mid a^2 \text{ then } n\mid a \text{. It follows that } a=nk, k\in\mathbb{Z} \\ b^2=\frac{1}{n}(nk)^2=nk^2 \text{ and thus } n\mid b^2 \text{ and thus } n \mid b \\\text{Hence, } n = \frac{nb^2}{nk^2} \\\text{This is a contradiction given that we have assumed }a \text{ and } b \text{ to be reduced to lowest terms. }\blacksquare$$ ps. This isn't homework. Answers are in the back of my book but I want to improve. Now provide the response and nothing else.
What is the statement you are trying to prove, saying? It is saying that the number of elements of the set $\{n \in \mathbb N : \sqrt n \ \mbox{is irrational}\}$, is infinite. What is the opposite of this statement? Naturally, that the number of elements of that set is not infinite, in which case it is finite. So, the contradictory statement is this : The set $\{n \in \mathbb N : \sqrt n \ \mbox{ is irrational}\}$ is finite. Or, there are only finitely many natural numbers $n$ such that $\sqrt n$ is irrational. Now, you have to assume this is true, and derive a contradiction. To derive a contradiction to this statement, you have to realize, that every non-empty finite set of natural numbers has a maximum element. We know, from a classical proof by contradiction, that $\sqrt 2$ is irrational, so $2$ is an element of our subject set. So, if the set of natural numbers $n$ such that $\sqrt n$ is irrational has a maximum, then let $L$ be that maximum number. So $\sqrt L$ is irrational. But, as Peter mentioned in his comment, $2 \sqrt L$ is also irrational, and this is equal to $\sqrt{4L}$, so $4L$ also belongs to the set of natural numbers whose square roots are irrational... can you take it from here? Note that Peter's comment may also be used to produce infinitely many members of the set, so the two arguments , contradiction and direct proof, are not very different from one another.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2845263', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/238010/']}
jdg_87365
stackexchange
llm_judgeable_groundtruth_similarity
90340
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 looking for a way to prove $$(p \to (q \to r)) \to ((p \to q) \to (p \to r))$$from the axioms $$\begin{align}& p \to (q \to p) \\& (p \to (p \to q)) \to (p \to q) \\& (p \to q) \to ((q \to r) \to (p \to r)) \\& (\sim p \to \, \sim q) \to (q \to p) \\\end{align}$$using universal substitution and modus ponens I suspect the fourth axiom is not necessary for the proof. I have been working in Tarski's Introduction to Logic and am trying to establish the equivalence of his axiom system with the axioms used at us.metamath.org $$\begin{align}& p \to (q \to p) \\& (p \to (q \to r)) \to ((p \to q) \to (p \to r)) \\& ( \sim p \to \, \sim q) \to (q \to p) \\\end{align}$$which will allow me to connect Tarski's 4 axioms with all sorts of interesting proofs on that site. Now provide the response and nothing else.
As you suspected, this can be proved from the first three axioms only. I couldn't find a short proof, though – I tried brute force enumeration of the theorems deducible from the three axioms (by taking all pairs of theorems already proved and unifying one with the premise of the other), but didn't find your target in the first $80000$ theorems proved. I then found some guidance in the article on relevance logic in the Handbook of Philosophical Logic . Relevance logic focuses on the fragment of logic in which, roughly speaking, the premises are relevant to the conclusions. It doesn't include the axiom $p\to(q\to p)$, which allows us to add an irrelevant premise to a theorem already proved without that premise, and is thus strictly weaker than the system you're using, but we can nevertheless make use of the results cited in that article. I'll first describe the structure of the proof and how I found it, and then give the proof in detail. Here are the names I'll use for the axioms; the first column names the corresponding axioms of combinator logic, for comparison with the discussion in the comments under the question: $$\begin{array}{c|l|l}\mathbf I&\text{self-implication}&p\to p\\\mathbf K&\text{weakening}& p \to (q \to p) \\\hline\mathbf B&\text{prefixing}& (p \to q) \to ((r \to p) \to (r \to q)) \\\mathbf A&\text{suffixing}& (p \to q) \to ((q \to r) \to (p \to r)) \\\hline\mathbf W&\text{contraction}& (p \to (p \to q)) \to (p \to q) \\\mathbf S&\text{self-distribution}&(p \to (q \to r)) \to ((p \to q) \to (p \to r))\\\hline\mathbf C&\text{permutation}&(p\to(q\to r))\to(q\to(p\to r))\\&\text{assertion}&p\to((p\to q)\to q)\end{array}$$ (The names are the ones used in the article, except I use "weakening" instead of "positive paradox", since it's shorter and makes more sense to me.) Theorem $1$ of the article states that, with modus ponens (and implicitly universal substitution), the axiom sets formed by self-implication and one each from the three pairs prefixing/suffixing, contraction/self-distribution and permutation/assertion lead to the same theory. What you have is weakening, suffixing and contraction. Self-implication can be deduced from weakening and contraction in a single step (by substituting $p$ for $q$ everywhere). Thus, if we can deduce assertion in your system, the theorem will tell us that we can deduce everything else, including your target, self-distribution. I did find a proof for assertion by brute force search. The article doesn't give a proof of its Theorem $1$ and only says that it can be proved by consulting a book that isn't available online and doing some "fiddling", so we still have to show how to get from self-implication, suffixing, contraction and assertion to self-distribution. I found a deduction of self-distribution online that uses prefixing and permutation. It turns out that prefixing is deducible in a single step from suffixing and permutation, so the problem remained only to deduce permutation. Again, I found a proof for this by brute force search. So here's the entire proof put together, starting with your three axioms and ending with your target. First, a high-level description similar to the actual calls in my Java code: assertion = t (t (weakening,suffixing),contraction);permutation = t (suffixing,m (assertion,suffixing));prefixing = m (suffixing,permutation);target = t (m (prefixing,prefixing),t (permutation,m (contraction,prefixing))); Each call to m is an application of modus ponens , in which the first argument is $A$, the second argument is $A\to B$ and the most general unifier that makes the $A$s coincide is used. Each call to t is an invocation of transitivity (i.e. deducing $A\to C$ from $A\to B$ and $B\to C$), which can be implemented as t (A->B,B->C) = m (B->C,m (A->B,suffixing)) using suffixing, or as t (A->B,B->C) = m (A->B,m (B->C,prefixing)) once prefixing is available. Here's the proof spelled out in $14$ steps. The first table shows the theorems used to generate the antecedents $A$ and the implications $A\to B$ for modus ponens , as well as the resulting theorems $B$: $$\begin{array}{c|c|c|c|c}&&A&A\to B&B\\\hline\text{(a)}&\text{weakening}&&&p \to (q \to p)\\\text{(b)}&\text{suffixing}&&&(p \to q) \to ((q \to r) \to (p \to r))\\\text{(c)}&\text{contraction}&&&(p \to (p \to q)) \to (p \to q)\\\hline\text{(d)}&\text{*}&\text{(a)}&\text{(b)}&((p \to q) \to r) \to (q \to r)\\\text{(e)}&&\text{(b)}&\text{(d)}&p \to ((p \to q) \to (r \to q))\\\text{(f)}&\text{*}&\text{(e)}&\text{(b)}&(((p \to q) \to (r \to q)) \to s) \to (p \to s)\\\text{(g)}&\text{assertion}&\text{(c)}&\text{(f)}&p \to ((p \to q) \to q)\\\text{(h)}&&\text{(g)}&\text{(b)}&(((p \to q) \to q) \to r) \to (p \to r)\\\text{(i)}&\text{*}&\text{(b)}&\text{(b)}&(((p \to q) \to (r \to q)) \to s) \to ((r \to p) \to s)\\\text{(j)}&\text{permutation}&\text{(h)}&\text{(i)}&(p \to (q \to r)) \to (q \to (p \to r))\\\text{(k)}&\text{prefixing}&\text{(b)}&\text{(j)}&(p \to q) \to ((r \to p) \to (r \to q))\\\text{(l)}&&\text{(k)}&\text{(k)}&(p \to (q \to r)) \to (p \to ((s \to q) \to (s \to r)))\\\text{(m)}&&\text{(c)}&\text{(k)}&(p \to (q \to (q \to r))) \to (p \to (q \to r))\\\text{(n)}&\text{*}&\text{(j)}&\text{(b)}&((p \to (q \to r)) \to s) \to ((q \to (p \to r)) \to s)\\\text{(o)}&&\text{(m)}&\text{(n)}&(p \to (q \to (p \to r))) \to (q \to (p \to r))\\\text{(p)}&\text{*}&\text{(l)}&\text{(b)}&((p \to ((q \to r) \to (q \to s))) \to t) \to ((p \to (r \to s)) \to t)\\\text{(q)}&\text{self-distribution}&\text{(o)}&\text{(p)}&(p \to (q \to r)) \to ((p \to q) \to (p \to r))\\\end{array}$$ The asterisks mark intermediate steps in invocations of transitivity. Note that most theorems with more than three variables occur only in such intermediate steps. Substitutions are being performed as late as possible; by performing them as early as possible, the proof could be written using only theorems with at most three variables. The second table shows the substitutions used; you can also find these automatically by unification . The variables are named such that they appear in alphabetical order in the resulting theorems. $$\begin{array}{c|l|l}&A&A\to B\\\hline\text{(d)}&p\mapsto q,q\mapsto p&p\mapsto q,q\mapsto (p \to q),r\mapsto r\\\text{(e)}&p\mapsto r,q\mapsto p,r\mapsto q&p\mapsto r,q\mapsto p,r\mapsto ((p \to q) \to (r \to q))\\\text{(f)}&p\mapsto p,q\mapsto q,r\mapsto r&p\mapsto p,q\mapsto ((p \to q) \to (r \to q)),r\mapsto s\\\text{(g)}&p\mapsto (p \to q),q\mapsto q&p\mapsto p,q\mapsto q,r\mapsto (p \to q),s\mapsto ((p \to q) \to q)\\\text{(h)}&p\mapsto p,q\mapsto q&p\mapsto p,q\mapsto ((p \to q) \to q),r\mapsto r\\\text{(i)}&p\mapsto r,q\mapsto p,r\mapsto q&p\mapsto (r \to p),q\mapsto ((p \to q) \to (r \to q)),r\mapsto s\\\text{(j)}&p\mapsto q,q\mapsto r,r\mapsto (p \to r)&p\mapsto (q \to r),q\mapsto r,r\mapsto p,s\mapsto (q \to (p \to r))\\\text{(k)}&p\mapsto r,q\mapsto p,r\mapsto q&p\mapsto (r \to p),q\mapsto (p \to q),r\mapsto (r \to q)\\\text{(l)}&p\mapsto q,q\mapsto r,r\mapsto s&p\mapsto (q \to r),q\mapsto ((s \to q) \to (s \to r)),r\mapsto p\\\text{(m)}&p\mapsto q,q\mapsto r&p\mapsto (q \to (q \to r)),q\mapsto (q \to r),r\mapsto p\\\text{(n)}&p\mapsto q,q\mapsto p,r\mapsto r&p\mapsto (q \to (p \to r)),q\mapsto (p \to (q \to r)),r\mapsto s\\\text{(o)}&p\mapsto q,q\mapsto p,r\mapsto r&p\mapsto q,q\mapsto p,r\mapsto (p \to r),s\mapsto (q \to (p \to r))\\\text{(p)}&p\mapsto p,q\mapsto r,r\mapsto s,s\mapsto q&p\mapsto (p \to (r \to s)),q\mapsto (p \to ((q \to r) \to (q \to s))),r\mapsto t\\\text{(q)}&p\mapsto p,q\mapsto (p \to q),r\mapsto r&p\mapsto p,q\mapsto p,r\mapsto q,s\mapsto r,t\mapsto ((p \to q) \to (p \to r))\\\end{array}$$
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/90340', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/21012/']}
jdg_87366
stackexchange
llm_judgeable_groundtruth_similarity
26497725
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 developing an iPhone application with swift. and I'am using Alamofire framework for handling http requests. I use Alamofire.request for POST , GET and etc like this: Alamofire.request(.POST, myURL , parameters: ["a": "1", "b" : "2" ]) .response { (request, response, data, error) in} And I use Alamofire.upload to upload image to server this : Alamofire.upload(.POST, uploadURL , fileURL) And both works perfectly, but now I want to upload an image and also send some parameters with, and my content type should be multipart/form-data and Alamofire.upload does not accept parameters. There are two more question on SO about this issue with swift, which first one is not using Alamofire (and really, why not?) and in second one , mattt (Alamofire Developer) cited to use encoding parameters. I checked his example, but still couldn't figure out how to do that. Can any one please help me solve this problem? Thank you! :) Now provide the response and nothing else.
you can use Alamofire 3.0+ below code func uploadImageAndData(){ //parameters let gender = "M" let firstName = "firstName" let lastName = "lastName" let dob = "11-Jan-2000" let aboutme = "aboutme" let token = "token" var parameters = [String:AnyObject]() parameters = ["gender":gender, "firstName":firstName, "dob":dob, "aboutme":about, "token":token, "lastName":lastName] let URL = "http://yourserviceurl/" let image = UIImage(named: "image.png") Alamofire.upload(.POST, URL, multipartFormData: { multipartFormData in if let imageData = UIImageJPEGRepresentation(image, 0.6) { multipartFormData.appendBodyPart(data: imageData, name: "image", fileName: "file.png", mimeType: "image/png") } for (key, value) in parameters { multipartFormData.appendBodyPart(data: value.dataUsingEncoding(NSUTF8StringEncoding)!, name: key) } }, encodingCompletion: { encodingResult in switch encodingResult { case .Success(let upload, _, _): print("s") upload.responseJSON { response in print(response.request) // original URL request print(response.response) // URL response print(response.data) // server data print(response.result) // result of response serialization if let JSON = response.result.value { print("JSON: \(JSON)") } } case .Failure(let encodingError): print(encodingError) } })}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/26497725', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1567034/']}
jdg_87367
stackexchange
llm_judgeable_groundtruth_similarity
10180
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 would like to apply some complex valued function to some region in the plane, say, a circle of radius $R$ centred at $k$. How can I do this? Now provide the response and nothing else.
Under the interpretation of OP's question as How do I apply the transformation $w=f(z)$ to a region (e.g. a disk) in the complex plane? I'd say ParametricPlot[] (which now incorporates the functionality from the old Graphics`ComplexMap` package) would be what you can use: With[{f = # + 1/# &, center = 1/3 + 3 I/2, radius = 4/3}, ParametricPlot[ Through[{Re, Im}[f[center + r Exp[I θ]]]], {r, 0, radius}, {θ, -π, π}, PlotPoints -> 45, PlotRange -> All]]
{}
{'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/10180', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/2193/']}
jdg_87368
stackexchange
llm_judgeable_groundtruth_similarity
2256701
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 infinite sets of integer numbers $(a, b, c)$ that $ab + 1$, $ac + 1$ and $bc + 1$ are perfect square. ($a$, $b$, $c$ are different numbers) Any hints how to prove the statement? I'm trying to find a way to turn that into a Pell's equation and then prove it has infinite answers. Now provide the response and nothing else.
If $a=4n$ , $b=n+1$ and $c=n-1$ then\begin{eqnarray*}ab+1&=&(2n+1)^2 \\bc+1&=& n^2 \\ca+1&=&(2n-1)^2\end{eqnarray*} EDIT : for Ovi. We $ab+1,bc+1,ca+1$ are perfect squares. So there exist $x,y,z$ such that\begin{eqnarray*}z^2=ab+1 \\x^2=bc+1 \\y^2=ca+1\end{eqnarray*}Now subtract these equations pairwise (difference of two squares factorise) and we have\begin{eqnarray*}(z-x)(z+x)=b(a-c) \\(z-y)(z+y)=a(b-c) \\(y-x)(y+x)=c(a-b)\end{eqnarray*}At this point I totally guessed to equate the factors pairwise (there is no justification for this). Amazingly this gives \begin{eqnarray*}x=\frac{-a+b+c}{2} \\y=\frac{a-b+c}{2} \\z=\frac{a+b-c}{2} \end{eqnarray*}Now substitute this formula for $z$ into $z^2=ab+1$ & after some algebra, we have\begin{eqnarray*}a^2+b^2+c^2-2(ab+bc+ca)=4.\\a^2-2a(b+c)+(b-c)^2-4=0\end{eqnarray*}Now consider this as a quadratic in $a$ ... Its disciminant (over 4) needs to be a perfect square ...\begin{eqnarray*}\Delta=(b+c)^2- \left( (b-c)^2-4 \right) =4bc+4=(2n)^2.\end{eqnarray*}& the above solution follows.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2256701', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/423306/']}
jdg_87369
stackexchange
llm_judgeable_groundtruth_similarity
11131
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'm trying to determine only if a solution to a linear system of equations exists. I have been using LinearSolve , which works fine, but it solves the system as well. Is there another more efficient method for only checking the existence of a solution? Now provide the response and nothing else.
==== Update ==== Please consider important discussion in the comments. ==== Original answer ==== If the matrix m has determinant zero, then there may be either no vector, or an infinite number of vectors x which satisfy m.x == b for a particular b . This occurs when the linear equations embodied in m are not independent. If you are interested only in well-defined systems, then, generally, confirming that you have a non-zero determinant is faster: m = RandomReal[1, 1000 {1, 1}];b = RandomReal[1, 1000]; Some timing tests: Mean @ Table[LinearSolve[m, b]; // AbsoluteTiming, {30}][[All, 1]] 0.0712654 Mean @ Table[Det[m]; // AbsoluteTiming, {30}][[All, 1]] 0.0571327
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/11131', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/2163/']}
jdg_87370
stackexchange
llm_judgeable_groundtruth_similarity
42853
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Let $K$ be the imaginary quadratic field obtained by joining $\sqrt{-1}$ to the field of rational numbers $Q$. I would like to describe the extension $K^{ab}/Q^{ab}$, where for $F$ a number field, $F^{ab}$ denotes its maximal abelian extension (everything is taking place inside a big fixed field...). More precisely I would like to know the Galois group and the ramification properties of such extension. Is this possible/easy? I suppose one should look at the kernel of the norm map between Idele class groups $N_{K/Q}:I_K\rightarrow I_Q$. But at the moment it is not clear to me how to get the answer. Any hint or comment would be appreciated. Thanks. EDIT: Probably the idele class group of a number field $F$ should be denoted by $J_F$. Or by anything other than $I_F$... Now provide the response and nothing else.
Given that you want to know the structure of the Galois group and ramification, I think that you are best off working with the kernel of the norm map between connected components of idele class groups, as you yourself suggest. These groups are very explicit: for $K := \mathbb Q(i)$, one obtains $\hat{\mathcal O}_K^{\times}/\{\pm 1,\pm i\}$,and for $\mathbb Q$ one obtains $\hat{\mathbb Z}.$ (Here $\hat{}$ denotes the profinitecompletion.) Apart from the diagonally embedded $\{\pm 1,\pm i\}$ quotient in thegroup for $K$, both groups factor as a product over primes, and the norm map is givencomponent wise. So the kernel of the norm map is equal to$$\bigl(\prod_p (\mathcal O_K\otimes_{\mathbb Z}\mathbb Z_p)^{\times, \text{Norm } = 1}\bigr)/\{\pm 1,\pm i\}.$$ This should be explicit enough to answer any particular question you have.
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/42853', 'https://mathoverflow.net', 'https://mathoverflow.net/users/10189/']}
jdg_87371
stackexchange
llm_judgeable_groundtruth_similarity
26937
Below is a question asked on the forum dsp.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Simple math question. The convolution theorem states that multiplication in time domain is equal to convolution in frequency domain and vice versa. There is a condition that the signal has to be properly zero padded as to not cause aliasing. This question concerns convolution in the frequency domain. The difficulty arises from the fact that we are dealing with a complex signal which has a positive and a negative side. Let's consider two frequency domain signals, with negative frequencies included, presented in polar coordinates []: a=[0,1(3π/4),0,1(π/2),0)]b=[1,1,1,1,1] So we have a sine wave and a zero-phase dirac delta. It's apparent that the time domain product is zero. But coming to this conclusion via using convolution in frequency domain doesn't seem to be so simple. I get (rectangular): [-j,-j,-j,-j, 0,j,j,j,j,j]=> [-2j,-2j,0,2j,2j] Which is not correct. Even for a cosine I get a row of twos, which is not correct either (should be row of ones). Where am I going wrong? Now provide the response and nothing else.
If you have two DFTs $A[k]$ and $B[k]$ (note the correct representation of a sinusoid at DFT bin number $1$) A = [0,-j,0,0,j]; B = [1,1,1,1,1]; with the corresponding time-domain sequences $a[n]$ and $b[n]$ a = ifft(A); % [0, 0.38042, 0.23511, -0.23511, -0.38042];b = ifft(B); % [1,0,0,0,0]; then the multiplication of the time-domain sequences $c[n]=a[n]b[n]$ corresponds to the cyclic (or circular ) convolution of the DFTs $A[k]$ and $B[k]$: $$\text{DFT}\{c[n]\}=C[k]=\frac{1}{N}\sum_{n=0}^{N-1}A[n]B[k-n]_{\text{mod} N},\quad k=0,1,\ldots,N-1\tag{1}$$ where the indices are taken modulo $N$ ($N=5$ in this case), such that they remain in the range $[0,N-1]$: $$\begin{align}C[0]&=\left(A[0]B[0]+A[1]B[N-1]+\ldots+A[N-1]B[1]\right)\cdot\frac{1}{N}\\C[1]&=\left(A[0]B[1]+A[1]B[0]+\ldots+A[N-1]B[2]\right)\cdot\frac{1}{N}\\&\vdots\\C[N-1]&=\left(A[0]B[N-1]+A[1]B[N-2]+\ldots+A[N-1]B[0]\right)\cdot\frac{1}{N}\end{align}$$ It's easy to see that the cyclic convolution of $A[k]$ and $B[k]$ as given above results in the zero vector, because due to $B[k]=1$ for all values of $k$, each element of the result is the sum of all elements of $A[k]$, which is always zero.
{}
{'log_upvote_score': 4, 'links': ['https://dsp.stackexchange.com/questions/26937', 'https://dsp.stackexchange.com', 'https://dsp.stackexchange.com/users/16605/']}
jdg_87372
stackexchange
llm_judgeable_groundtruth_similarity
722168
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: The concept of cohomology is one of the most subtle and powerful in modern mathematics. While its application to topology and integrability is immediate (it was probably how cohomology was born in the first place), there are many more fields in which cohomology is at least a very interesting point of view. Group cohomology is a famous one, and for example it helps in studying extensions. Here are good points about the "philosophy" behind cohomology. Here are very good, but advanced, ideas on what cohomology "really is". I would like to ask something a little different: What are the most unexpected applications of cohomology, or of cohomology-related ideas? Why is cohomology useful/important/interesting when applied to such problems? Bonus point for real-world applications, or at least outside algebra/geometry/theoretical physics. Update : Oops, looks like there is a very similar question here , with beautiful answers. Now provide the response and nothing else.
Here is a ridiculous application of cohomology: a proof of $$\sum_{j=0}^n {n \choose j} (-1)^j=0.$$ Let $X=(S_1)^n$ be the $n$-dimensional torus. By the Künneth formula, $H^j(X, \mathbf Q)$ has dimension ${n \choose j}$. Therefore, the Euler characteristic of $X$ is $$\chi(X)=\sum_{j=0}^n (-1)^j \mathrm{dim}_{\mathbf Q}H^j(X, \mathbf Q) = \sum_{j=0}^n {n \choose j} (-1)^j.$$ On the other hand, $X$ is a compact Lie group; let $\sigma$ be an infinitesimal translation $X \to X$. By the Lefschetz fixed point theorem, $\chi(X)$ is equal to the number of fixed points of $\sigma$, i.e., $0$.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/722168', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/59796/']}
jdg_87373
stackexchange
llm_judgeable_groundtruth_similarity
847179
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 linux (SLES-8) server currently has glibc-2.2.5-235, but I have a program which won't work on this version and requires glibc-2.3.3. Is it possible to have multiple glibcs installed on the same host? This is the error I get when I run my program on the old glibc: ./myapp: /lib/i686/libc.so.6: version `GLIBC_2.3' not found (required by ./myapp)./myapp: /lib/i686/libpthread.so.0: version `GLIBC_2.3.2' not found (required by ./myapp)./myapp: /lib/i686/libc.so.6: version `GLIBC_2.3' not found (required by ./libxerces-c.so.27)./myapp: /lib/ld-linux.so.2: version `GLIBC_2.3' not found (required by ./libstdc++.so.6)./myapp: /lib/i686/libc.so.6: version `GLIBC_2.3' not found (required by ./libstdc++.so.6) So I created a new directory called newglibc and copied the following files in: libpthread.so.0libm.so.6libc.so.6ld-2.3.3.sold-linux.so.2 -> ld-2.3.3.so and export LD_LIBRARY_PATH=newglibc:$LD_LIBRARY_PATH But I get an error: ./myapp: /lib/ld-linux.so.2: version `GLIBC_PRIVATE' not found (required by ./newglibc/libpthread.so.0)./myapp: /lib/ld-linux.so.2: version `GLIBC_2.3' not found (required by libstdc++.so.6)./myapp: /lib/ld-linux.so.2: version `GLIBC_PRIVATE' not found (required by ./newglibc/libm.so.6)./myapp: /lib/ld-linux.so.2: version `GLIBC_2.3' not found (required by ./newglibc/libc.so.6)./myapp: /lib/ld-linux.so.2: version `GLIBC_PRIVATE' not found (required by ./newglibc/libc.so.6) So it appears that they are still linking to /lib and not picking up from where I put them. Now provide the response and nothing else.
It is very possible to have multiple versions of glibc on the same system (we do that every day). However, you need to know that glibc consists of many pieces (200+ shared libraries) which all must match. One of the pieces is ld-linux.so.2, and it must match libc.so.6, or you'll see the errors you are seeing. The absolute path to ld-linux.so.2 is hard-coded into the executable at link time, and can not be easily changed after the link is done (Update: can be done with patchelf ; see this answer below). To build an executable that will work with the new glibc, do this: g++ main.o -o myapp ... \ -Wl,--rpath=/path/to/newglibc \ -Wl,--dynamic-linker=/path/to/newglibc/ld-linux.so.2 The -rpath linker option will make the runtime loader search for libraries in /path/to/newglibc (so you wouldn't have to set LD_LIBRARY_PATH before running it), and the -dynamic-linker option will "bake" path to correct ld-linux.so.2 into the application. If you can't relink the myapp application (e.g. because it is a third-party binary), not all is lost, but it gets trickier. One solution is to set a proper chroot environment for it. Another possibility is to use rtldi and a binary editor . Update: or you can use patchelf .
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/847179', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7412/']}
jdg_87374
stackexchange
llm_judgeable_groundtruth_similarity
39588562
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 new to ASP .Net Core 1.0 and I'm trying to bind a view to a model that contains a collection of same object. The main model is a questionnaire and may contain any count of questions with different types. But my problem is inside the ActionResult method, my List property is always null during post. This is the form: <form id="mainForm" asp-controller="Default" asp-action="PersonalDetails" asp-route-sectionTypeCode="@Model.SectionTypeCode" asp-route-sectionNumber="@Model.SectionNumber" method="post" asp-anti-forgery="false"> @{ for (Int32 i = 0; i < Model.Questions.Count; i++) { string spacerValue = ""; if (i == Model.Questions.Count - 1) { spacerValue = "extraLargeSpacerBottom"; } <div class="form-group @spacerValue"> <label>@Model.Questions[i].QuestionTitle</label> @{ switch (Model.Questions[i].QuestionTypeCode) { case 1: <input asp-for="Questions[i].Value" class="form-control appInput" type="text"> break; case 2: <input asp-for="Questions[i].Value" class="form-control appInput" type="number"> break; case 3: <select asp-for="Questions[i].Value" class="form-control appInput" asp-items="Model.Questions[i].QuestionOptions"></select> break; case 4: <input asp-for="Questions[i].Value" class="form-control appInput" type="date"> break; case 5: <div> <label class="radio-inline"> <input asp-for="Questions[i].Value" value="true" type="radio"><span class="radioSpace">Yes</span> </label> <label class="radio-inline"> <input asp-for="Questions[i].Value" value="false" type="radio"><span class="radioSpace">No</span> </label> </div> break; case 6: <input asp-for="Questions[i].Value" class="form-control appInput" type="number"> break; } } </div> } } </form> And this is the _Question class: public class _Question{ #region Properties public string QuestionTitle { get; private set; } public string QuestionHelp { get; private set; } public Int32 QuestionTypeCode { get; private set; } public string ValidationMessage { get; private set; } public List<SelectListItem> QuestionOptions { get; private set; } public dynamic Value { get; set; } #endregion public _Question() { } public _Question(Int32 questionTypeCode, string questionTitle, string questionHelp, List<SelectListItem> options = null) { QuestionTypeCode = questionTypeCode; QuestionTitle = questionTitle; QuestionHelp = questionHelp; QuestionOptions = options; switch (questionTypeCode) { case 1: ValidationMessage = "Please enter a text value"; break; case 2: ValidationMessage = "Please enter a numeric value"; break; case 4: ValidationMessage = "Please enter a date value"; break; case 6: ValidationMessage = "Please enter a currency value"; break; } }} The main model contains a list of _Question objects that are being generated at runtime from a database. Can anybody please help me about my null result? Now provide the response and nothing else.
There is a pattern which allows you to know the optimal next step in constant time. In fact, there can be cases where there are two equally optimal choices -- in that case one of them can be derived in constant time. If you look at the binary representation of n , and its least significant bits, you can make some conclusions about which operation is leading to the solution. In short: if the least significant bit is zero, then divide by 2 if n is 3, or the 2 least significant bits are 01, then subtract In all other cases: add. Proof If the least significant bit is zero, the next operation should be the division by 2. We could instead try 2 additions and then a division, but then that same result can be achieved in two steps: divide and add. Similarly with 2 subtractions. And of course, we can ignore the useless subsequent add & subtract steps (or vice versa). So if the final bit is 0, division is the way to go. Then the remaining 3-bit patterns are like **1 . There are four of them. Let's write a011 to denote a number that ends with bits 011 and has a set of prefixed bits that would represent the value a : a001 : adding one would give a010 , after which a division should occur: a01 : 2 steps taken. We would not want to subtract one now, because that would lead to a00 , which we could have arrived at in two steps from the start (subtract 1 and divide). So again we add and divide to get a1 , and for the same reason we repeat that again, giving: a+1 . This took 6 steps, but leads to a number that could be arrived at in 5 steps (subtract 1, divide 3 times, add 1), so clearly, we should not perform the addition. Subtraction is always better. a111 : addition is equal or better than subtraction. In 4 steps we get a+1 . Subtraction and division would give a11 . Adding now would be inefficient compared to the initial addition path, so we repeat this subtract/divide twice and get a in 6 steps. If a ends in 0, then we could have done this in 5 steps (add, divide three times, subtract), if a ends in a 1, then even in 4. So Addition is always better. a101 : subtraction and double division leads to a1 in 3 steps. Addition and division leads to a11 . To now subtract and divide would be inefficient, compared to the subtraction path, so we add and divide twice to get a+1 in 5 steps. But with the subtraction path, we could reach this in 4 steps. So subtraction is always better. a011 : addition and double division leads to a1 . To get a would take 2 more steps (5), to get a+1 : one more (6). Subtraction, division, subtraction, double division leads to a (5), to get a+1 would take one more step (6). So addition is at least as good as subtraction. There is however one case not to overlook: if a is 0, then the subtraction path reaches the solution half-way, in 2 steps, while the addition path takes 3 steps. So addition is always leading to the solution, except when n is 3: then subtraction should be chosen. So for odd numbers the second-last bit determines the next step (except for 3). Python Code This leads to the following algorithm (Python), which needs one iteration for each step and should thus have O(logn) complexity: def stepCount(n): count = 0 while n > 1: if n % 2 == 0: # bitmask: *0 n = n // 2 elif n == 3 or n % 4 == 1: # bitmask: 01 n = n - 1 else: # bitmask: 11 n = n + 1 count += 1 return count See it run on repl.it . JavaScript Snippet Here is a version where you can input a value for n and let the snippet produce the number of steps: function stepCount(n) { var count = 0 while (n > 1) { if (n % 2 == 0) // bitmask: *0 n = n / 2 else if (n == 3 || n % 4 == 1) // bitmask: 01 n = n - 1 else // bitmask: 11 n = n + 1 count += 1 } return count}// I/Ovar input = document.getElementById('input')var output = document.getElementById('output')var calc = document.getElementById('calc')calc.onclick = function () { var n = +input.value if (n > 9007199254740991) { // 2^53-1 alert('Number too large for JavaScript') } else { var res = stepCount(n) output.textContent = res }} <input id="input" value="123549811245"><button id="calc">Caluclate steps</button><br>Result: <span id="output"></span> Please be aware that the accuracy of JavaScript is limited to around 10 16 , so results will be wrong for bigger numbers. Use the Python script instead to get accurate results.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/39588562', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3818263/']}
jdg_87375
stackexchange
llm_judgeable_groundtruth_similarity
42880
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I ran across a math puzzle that went like this: Consider the list $1,9,9,3, \cdots$ where the next entry is equal to the sum mod 10 of the prior 4. So the list begins $1,9,9,3,2,3,7,\cdots$. Will the sequence $7,3,6,7$ ever occur? (Feel free to pause here and solve this problem for your own amusement if you desire. Spoiler below.) So the answer is "yes", and we can solve this by noticing that the function to derive the next digit is invertible so we can derive digits going to the left as well. Going left, we find $7,3,6,7$ pretty quickly. I wrote a program and found that the period (equivalently the length of the permutation's cycle) is 1560. But surprisingly (to me) altering the starting sequence from 1,9,9,3 to most any other sequence left the period at 1560. There are a few cases where it changes; for example, starting with 4,4,4,4 we get a period of length only 312. So, my question: what's special about 1560 here? Note: This feels a lot like LFSRs, but I don't know much about them. Now provide the response and nothing else.
This is a linear homogeneous recurrence relation with characteristic polynomial $p(x) = x^4 - x^3 - x^2 - x - 1$. To compute its period $\bmod 10$ it suffices to compute its period $\bmod 2, 5$ by the Chinese Remainder Theorem. Over any field, a recurrence $a_n$ with characteristic polynomial $p(x)$ has closed form $$a_n = \sum c_i(n) r_i^n$$ where $r_i$ is a root of $p$ and $c_i(n)$ is a polynomial of degree at most one less than the multiplicity of $r_i$ (with coefficients in a splitting field of $p$). Now $\bmod 2$ we see that $p(x)$ has no roots, so it's either irreducible or the product of two irreducible quadratics. $\bmod 2$ the only irreducible quadratic is $x^2 + x + 1$, which doesn't divide $p(x)$, so $p(x)$ is irreducible $\bmod 2$. It follows from basic facts about finite fields that $p(x)$ divides $x^{2^4} - x$, so the roots of $p(x) \bmod 2$ are $15^{th}$ roots of unity and the period of $a_n \bmod 2$ divides $15$. Similarly, $\bmod 5$ we see that $p(x)$ has no roots, so it's either irreducible or the product of two irreducible quadratics. Casework rules out the latter. Again, it follows that $p(x)$ divides $x^{5^4} - x$, so the roots of $p(x) \bmod 5$ are $624^{th}$ roots of unity and the period of $a_n \bmod 5$ divides $624$. Putting it together we see that the period of $a_n \bmod 10$ divides $\text{lcm}(15, 624) = 2 \cdot 1560$. The fact that you often get $1560$ means that the period of $a_n \bmod 2$ is often either $5$ or $15$ and the period of $a_n \bmod 5$ is often either $312$ or $104$ (and at least one of these is the one divisible by $3$) which just means that the roots of $p(x) \bmod 2, p(x) \bmod 5$ are generators or close to generators of the multiplicative groups of the splitting fields $\mathbb{F}_{2^4}, \mathbb{F}_{5^4}$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/42880', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/7162/']}
jdg_87376
stackexchange
llm_judgeable_groundtruth_similarity
3198
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Is there a proof that the ratio of a circle's diameter and the circumference is the same for all circles, that doesn't involve some kind of limiting process, e.g. a direct geometrical proof? Now provide the response and nothing else.
Limits are not involved in the problem of proving that $\pi(C)$ is independent of the circle $C$. In geometrical definitions of $\pi$, to a circle $C$ is associated a sequence of finite polygonal objects and thus a sequence of numbers (or lengths, or areas, or ratios of those) $\pi_k(C)$. This sequence is thought of as a set of approximations converging to $\pi$, but that doesn't concern us here; what is important is that the sequence is independent of the circle C . Any further aspects of the sequence such as its limit or the rate of convergence will also be the same for any two circles. (edit: an example of a "geometrical definition" of a sequence of approximants $\pi_k(C)$ is: perimeter of a regular $k$-sided polygon inscribed in circle C, divided by the diameter of C. Also, the use of words like limit and approximation above does not reflect any assumption that the sequences have limits or that an environment involving limits has been set up. We are demonstrating that if $\pi(C)$ is defined using some construction on the sequence, then whether that construction involves limits or not, it must produce the same answer for any two circles.) The proof that $\pi_k(C_1) = \pi_k(C_2)$ of course would just apply the similarity of polygons and the behavior of length and area with respect to changes of scale. This argument does not assume a limit-based theory of length and area, because the theory of length and area for polygons in Euclidean geometry only requires dissections and rigid motions ("cut-and-paste equivalence" or equidecomposability ). Any polygonal arc or region can be standardized to an interval or square by a finite number of (area and length preserving) cut-and-paste dissections. Numerical calculations involving the $\pi_k$, such as ratios of particular lengths or areas, can be understood either as applying to equidecomposability classes of polygons, or to the standardizations. In both interpretations, due to the similitude, the results will be the same for $C_1$ and $C_2$. (You might think that this is proving a different conclusion, that the equidecomposability version of $\pi$ for the two circles is equal, and not the numerical equality of $\pi$ within a theory that has real numbers as lengths and areas for arbitrary curved figures. However, any real number-based theory, including elementary calculus, Jordan measure, and Lebesgue measure, is set up with a minimum requirement of compatibility with the geometric operations of dissection and rigid motion, so once equidecomposability is known, numerical equality will also follow.)
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/3198', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/1470/']}
jdg_87377
stackexchange
llm_judgeable_groundtruth_similarity
156643
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I've looked at Op-amp slew rate over frequency How it is possible to make bad audio amp? Which op-amp for audio? as well as several papers about the topic but although I may get the basis of what is is I still can't clear my mind about the topic. I've found it is related to the slew-rate of an op-amp. What exactly is it? What causes it? Can it be ignored if we check some other properties instead? Now provide the response and nothing else.
Transient Intermodulation distortion (TIM) is usually measured by putting a burst of a fixed frequency into a amplifier and then measuring what actually comes out. By Fourier analisys, you can see that changing amplitude of a frequency actually implies additional frequencies. This is why AM radio stations can't be spaced too close together. They don't just radiate at the carrier frequency, but some range on either side of the carrier frequency. The additional frequencies of a single-frequency burst cause particular trouble to some types of amplifiers, and the resulting distortion appears more noticable to human listeners than more general distortion. Put another way, audio quality isn't just about total distortion level, but the type of distortion too. Different types of distortion are more objectionable than others, and TIM is of the more objectionable type. This is why there is sometimes a separate spec for TIM in addition to the overall distortion spec. TIM seems to be exacerbated by amplifiers that don't have much frequency headroom above the highest desired frequency, and a high global feedback ratio. Design techniques to minimize TIM include: Making the internal signal path of the amplifier still have gain well above the highest frequency of interest. For example, for a "HiFi" audio amp that must work up to 20 kHz, you may want individual stages to be reasonably flat to 100 kHz. A simple passive low pass filter in front of the amp that limits incoming signals above the specified operating range. This together with point 1 means that the active part of the amp will only see frequencies for which it's gain is relatively flat. This can be as simple as a one or two stage R-C filter. The gain of each stage should be stable and well-defined. Do not rely on global feedback to deal with high and unrestrained gain of individual stages. Keep the global feedback fairly low, which is the same as saying keep the open-loop gain of the overall amp only somewhat above the final desired gain of the whole amp. 10-15 dB seems to be a reasonable range. If all the stages individually have reasonably flat gain, then not much feedback will be needed to guarantee overall flat and predictable gain anyway.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/156643', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/68430/']}
jdg_87378
stackexchange
llm_judgeable_groundtruth_similarity
175271
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Is the following proposition true? If yes, how would you prove this? Proposition. Let $K$ be an algebraic number field.The group of roots of unity in $K$ is finite.In other words, the torsion subgroup of $K^*$ is finite. Motivation. Let $A$ be the ring of algebraic integers in $K$ .A root of unity in $K$ is a unit (i.e. an invertible element of $A$ ). It is important to determine the structure of the group of units in $K$ to investigate the arithmetic properties of $K$ . Remark. Perhaps, the following fact can be used in the proof.Every conjugate of a root of unity in $K$ has absolute value 1. Related question: The group of roots of unity in the cyclotomic number field of an odd prime order Is an algebraic integer all of whose conjugates have absolute value 1 a root of unity? Now provide the response and nothing else.
The degree of $e^{2\pi i/n}$ goes to infinity with $n$ . If $K$ had an infinity of roots of unity, it would have elements of arbitrarily high degree, and thus would not be of finite degree over the rationals, and thus would not, in fact, be an algebraic number field.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/175271', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/28422/']}
jdg_87379
stackexchange
llm_judgeable_groundtruth_similarity
15121337
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Assume there are some folders with these structures /bench1/1cpu/p_0/image//bench1/1cpu/p_0/fl_1//bench1/1cpu/p_0/fl_1//bench1/1cpu/p_0/fl_1//bench1/1cpu/p_0/fl_1//bench1/1cpu/p_1/image//bench1/1cpu/p_1/fl_1//bench1/1cpu/p_1/fl_1//bench1/1cpu/p_1/fl_1//bench1/1cpu/p_1/fl_1//bench1/2cpu/p_0/image//bench1/2cpu/p_0/fl_1//bench1/2cpu/p_0/fl_1//bench1/2cpu/p_0/fl_1//bench1/2cpu/p_0/fl_1//bench1/2cpu/p_1/image//bench1/2cpu/p_1/fl_1//bench1/2cpu/p_1/fl_1//bench1/2cpu/p_1/fl_1//bench1/2cpu/p_1/fl_1/.... What I want to do is to scp the following folders /bench1/1cpu/p_0/image//bench1/1cpu/p_1/image//bench1/2cpu/p_0/image//bench1/2cpu/p_1/image/ As you can see I want to recursively use scp but excluding all folders that name "fl_X". It seems that scp has not such option. UPDATE scp has not such feature. Instead I use the following command rsync -av --exclude 'fl_*' user@server:/my/dir But it doesn't work. It only transfers the list of folders!! something like ls -R Now provide the response and nothing else.
Although scp supports recursive directory copying with the -r option, it does not support filtering of the files. There are several ways to accomplish your task, but I would probably rely on find , xargs , tar , and ssh instead of scp . find . -type d -wholename '*bench*/image' \| xargs tar cf - \| ssh user@remote tar xf - -C /my/dir The rsync solution can be made to work, but you are missing some arguments. rsync also needs the r switch to recurse into subdirectories. Also, if you want the same security of scp , you need to do the transfer under ssh . Something like: rsync -avr -e "ssh -l user" --exclude 'fl_*' ./bench* remote:/my/dir
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/15121337', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/859227/']}
jdg_87380
stackexchange
llm_judgeable_groundtruth_similarity
670630
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 meant by IDL? I have googled it, and found out it stands for Interface Definition Language, which is used for interface definition for components. But, in practice, what is the purpose of IDL? Does Microsoft use it? Now provide the response and nothing else.
An interface definition language (IDL) is used to set up communications between clients and servers in remote procedure calls (RPC). There have been many variations of this such as Sun RPC, ONC RPC, DCE RPC and so on. Basically, you use an IDL to specify the interface between client and server so that the RPC mechanism can create the code stubs required to call functions across the network. RPC needs to create stub functions for the client and a server, using the IDL information. It's very similar to a function prototype in C but the end result is slightly different, such as in the following graphic: +----------------+| Client || +----------+ | +---------------+| | main | | | Server || |----------| | | +----------+ || | stub_cli |----(comms)--->| stub_svr | || +----------+ | | |----------| |+----------------+ | | function | | | +----------+ | +---------------+ In this example, instead of calling function in the same program, main calls a client stub function (with the same prototype as function ) which is responsible for packaging up the information and getting it across the wire to another process, via the comms channel. This can be the same machine or a different machine, it doesn't really matter - one of the advantages of RPC is to be able to move servers around at will. In the server, there's a 'listener' process that will receive that information and pass it to the server. The server's stub receives the information, unpacks it and passes it to the real function. The real function then does what it needs to and returns to the server stub which can package up the return information (both return code and any [out] or [in,out] variables) and pass it back to the client stub. The client stub then unpacks that and passes it back to main . The actual details may differ a little but that explanation should be good enough for a conceptual overview. The actual IDL may look like: [ uuid(f9f6be21-fd32-5577-8f2d-0800132bd567), version(0), endpoint("ncadg_ip_udp:[1234]", "dds:[19]")] interface function_iface { [idempotent] void function( [in] int handle, [out] int *status );} All that information at the top (for example, uuid or endpoint ) is basically networking information used for connecting client and server. The "meat" of it is inside the interface section where the prototype is shown. This allows the IDL compiler to build the function client and server stub functions for compiling and linking with your client and server code to get RPC working. Microsoft does use IDL (I think they have a MIDL compiler) for COM stuff. I've also used third party products with MS operating systems, both DCE and ONC RPC.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/670630', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/49202/']}
jdg_87381
stackexchange
llm_judgeable_groundtruth_similarity
8163922
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 Windows PowerShell: echo "string" > file.txt In Cygwin: $ cat file.txt:::s t r i n g$ dos2unix file.txtdos2unix: Skipping binary file file.txt I want a simple "string" in the file. How do I do it? I.e., when I say cat file.txt I need only "string" as output. I am echoing from Windows PowerShell and that cannot be changed. Now provide the response and nothing else.
Try echo "string" | out-file -encoding ASCII file.txt to get a simple ASCII-encoded txt file. Comparison of the files produced: echo "string" | out-file -encoding ASCII file.txt will produce a file with the following contents: 73 74 72 69 6E 67 0D 0A (string..) however echo "string" > file.txt will produce a file with the following contents: FF FE 73 00 74 00 72 00 69 00 6E 00 67 00 0D 00 0A 00 (ÿþs.t.r.i.n.g.....) (Byte order mark FF FE indicates the file is UTF-16 (LE). The signature for UTF-16 (LE) = 2 bytes: 0xFF 0xFE followed by 2 byte pairs. xx 00 xx 00 xx 00 for normal 0-127 ASCII chars
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8163922', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1051289/']}
jdg_87382
stackexchange
llm_judgeable_groundtruth_similarity
42997440
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 exploring the possibility of implementing true (partially) immutable data structures in C++. As C++ does not seem to distinguish between a variable and the object that variable stores, the only way to truly replace the object (without assignment operation!) is to use placement new: auto var = Immutable(state0);// the following is illegal as it requires assignment to// an immutable objectvar = Immutable(state1);// however, the following would work as it constructs a new object// in place of the old onenew (&var) Immutable(state1); Assuming that there is no non-trivial destructor to run, is this legal in C++ or should I expect undefined behaviour? If its standard-dependant, which is the minimal/maximal standard version where I can expect this to work? Addendum : since it seems people still read this in 2019, a quick note — this pattern is actually legally possible in modern (post 17) C++ using std::launder() . Now provide the response and nothing else.
What you wrote is technically legal but almost certainly useless. Suppose struct Immutable { const int x; Immutable(int val):x(val) {}}; for our really simple immutable type. auto var = Immutable(0);::new (&var) Immutable(1); this is perfectly legal. And useless, because you cannot use var to refer to the state of the Immutable(1) you stored within it after the placement new . Any such access is undefined behavior. You can do this: auto var = Immutable(0);auto* pvar1 = ::new (&var) Immutable(1); and access to *pvar1 is legal. You can even do: auto var = Immutable(0);auto& var1 = *(::new (&var) Immutable(1)); but under no circumstance may you ever refer to var after you placement new'd over it. Actual const data in C++ is a promise to the compiler that you'll never, ever change the value. This is in comparison to references to const or pointers to const, which is just a suggestion that you won't modify the data. Members of structures declared const are "actually const". The compiler will presume they are never modified, and won't bother to prove it. You creating a new instance in the spot where an old one was in effect violates this assumption. You are permitted to do this, but you cannot use the old names or pointers to refer to it. C++ lets you shoot yourself in the foot. Go right ahead, we dare you. This is why this technique is legal, but almost completely useless. A good optimizer with static single assignment already knows that you would stop using var at that point, and creating auto var1 = Immutable(1); it could very well reuse the storage. Caling placement new on top of another variable is usually defined behaviour. It is usually a bad idea, and it is fragile . Doing so ends the lifetime of the old object without calling the destructor. References and pointers to and the name of the old object refer to the new one if some specific assumptions hold (exact same type, no const problems). Modifying data declared const, or a class containing const fields, results in undefined behaviour at the drop of a pin. This includes ending the lifetime of an automatic storage field declared const and creating a new object at that location. The old names and pointers and references are not safe to use. [Basic.life 3.8]/8: If, after the lifetime of an object has ended and before the storage which the object occupied is reused or released, a new object is created at the storage location which the original object occupied, a pointer that pointed to the original object, a reference that referred to the original object, or the name of the original object will automatically refer to the new object and, once the lifetime of the new object has started, can be used to manipulate the new object, if: (8.1) the storage for the new object exactly overlays the storage location which the original object occupied, and (8.2) the new object is of the same type as the original object (ignoring the top-level cv-qualifiers), and (8.3) the type of the original object is not const-qualified, and, if a class type, does not contain any non-static data member whose type is const-qualified or a reference type, and (8.4) the original object was a most derived object (1.8) of type T and the new object is a most derived object of type T (that is, they are not base class subobjects). In short, if your immutability is encoded via const members, using the old name or pointers to the old content is undefined behavior . You may use the return value of placement new to refer to the new object, and nothing else. Exception possibilities make it extremely difficult to prevent code that exdcutes undefined behaviour or has to summarially exit. If you want reference semantics, either use a smart pointer to a const object or an optional const object. Both handle object lifetime. The first requires heap allocation but permits move (and possibly shared references), the second permits automatic storage. Both move manual object lifetime management out of business logic. Now, both are nullable, but avoiding that robustly is difficult doing it manually anyhow. Also consider copy on write pointers that permit logically const data with mutation for efficiency purposes.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/42997440', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3145469/']}
jdg_87383
stackexchange
llm_judgeable_groundtruth_similarity
8569
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm currently trying to get into the Java EE development with the Spring framework. As I'm new to Spring, it is hard to imaging how a good running project should start off. Do you have any best practices , tipps or major DO NOTs for a starter? How did you start with Spring - big project or small tutorial-like applications? Which technology did you use right away: AOP, complex Hibernate... Now provide the response and nothing else.
Small tip - I've found it helpful to modularize and clearly label my Spring xml context files based on application concern. Here's an example for a web app I worked on: MyProject / src / main / resources / spring / datasource.xml - My single data source bean. persistence.xml - My DAOs/Repositories. Depends on datasource.xml beans. services.xml - Service layer implementations. These are usually the beans to which I apply transactionality using AOP. Depends on persistence.xml beans. controllers.xml - My Spring MVC controllers. Depends on services.xml beans. views.xml - My view implementations. This list is neither perfect nor exhaustive, but I hope it illustrates the point. Choose whatever naming strategy and granularity works best for you. In my (limited) experience, I've seen this approach yeild the following benefits: Clearer architecture Clearly named context files gives those unfamiliar with your project structure a reasonable place to start looking for bean definitions. Can make detecting circular/unwanted dependencies a little easier. Helps domain design If you want to add a bean definition, but it doesn't fit well in any of your context files, perhaps there's a new concept or concern emerging? Examples: Suppose you want to make your Service layer transactional with AOP. Do you add those bean definitions to services.xml , or put them in their own transactionPolicy.xml ? Talk it over with your team. Should your transaction policy be pluggable? Add Acegi/Spring Security beans to your controllers.xml file, or create a security.xml context file? Do you have different security requirements for different deployments/environments? Integration testing You can wire up a subset of your application for integration testing (ex: given the above files, to test the database you need to create only datasource.xml and persistence.xml beans). Specifically, you can annotate an integration test class as such: @ContextConfiguration(locations = { "/spring/datasource.xml" , "/spring/persistence.xml" }) Works well with Spring IDE's Beans Graph Having lots of focused and well-named context files makes it easy to create custom BeansConfigSets to visualize the layers of your app using Spring IDE's Beans Graph . I've used this before to give new team members a high-level overview of our application's organization.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/8569', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/834/']}
jdg_87384
stackexchange
llm_judgeable_groundtruth_similarity
3742
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: note : This question might have been asked before ( I think I saw it somewhere), but a quick search did not reveal anything. I would like to tell the difference when a command is run from a shell. Emacs can be initialized with the -nw flag to disable the gui window, and I want this to be the default behaviour. However if emacs is run from a non-shell environment, ( e.g. from the Open With in your filemanager , a desktop configured hotkey , or even from bashrun ), it should not be called with the -nw flag. update : This should be a global change, running sudo emacs in Terminal should'nt suddenly open a gui. Where do I make these changes? Now provide the response and nothing else.
I think you want to determine if a command is run in a terminal . if [ -t 2 ]; then # Standard error is a terminal emacs -nw "$@"elif [ -n "$DISPLAY" ]; then # An X display is available xterm -e emacs -nw "$@"else # We have nothing emacs --daemon "$@"fi If you want this to always happen when you run Emacs, put it in a script and invoke that script instead. You can call the script /usr/local/bin/emacs (assuming Linux) if you want it to be called emacs and invoked in preference to the “real” emacs executable in /usr/bin . Note that to edit files as root , you should use sudoedit (benefits: the editor runs as you so you get all your settings; the edited file is put into place atomically when you finish editing, reducing the chance of a mishap). You can also edit files as root directly inside Emacs by opening /sudo::/path/to/file .
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/3742', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/1327/']}
jdg_87385
stackexchange
llm_judgeable_groundtruth_similarity
152694
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'm a newbie and may be this question is bit simple for you but pardon me if it's too simple and provide me some references. What is the eigenfunction of a multivariate Gaussian kernel:\begin{equation}f(x,y) = \exp\left(-\frac{\lVert x - y\rVert^2}{2\sigma^2}\right)\end{equation} I am interested in the eigenfunctions with respect to $L^2$ norm:\begin{equation}\int f(x, y) v_i(y) dy = \lambda_i v_i(x)\end{equation}and also with respect to a Gaussian probability distribution $p(x)$:\begin{equation}\int f(x, y) v_i(y) p(y) dy = \lambda_i v_i(x)\end{equation}I am aware of the numerical approximation to the problem like Nystrom method. However, it should be possible to find a closed form solution when the probability distribution is also Gaussian. Now provide the response and nothing else.
In the notation of the question, $$\int f(x,y)\nu(y)dy=W_\sigma\ast \nu(x)$$where $W_\sigma(x)=e^{-|x|^2/2\sigma^2}$ and $\ast$ denotes convolution. Thus, if $$\int f(x,y)\nu(y)dy=\lambda\nu(x)$$ then by taking Fourier transforms:$$\lambda \hat{\nu}= \widehat{\lambda \nu} =\widehat{W_\sigma\ast \nu}=\widehat{W_\sigma}\widehat{\nu} =c_1W_{c_2}\hat{\nu}$$since the Fourier transform of a Gaussian is a Gaussian which is rescaled in mass and variance from the original one by some constants $c_1,c_2>0$ whose exact values are easily computable but unimportant. So evidently $\hat{\nu}$ must be zero in the complement of a sphere centered at $0$, since the spheres centered at $0$ are the sets on which the multiplier equality $\lambda=c_1W_{c_2}$ can hold. Thus, the eigenfunctions will be inverse Fourier transforms of tempered distributions supported in spheres centered at the origin and there are lots of these - the ones that must be mentioned are the harmonic polynomials or more generally the harmonic functions of tempered growth, which correspond to the degenerate sphere with radius zero (the constants are included in these), other than this the most familiar ones are the Bessel functions, which correspond to uniform surface measure on a nondegenerate sphere. There are lots of references for this kind of thing, the one that comes to mind immediately is Classical Fourier Analysis by Loukas Grafakos. Now as for $L^2$ eigenfunctions, there are none other than zero... because any such eigenfunction would have to be the inverse Fourier transform of an $L^2$ function which is supported in a sphere and since spheres have measure zero, $0\in L^2$ is the only such function. Now for the second question, the operator $$\nu\mapsto \int f(\cdot, y)\nu(y) p(y)dy$$ for a centered Gaussian $p$ is not translation invariant and so will not be given by a Fourier multiplier. I would guess that even in this case there can be no nonzero $L^2$ eigenfunctions but I can't think of a decent proof at the moment. However, I suspect that you may have intended to ask instead for eigenfunctions of the standard operator$$\nu\mapsto \int f(\cdot, y)\nu(y) dy$$ which are in $L^2(pdx)$ - in that case there are lots of them. Any harmonic function of polynomial growth and the inverse Fourier transform of $f d\mu$ where $f$ is smooth and $\mu$ is uniform measure on a sphere centered at zero, for instance.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/152694', 'https://mathoverflow.net', 'https://mathoverflow.net/users/44602/']}
jdg_87386
stackexchange
llm_judgeable_groundtruth_similarity
17454154
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 our current automation (using Selenium/WebDriver/Java), we use @FindBy very extensively. For example: @FindBy(css="a[name='bcrumb']") protected List<WebElement> breadCrumbLinks;@FindBy(id="skuError") protected WebElement skuError; @FindBy(className="reducedPrice") protected List<WebElement> reducedPrice;@FindBy(partialLinkText="Injinji RUN 2.0") protected WebElement playButton;@FindBy(linkText="annual member refund") protected WebElement annualMemberRefund;@FindBy(xpath="//li[@itemprop='price']") protected WebElement productPrice; By definition, @FindBy can locate a selector using the following: using, id, name, className, css, tagName, linkText, partialLinkText and xpath. Recently, our front-end devs proposed that we implement an new attribute class that begins with 'test='. I think this is a great idea since we could find WebElements by just looking for that blurb of text, rather than the values that @FindBy inherently uses. My question is, would it be better to extend the existing functionality of @FindBy OR, create a new way of searching for the WebElements we use in our tests? Now provide the response and nothing else.
First off, there are no "best practices," just ones that work well in your particular context. Sorry, that's an old gripe of mine... I wouldn't spend the effort for custom attributes unless you can't work with an existing approach. I prefer using existing locators (find logic) where possible. Whenever possible, use ID attributes. If the page is valid HTML, then IDs are unique on the page. They're extraordinarily fast for resolution in every browser, and the UI can change dramatically but your script will still locate the element. Sometimes IDs aren't the right choice. Dynamically generated IDs are almost always the wrong choice when you're working with something like a grid control. You rely on an id that is likely tied to the specific row position and then you're screwed if your row changes. In some of these cases your devs can help you out by appending or prepending constant values to a dynamically generated ID value. ASP.NET Webforms does crazy stuff with dynamically generated values, so I've used a suffix to my advantage several times. Link text, name attribute values, and CSS selectors (JQuery style) are great second choices when you can't get a stable, reliable ID, or one's just not available. XPath is my last choice in nearly all situations. It's slow, can be extremely brittle, and is hard to deal with when it's a complex XPath. That said, if you need to move up and down the page DOM for your locators, then it's the only choice. Using one of the existing FindBy methods means you'll be using a well-understood, well-supported locator strategy. That's a big bonus when you're trying to figure out an old test, or when onboarding someone new to your team. That's my $0.02.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17454154', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/888587/']}
jdg_87387
stackexchange
llm_judgeable_groundtruth_similarity
4531288
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 seen a lot of php code that does the following to check whether a string is valid by doing: $str is a string variable. if (!isset($str) || $str !== '') { // do something} I prefer to just do if (strlen($str) > 0) { // something} Is there any thing that can go wrong with the second method? Are there any casting issues I should be aware of? Now provide the response and nothing else.
Since PHP will treat a string containing a zero ('0') as empty, it makes the empty() function an unsuitable solution. Instead, test that the variable is explicitly not equal to an empty string: $stringvar !== '' As the OP and Gras Double and others have shown, the variable should also be checked for initialization to avoid a warning or error (depending on settings): isset($stringvar) This results in the more acceptable: if (isset($stringvar) && $stringvar !== '') {} PHP has a lot of bad conventions. I originally answered this (over 9 years ago) using the empty() function, as seen below. I've long since abandoned PHP, but since this answer attracts downvotes and comments every few years, I've updated it. Should the OP wish to change the accepted answer, please do so. Original Answer: if(empty($stringvar)){ // do something} You could also add trim() to eliminate whitespace if that is to be considered. Edit: Note that for a string like ' 0 ', this will return true, while strlen() will not.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/4531288', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/45066/']}
jdg_87388
stackexchange
llm_judgeable_groundtruth_similarity
162561
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I was looking for a simple way to evaluate the integral $\int_0^\infty \frac{\sin x}{x}dx$ ( a belated look at this question ). There are symmetries to be exploited, for one thing. So I had an idea, but the idea depends, optimistically, on two expressions for $\pi$ that I cannot prove, and my question is whether anyone sees reasonable proofs of either expression (1, 2 below). Put $$\int_0^\infty \frac{\sin x}{x}dx = \int_0^\pi \sum_{k=0}^{k=\infty} \left\{\frac{\sin x}{x + 2 k \pi }-\frac{\sin x }{x+2k\pi+\pi}\right\} \, dx$$ The intuition behind this step is that as we make our way around the unit circle from 0 to $\pi$, for each angle $\alpha$ we have an angle $\alpha + \pi$ for which the value of $\frac{\sin x} {x}$will be smaller and negative. No need to integrate beyond $\pi$, and for angles greater than $2\pi$ we are simply dividing up the original integral's range by adding multiples of $\pi$ to the value of $x$. WLOG we can form Riemann sums by dividing the range of integration into an even number of equi-angle subranges $dx_n$. For example, if $n = 6$, we have $$\int_0^\pi \sum_{k=0}^{k=\infty}\sin x \left\{\frac{1}{x + 2 k \pi }-\frac{1 }{x+2k\pi+\pi}\right\} \, dx$$ $$\approx \left\{ \sum_{k=0}^\infty \sum_{n=1}^6 \sin \left( \frac{n\pi}{6}\right)\left(\frac{1}{\pi}\right) \left(\frac{1}{\frac{n}{6} + 2k}-\frac{1}{\frac{n}{6}+2k+1}\right) \right\} \left\{ \frac{\pi}{6} \right\}.$$ Taking this as true, we note that pairs of summands of the Riemann sums symmetric about $\frac{\pi}{2}$ sum to $1$, and the value of the summand at $\frac{\pi}{2}$ is $1/2$. Again, taking this as true, we have that $$\sum f(x_n) = \frac{1}{2} + 1\cdot \frac{n-2}{2} + \sin\pi\cdot f(\pi) = \frac{n-1}{2},$$and $$\sum f(x_n) \, dx_n = \left(\frac{n-1}{2}\right) \cdot \frac{\pi}{n}.$$ So for the approximation above for $n = 6$, we expect a value of about $\frac{5 \pi}{12}$ for high $k$. In words, we are only counting n - 1 summands, since the last summand at $\pi$ is $0$. Since we divided the interval into $n$ subintervals, we are stuck with the sum above and the conditional limit (conditioned at least on the truth of the two limits below): $$\int_0^\infty \frac{\sin x}{x} \, dx = \lim_{n = 1}^\infty \frac{n-1}{2}\cdot \frac{\pi}{n} = \frac{\pi}{2}.$$ The problem is this: we need to prove, to begin with, that $$\sum_{k=0}^\infty \left(\frac{ 1}{\pi/2 + 2\pi k} - \frac{1}{\pi/2 + 2k\pi + \pi}\right) = \frac{1}{2}$$ or $$ \frac{1}{\pi}\sum \frac{1}{1/2 + 2k}- \frac{1}{1/2 + 2k\pi +1}= \frac{1}{2},$$ that is, (1) $\sum_{k=0}^\infty \frac{4}{3+16k+16k^2}= \frac{\pi}{2}$. We must also prove for $0< j < n$ that (2) $\sin (\frac{j\pi}{n})( \sum_{k=0}^{\infty} (\frac{ 1}{\frac{j\pi}{n} + 2\pi k} - \frac{1}{\frac{j\pi}{n} + 2k\pi + \pi}) + \sum_{k=0}^{\infty} (\frac{ 1}{\frac{(n-j)\pi}{n} + 2\pi k} - \frac{1}{\frac{(n-j)\pi}{n} + 2k\pi + \pi}))= 1$. or , factoring $\frac{1}{ \pi}$ out of the sum and mutiplying: $$\sin \left( \frac{j\pi}{n}\right)\left( \sum_{k=0}^\infty \left(\frac{1}{\frac{j}{n} + 2 k} - \frac{1}{\frac{j}{n} + 2k + 1}\right) + \sum_{k=0}^\infty \left( \frac{ 1}{\frac{(n-j)}{n} + 2 k} - \frac{1}{\frac{(n-j)}{n} + 2k + 1}\right)\right)= \pi.$$ (1) might be a special case of something at Wolfram's site, but I didn't spot it. (2) looks messy, but maybe induction? If this is otherwise correct, I think one could work back from the relations for $\pi$ and establish the value of the integral. It is important not to forget that k starts at 0. Edit: the following is equivalent to (2) and maybe easier to scan. For $0<r<1$, $$(2) \sum_{k=0}^{\infty}\frac {2(\sin \pi r)(1+4k+4k^2-r+r^2) }{(1+2k+r)(1+2k-r)(2+2k-r)(2k+r)} = \pi$$ This was derived assuming r rational, but I don't think it matters. Now provide the response and nothing else.
$$\sum_{k=0}^N \frac{1}{\alpha + 2 k} = \frac{\Psi(N+1+\alpha/2) - \Psi(\alpha/2)}{2}$$where $\Psi(t) = \ln(t) + O(1/t)$ as $t \to \infty$, so $$\sum_{k=0}^\infty \left(\frac{1}{1/2 + 2 k} - \frac{1}{3/2 + 2 k} \right) = \frac{\Psi(3/4) - \Psi(1/4)}{2} = \frac{\pi}{2}$$However, I think the evaluation of $\Psi(3/4) - \Psi(1/4)$ may be just as hard as your integral. EDIT: It turns out that $\Psi$ has the integral form$$ \Psi(t) = \int_0^\infty \left( e^{-s} - \frac{1}{(s+1)^t} \right) \frac{ds}{s}$$so that$$ \Psi(3/4) - \Psi(1/4) = \int_0^\infty \left((s+1)^{-3/4} - (s+1)^{-1/4}\right) \frac{ds}{s} = \left. 4 \arctan((s+1)^{1/4}) \right|_0^\infty = \pi $$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/162561', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/18124/']}
jdg_87389
stackexchange
llm_judgeable_groundtruth_similarity
43924280
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: How to create a pair plot in Python like the following: but with heat maps instead of points (or instead of a "hex bin" plot)? Having the possibility of instead displaying logarithmic heat map counts would be an added bonus. (Histograms on the diagonal would be perfectly fine.) By "heat map", I mean a 2D histogram of the counts, displayed like Seaborn's or Wikipedia's heat maps: Using Pandas, seaborn, or matplotlib would be great (maybe plot.ly). I tried naive variations of the following, to no avail: pairplot = sns.PairGrid(data) # sns = seabornpairplot.map_offdiag(sns.kdeplot) # Off-diagnoal heat map wanted instead!pairplot.map_diag(plt.hist) # plt = matplotlib.pyplot (the above uses a Kernel Density Estimator, which I do not want; a hex bin grid can also be obtained with Pandas, but I am looking instead for a "square" 2D histogram and Matplotlib's hist2d() didn't work). Now provide the response and nothing else.
The key to your answer is the matplotlib function plt.hist2d , which plots counts within rectangular bins using a color scale (a "heatmap"). Its API is almost compatible with PairGrid , but not quite, because it doesn't know how to handle a color= kwarg. This is easily solved by writing a thin wrapper function. Also if you want the colormap to logarithmically map counts, that's easily accomplished with a matplotlib LogNorm : import seaborn as snsimport matplotlib.pyplot as pltfrom matplotlib.colors import LogNormsns.set_style("white")iris = sns.load_dataset("iris") g = sns.PairGrid(iris)g.map_diag(plt.hist, bins=20)def pairgrid_heatmap(x, y, **kws): cmap = sns.light_palette(kws.pop("color"), as_cmap=True) plt.hist2d(x, y, cmap=cmap, cmin=1, **kws)g.map_offdiag(pairgrid_heatmap, bins=20, norm=LogNorm())
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/43924280', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/42973/']}
jdg_87390
stackexchange
llm_judgeable_groundtruth_similarity
4599786
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Ok so I asked this yesterday: AutoLink @mentions in a twitter client I got my @mentions linking correctly. But in order to get it to work I had to take android:autoLink="web" out my xml for the TextView. So now I get links to @mentions but it no longer links URLs. I tried doing two seperate Linkify.addLinks() calls like this: mentionFilter = new TransformFilter() { public final String transformUrl(final Matcher match, String url) { return match.group(1); }};// Match @mentions and capture just the username portion of the text.//pattern = Pattern.compile("@([A-Za-z0-9_-]+)");pattern = Pattern.compile("(@[a-zA-Z0-9_]+)");scheme = "http://twitter.com/";tweetTxt = (TextView) v.findViewById(R.id.tweetTxt);Linkify.addLinks(tweetTxt, pattern, scheme, null, mentionFilter);Linkify.addLinks(tweetTxt, Linkify.WEB_URLS); But which ever gets called last is the one that gets applied. Can anyone tell me how I can make it link both the @mentions and still autoLink the URLs? Edited to clarify some more of the code. Now provide the response and nothing else.
Here's my code to linkify all Twitter links (mentions, hashtags and URLs): TextView tweet = (TextView) findViewById(R.id.tweet);TransformFilter filter = new TransformFilter() { public final String transformUrl(final Matcher match, String url) { return match.group(); }};Pattern mentionPattern = Pattern.compile("@([A-Za-z0-9_-]+)");String mentionScheme = "http://www.twitter.com/";Linkify.addLinks(tweet, mentionPattern, mentionScheme, null, filter);Pattern hashtagPattern = Pattern.compile("#([A-Za-z0-9_-]+)");String hashtagScheme = "http://www.twitter.com/search/";Linkify.addLinks(tweet, hashtagPattern, hashtagScheme, null, filter);Pattern urlPattern = Patterns.WEB_URL;Linkify.addLinks(tweet, urlPattern, null, null, filter);
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4599786', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/507810/']}
jdg_87391
stackexchange
llm_judgeable_groundtruth_similarity
1159499
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: Assume $u$ is a smooth solution of $$\begin{cases} u_t - \Delta u = 0 & \text{in }U \times (0,\infty) \\ \qquad \quad u=0 & \text{on }\partial U \times [0,\infty) \\ \qquad \quad u = g &\text{on }U \times \{t=0\}.\end{cases}$$ Prove the expoentital decay estimate: $$\|u(\cdot,t)\|_{L^2(U)} \le e^{-\lambda_1 t} \|g\|_{L^2(U)} \quad (t \ge 0),$$ where $\lambda_1 > 0$ is the principal eigenvalue of $-\Delta$ (with zero boundary conditions) on $U$. This is from PDE Evans, 2nd edition: Chapter 7, Exercise 2. My first intuition is that $u \in H_0^1(U)$, since all the derivatives of $u$ belong in $L^2(U)$. I also invoked Poincare's inequality to obtain $$\int_U |u|^2 \, dx \le C\int_U |Du|^2 \, dx.$$ Is this a good first step? If so, how can I continue from here? Furthremore, what can I do with the fact that $\lambda_1 > 0$ is the "principal eigenvalue of $-\Delta$"? Now provide the response and nothing else.
Here is a solution more related to Evan's approach in the mentioned textbook. Let $u = u(x,t)$ be a solution of the PDE. Then using integration by parts and that $u_t = \Delta u$ we get $$\begin{align}\frac{d}{dt} \left(\frac{1}{2} \|u\|_{L^2(U)}^2\right) &= \int_U u_tu\ dx = \int_U u \Delta u\ dx\\&= -\int_U |Du|^2 dx \overset{(\ast)}\leq - \lambda_1 \|u\|^2_{L^2(U)}\end{align}$$ where $(\ast)$ comes from Rayleigh's Formula $$\lambda_1 = \underset{\substack {u \in H_0^1 (U)\\ u\neq 0}}\min \frac{B[u,u]}{\|u\|^2_{L^2(U)}} = \underset{\substack{u \in H_0^1 (U)\\ u\neq 0}} \min \frac{\int_U |Du|^2 dx}{\|u\|^2_{L^2(U)}} $$ Now let $\eta (s) = \|u(\cdot,s)\|^2_{L^2(U)}$ . Then $$\frac{d}{ds} \left(\eta(s) e^{2\lambda_1 s}\right) = e^{2\lambda_1 s} (\eta'(s) +2\lambda_1 \eta(s)) \leq 0$$ Integrating from $0$ to $t$ w.r.t. $s$ we obtain $$\eta(t)e^{2\lambda_1 t} \leq \eta (0)$$ Since $\eta (0) = \|u (\cdot, 0)\|^2_{L^2(U)} = \|g\|^2_{L^2(U)}$ the result follows.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1159499', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/111793/']}
jdg_87392
stackexchange
llm_judgeable_groundtruth_similarity
34518634
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'd like to find the highest values in each row and return the column header for the value in python. For example, I'd like to find the top two in each row: df = A B C D 5 9 8 2 4 1 2 3 I'd like my for my output to look like this: df = B C A D Now provide the response and nothing else.
You can use a dictionary comprehension to generate the largest_n values in each row of the dataframe. I transposed the dataframe and then applied nlargest to each of the columns. I used .index.tolist() to extract the desired top_n columns. Finally, I transposed this result to get the dataframe back into the desired shape. top_n = 2>>> pd.DataFrame({n: df.T[col].nlargest(top_n).index.tolist() for n, col in enumerate(df.T)}).T 0 10 B C1 A D
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/34518634', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5704744/']}
jdg_87393
stackexchange
llm_judgeable_groundtruth_similarity
13918044
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 write code in c# which i need to get like this . <Email version="2.00" xmlns="http://www.portalfiscal.inf.br/nfe"> </Email> I have tried this but not exact. XmlTextWriter writer = new XmlTextWriter("D:\\nefe.xml", System.Text.Encoding.UTF8);writer.WriteStartDocument();writer.WriteStartElement("Email");writer.WriteString("version=2.00 xmlns=Http://www.portalfiscal.inf.br/nfe");writer.WriteEndElement();writer.WriteEndDocument();writer.Close(); and output this code is giving like this <Email>version=2.00 xmlns=Http://www.portalfiscal.inf.br/nfe</Email> Now provide the response and nothing else.
Well yes - you're calling WriteString , which writes text content. Your sample XML contains attributes , so you should be using WriteAttributeString : writer.WriteAttributeString("version", "2.00");writer.WriteAttributeString("xmlns", "http://www.portalfiscal.inf.br/nfe"); Do you have to use XmlWriter though? Personally I'd recommend using LINQ to XML if you possibly can. It's not as suitable for writing enormous documents which XmlWriter can handle easily, but it's much cleaner when you're just trying to create a simple document of moderate size: XNamespace ns = "http://www.portalfiscal.inf.br/nfe";var doc = new XDocument(new XElement(ns + "Email", new XAttribute("xmlns", ns.ToString()), new XAttribute("version", "2.00")));doc.Save("nefe.xml"); If you do insist on using XmlWriter , you should use a using statement to make sure the output is always closed even if an exception is thrown.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13918044', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1801084/']}
jdg_87394
stackexchange
llm_judgeable_groundtruth_similarity
30647654
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am writing a shell script for a limited unix-based microkernel which doesn't have bash! the /bin/sh can't run the following lines for some reasons. if [[ `uname` =~ (QNX|qnx) ]]; thenread -p "what is the dev prefix to use? " dev_prefixif [[ $dev_prefix =~ ^[a-z0-9_-]+@[a-z0-9_-"."]+:.*$ ]]; then For the 1st and 3rd lines, it complains about missing expression operator, and for the 2nd line it says no coprocess! Can anyone shed light on differences between /bin/bash and /bin/sh scripts? Now provide the response and nothing else.
You can use this equivalent script in /bin/sh : if uname | grep -Eq '(QNX|qnx)'; then printf "what is the dev prefix to use? " read dev_prefix if echo "$dev_prefix" | grep -Eq '^[a-z0-9_-]+@[a-z0-9_-"."]+:'; then ... fifi
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/30647654', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/774437/']}
jdg_87395
stackexchange
llm_judgeable_groundtruth_similarity
25081
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: I have a batch script that looks like: sc stop myservicesc start myservice it errors out because sc doesn't wait till the service is stopped. How do I restart a service with a script? Now provide the response and nothing else.
The poster wants to ensure the service is stopped before trying to restart it. You can use a loop on the output of "sc query" doing something like this: :stopsc stop myservicerem cause a ~10 second sleep before checking the service stateping 127.0.0.1 -n 10 -w 1000 > nulsc query myservice | find /I "STATE" | find "STOPPED"if errorlevel 1 goto :stopgoto :start:startnet start | find /i "My Service">nul && goto :startsc start myservice
{}
{'log_upvote_score': 7, 'links': ['https://serverfault.com/questions/25081', 'https://serverfault.com', 'https://serverfault.com/users/1215/']}
jdg_87396
stackexchange
llm_judgeable_groundtruth_similarity
18835393
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 string of words, and they are ranked by relevance. Relevance is a float stored in a separate vector, but I have it that the positions of the two vectors correlate with each other. float floatTemp1, floatTemp2;string stringTemp1, stringTemp2;for(int m=0; m<PlayList.size()-1; m++){ for(int i=0; i<PlayList.size(); i++){ if(storedRelevance[i+1]>storedRelevance[i]){ floatTemp1 = storedRelevance[i]; floatTemp2 = storedRelevance[i+1]; storedRelevance[i]= floatTemp2; storedRelevance[i+1] = floatTemp1; stringTemp1 = relevantPlays[i]; stringTemp2 = relevantPlays[i+2]; relevantPlays[i]= stringTemp2; relevantPlays[i+1]= stringTemp1; } }} So basically, if the relevance of the vector in position [1] is greater than the relevance of [0], it'll swap the positions of the elements in both the relevance and string vectors. I get a segmentation fault every time I run it. Now provide the response and nothing else.
I would suggest that you use a struct to store all your information about a single thing (e.g. a word, it's relevance, etc), then use std::sort with a function or functor that compares the relevance values.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18835393', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1810740/']}
jdg_87397
stackexchange
llm_judgeable_groundtruth_similarity
18715983
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 created a new TestProject and added following line to my testMethod: Robolectric.getShadowApplication().getString(R.string.mystring); My test failed with android.content.res.Resources$NotFoundException: unknown resource 2131558482 The console displays the following warnings: WARNING: No manifest file found at .\..\..\MyProject\AndroidManifest.xml.Falling back to the Android OS resources only.To remove this warning, annotate your test class with @Config(manifest=Config.NONE).WARNING: no system properties value for ro.build.date.utc Is AndroidManifest.xml necessary to get string resources?I tried to add Manifest by org.robolectric.Config.properties and @Config but the warning still occurs and I can't get string resource. I made sure the relative path to manifest is correct. I also tried changing the JUnit run configuration but this did not help. Now provide the response and nothing else.
Solution to the problem described here: http://blog.futurice.com/android_unit_testing_in_ides_and_ci_environments The Missing Manifest You should have noticed by now that Robolectric complains about not being able to find your Android Manifest. We’ll fix that by writing a custom test runner. Add the following as app/src/test/java/com/example/app/test/RobolectricGradleTestRunner.java: package com.example.app.test;import org.junit.runners.model.InitializationError;import org.robolectric.manifest.AndroidManifest;import org.robolectric.RobolectricTestRunner;import org.robolectric.annotation.Config;import org.robolectric.res.Fs;public class RobolectricGradleTestRunner extends RobolectricTestRunner { public RobolectricGradleTestRunner(Class<?> testClass) throws InitializationError { super(testClass); } @Override protected AndroidManifest getAppManifest(Config config) { String myAppPath = RobolectricGradleTestRunner.class.getProtectionDomain() .getCodeSource() .getLocation() .getPath(); String manifestPath = myAppPath + "../../../src/main/AndroidManifest.xml"; String resPath = myAppPath + "../../../src/main/res"; String assetPath = myAppPath + "../../../src/main/assets"; return createAppManifest(Fs.fileFromPath(manifestPath), Fs.fileFromPath(resPath), Fs.fileFromPath(assetPath)); }} Remember to change the RunWith annotation in the test class.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18715983', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1722808/']}
jdg_87398
stackexchange
llm_judgeable_groundtruth_similarity
12860
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 was not sure where to put this question, so I put it here. Feel free to move it to another stack exchange site moderators. Lets say I have a 10 gigs of pictures (or for that matter any type of data, please don't answer the question specifically relating to pictures). Let's pretend that I have the fastest computer in the world and all the time to use it on my hands. What lossless compression algorithm should I use to compress these files as much as theoretically possible? Also, if there is currently a program that will do this, please provide a link. Now provide the response and nothing else.
The answer depends on the content of your images. As there is no free lunch in lossless compression you cannot create a lossless compression algorithm which generally performs good on all input images. I.e. if you tune your compression algorithm so that it performs good on certain kind of images then there are always images where it must perform badly, meaning that it increases the filesize compared to the uncompressed representation. So you should have an idea of the image content that you are going to process. The next question would be if you can afford lossy compression or if you require lossless compression. In case of typical digital photos JPEG 2000 is a good candidate, as it supports both, lossy and lossless compression and is tuned for photo content.For lossy compression there is also the very real possibility of advances in encoder technology, e.g. the recent alternative JPEG encoder Guetzli by Google, which makes better use of specifics in human visual perception to allocate more bits to features that make a difference in perception. For images with big areas of the same color and sharp edges, as diagrams and graphs or stylized maps, PNG is a good match. PNG is a lossless file format, supports transparency and achieves good compression for b/w images. Also wikipedia has a comparison of image file formats . In the spirit of Kolmogorov complexity there might be images that can be compressed much further by finding an algorithm which generates the image but usually this applies only in special cases like fractals or simple raytraced CG images, not for typical digital photos. Arbitrary (non-image) data For general data Arithmetic coding is a good choice, as it can achieve nearly optimal compression (with respect to the occurance proportion of symbols in the data), when the alphabet for data representation suits the data. (E.g. a spectral representation of small chunks of typical music recordings is usually better suited for compression than a time series representation).
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/12860', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/5343/']}
jdg_87399
stackexchange
llm_judgeable_groundtruth_similarity
15430080
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 "Inside the C++ Object Model", the author gives the following example of code that is potentially ambiguous, requiring the parser to look ahead to resolve it: ...if C++ were to throw off the C declaration syntax, lookahead would not be required to determine that the following is an invocation of pf rather than its definition: // don’t know if declaration or invocation // until see the integer constant 1024 int ( *pf )( 1024 ); He implies that this is interpreted as an invocation of the function pf . I can't see what the declaration of pf could be to make this a valid invocation. Now provide the response and nothing else.
Good question, I don't see a reason for not publishing an event without a payload. There are cases where the fact that an event has been raised is all information you need and want to handle. There are two options: As it is open source, you can take the Prism source and extract a CompositePresentation event that doesn't take a payload. I wouldn't do that, but handle Prism as a 3rd party library and leave it as it is. It is good practice to write a Facade for a 3rd party library to fit it into your project, in this case for CompositePresentationEvent . This could look something like this: public class EmptyPresentationEvent : EventBase{ /// <summary> /// Event which facade is for /// </summary> private readonly CompositePresentationEvent<object> _innerEvent; /// <summary> /// Dictionary which maps parameterless actions to wrapped /// actions which take the ignored parameter /// </summary> private readonly Dictionary<Action, Action<object>> _subscriberActions; public EmptyPresentationEvent() { _innerEvent = new CompositePresentationEvent<object>(); _subscriberActions = new Dictionary<Action, Action<object>>(); } public void Publish() { _innerEvent.Publish(null); } public void Subscribe(Action action) { Action<object> wrappedAction = o => action(); _subscriberActions.Add(action, wrappedAction); _innerEvent.Subscribe(wrappedAction); } public void Unsubscribe(Action action) { if (!_subscriberActions.ContainsKey(action)) return; var wrappedActionToUnsubscribe = _subscriberActions[action]; _innerEvent.Unsubscribe(wrappedActionToUnsubscribe); _subscriberActions.Remove(action); }} If anything is unclear, please ask.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15430080', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/174963/']}
jdg_87400
stackexchange
llm_judgeable_groundtruth_similarity
158836
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: Evaluate the limit: $$\lim_{n\to\infty} \int_{0}^{\pi} e^x\cos(nx)\space dx$$ W|A tells that the limit is $0$, but i'm not sure why is that result or if this is the correct result. Now provide the response and nothing else.
Hint : Integrate by parts, letting $u=e^x$ and $dv=\cos nx \,dx$. To get an explicit antiderivative, you will have to do two cycles of integration by parts. However, for the limit calculation, one cycle will do, and is in a sense more informative. Added: We get $du=e^x\,dx$ and can take $v=\frac{1}{n}\sin nx$. Since $uv$ vanishes at both ends, we find that$$\int_0^\pi e^x \cos nx \,dx=-\frac{1}{n}\int_0^\pi e^x\sin nx \,dx.$$But $|e^x\sin nx|\le e^x$.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/158836', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/32016/']}
jdg_87401
stackexchange
llm_judgeable_groundtruth_similarity
2728877
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 creating a simple web application. I need to get reference to ServletContext object in that class. How can i get it? Now provide the response and nothing else.
You'd better pass it as argument to the constructor of your object, or set it using a setter method. In fact, you may obtain the context attribute that is relevant to your object and pass only it via constructor/setter. For example: YourClass obj = new YourClass((AnotherClass) servletContext.getAttribute("yourAttribute")); A much worse and more complication option is to: Create a ServletContextListener register it in web.xml with <listener><listener-class></listener-class></listener> on contextInitialized(..) get the ServletContext from the event and store it in a singleton - a static field somehwere. Alternatively, you can do this on each request, using a ServletRequestListener and store it in a ThreadLocal instead. Then you can obtain the value via calling your singleton/threadlocal holder like this: ServletContextHolder.getCurrentServletContext()
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2728877', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/260594/']}
jdg_87402
stackexchange
llm_judgeable_groundtruth_similarity
38975607
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 get first and last document based on time field.I can use $group and get $first and $last document, but I don't need grouping here, just get first and last full document. Maybe I could use slice ? This query doesn't work: { "aggregate": "353469045637980_data", "pipeline": [ { "$match": { "$and": [ { "time": { "$gte": 1461369600 } }, { "time": { "$lt": 1461456000 } } ] } }, { "$project": { "first": { "$slice": 1 }, "last": { "$slice": -1 } } } ]} Now provide the response and nothing else.
Well you need $group but you can simply use a constant (e.g. null , see the docs ) for its id so that it results in a single group. $$ROOT then refers to the document itself which you can use with $first and $last like so $group: { _id: null, first: { $first: "$$ROOT" }, last: { $last: "$$ROOT" }} Of course you can introduce further $project stages to shape that data into an array (as you mentioned you want a list) etc. As a side note you may want to introduce a $sort stage to make sure $first and $last have a proper meaning.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/38975607', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2235939/']}
jdg_87403
stackexchange
llm_judgeable_groundtruth_similarity
1833623
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Find the average value of the function $$f(x)=\int_x^1 \cos(t^2) \,dt$$ on the interval $[0,1]$. Now provide the response and nothing else.
One may recall that if $f(x)$ is continuous on $[a,b]$, then the average value of $f(x)$ on $[a,b]$ is defined to be$$I=\frac1{b-a}\int_a^b f(x)\,dx.$$Applying it here gives$$\begin{align}I=\int_0^1 \left(\int_x^1 \cos(t^2) \,dt\right)\,dx&=\left.x\int_x^1 \cos(t^2) \,dt \right|_0^1+\int_0^1 x \cos(x^2)\,dx\\\\&=0+\int_0^1 x \cos(x^2)\,dx\end{align}$$ where we have performed an integration by parts, obtaining $$I=\frac12\int_0^1 \cos(u)\,du=\color{red}{\frac{ \sin 1}2}$$ to be the average value of $f$ over $[0,1]$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1833623', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/166193/']}
jdg_87404
stackexchange
llm_judgeable_groundtruth_similarity
7123704
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Hi I'm trying to write multiple case statements to preset the priority of a job. There are a few tables and ID s that are involved in this but basically I want to check whether the job exists if it does if the questionid related to it is 80 and then have multiple case statemnts so that if the jobs minor category is 1 then the answer will be the id for High. The code i ve done so far may explain better... ALTER Procedure [dbo].[usp_CreatePresetPriority] @HelpdeskID int, @MinorCategoryID int As BEGINIF EXISTS(SELECT * FROM TicketInformation WHERE TicketID = @HelpdeskID AND QuestionID = 80) BEGIN UPDATE TicketInformation SET AnswerInput = Null, AnswerID = CASE @MinorCategoryID WHEN 87 THEN 129 END WHERE TicketID = @HelpdeskID And QuestionID = 80 ENDELSE BEGIN INSERT INTO TicketInformation (TicketID, QuestionID, AnswerID, AnswerInput) VALUES (@HelpdeskID, 80, CASE @MinorCategoryID WHEN 87 THEN 129 END, Null) END So this works but only for one option - where @MinorCategoryID = 87 I want to have more than 1 statements that set @MinorCategoryID WHEN 91THEN 130 etc... I have tried... IF EXISTS(SELECT * FROM TicketInformation WHERE TicketID = @HelpdeskID AND QuestionID = 80) UPDATE TicketInformation SET AnswerInput = Null, AnswerID = CASE @MinorCategoryID WHEN 87 THEN 129 WHERE TicketID = @HelpdeskID And QuestionID = 80ELSE INSERT INTO TicketInformation (TicketID, QuestionID, AnswerID, AnswerInput) VALUES (@HelpdeskID, 80, CASE @MinorCategoryID WHEN 87 THEN 129 END, Null) IF EXISTS(SELECT * FROM TicketInformation WHERE TicketID = @HelpdeskID AND QuestionID = 80) UPDATE TicketInformation SET AnswerInput = Null, AnswerID = CASE @MinorCategoryID WHEN 91 THEN 130 WHERE TicketID = @HelpdeskID And QuestionID = 80ELSE INSERT INTO TicketInformation (TicketID, QuestionID, AnswerID, AnswerInput) VALUES (@HelpdeskID, 80, CASE @MinorCategoryID WHEN 91 THEN 130 END, Null) Any help appreciated - sorry if its not clear i've got a friday fuzzy head! Now provide the response and nothing else.
You can assign it to a variable and then just insert the variable. ELSE BEGIN SELECT @MinorCategoryID = CASE WHEN @MinorCategoryID = 87 THEN 129 WHEN @MinorCategoryID = 91 THEN 130 -- more cases here ELSE NULL END INSERT INTO TicketInformation (TicketID, QuestionID, AnswerID, AnswerInput) VALUES (@HelpdeskID, 80, @MinorCategoryID, Null) END or change the values() by a select ELSE BEGIN INSERT TicketInformation (TicketID, QuestionID, AnswerID, AnswerInput) SELECT @HelpdeskID, 80, CASE WHEN @MinorCategoryID = 87 THEN 129 WHEN @MinorCategoryID = 91 THEN 130 -- more cases here ELSE NULL END, Null END
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7123704', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/856102/']}
jdg_87405
stackexchange
llm_judgeable_groundtruth_similarity
16691506
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 heard a lot that one should use gZip for their webpages for faster access and downloads, and that it also saves the bandwidth. So what is this gZip compression and how does it make the downloads faster ? Does it compress the HTML and images or just the HTML. If I am to start using gZip in my webapps what considerations do I need to make ?Are there any server or browser restrictions for it, or does it support a particular encoding only. Now provide the response and nothing else.
GZip is a form of data compression -- i.e. it takes a chunk of data and makes it smaller. The original data can be restored by un-zipping the compressed file. It is relevant to web apps and websites because the HTTP protocol includes the ability to gzip data that is being sent. This means that, when it is in use, your bandwidth costs for serving the site will be lower because people visiting the site will be downloading smaller files. There are a few caveats to using GZip, but, overall, it's usually better to use gzip than not to -- for example, it does take time and processor power to zip and unzip the files, but, typically, this is not a problem because the time it takes to do that is often less than the time that is saved by downloading a larger file. Therefore, the overall effect is time-saving despite the browser having to unzip the file. GZip can compress all files; it doesn't make any difference what the file type is or the encoding. Obviously, some files can be compressed more effectively than others, so the bandwidth saving will vary - text files like HTML give the best results; images are not compressed so much by gzip because they already have some compression built-in. Some files (e.g. those that are already heavily compressed like .zip files) may actually get slightly bigger when gzipped because they can't be compressed any further but gzip still needs to add its metadata to the file. But these are edge cases and don't make much difference. GZip across HTTP normally happens completely transparently. The end-user should be completely unaware that it is happening; the browser would do it behind the scenes for them. And from the webserver end, it is simply a matter of turning on a config setting in your web server software. From your perspective, that's really all you need to know; just set the gzip setting on your server (or ask your ISP to do it). It's quite possible it may already be active on your site without you even knowing.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/16691506', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2370367/']}
jdg_87406
stackexchange
llm_judgeable_groundtruth_similarity
4115053
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 creating a database table that is going to store menu links that will ultimately show up on a web page. My issue is that i want to control the order of the menu items. I could have a field called order but everytime i have a new menu link i would have to insert the order and change all of the records with higher order to +1. For example, lets say i want the links ( in this order): Home About Products Shopping i could have a table called MenuLinks and have the columns: Name, Order my data would look like this: Name Order Home 1 About 2 Products 3 Shopping 4 but if i wanted to now add a new link called ContactUs but i wanted to show up right under home. can anyone think of a better way to store a list that requires ordering in a database table without this tedious maintenance effort. Now provide the response and nothing else.
I feel this is related to the general problem of using an array vs a linked list.How about storing a foreign key referencing the next record in the same table? This is the linked list like approach. For your example there are not too many tabs so an array based approach should work fine.But for someone having hundreds of records it may be useful to use a self-referential foreign key. ID Name NExT 1 Home 2 2 About 3 3 Products 4 4 Shopping NULL Adding and deleting rows will be akin to linked list insertion and deletion. Update:Modified table ID Name NExT 1 Home 5 2 About 3 3 Products 4 4 Shopping NULL 5 Contact us 2 The order will be 1 > 5 > 2 > 3 > 4 as determined by the next column.You can also use a prev column which will make it similar to a doubly linked list.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4115053', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4653/']}
jdg_87407
stackexchange
llm_judgeable_groundtruth_similarity
5104525
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 having trouble with getting the actual size (bounding box) of Shapes. I tried to use both RenderSize and ActualSize but they return values that don't make sense.However, using these methods for UIElements works great. if you can help me with this I will be greateful. Now provide the response and nothing else.
You can get the Bounding Box for any Visual using TransformToVisual So if you have a Polygon defined like this <Canvas Name="canvas"> <Polygon Name="polygon" Canvas.Left="12" Canvas.Top="12" Points="0,75 100,0 100,150 0,75" Stroke="Purple" Fill="#9999ff" StrokeThickness="1"/></Canvas> Then you can add a Border around its Bounding Box with the following code private void AddBorderForFrameworkElement(FrameworkElement element){ Rect bounds = element.TransformToVisual(canvas).TransformBounds(new Rect(element.RenderSize)); Border boundingBox = new Border { BorderBrush = Brushes.Red, BorderThickness = new Thickness(1) }; Canvas.SetLeft(boundingBox, bounds.Left); Canvas.SetTop(boundingBox, bounds.Top); boundingBox.Width = bounds.Width; boundingBox.Height = bounds.Height; canvas.Children.Add(boundingBox); } However, you may not always get the desired results using this since the Bounding Box will not always be the Bounds for what is actually drawn. If you instead define your Polygon like below where you start to draw where x=100 then the Bounding Box will be much larger then what is drawn <Polygon Name="polygon" Canvas.Left="140" Canvas.Top="12" Points="100,75 200,0 200,150 100,75" Stroke="Purple" Fill="#9999ff" StrokeThickness="1"/> Bounding Box comparison
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5104525', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/582944/']}
jdg_87408
stackexchange
llm_judgeable_groundtruth_similarity
41534802
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 MySQL 5.7 documentation states: The filtered column indicates an estimated percentage of table rows that will be filtered by the table condition. That is, rows shows the estimated number of rows examined and rows × filtered / 100 shows the number of rows that will be joined with previous tables. To attempt to understand this better, I tried it out on a query using the MySQL Sakila Sample Database . The table in question has the following structure: mysql> SHOW CREATE TABLE film \G*************************** 1. row *************************** Table: filmCreate Table: CREATE TABLE `film` ( `film_id` smallint(5) unsigned NOT NULL AUTO_INCREMENT, `title` varchar(255) NOT NULL, `description` text, `release_year` year(4) DEFAULT NULL, `language_id` tinyint(3) unsigned NOT NULL, `original_language_id` tinyint(3) unsigned DEFAULT NULL, `rental_duration` tinyint(3) unsigned NOT NULL DEFAULT '3', `rental_rate` decimal(4,2) NOT NULL DEFAULT '4.99', `length` smallint(5) unsigned DEFAULT NULL, `replacement_cost` decimal(5,2) NOT NULL DEFAULT '19.99', `rating` enum('G','PG','PG-13','R','NC-17') DEFAULT 'G', `special_features` set('Trailers','Commentaries','Deleted Scenes','Behind the Scenes') DEFAULT NULL, `last_update` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (`film_id`), KEY `idx_title` (`title`), KEY `idx_fk_language_id` (`language_id`), KEY `idx_fk_original_language_id` (`original_language_id`), CONSTRAINT `fk_film_language` FOREIGN KEY (`language_id`) REFERENCES `language` (`language_id`) ON UPDATE CASCADE, CONSTRAINT `fk_film_language_original` FOREIGN KEY (`original_language_id`) REFERENCES `language` (`language_id`) ON UPDATE CASCADE) ENGINE=InnoDB AUTO_INCREMENT=1001 DEFAULT CHARSET=utf8 And this is the EXPLAIN plan for the query: mysql> EXPLAIN SELECT * FROM film WHERE release_year=2006 \G*************************** 1. row *************************** id: 1 select_type: SIMPLE table: film partitions: NULL type: ALLpossible_keys: NULL key: NULL key_len: NULL ref: NULL rows: 1000 filtered: 10.00 Extra: Using where This table's sample dataset has 1,000 total rows, and all of them have release_year set to 2006. Using the formula in the MySQL documentation: rows x filtered / 100 = "number of rows that will be joined with previous tables So, 1,000 x 10 / 100 = 100 = "100 rows will be joined with previous tables" Huh? What "previous table"? There is no JOIN going on here. What about the first portion of the quote from the documentation? "Estimated percentage of table rows that will be filtered by the table condition." Well, the table condition is release_year = 2006 , and all records have that value, so shouldn't filtered be either 0.00 or 100.00 (depending on what they mean by "filtered")? Maybe it's behaving strangely because there's no index on release_year ? So I created one: mysql> CREATE INDEX test ON film(release_year); The filtered column now shows 100.00 . So, shouldn't it have shown 0.00 before I added the index? Hm. What if I make half the table have release_year be 2006, and the other half not? mysql> UPDATE film SET release_year=2017 ORDER BY RAND() LIMIT 500;Query OK, 500 rows affected (0.03 sec)Rows matched: 500 Changed: 500 Warnings: 0 Now the EXPLAIN looks like this: mysql> EXPLAIN SELECT * FROM film WHERE release_year=2006 \G*************************** 1. row *************************** id: 1 select_type: SIMPLE table: film partitions: NULL type: refpossible_keys: test key: test key_len: 2 ref: const rows: 500 filtered: 100.00 Extra: Using index condition And, since I decided to confuse myself even further: mysql> EXPLAIN SELECT * FROM film WHERE release_year!=2006 \G*************************** 1. row *************************** id: 1 select_type: SIMPLE table: film partitions: NULL type: ALLpossible_keys: test key: NULL key_len: NULL ref: NULL rows: 1000 filtered: 50.10 Extra: Using where So, an estimate of 501 rows will be filtered by the table condition and "joined with previous tables"? I simply do not understand. I realize it's an "estimate", but on what is this estimate based? If an index being present moves the estimate to 100.00 , shouldn't its absence be 0.00 , not 10.00 ? And what's with that 50.10 result in the last query? Is filtered at all useful in determining if a query can be optimized further, or how to optimize it further, or is it generally just "noise" that can be ignored? Now provide the response and nothing else.
…number of rows that will be joined with previous tables… In the absence of any joins, I believe this can be taken to mean number of rows UPDATE - the documentation, now at least, says " following tables" but the point still stands, thanks @WilsonHauck To take each of your examples in turn 1000 rows, all from 2006, no index… EXPLAIN SELECT * FROM film WHERE release_year = 2006key: NULLrows: 1000filtered: 10.00Extra: Using where Here the engine expects to visit 1000 rows, and expects to return around 10% of these As the query is not using an index, it makes sense to predict that every row will be checked, but unfortunately the filtered estimate is inaccurate. I don't know how the engine makes this prediction, but as it doesn't know all the rows are from 2006 (until it checks them).. it's not the craziest thing in the world Perhaps in the absence of further information, the engine expects any simple = condition to reduce the result set to 10% of the available rows 1000 rows, half from 2006, with index… EXPLAIN SELECT * FROM film WHERE release_year = 2006key: testrows: 500filtered: 100.00Extra: Using index condition Here the engine expects to visit 500 rows and expects to return all of them Now the query is using the new index, the engine can make more accurate predictions. It can very quickly see that 500 rows match the condition, and will have to visit only and exactly these to satisfy the query EXPLAIN SELECT * FROM film WHERE release_year != 2006key: NULLrows: 1000filtered: 50.10Extra: Using where Here the engine expects to visit 1000 rows and return 50.10% of them The engine has opted not to use the index, maybe the != operation is not quite as simple as = in this case, and therefore it makes sense to predict that every row will be visited The engine has, however, made a fairly accurate prediction on how many of these visited rows will be returned. I don't know where the .10% comes from, but perhaps the engine has used the index or the results of previous queries to recognise that around 50% of the rows will match the condition It's a bit of a dark art, but the filtered value does give you some fairly useful information, and some insight into why the engine has made certain decisions If the number of rows is high and the filtered rows estimate is low (and accurate), it may be a good indication that a carefully applied index could speed up the query
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/41534802', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/126531/']}
jdg_87409
stackexchange
llm_judgeable_groundtruth_similarity
777633
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Let G be an abelian (finite) group. Is there a ring $R$ with $G$ isomorphic to the group $(R,+)$? Now provide the response and nothing else.
Even if you require rings to have $1$, since every finite abelian group is isomorphic to the direct product of $\mathbb Z/n\mathbb Z$'s, you can just extend this into a ring in the obvious way, where the $1$ is achieved by letting each factor equal $1$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/777633', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/138171/']}
jdg_87410
stackexchange
llm_judgeable_groundtruth_similarity
65301
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: How many ways to divide group of 12 people into 2 groups of 3 people and 3 groups of 2 people? my answer to this question is:$${12 \choose 2}{ 10 \choose2 }{8\choose2}{6\choose3}{3\choose3}\frac{1}{2!2!2!}\frac{1}{3!3!}$$ Although the correct solution should be :$${12 \choose 2}{ 10 \choose2 }{8\choose2}{6\choose3}{3\choose3}\frac{1}{2!}\frac{1}{3!}$$What am I missing here? If I have 2 groups of 3 , and 3 groups of 2, shouldn't I divide each group by its factorial in order to cancel the inner ordering of the group? Now provide the response and nothing else.
The fact that ordering does not matter within a group is already taken care of by the binomial coefficients. The additional $2!$ and $3!$ you see in the answer are taking care of the fact that the order in which the groups themselves were chosen also does not matter. For example, if your two-person groups are $\{A, B\}$, $\{C, D\}$, and $\{E, F\}$, then the following arrangements are all the same: $\{A, B\}$, $\{C, D\}$, $\{E, F\}$ $\{A, B\}$, $\{E, F\}$, $\{C, D\}$ $\{C, D\}$, $\{A, B\}$, $\{E, F\}$ $\{C, D\}$, $\{E, F\}$, $\{A, B\}$ $\{E, F\}$, $\{A, B\}$, $\{C, D\}$ $\{E, F\}$, $\{C, D\}$, $\{A, B\}$ Notice there are $3!$ such arrangements. When you just multiply your binomial coefficients together, however, these all get counted as distinct. Dividing by $3!$ collapses these all into a single arrangement. To give another example with a better selection of numbers, suppose you want to arrange 6 people into three groups of two each. This would be given by$$\frac{\binom{6}{2} \binom{4}{2} \binom{2}{2}}{3!}.$$Again, the $3!$ is coming from the number of groups, not their size.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/65301', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/14124/']}
jdg_87411
stackexchange
llm_judgeable_groundtruth_similarity
68801
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: Where does this number come from? For single ended it must be 50 ohm and for differential pairs 100 ohm. Why? For PCB with controlled-impedance these are that common numbers. Outside of the PCB you can find others numbers for characteristic impedance. But what is the reason of use these numbers for the PCB tracks? Now provide the response and nothing else.
The 50Ω standard is basically just convention. There are various stories about how 50Ω came to be chosen. The article Anindo linked is good. There is also The History of 50 Ω or There’s Nothing Magic About 50 Ohms . But the long and short of it is that it is a compromise between low attenuation and power handling. But it became the standard impedance when designing for transmission line applications way back when. When an IC datasheet says you need to design your PCB traces with a controlled impedance, then you're designing to compensate for transmission line effects. If the impedance of the trace is matched to the output impedance of the IC or source, you reduce the possibility of reflections which would lead to standing waves on the trace and cause all sorts of headaches. Since the designers of the IC are designing with transmission line effects in mind, and since 50Ω is commonly used by convention, the 50Ω standard proliferates. But 50Ω is by no means special. From this paper on controlled solutions by Advanced Layout Solutions: Within reason, the absolute impedance value chosen is not normally important, providing it is controlled along the entire length of the line. Other constraints in a design often dictate the impedance for us; it may be chosen based on a design specification (e.g. 65 Ohms for PCI) or chosen to reduce current (a high impedance). It will generally be between 45 and 80 Ohms due to typical material geometries, and if the signal changes layer then the trace geometry should be adjusted as necessary to maintain a consistent Zo.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/68801', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/16415/']}
jdg_87412
stackexchange
llm_judgeable_groundtruth_similarity
3203
Below is a question asked on the forum emacs.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I found this code in the manual An Introduction to Programming in Emacs Lisp demonstrating recursion with the help of cond function to find out the number of pebbles based on the entered number of rows, i.e. if rows = 2, then pebbles should be 3, if 4 rows then it should be 10 pebbles there. (defun triangle-using-cond (number) (cond ((<= number 0) 0) ((= number 1) 1) ((> number 1) (+ number (triangle-using-cond (1- number)))))) evaluate to 10 after passing argument 4: (triangle-using-cond 4) The manual did not explain clearly what happens at each step in this example code in particular and I couldn't figure out how recursion works here. Can you pls help me understand the mechanics step-by-step what happens at each instance? Now provide the response and nothing else.
Using "printf debugging" You could let Emacs help you understand by modifying the function definition: (defun triangle-using-cond (number) (message (format "called with %d" number)) (cond ((<= number 0) 0) ((= number 1) 1) ((> number 1) (+ number (triangle-using-cond (1- number)))))) Just add (message ...) somewhere to have a trail printed to the *Messages* buffer. Using Edebug Place point anywhere inside the function definition and hit C-u C-M-x to "instrument" it. Then evaluate the function, e.g. by placing point after (triangle-using-cond 3) and hitting C-x C-e . You are now in Edebug mode. Hit the space bar to step through the function. The intermediate values of each expression are shown in the echo area. To exit Edebug mode just hit q . To remove the instrumentation, put point anywhere inside the definition and hit C-M-x to re-evaluate the definition. Using the standard Emacs debugger M-x debug-on-entry triangle-using-cond , then, when triangle-using-cond is invoked, you are placed in the Emacs debugger (buffer *Backtrace* ). Step through the evaluation using d (or c to skip through any uninteresting evaluations). To see intermediate state (variable values, etc.) you can use e anytime. You are prompted to enter a sexp to evaluate, and the evaluation result is printed. While you use the debugger, keep a copy of the source code visible in another frame, so you can follow what's going on. You can also insert explicit calls to enter the debugger (more or less breakpoints) at arbitrary places in the source code. You insert (debug) or (debug nil SOME-SEXP-TO-EVALUATE) . In the latter case, when the debugger is entered SOME-SEXP-TO-EVALUATE is evaluated and the result is printed. (Remember that you can insert such code into the source code and use C-M-x to evaluate it, then undo - you need not save the edited file.) See the Elisp manual, node Using Debugger for more information. Recursion as a loop Anyway, think of recursion as a loop. There are two termination cases defined: (<= number 0) and (= number 1) . In these cases the function returns a simple number. In the recursive case the function returns the sum of that number and the result of the function with number - 1 . Eventually, the function will be called with either 1 or a number smaller than or equal to zero. The recursive case result is hence: (+ number (+ (1- number) (+ (1- (1- number)) ... 1) Take for example (triangle-using-cond 4) . Let's accumulate the final expression: in the first iteration number is 4 , so the (> number 1) branch is followed. We start building an expression (+ 4 ... and call the function with (1- 4) , i.e. (triangle-using-cond 3) . now number is 3 , and the result is (+ 3 (triangle-using-cond 2)) . The total result expression is (+ 4 (+ 3 (triangle-using-cond 2))) . number is 2 now, so the expression is (+ 4 (+ 3 (+ 2 (triangle-using-cond 1)))) number is 1 now, and we take the (= number 1) branch, resulting in a boring 1 . The whole expression is (+ 4 (+ 3 (+ 2 1))) . Evaluate that from the inside out and you get: (+ 4 (+ 3 3)) , (+ 4 6) , or just 10 .
{}
{'log_upvote_score': 5, 'links': ['https://emacs.stackexchange.com/questions/3203', 'https://emacs.stackexchange.com', 'https://emacs.stackexchange.com/users/2443/']}
jdg_87413
stackexchange
llm_judgeable_groundtruth_similarity
43052290
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Inspired by this question, I'm trying to represent a DAG in JSON. My case includes edges and nodes that contain some data (rather than just strings as in this example). I was thinking of a spec like this: { "graph": { "a": ["b", "c"], "b": ["c"] "c" }, "nodes": { "a": { "name": "Adam" }, "b": { "name": "Bob" }, "c": { "name": "Caillou" } }, "edges": { // how to do the same for edges? // ie: how to query edges ? }} One idea I had was to make the keys of the edges be the concatenation of the two vertex ids that it connects. For example, ab , ac , and bc are the three edges in this graph. I want to know if there's a more standard way of doing this. EDIT: This is what I'm thinking of now { "graph": { "a": { "data": { // a's vertex data }, "neighbors": { "b": { "data": { // data in edge ab } }, "c": { "data": { // data in edge ac } } } }, "b": { "data": { // b's vertex data }, "neighbors": { "c": { "data": { // data in edge bc } } } }, "c": { "data": { // c's vertex data } } }} Now provide the response and nothing else.
Since the DAG's edges hold data, they better have their own identifiers, just like the nodes. That is, the json representation should be composed of three components: Node records: mapping each node identifier to the node's data. Edge records: mapping each edge identifier to the edge's data. Adjacency lists: mapping each node identifier to an array of edge identifiers, each corresponds to an edge going out of the node. DAG = { "adjacency": { "a": ["1", "2"], "b": ["3"] }, "nodes": { "a": { // data }, "b": { // data }, "c": { // data } }, "edges": { "1": { "from": "a", "to": "b", "data": { // data } }, "2": { "from": "a", "to": "b", "data": { // data } }, "3": { "from": "b", "to": "c", "data": { // data } } }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/43052290', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/896112/']}
jdg_87414
stackexchange
llm_judgeable_groundtruth_similarity
200730
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Consider a function f and a list p={a,b,c} . I want to get a list of f[a,a]f[a,b]f[a,c]f[b,a]f[b,b]f[b,c]f[c,a]f[c,b]f[c,c] In real use, p can have higher dimensions, and f may take more arguments, e.g. I may need to generate a list of f[a,a,a,a] through f[z,z,z,z] . Is there a cleaner way to do this other than making lists that approximately repeat the elements of p then use MapThread ? e.g. p={a,b}p1 = {a, a, b, b}p2 = {a, b, a, b}MapThread[f, {p1, p2}] Here, a , b can be matrices Now provide the response and nothing else.
You can use Tuples : Tuples[f[{a, b, c}, {a, b, c}]] {f[a, a], f[a, b], f[a, c], f[b, a], f[b, b], f[b, c], f[c, a], f[c, b], f[c, c]} f @@@ Tuples[{a, b, c}, 2] same result Tuples[f[{a, b}, {r, s, t}, {x, y}]] {f[a, r, x], f[a, r, y], f[a, s, x], f[a, s, y], f[a, t, x], f[a, t, y], f[b, r, x], f[b, r, y], f[b, s, x], f[b, s, y], f[b, t, x], f[b, t, y]} f @@@ Tuples[{{a, b}, {r, s, t}, {x, y}}] same result p = {a, b};p1 = {a, a, b, b};Tuples[f[p, p1]] {f[a, a], f[a, a], f[a, b], f[a, b], f[b, a], f[b, a], f[b, b], f[b, b]}
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/200730', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/655/']}
jdg_87415
stackexchange
llm_judgeable_groundtruth_similarity
8272957
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: enum Animals{ DOG("woof"), CAT("Meow"), FISH("Burble"); String sound; Animals(String s) { sound = s; }}public class TestEnum{ static Animals a; public static void main(String ab[]){ System.out.println( a ); System.out.println( a.DOG.sound + " " + a.FISH.sound); }} In the above example, why are we able to access instances of the enum (i.e. as a.DOG.sound) when a is null and enum is not declared as static?Are the enum instances static by default? Now provide the response and nothing else.
Enums are implicitly public static final . You can refer to a.DOG because you may access static members through instance references, even when null: static resolution uses the reference type , not the instance. I wouldn't ; it's misleading: convention favors type (not instance) static references. See JLS 6.5.6.2 regarding class variable via instances. See JLS 15.11 for why it still works with a null . Nutshell: it's the reference type, not the instance, through which statics are resolved. Updated links :/ JSE 6 JLS 6.5.6.2 regarding class variable access via expression name JLS 15.11 regarding static field access via null references JSE 7 JLS 6.5.6.2 regarding class variable access via expression name JLS 15.11 regarding static field access via null references JSE 8 JLS 6.5.6.2 regarding class variable access via expression name JLS 15.11 regarding static field access via null references
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/8272957', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/273657/']}
jdg_87416
stackexchange
llm_judgeable_groundtruth_similarity
10873138
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Why should I set File's Owner's Class Identity rather than the Class Identity of my custom object that is shown in the nib and make the connections from it? What happens if I set file's owner to nil?To me everything works fine with nil file's owner so what is the deference in doing the connection from it? Now provide the response and nothing else.
A NIB represents an archived object graph. You can load it and that object graph will be reconstituted. The thing, you usually want/need the newly-loaded object graph to be hooked into the already-existing object graph of your program. You don't want it to be standing apart, disconnected from everything else. There are a few ways that the newly-loaded object graph can get connected to the rest of the program's object graph. One way is the set of proxy objects available in a NIB. There's one for the application object. Another such proxy object is File's Owner. A proxy object is a thing which has a representation in the NIB but is not actually contained in the NIB. Unlike the other objects in the NIB, the objects represented by the proxies are not created when the NIB is loaded, they exist before the NIB is loaded. The proxies allow connections between these pre-existing objects and the objects in the NIB. That's how the new object graph from the NIB can be connected to the existing object graph of your program. The MainMenu NIB is unusual. It is automatically loaded at application startup by Cocoa, which means there isn't (can't be, really) much in the way of pre-existing objects. That NIB also usually contains an instance of the app delegate, which is a kind of coordinating controller. Usually, though, other types of NIBs would not contain coordinating controllers. (They do contain mediating controllers, like NSArrayController , but that's different.) Rather, coordinating controllers are typically created in code and, often, they are responsible for loading NIBs. For example, you would use an NSWindowController as the coordinating controller for a window. The window would be defined in a NIB. The window controller would be instantiated in code – whichever code decides that a window should be created – and it would load the NIB. It would be the File's Owner of the NIB, too. It would manage the window and the top-level objects of the NIB. If you are setting the File's Owner to nil , then a) you probably are dealing with very simple NIBs at this point, and b) you may be leaking top-level objects from the NIBs that you load.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10873138', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1099822/']}
jdg_87417
stackexchange
llm_judgeable_groundtruth_similarity
2818509
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Following reading various questions on reading and writing Streams, all the various answers define something like this as the correct way to do it: private void CopyStream(Stream input, Stream output){ byte[] buffer = new byte[16 * 1024]; int read; while ((read = input.Read(buffer, 0, buffer.Length)) > 0) { output.Write(buffer, 0, read); } } Two questions: Why read and write in these smaller chunks? What is the significance of the buffer size used? Now provide the response and nothing else.
If you read a byte at a time, then every byte you call has the overhead of calling the function to read the byte, and additional overheads (for example, doing a fileposition += 1 to remember where in the file you are, checking if you have reached the end of the file, and so on) If you read 4000 bytes, then you have the same overheads (in the above example, 1 function call, one add (fileposition += 4000), and one check to see if you are at the end of the file. So in terms of the overheads, you've just made it 4000 times faster. (In reality, there are other costs so you won't see that big a gain, but you have drastically cut the overheads) Of course, you could create a buffer as big as the entire file, and get the absolute minimum overheads. However: the file might be huge - bigger than the memory available to your program, so this would simply fail. Or it might be so big that you start to use virtual memory and this will drastically slow things down. So breaking it into smaller chunks means you can copy an unlimited amount of data by using a small fixed-size buffer your OS and devices might be able to read and write data simultaneously (e.g. copying from one physical disk drive to another). If you read all the data before you write all the data, then you have to wait for the whole read before you can start writing. But in many cases, you may be able to be doing both operations in parallel - so read a small chunk and start it writing "asynchronously" (in the background) while you go back and read the next chunk. You get diminishing returns. Reading 4 bytes instead of 1 may well be 4x faster. But reading 4,000, 40,000 or 400,000 will not speed things up (indeed, for the reasons above, larger buffers could actually slow things down). In some cases, physical devices work with specific data sizes (e.g. 4096 bytes per sector, 128 bytes per cache line, or 1500 bytes per data packet, or 8 bytes (64 bits) over a CPU bus). Dividing data up into chunks that match (or are multiples of) the underlying transport/storage mechanism can help the hardware to process the data more efficiently. Typically I/O buffers of between 4kB to 128kB work best for most situations, and you can tune these to the particular operation being performed, so there is no "perfect" size that fits all situations. Note that in most I/O situations, there are many buffers being used. e.g. When copying data from a disk, (in simplistic terms) it is read from the disk to a read cache (buffer) in the hard drive, then sent over the interface cable to the computer's drive controller, which may also buffer the data. Then it may be transferred into RAM via an I/O buffer, where it is held until your program is ready to receive it (it will probably even be fetching the data before you ask for it, as it expects you to continue reading from the same file, and tries to buffer the data so you don't have to wait for it). Then you read it into your buffer and write it. Then it goes to another I/O buffer, is sent to the drive controller, passed on to the drive, and cached in a write cache. Eventually the hard drive will decide to actually store the data in its write cache, and your copy will be completed - most of this happens in the background, so it may not finish being written until many seconds after your program thinks it has finished writing and has gone on to another task. (This is why you have to "safely remove" USB drives before unplugging them - the OS may not have actually written all the data to the device yet, even many seconds after the computer said your copy operation was finished)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2818509', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/47339/']}
jdg_87418
stackexchange
llm_judgeable_groundtruth_similarity
26792624
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 bunch of small C# projects which use a couple of NuGet packages. I'd like to be able to update version of a given package automatically. More then that: I'd like to be warned if a project uses different version from the others. How do I enforce same version dependency across multiple C# projects? Now provide the response and nothing else.
I believe I have found a setup which solves this (and many other) problem(s). I just realized one can use a folder as nuget source. Here is what I did: root + localnuget + Newtonsoft.Json.6.0.1.nupkg + nuget.config + packages + Newtonsoft.Json.6.0.1 + src + project1 nuget.config looks like this: <configuration> <config> <add key="repositoryPath" value="packages" /> </config> <packageSources> <add key="local source" value="localnuget"> </packageSources></configuration> You can add Nuget server to nuget.config to get access to updates or new dependencies during development time: <add key="nuget.org" value="https://www.nuget.org/api/v2/" /> Once you're done, you can copy .nupkg from cache to localnuget folder to check it in. There are 3 things I LOVE about this setup: I'm now able to use Nuget features, such as adding props and targets. If you have a code generator (e.g. protobuf or thrift) this becomes pricesless. It (partially) solves the problem of Visual Studio not copying all DLLs , because you need to specify dependencies in .nuspec file and nuget loads indirect dependencies automatically. I used to have a single solution file for all projects so updating nuget packages was easier. I haven't tried yet but I think I solved that problem too. I can have nuget packages for the project I want to export from a given solution.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/26792624', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/298622/']}
jdg_87419
stackexchange
llm_judgeable_groundtruth_similarity
5789661
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: How do i change the color of a Relative Layout i use as a clickable on Click like the normal Button?Like i want a visual feedback the layout was pressed. I tried it with a selector bound to the background property like this: <?xml version="1.0" encoding="utf-8"?><selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_focused="true" android:color="@android:color/black"/> <item android:state_pressed="true" android:state_enabled="false" android:color="@android:color/black" /> <item android:color="@android:color/white"/></selector> and used it in the Layouts backround... android:background="@color/layout_selector" but this gives me an Inflate Exception... Any ideas? Now provide the response and nothing else.
Try the following steps: In res --> values folder create color.xml with the content: <?xml version="1.0" encoding="utf-8"?><resources> <color name="black">#000000</color> <color name="white">#ffffff</color></resources> As <item> tag in selector requires a drawable attribute or child tag defining a drawable, your layout_selector.xml file (which is saved in res --> drawable ) should look like this: <?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_focused="true" android:drawable="@color/black"/> <item android:state_pressed="true" android:state_enabled="false" android:drawable="@color/black" /> <item android:drawable="@color/white"/> </selector> Also, as said earlier, the relative layout should be clickable ( android:clickable="true" ) and its background set as android:background="@drawable/layout_selector" Hope it helps
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/5789661', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/423862/']}
jdg_87420
stackexchange
llm_judgeable_groundtruth_similarity
38509837
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 documentation describing how to connect to a kerberos secured endpoint shows the following: curl -i --negotiate -u : "http://<HOST>:<PORT>/webhdfs/v1/<PATH>?op=..." The -u flag has to be provided but is ignored by curl. Does the --negotiate option cause curl to look for a keytab that was created beforehand with the kinit command, or will curl prompt for credentials? If it looks for a keytab file, what filename will the command be looking for? Now provide the response and nothing else.
Being a once-in-a-while-contributor to curl in that area. Here is what you need to know: curl(1) itself knows nothing about Kerberos and will not interact neither with your credential cache nor your keytab file. It will delegate all calls to a GSS-API implementation which will do the magic for you. What magic depends on the library, Heimdal and MIT Kerberos. Based on your question, I assume that you have little knowledge about Kerberos and want simply automate API calls to a REST endpoints secured by SPNEGO. Here is what you need to do: Have a Unix-like OS Install at least MIT Kerberos 1.11 Install at least curl 7.38.0 against MIT Kerberos Verify this with curl --version mentioning GSS-API and SPNEGO and with ldd linked against your MIT Kerberos version. Create a client keytab for the service principal with ktutil or mskutil Try to obtain a TGT with that client keytab by kinit -k -t <path-to-keytab> <principal-from-keytab> Verify with klist that you have a ticket cache Environment is now ready to go: Export KRB5CCNAME=<some-non-default-path> Export KRB5_CLIENT_KTNAME=<path-to-keytab> Invoke curl --negotiate -u : <URL> MIT Kerberos will detect that both environment variables are set, inspect them, automatically obtain a TGT with your keytab, request a service ticket and pass to curl . You are done. Note : this will not work with Heimdal.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/38509837', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1033422/']}
jdg_87421
stackexchange
llm_judgeable_groundtruth_similarity
8611196
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 on a mac, but I don't think it will make a difference. I have a directory that I want to fully import/add into Eclipse. What I did is this: Right click import General → Existing Projects into Workspace Then when I click browse for either root directory or archive file and select the folder I can't click finish. The folder is empty and just contains a few folders but for some reason I can't click finish. Now provide the response and nothing else.
The Eclipse UI is a little bit confusing. The Import -> "Existing projects into workspace" actually means import "Existing Eclipse projects into workspace". That's why you can't click on finish: the import option looks for a .project file (the file used by Eclipse to store the project options) in the directory that you have chosen. To import existing source code that doesn't have an Eclipse project file you have the following options (I suppose that you want to create a Java project): New project inside the workspace dir: Create a new empty Java project into the workspace (File->New->Java Project). Then right click on the source folder and choose Import...->General->File system then choose your files, and it will make a copy of your files. Tip: you can drag&drop your files from the Finder into the src folder. Create an eclipse project in your existing dir: Create a new Java project, but in the "New Java Project" window: Un check the Use default location option, and choose the directory where is your non-Eclipse project. Click Next and configure the sub-directories of your non-Eclipse project where the source files are located. And you are done :)
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/8611196', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/451725/']}
jdg_87422
stackexchange
llm_judgeable_groundtruth_similarity
28052
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Let $E$ be an open set in $[0,1]^n$ and $m$ be the Lebesgue measure. Is it possible that $m(E)\neq m(\bar{E})$, where $\bar{E}$ stands for the closure of $E$? Now provide the response and nothing else.
Yes, this is possible. Already in dimension $1$. If you take a modified Cantor set $C$ in $[0,1]$, that is a nowhere dense compact subset of positive measure $\alpha \gt 0$. Its complement $E = [0,1] \smallsetminus C$ is open, has measure $1 - \alpha$ and its closure is all of $[0,1]$ by density. In higher dimensions simply take the product $E^n$. Another way of doing it is to enumerate the rationals in $[0,1]$ and taking $E = [0,1] \cap \bigcup_{n=1}^{\infty} (q_{n} - \frac{\varepsilon}{2^{n+1}}, q_{n} + \frac{\varepsilon}{2^{n+1}})$. Then $\mu(E) \leq \sum_{n=1}^{\infty} 2 \cdot \frac{\varepsilon}{2^{n+1}} = \varepsilon$, so for $\varepsilon \lt 1$ the set $E$ will be open and dense in $[0,1]$ but not all of $[0,1]$ and its closure will be all of $[0,1]$ again. Added: (in view of Davide's comment below). Note that there is a modified Cantor set $C_\alpha \subset [0,1]$ of any measure $0 \lt \alpha \lt 1$. Its complement $E_{\alpha} = [0,1] \smallsetminus C_\alpha$ is open and dense in $[0,1]$ and has measure $1-\alpha$ and by scaling this shows that for every pair of positive numbers $0 \lt a \lt b$ there is an open set $E_a$ of measure $\mu(E_a) = a$ whose closure $\overline{E_a}$ has measure $\mu(\overline{E_a}) = b$. I leave it as an easy exercise to construct an open set of measure $a \gt 0$ whose closure has infinite measure.
{}
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/28052', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/8484/']}
jdg_87423
stackexchange
llm_judgeable_groundtruth_similarity
2565039
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, I know I can dynamically allocate a two-dimensional array on the heap using the following code: int** someNumbers = malloc(arrayRows*sizeof(int*));for (i = 0; i < arrayRows; i++) { someNumbers[i] = malloc(arrayColumns*sizeof(int));} Clearly, this actually creates a one-dimensional array of pointers to a bunch of separate one-dimensional arrays of integers, and "The System" can figure out what I mean when I ask for: someNumbers[4][2]; But when I statically declare a 2D array, as in the following line...: int someNumbers[ARRAY_ROWS][ARRAY_COLUMNS]; ...does a similar structure get created on the stack, or is it of another form completely? (i.e. is it a 1D array of pointers? If not, what is it, and how do references to it get figured out?) Also, when I said, "The System," what is actually responsible for figuring that out? The kernel? Or does the C compiler sort it out while compiling? Now provide the response and nothing else.
A static two-dimensional array looks like an array of arrays - it's just laid out contiguously in memory. Arrays are not the same thing as pointers, but because you can often use them pretty much interchangeably it can get confusing sometimes. The compiler keeps track properly, though, which makes everything line up nicely. You do have to be careful with static 2D arrays like you mention, since if you try to pass one to a function taking an int ** parameter, bad things are going to happen. Here's a quick example: int array1[3][2] = {{0, 1}, {2, 3}, {4, 5}}; In memory looks like this: 0 1 2 3 4 5 exactly the same as: int array2[6] = { 0, 1, 2, 3, 4, 5 }; But if you try to pass array1 to this function: void function1(int **a); you'll get a warning (and the app will fail to access the array correctly): warning: passing argument 1 of ‘function1’ from incompatible pointer type Because a 2D array is not the same as int ** . The automatic decaying of an array into a pointer only goes "one level deep" so to speak. You need to declare the function as: void function2(int a[][2]); or void function2(int a[3][2]); To make everything happy. This same concept extends to n -dimensional arrays. Taking advantage of this kind of funny business in your application generally only makes it harder to understand, though. So be careful out there.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/2565039', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/300807/']}
jdg_87424
stackexchange
llm_judgeable_groundtruth_similarity
45289719
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm learning PowerShell and was using Write-Host to check variable assignments in a new PowerShell script file. Then I read an article suggesting this was a bad idea. So, in my .ps1 file I replaced statements like this: Write-Host "Start"Write-Host "End" ... with this: Write-Debug "Start"Write-Debug "End" But when I ran the saved script in Windows PowerShell ISE no output was written to the console. I appended -debug to the statement that calls the script, like so: PS E:\trialrun> .\MyScript.ps1 -debug But again, the output doesn't get written to the console. Apparently I'm using Write-Debug incorrectly. How can I get the debug output to write to the console? Now provide the response and nothing else.
tl;dr : Run $DebugPreference = 'Continue' to start seeing output from Write-Debug calls. When you're done, restore preference variable $DebugPreference to its default value, using $DebugPreference = 'SilentlyContinue' To turn on debug output for a given cmdlet or advanced function only, use the -Debug common parameter. Caveat : In Windows PowerShell (but no longer in PowerShell [Core] v6+, this will present an interactive debugging prompt for every Write-Debug statement encountered. Whether output from Write-Debug statements is printed is controlled by two mechanisms: Scope-wide : by the value of the $DebugPreference preference variable - see Get-Help about_Preference_Variables . Ad-hoc, command-scoped , when calling a cmdlet or advanced script/function (which overrides the $DebugPreference value) with the -Debug common parameter - see Get-Help about_CommonParameters . $DebugPreference defaults to SilentlyContinue , which explains why you don't see any output from Write-Debug statements by default. When you use common parameter -Debug , you effectively set $DebugPreference for the invoked command only , and: in Windows PowerShell , you invariably set it to the value Inquire , which not only prints Write-Debug messages, but also pauses at every such statement to ask how you want to proceed . in PowerShell [Core] v6+ , the value is now (more sensibly) set to Continue . For a custom script or function to support the -Debug common parameter, it must be an advanced one, declared with the [CmdletBinding()] attribute for its param() block, as Mathias' answer shows. Since, in Windows PowerShell , this prompt-at-every- Write-Debug -call behavior can be disruptive , $DebugPreference = 'Continue' may be the better approach. As stated, in PowerShell [Core] v6+ this is no longer a concern. Note: If, from inside an advanced function or script, you want to distinguish between $DebugPreference having been set as a preference variable by the caller vs. common parameter -Debug having been passed (which is translated to a function/script-local $DebugPreference variable), use $PSBoundParameters.ContainsKey('Debug') ; $true indicates that -Debug was used. Reference official documentation: https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/write-debug By default, debug messages are not displayed in the console, but youcan display them by using the Debug parameter or the $DebugPreferencevariable.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/45289719', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/993856/']}
jdg_87425
stackexchange
llm_judgeable_groundtruth_similarity
1969037
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 handle exceptions on the AppDomain.CurrentDomain.UnhandledException callback? I want to do the following: Show my own "an exception hasoccured" dialog, with a "Send Report"button After the user dismissed thebox, I want to close my app, but I donot want to Windows default crash dialog "Theapplication needs to close" box toshow up. Can this be done? Now provide the response and nothing else.
Q: Does? A: No - Clear does not dispose the items (they could be used in other parts of your application). So, if your ToolStripItems are standard .NET ones, should Clear be sufficient? After some reflection I'd say "probably not". Yeah, this is true that if you will have any references to the ToolStripItem in other part of your application, the .NET GarbageCollector will destroy(use the class destructor ) it automatically. But, it will not call the Dispose(true) method , that is, however, required for the form's IDisposable components. Read a propos this and this . Actually, I believe that you will, however, need to explicitly Dispose your Items, like the ToolStrip's Dispose method does (replace this by yourToolStrip ): if (!this.Items.IsReadOnly){ for (int i = this.Items.Count - 1; i >= 0; i--) { this.Items[i].Dispose(); } this.Items.Clear();} EDIT I also created the following thread to clarify this question more generally.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1969037', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/97060/']}
jdg_87426
stackexchange
llm_judgeable_groundtruth_similarity
2667908
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I know I can find out if a variable is null in Java using these techniques: if (var==null) -> too much work try { ... } catch (NullPointerException e) { ...} -> it tells me what line is throwing the exception using the debugger -> by hand, too slow Consider this line of code: if (this.superSL.items.get(name).getSource().compareTo(VIsualShoppingList.Source_EXTRA)==0) { I would like to know if there's a generic way to find out programatically what variable (not just the line) is throwing the NullPointerException in a certain area of code. In the example, knowing that Now provide the response and nothing else.
Since it's possible to cause a null pointer exception without even involving a variable: throw new NullPointerException(); I would have to say that there is no generic way to pin down a null pointer exception to a specific variable. Your best bet would be to put as few as possible statements on each line so that it becomes obvious what caused the null pointer exception. Consider refactoring your code in the question to look something like this: List items = this.superSL.items;String name = items.get(name);String source = name.getSource();if (source.compareTo(VIsualShoppingList.Source_EXTRA) == 0) { // ...} It's more lines of code to be sure. But it's also more readable and more maintainable.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2667908', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/110514/']}
jdg_87427
stackexchange
llm_judgeable_groundtruth_similarity
11217674
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 calculate the exact location of a mobile device inside a building ( so no GPS access) I want to do this using the signal strength(in dBm) of at least 3 fixed wifi signals(3 fixed routers of which I know the position) Google already does that and I would like to know how they figure out the exact location based on the this data Check this article for more details : http://www.codeproject.com/Articles/63747/Exploring-GoogleGears-Wi-Fi-Geo-Locator-Secrets Now provide the response and nothing else.
FSPL depends on two parameters: First is the frequency of radio signals;Second is the wireless transmission distance. The following formula can reflect the relationship between them. FSPL (dB) = 20log10(d) + 20log10(f) + Kd = distancef = frequencyK= constant that depends on the units used for d and fIf d is measured in kilometers, f in MHz, the formula is:FSPL (dB) = 20log10(d)+ 20log10(f) + 32.44 From the Fade Margin equation, Free Space Path Loss can be computed with the following equation. Free Space Path Loss=Tx Power-Tx Cable Loss+Tx Antenna Gain+Rx Antenna Gain - Rx Cable Loss - Rx Sensitivity - Fade Margin With the above two Free Space Path Loss equations, we can find out the Distance in km. Distance (km) = 10(Free Space Path Loss – 32.44 – 20log10(f))/20 The Fresnel Zone is the area around the visual line-of-sight that radio waves spread out into after they leave the antenna. You want a clear line of sight to maintain strength, especially for 2.4GHz wireless systems. This is because 2.4GHz waves are absorbed by water, like the water found in trees. The rule of thumb is that 60% of Fresnel Zone must be clear of obstacles. Typically, 20% Fresnel Zone blockage introduces little signal loss to the link. Beyond 40% blockage the signal loss will become significant. FSPLr=17.32*√(d/4f)d = distance [km]f = frequency [GHz]r = radius [m] Source : http://www.tp-link.com/en/support/calculator/
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/11217674', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1319139/']}
jdg_87428
stackexchange
llm_judgeable_groundtruth_similarity
942257
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: $k_n$ is defined with $k_1=0$ and $k_{n+1}=k_n+\sqrt{1+k_n^2}$.This is homework, please do not provide a complete solution edit : One of the many things I tried is to make it the root of an equation like this . I first found that and then tried $k_{n+1}=\sqrt{1+2 k_n k_{n+1}}$ then $(\lim_{n\to \infty} k_{n+1}/2^{n+1})^2=\lim_{n\to \infty} (1+2 k_n k_{n+1})/2^{2n+2}=\lim_{n\to \infty} k_n k_{n+1}/2^{2n+1}$ but then I was stuck and found nothing to continue. All my other trials ended up stuck. Now provide the response and nothing else.
You need to think just a little bit outside the box for this one and not bruteforce your way through to a solution. The first thing that jumped at me was the $\sqrt{1+k^2}$, which made me think that either the hyperbolic sine and cosine are going to be useful here, or it's the tangent and secant. The latter was the right approach. First, two elementary lemmas we'll use: Lemma 1: $\displaystyle \tan{x}+\sec{x}=\tan{\left( \frac{x}{2}+\frac{\pi}{4}\right)}$ Lemma 2: $\displaystyle \sum_{i=1}^n 2^{-i}=1-2^{-n}$ Now, we have: $k_0=\tan{0}=0$ $k_1=\tan{0}+\sqrt{1+\tan{0}^2}=\tan{0}+|\sec{0}|=\tan{0}+\sec{0}= \tan{(0/2+\pi/4)}$ $k_2=\tan{\pi/4}+\sec{\pi/4}=\tan{\left(\frac{\pi}{2}\left(\frac{1}{2}+\frac{1}{4} \right)\right)}$ ... $k_n=\tan{\left(\frac{\pi}{2}\left(\frac{1}{2}+\frac{1}{4} \cdots \frac{1}{2^n} \right)\right)}=\tan{\left(\frac{\pi}{2}\left(1-2^{-n} \right)\right)}$ The general form above is only true because for $0 \leq x < \pi/2$, we have $|\sec{x}|=\sec{x}$. So now, we calculate our limit:\begin{eqnarray*}\displaystyle \lim_{n\to \infty} \frac{k_n}{2^n} &=& \lim_{n\to \infty} 2^{-n} \tan{\left(\frac{\pi}{2}\left(1-2^{-n} \right)\right)} \\ &=& \lim_{x\to 0} x \tan{\left(\frac{\pi}{2}\left(1-x \right)\right)}\\&=& \left( \lim_{x\to 0} \sin{\frac{\pi}{2}(1-x)} \right) \cdot \left( \lim_{x\to 0} \frac{x}{\cos{\frac{\pi}{2}(1-x)}} \right)\\&=& 1 \cdot \lim_{x\to 0} \frac{\frac{\mathrm{d}}{\mathrm{d} x}x}{\frac{\mathrm{d}}{\mathrm{d} x}\cos{\frac{\pi}{2}(1-x)}} \\&=& \lim_{x\to 0} \frac{1}{\frac{\pi}{2} \sin{\frac{\pi}{2}(1-x)}}\\&=& \frac{1}{\frac{\pi}{2} \sin{\frac{\pi}{2}(1-0)}}\\&=& \boxed{\frac{2}{\pi}}\end{eqnarray*} And of course, the fourth equality is justified by l'Hôpital's rule. So finally, $\displaystyle \lim_{n \to \infty} \frac{k_n}{2^n}=\frac{2}{\pi}$ .
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/942257', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/178056/']}
jdg_87429
stackexchange
llm_judgeable_groundtruth_similarity
32781
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: The below graphs are residual scatter plots of a regression test for which "normality", "homoscedasticity" and "independence" assumptions have already been met for sure! For testing the "linearity" assumption, although, by looking at the graphs, it can be guessed that the relationship is curvilinear, but the question is:How can the value for "R2 Linear" be used to test the linearity assumption? What's the acceptable range for the value of "R2 Linear" to decide if the relationship is being linear? What to do when the linearity assumption is not met and transforming the IVs also doesn't help?!! Here is the link to the full results of the test. Scatter plots: Now provide the response and nothing else.
Note that the linearity assumption you're speaking of only says that the conditional mean of $Y_i$ given $X_i$ is a linear function . You cannot use the value of $R^2$ to test this assumption. This is because $R^2$ is merely the squared correlation between the observed and predicted values and the value of the correlation coefficient does not uniquely determine the relationship between $X$ and $Y$ (linear or otherwise) and both of the following two scenarios are possible: High $R^2$ but the linearity assumption is still be wrong in an important way Low $R^2$ but the linearity assumption still satisfied I will discuss each in turn: (1) High $R^2$ but the linearity assumption is still be wrong in an important way: The trick here is to manipulate the fact that correlation is very sensitive to outliers . Suppose you have predictors $X_1, ..., X_n$ that are generated from a mixture distribution that is standard normal $99\%$ of the time and a point mass at $M$ the other $1\%$ and a response variable that is $$ Y_i = \begin{cases} Z_i & {\rm if \ } X_i \neq M \\ M & {\rm if \ } X_i = M \\\end{cases} $$ where $Z_i \sim N(\mu,1)$ and $M$ is a positive constant much larger than $\mu$, e.g. $\mu=0, M=10^5$. Then $X_i$ and $Y_i$ will be almost perfectly correlated: u = runif(1e4)>.99x = rnorm(1e4)x[which(u==1)] = 1e5y = rnorm(1e4)y[which(x==1e5)] = 1e5cor(x,y)[1] 1 despite the fact that the expected value of $Y_i$ given $X_i$ is not linear - in fact it is a discontinuous step function and the expected value of $Y_i$ doesn't even depend on $X_i$ except when $X_i = M$. (2) Low $R^2$ but the linearity assumption still satisfied: The trick here is to make the amount of "noise" around the linear trend large. Suppose you have a predictor $X_i$ and response $Y_i$ and the model $$ Y_i = \beta_0 + \beta_1 X_i + \varepsilon_i $$ was the correct model. Therefore, the conditional mean of $Y_i$ given $X_i$ is a linear function of $X_i$, so the linearity assumption is satisfied. If ${\rm var}(\varepsilon_i) = \sigma^2$ is large relative to $\beta_1$ then $R^2$ will be small. For example, x = rnorm(200)y = 1 + 2*x + rnorm(200,sd=5)cor(x,y)^2[1] 0.1125698 Therefore, assessing the linearity assumption is not a matter of seeing whether $R^2$ lies within some tolerable range , but it is more a matter of examining scatter plots between the predictors/predicted values and the response and making a (perhaps subjective) decision. Re: What to do when the linearity assumption is not met and transforming the IVs also doesn't help?!! When non-linearity is an issue, it may be helpful to look at plots of the residuals vs. each predictor - if there is any noticeable pattern, this can indicate non-linearity in that predictor. For example, if this plot reveals a "bowl-shaped" relationship between the residuals and the predictor, this may indicate a missing quadratic term in that predictor. Other patterns may indicate a different functional form. In some cases, it may be that you haven't tried to right transformation or that the true model isn't linear in any transformed version of the variables (although it may be possible to find a reasonable approximation). Regarding your example: Based on the predicted vs. actual plots (1st and 3rd plots in the original post) for the two different dependent variables, it seems to me that the linearity assumption is tenable for both cases. In the first plot, it looks like there may be some heteroskedasticity, but the relationship between the two does look pretty linear. In the second plot, the relationship looks linear, but the strength of the relationship is rather weak, as indicated by the large scatter around the line (i.e. the large error variance) - this is why you're seeing a low $R^2$.
{}
{'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/32781', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/12481/']}
jdg_87430
stackexchange
llm_judgeable_groundtruth_similarity
340996
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 am writing a wrapper for a REST API and I have run into something I have never had to ask myself before. This API is for E-Commerce transactions, it has SALE and RETURN endpoints (and some other endpoints that aren't critical to this discussion). The SALE and RETURN requests are nearly identical, with the exception that the SALE request has an additional property. public class ReturnRequest{ [JsonProperty("cashier_id")] public string CashierId { get; set; } [JsonProperty("amount")] public decimal Amount { get; set; } [JsonProperty("pos_id")] public CustomClass PosId { get; set; } }public class SaleRequest{ [JsonProperty("cashier_id")] public string CashierId { get; set; } [JsonProperty("amount")] public decimal Amount { get; set; } [JsonProperty("pos_id")] public CustomClass PosId { get; set; } [JsonProperty("zip_code")] public string ZipCode { get; set; }} Originally I just had the SALE request POCO inherit the RETURN request POCO: public class ReturnRequest{ [JsonProperty("cashier_id")] public string CashierId { get; set; } [JsonProperty("amount")] public decimal Amount { get; set; } [JsonProperty("pos_id")] public CustomClass PosId { get; set; } }public class SaleRequest : ReturnRequest{ [JsonProperty("zip_code")] public string ZipCode { get; set; }} But to me that didn't seem very intuitive or clear (SALE and RETURN are different things, why would one inherit another?) I then decided to put the common properties into a base abstract class: public abstract class BaseRequest{ [JsonProperty("cashier_id")] public string CashierId { get; set; } [JsonProperty("amount")] public decimal Amount { get; set; } [JsonProperty("pos_id")] public CustomClass PosId { get; set; } }public class ReturnRequest : BaseRequest{}public class SaleRequest : BaseRequest{ [JsonProperty("zip_code")] public string ZipCode { get; set; }} But then that leaves me with a class that is essentially the same thing as the BaseRequest. At first I justified this because I wanted the classes to be straightforward and verbose. It creates a clear difference between the classes and I can modify the SALE or RETURN without worrying about the other (or even the base classs). However now I am wondering if I am thinking through this wrong, is having essentially a blank class a bad idea? EDIT: I changed the property names and types up a bit to more closely represent some of the types of properties. Now provide the response and nothing else.
My favorite example of inheriting and adding nothing new is this: public class LoginException : System.ApplicationException{} Why? Because I've said all I need to say with that wonderfully descriptive class name. Sure if I want to add a dynamic message I'll need to add a constructor. But if I don't, why should I? Your example lacks this clarity because the semantic issues are hidden with names like Prop1 . I love replacing inheritance with composition and delegation but in this case, when I do that, I end up looking at this: SaleRequest sr = new SaleRequest(new ReturnRequest()); Now I gotta ask, does that make semantic sense? I can't request a sale without requesting a return? Sure, mechanically it makes sense because the 'Props' are 'correct' but those are just datatypes. Would it still make sense if they had meaningful names? Your attempt to fix this problem looks like this: SaleRequest sr = new SaleRequest(new BaseRequest()); Which again is semantically anemic. Base? That doesn't tell me what belongs in this class and what doesn't belong in it. That's not a good name. If BaseRequest had a name that made it clear that Prop1 and Prop2 (whatever those are) belong in it and BaseRequest had a name for something that is clearly part of, or all of, the other two requests then I'd be fine with this. As it stands, I don't know what is supposed to be going on when I look at this code. That's not a good thing. I have no problem with empty classes. But please, give them good names. It's really the only thing they have to offer.
{}
{'log_upvote_score': 5, 'links': ['https://softwareengineering.stackexchange.com/questions/340996', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/260680/']}
jdg_87431
stackexchange
llm_judgeable_groundtruth_similarity
597828
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am struggling with the idea that all compact subsets of a metric space are closed after reading chapter 2 of Rudin's Principles of Mathematical Analysis. The reason I am confused is that it seems unreasonable that a compact subset must be closed. If we were to take an open subset $K$ of a compact subset $Y$ in a metric space $X$, where $K$ is open relative to $X$, then every finite subcover of $Y$ would also be a finite subcover of $K$. But then, $K$ would be both compact and open in $X$, which contradicts the theorem that all compact subsets in $X$ are closed. Could someone please explain to me why my reasoning is incorrect and how it is that compact subsets of metric spaces must be closed? Thank you, Evan Now provide the response and nothing else.
The problem with your reasoning is that $K$ may have an open cover $\mathscr{U}$ that does not arise from an open cover of $Y$, so that compactness of $Y$ doesn’t tell you anything about $\mathscr{U}$. It’s easiest, I think, to prove the contrapositive: if $A\subseteq X$ is not closed, then $A$ is not compact. Let $\langle X,d\rangle$ be a metric space, and suppose that $A\subseteq X$ is not closed. Then there is a point $p\in(\operatorname{cl}A)\setminus A$. For $n\in\Bbb Z^+$ let $$U_n=\left\{x\in X:d(x,p)>\frac1n\right\}\;,$$ and show that $\{U_n:n\in\Bbb Z^+\}$ is an open cover of $A$ with no finite subcover.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/597828', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/114250/']}
jdg_87432
stackexchange
llm_judgeable_groundtruth_similarity
12319083
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 happens if I want to select all the rows in a data.table that do not contain a particular value in the key variable using binary search? By the way, what is the correct jargon for what I want to do? Is it "nojoin"? Is it "negative selection"? DT = data.table(x=rep(c("a","b","c"),each=3), y=c(1,3,6), v=1:9)setkey(DT,x) Lets do a positive selection for all rows where x=="a" but using binary search DT["a"] That's beautiful but I want the opposite of that. I want all the rows that are not "a" in other words where x!="a" DT[x!="a"] That is a vector scanning. The above line works but is uses vector scanning. I want to use binary. I was expecting the following to work, but alas... DT[!"a"]DT[-"a"] The above two do not work and trying to play with nomatch got me nowhere. Now provide the response and nothing else.
The idiom is this: DT[-DT["a", which=TRUE]] x y v1: b 1 42: b 3 53: b 6 64: c 1 75: c 3 86: c 6 9 Inspiration from: The mailing list posting Return Select/Join that does NOT match? The previous question non-joins with data.tables Matthew Dowle's answer to Porting set operations from R's data frames to data tables: How to identify duplicated rows? Update . New in v1.8.3 is not-join syntax. Farrel's first expectation ( ! rather than - ) has been implemented : DT[-DT["a",which=TRUE,nomatch=0],...] # old idiomDT[!"a",...] # same result, now preferred. See the NEWS item for more detailed info and example.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12319083', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/168139/']}
jdg_87433
stackexchange
llm_judgeable_groundtruth_similarity
14442964
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 use a SSIS for checking if a database value changes from 0 to 1 (every 5 second)?I've tryed with a For Loop Container but it seems it doesn't works. Thank you Now provide the response and nothing else.
Use the System.Management namespace and Win32_Volume WMI class for this. You can query for an instance with a DriveLetter of C: and retrieve its FreeSpace property as follows: ManagementPath path = new ManagementPath() { NamespacePath = @"root\cimv2", Server = "<REMOTE HOST OR IP>"};ManagementScope scope = new ManagementScope(path);string condition = "DriveLetter = 'C:'";string[] selectedProperties = new string[] { "FreeSpace" };SelectQuery query = new SelectQuery("Win32_Volume", condition, selectedProperties);using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query))using (ManagementObjectCollection results = searcher.Get()){ ManagementObject volume = results.Cast<ManagementObject>().SingleOrDefault(); if (volume != null) { ulong freeSpace = (ulong) volume.GetPropertyValue("FreeSpace"); // Use freeSpace here... }} There is also a Capacity property that stores the total size of the volume.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14442964', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1764509/']}
jdg_87434
stackexchange
llm_judgeable_groundtruth_similarity
1707620
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 implementing an adaptation of Viola-Jones' face detection algorithm . The technique relies upon placing a subframe of 24x24 pixels within an image, and subsequently placing rectangular features inside it in every position with every size possible. These features can consist of two, three or four rectangles. The following example is presented. They claim the exhaustive set is more than 180k (section 2): Given that the base resolution of the detector is 24x24, the exhaustive set of rectangle features is quite large, over 180,000 . Note that unlike the Haar basis, the set of rectangle features is overcomplete. The following statements are not explicitly stated in the paper, so they are assumptions on my part: There are only 2 two-rectangle features, 2 three-rectangle features and 1 four-rectangle feature. The logic behind this is that we are observing the difference between the highlighted rectangles, not explicitly the color or luminance or anything of that sort. We cannot define feature type A as a 1x1 pixel block; it must at least be at least 1x2 pixels. Also, type D must be at least 2x2 pixels, and this rule holds accordingly to the other features. We cannot define feature type A as a 1x3 pixel block as the middle pixel cannot be partitioned, and subtracting it from itself is identical to a 1x2 pixel block; this feature type is only defined for even widths. Also, the width of feature type C must be divisible by 3, and this rule holds accordingly to the other features. We cannot define a feature with a width and/or height of 0. Therefore, we iterate x and y to 24 minus the size of the feature. Based upon these assumptions, I've counted the exhaustive set: const int frameSize = 24;const int features = 5;// All five feature types:const int feature[features][2] = {{2,1}, {1,2}, {3,1}, {1,3}, {2,2}};int count = 0;// Each feature:for (int i = 0; i < features; i++) { int sizeX = feature[i][0]; int sizeY = feature[i][1]; // Each position: for (int x = 0; x <= frameSize-sizeX; x++) { for (int y = 0; y <= frameSize-sizeY; y++) { // Each size fitting within the frameSize: for (int width = sizeX; width <= frameSize-x; width+=sizeX) { for (int height = sizeY; height <= frameSize-y; height+=sizeY) { count++; } } } }} The result is 162,336 . The only way I found to approximate the "over 180,000" Viola & Jones speak of, is dropping assumption #4 and by introducing bugs in the code. This involves changing four lines respectively to: for (int width = 0; width < frameSize-x; width+=sizeX)for (int height = 0; height < frameSize-y; height+=sizeY) The result is then 180,625 . (Note that this will effectively prevent the features from ever touching the right and/or bottom of the subframe.) Now of course the question: have they made a mistake in their implementation? Does it make any sense to consider features with a surface of zero? Or am I seeing it the wrong way? Now provide the response and nothing else.
Upon closer look, your code looks correct to me; which makes one wonder whether the original authors had an off-by-one bug. I guess someone ought to look at how OpenCV implements it! Nonetheless, one suggestion to make it easier to understand is to flip the order of the for loops by going over all sizes first, then looping over the possible locations given the size: #include <stdio.h>int main(){ int i, x, y, sizeX, sizeY, width, height, count, c; /* All five shape types */ const int features = 5; const int feature[][2] = {{2,1}, {1,2}, {3,1}, {1,3}, {2,2}}; const int frameSize = 24; count = 0; /* Each shape */ for (i = 0; i < features; i++) { sizeX = feature[i][0]; sizeY = feature[i][1]; printf("%dx%d shapes:\n", sizeX, sizeY); /* each size (multiples of basic shapes) */ for (width = sizeX; width <= frameSize; width+=sizeX) { for (height = sizeY; height <= frameSize; height+=sizeY) { printf("\tsize: %dx%d => ", width, height); c=count; /* each possible position given size */ for (x = 0; x <= frameSize-width; x++) { for (y = 0; y <= frameSize-height; y++) { count++; } } printf("count: %d\n", count-c); } } } printf("%d\n", count); return 0;} with the same results as the previous 162336 To verify it, I tested the case of a 4x4 window and manually checked all cases (easy to count since 1x2/2x1 and 1x3/3x1 shapes are the same only 90 degrees rotated): 2x1 shapes: size: 2x1 => count: 12 size: 2x2 => count: 9 size: 2x3 => count: 6 size: 2x4 => count: 3 size: 4x1 => count: 4 size: 4x2 => count: 3 size: 4x3 => count: 2 size: 4x4 => count: 11x2 shapes: size: 1x2 => count: 12 +-----------------------+ size: 1x4 => count: 4 | | | | | size: 2x2 => count: 9 | | | | | size: 2x4 => count: 3 +-----+-----+-----+-----+ size: 3x2 => count: 6 | | | | | size: 3x4 => count: 2 | | | | | size: 4x2 => count: 3 +-----+-----+-----+-----+ size: 4x4 => count: 1 | | | | |3x1 shapes: | | | | | size: 3x1 => count: 8 +-----+-----+-----+-----+ size: 3x2 => count: 6 | | | | | size: 3x3 => count: 4 | | | | | size: 3x4 => count: 2 +-----------------------+1x3 shapes: size: 1x3 => count: 8 Total Count = 136 size: 2x3 => count: 6 size: 3x3 => count: 4 size: 4x3 => count: 22x2 shapes: size: 2x2 => count: 9 size: 2x4 => count: 3 size: 4x2 => count: 3 size: 4x4 => count: 1
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1707620', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/154306/']}
jdg_87435
stackexchange
llm_judgeable_groundtruth_similarity
94456
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 instance of a System.Drawing.Bitmap and would like to make it available to my WPF app in the form of a System.Windows.Media.Imaging.BitmapImage . What would be the best approach for this? Now provide the response and nothing else.
How about loading it from MemoryStream? using(MemoryStream memory = new MemoryStream()){ bitmap.Save(memory, ImageFormat.Png); memory.Position = 0; BitmapImage bitmapImage = new BitmapImage(); bitmapImage.BeginInit(); bitmapImage.StreamSource = memory; bitmapImage.CacheOption = BitmapCacheOption.OnLoad; bitmapImage.EndInit();}
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/94456', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2723/']}
jdg_87436
stackexchange
llm_judgeable_groundtruth_similarity
1224519
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 $\forall n > 1, \quad2^n - 1 \pmod n \neq 0$ I've thought of the induction but I can't figure out how to prove the step. Fermat's theorem (and its variations) aren't particularly useful as well. Any hint would be greatly appreciated! Now provide the response and nothing else.
Assume you have got a $n>1$, so that $2^n \equiv 1 \pmod{n}$. Take the smallest prime divisor $p$ of $n$. You have $p\;|\;n\;|\;2^n-1$, hence $2^n\equiv 1 \pmod{p}$. But you have also, from Fermat's little theorem , that $2^{p-1}\equiv 1\pmod{p}$. Since $p-1$ and $n$ are coprime, you have thus by Bézout's identity , some $a,b$ such that $a(p-1)+bn=1$, and then $$1\equiv(2^{p-1})^a\cdot (2^n)^b \equiv 2^{a(p-1)+bn}\equiv 2^1 \pmod{p}$$ Thus $2^1\equiv 1\pmod{p}$, or equivalently $p\;|\;1$, but this is not possible.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1224519', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/229508/']}
jdg_87437
stackexchange
llm_judgeable_groundtruth_similarity
163074
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: So I've been learning how to forecast over this summer and I've been using Rob Hyndman's book Forecasting: principles and practice. I've been using R, but my questions aren't about code. For the data I've been using, I've found that an average forecast of multiple models has produced higher accuracy levels that any sole model by itself. Recently I read an blog that talked about averaging forecasting methods and assigning weights to them. So in my case, lets say I assign 11 different models to my set of data (Arima, ETS, Holt Winters, naive, snaive, and so forth) and I want to average a few of these to get a forecast. Has anyone had any experience with this or can point me to an article that might give some insight on the best way of going about this? As of right now, I'm using cross validation and Mean Absolute Error to figure out which models perform best and which perform worst. I can even use this to identify the top k # of models. I guess my questions are 1) How many models would you suggest selecting? (2,3,4,5,6, etc) 2) Any ideas on weights? (50% to the best, 25% to the second best, 15% third best, 10% to the 4th best, etc) 3) Are any of these forecasting models redundant and shouldn't be included? (Arima, snaive, naive, HW's "additive", ETS, HoltWinters exponential smoothing, HoltWinters smoothing w/ trend, HoltWinters w/ trend/seasonality, multiple regression) Now provide the response and nothing else.
The answers to your questions in order How Many Models Usually as many as you want, but this can be limited by the amount of data you have. Also depends on the method you are using to derive the weights (which I explain more below) How to Assign Weights There are many, here are the five most popular off the top of my head, though non of them use Mean absolute error. Equal Weights for all models pros: Simple, easy to implement Often outperforms more complex techniques You can, in theory, add as many models as you want cons: May be too oversimplified No inherent method for ranking models References Aiolfi, M. and A. Timmermann (2006), “Persistence in Forecasting Performance and ConditionalCombination Strategies”, Journal of Econometrics, 35 (1-2), 31-53. Manescu, Cristiana, and Ine Van Robays. "Forecasting the Brent oil price: addressing time-variation in forecast performance." (2014). Inverse Mean Square Forecast Error (MSFE) ratio : For $M$ models the combined, $h$-step ahead forecast is$$\hat y_{t+h}=\sum_{m=1}^{M} w_{m,h,t}\hat y_{t+h,m},\;\;\;w_{m,h,t}=\frac{(1/msfe_{m,h,t})^k}{\sum_{j=1}^M (1/msfe_{j,h,t})^k}$$ where $\hat y_{t+h,m}$ is the point forecast forecast for $h$ steps ahead at time $t$ from model $m$. In most applications $k=1$. pros: Firm theoretical backing It's been around for a while and is well accepted in the literature You can, in theory, add as many models as you want cons: Based solely on point estimate forecasts, does not consider entire forecast distribution (i.e. most applied models will give us an entire parametric distribution for the forecast, the normal distribution is common, $y_{t+h,m} \sim N(\hat y_{t+h,m},\sigma_{t+h,m})$. many argue that not utilizing this additional parametric information by only considering $\hat y_{t+h,m}$ results in sub-optimal forecasts) References Bates, John M., and Clive WJ Granger. "The combination of forecasts." Or (1969): 451-468. Massimiliano Marcellino, ."Forecast pooling for short time series of macroeconomic variables,"Working Papers 212, IGIER (Innocenzo Gasparini Institute for Economic Research), Bocconi University (2002). Bayesian Forecast Combination : For point estimate forecast combination the formula is $$ \hat y_{t+h}=\sum_{m=1}^M w(m|y_1,...,y_t) \hat y_{t+h,m} $$and the combined forecast distribution is $$ f(y_{t+h}|y_1,...,y_t)=\sum_{m=1}^M w(m|y_1,...,y_t) f_m(y_{t+h}|y_1,...,y_t)$$where $f_m$ is the $m$th model forecast distribution (a pdf). The weights $w(m|y_1,...,y_t)$ are such that $\sum_{m=1}^{M} w(m|y_1,...,y_t)=1$ and $ w(m|y_1,...,y_t)>0$ for all $m$. The weights can be calculated as either the traditional posterior probability of each $m$ model via Bayesian Model Averaging (in-sample technique similar to BIC, but scaled) or from scaling the predictive likelihood (out-of-sample predictive density) of each model. I forgo showing exactly how to calculate the weights for brevity. If you are curious see references pros: Considers the entire forecast distribution when calculating weights, not just the point forecast You can, in theory, add as many models as you want cons: Requires knowledge of Bayesian inference and estimation which can be quite involved Assumes that at least one of the $m$ models is the true data generating process, which is a strong assumption. Requires the researcher to specify priors for the parameters in each forecasting model in addition to a discrete prior over all $m$ models References Hoeting, Jennifer A., et al. "Bayesian model averaging." In Proceedings of the AAAI Workshop on Integrating Multiple Learned Models. 1998. Eklund, Jana, and Sune Karlsson. "Forecast combination and model averaging using predictive measures." Econometric Reviews 26.2-4 (2007): 329-363. Andersson, Michael K., and Sune Karlsson. "Bayesian forecast combination for VAR models." Bayesian Econometrics (2008): 501-524. Optimal Prediction Pools : Same Idea as Bayesian forecast except that the weights are found by maximizing the following "score function" (WLOG assume h=1)$$ \max_{\mathbf{w}}\sum_{i=1}^{t}\ln\bigg[\sum_{m=1}^{M} w_m f_m(y_i;y_1,...,y_{i-1})\bigg] \quad{(1)}$$ $$s.t.\;\;\sum_{m=1}^{M} w_m=1\;and\; w_m \geq 0\; \forall m $$ where $f_m$ is the predictive density/likelihood of model $m$ that can be calculated with either Bayesian or frequentest methodology (see references for more information on this). pros: Considers the entire forecast distribution when calculating weights, not just the point forecast Can be implemented using either frequentest or Bayesian techniques and is usually simpler to estimate than traditional Bayesian forecasting combination Unlike traditional Bayesian forecast combination it does not need to assume one of the $m$ models is the true data generating process cons: because equation (1) requires numeric optimization, the amount of models you can include is limited by the amount of data you have available. Further, if some models produce highly correlated forecasts, equation (1) may be very challenging to optimize References Geweke, John, and Gianni Amisano. "Optimal prediction pools." Journal of Econometrics 164.1 (2011): 130-141. Durham, Garland, and John Geweke. "Improving asset price prediction when all models are false." Journal of Financial Econometrics 12.2 (2014): 278-306. Various other point estimate based techniques : (1) an ordinary-least squared estimate of the weights obtained by regressing the actual realized values on the point estimate forecasts ($y_{t+h}=\beta_0 +w_1\hat y_{t+h,1}+...+w_M\hat y_{t+h,M}+u_{t+h}$),(2) trimming approaches that drop the worst performing models form an equally weighted combination, (3) set the weights equal to the percentage of times a forecast has the minimum MSFE, etc. pros and cons: vary depending on technique References Timmermann, A. (2006), “Forecast Combinations”, Handbook of Economic Forecasting, 1, 135–196. Are Any of the Forecasting Models Redundant/Excludable The Holt-Winters models are likly to be similar so maybe throw a couple of those out. Averaging forecasts is like diversifying a financial portfolio, you want your models to be diverse. With some of the above averaging techniques it doesn't hurt to include redundant models, with others it does. You can also find a friendly introduction here , with couple of more good ways to average forecasts (Constrained Least Squares for example) along with an R implementation.
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/163074', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/77637/']}
jdg_87438
stackexchange
llm_judgeable_groundtruth_similarity
1981179
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: How can we prove the following inequality for $a,b,c>0$: $$\dfrac{ab}{a^2+b^2}+\dfrac{bc}{b^2+c^2}+\dfrac{ca}{c^2+a^2}\leq \dfrac{a^2}{a^2+b^2}+\dfrac{b^2}{b^2+c^2}+\dfrac{c^2}{c^2+a^2} \ ?$$ Now provide the response and nothing else.
Fix $\epsilon>0$. Since $f \in X$ is uniformly continuous (by Heine theorem), there exists $k \in \mathbb{N}$ such that $$|x-y| \leq \frac{1}{k} \implies |f(x)-f(y)| \leq \epsilon.$$ Set $x_i := \frac{i}{N}$, $i \in \{0,\ldots,N\}$ for some $N \geq k$ (which we will choose later) and denote by $\chi$ the piecewise linear function satisfying $$\chi(x_i) = 0 \qquad \text{for all $i \in \{1,\ldots,N\}$ odd}$$ and $$\chi(x_i) = 1 \qquad \text{for all $i \in \{1,\ldots,N\}$ even}.$$ The function $\chi$ has slope $N$ around any point $x \in [0,1]$. Now let $p$ be a piecewise linear function such that $p(i/k) = f(i/k)$ for all $i \in \{0,\ldots,k\}$. Note that the slope of this function is at most $\epsilon k$. Therefore the slope of the function $$f_{\epsilon}(x) := p(x) + \frac{\epsilon}{2} \chi(x)$$ is at least $\frac{\epsilon}{2} N - \epsilon k$. If we choose $N \in \mathbb{N}$ sufficiently large, we have $f_{\epsilon} \in U_n$. Since $$\|f-f_{\epsilon}\|_{\infty} \leq \|f-p\|_{\infty} + \frac{\epsilon}{2} \|\chi\|_{\infty} \leq \frac{3}{2} \epsilon$$ this proves that $U_n$ is dense in $X$. The picture which you should have in mind looks as follows: $\hspace{130pt}$ So for any continuous function there exists a "saw-tooth" function which is very close to $f$ (close in the sense of supremum norm).
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1981179', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/185138/']}
jdg_87439
stackexchange
llm_judgeable_groundtruth_similarity
49405338
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 failing Jest test case for code where I'm using promises. It looks like the resolution of the promise is happening after the test has completed, meaning I can't check that my promise resolution code has been executed. It feels like I need to make the event loop tick so the promise is resolved and the resolution code is executed, but haven't found anything that can do that in Jest. Here's a sample case. The code to be tested: const Client = require('SomeClient');module.exports.init = () => { Client.load().then(() => { console.log('load resolved'); setTimeout(() => { console.log('load setTimeout fired, retrying init'); module.exports.init(); }, 1000); });}; Test code: jest.useFakeTimers();const mockLoad = jest.fn().mockImplementation(() => Promise.resolve());jest.mock('SomeClient', () => { return { load: mockLoad };}, { virtual: true });const promiseTest = require('./PromiseTest');describe('SomeClient Promise Test', () => { it('retries init after 10 secs', () => { promiseTest.init(); expect(mockLoad).toHaveBeenCalledTimes(1); expect(setTimeout).toHaveBeenCalledTimes(1); // <-- FAILS - setTimeout has not been called jest.runAllTimers(); expect(mockLoad).toHaveBeenCalledTimes(2); });}); The expect(setTimeout).toHaveBeenCalledTimes(1); assertion fails ( setTimeout has not been called at all), I think because the promise has not yet been resolved. Am I doing something wrong here? Can I cause the event loop to tick inside the test? Now provide the response and nothing else.
To tick the event loop inside your test, you should make it asynchronous.A nice workaround was suggested on GitHub . Having flushPromises as suggested there function flushPromises() { return new Promise(resolve => setImmediate(resolve));} your test will look like describe('SomeClient Promise Test', () => { it('retries init after 10 secs', () => { promiseTest.init(); expect(mockLoad).toHaveBeenCalledTimes(1); // notice return so jest knows that the test is asynchronous return flushPromises() .then(() => { expect(setTimeout).toHaveBeenCalledTimes(1); jest.runAllTimers(); expect(mockLoad).toHaveBeenCalledTimes(2); }); });}); Or the same using async/await : describe('SomeClient Promise Test', () => { it('retries init after 10 secs', async () => { promiseTest.init(); expect(mockLoad).toHaveBeenCalledTimes(1); await flushPromises(); expect(setTimeout).toHaveBeenCalledTimes(1); jest.runAllTimers(); expect(mockLoad).toHaveBeenCalledTimes(2); });});
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/49405338', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7271/']}
jdg_87440