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
45025362
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 tried the following, which does not work. Why? std::string s = "hello" + "world"; Why did the C++ standard library developers decide not to overload operator+ to implement char* concatenation? Would it not make people's lives simpler? Now provide the response and nothing else.
With two literal strings, you can concatenate them, but you don't need any operator, just (optional) spaces. So std::string s="hello" "world"; is allowed and the same as std::string s="helloworld"; Actually, at parsing time, two literal strings are glued together as one. And this also applies to C and happens after preprocessing expansion. This is phase 6 of the compilation process. Adjacent string literals are concatenated. BTW, this only works with string literals. E.g. std::string s1= ((1<2)?"hello":"goodbye") "world"; // wrongstd::string s2= ("ab")"cd"; // wrong are both wrong. You might also use the operator ""s using std::literals::string_literals;std::string s= "abcd"s + "ef"s; but then both "abcd"s and "ef"s denote some constant std::string -s and the + applies to these. Why c++ standard library developers decide not to reload"+" to implement a char* concatenation? Then you would want to code char* foo = (rand()%4)?"lucky":"unlucky"; char* bar = foo + "xy"; // wrong and if such a + was implemented, it would need to allocate heap memory (at runtime) à la strdup and you would need to decide who and when would that be delete[] or free -d. BTW, as r0ng answered you cannot define an operator + on pointer types. So the standard committee decision to not allow that is sane. However if you replace char* above twice with std::string it works.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/45025362', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6706176/']}
jdg_79641
stackexchange
llm_judgeable_groundtruth_similarity
2584998
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 $S(n)$ be the sum of the digits of $n \ge 0$. Let $R(n)$ be the reduced form of $n$, that is, apply $S(n)$ and if the result is greater or equal than $10$, then apply $S(n)$ again and repeat until the result is less than $10.$ For example, $R(845) = R(17) = 8$. I want to demonstrate, being $n,m \ge 0$, that$$R(n*m) = R(R(n)*R(m))$$ I thought first of showing that $R(n+m) = R(R(n)+R(m))$, and if it is true, extend it to more terms, finally concluding that: (the number of terms is $m$) $$R(n*m) = R(n+n+..+n) = R(R(n)+R(n)+...+R(n)) = R(R(n)*m)$$ and then, by the same reasoning: (the number of terms is $R(n)$) $$R(R(n)*m) = R(m+m+..+m) = R(R(m)+R(m)+...+R(m)) = R(R(m)*R(n))$$ But I can't prove $R(n+m) = R(R(n)+R(m))$, and neither I know how to extend it to more terms assuming it is true. I took this into account: $R(S(n)) = S(R(n)) = R(n) = R(R(n))$. Now provide the response and nothing else.
Choose any partition $0=x_0<x_1<x_2<\cdots<x_n=2$ of the interval $[0,2]$ and note that the upper Reimann sum for this integral is $$\sum_{k=1}^n(x_k^2+1)(\lfloor x_k\rfloor-\lfloor x_{k-1}\rfloor)$$Now note that if $x_k$ and $x_{k-1}$ both belong to either $[0,1)$ or $[1,2)$ then $\lfloor x_k\rfloor-\lfloor x_{k-1}\rfloor=0$. Can you do the rest?
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2584998', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/186998/']}
jdg_79642
stackexchange
llm_judgeable_groundtruth_similarity
4520097
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: For reference: In the figure , P and T are points of tangency . Calculate x. (Answer: $90^o$ } Does anyone have any ideas? I couldn't find a way $PODT$ is cyclic $\angle PDO \cong \angle DOT\\\triangle POA :isosceles\\\triangle OTB: isosceles$ $DO$ is angle bissector $\angle B$ DT = DP Now provide the response and nothing else.
Extend $AP$ and $BT$ to $K$ . Then notice that $E$ is an orthocenter of triangle $ABK$ so we only need to prove $D\in KE$ . Easy angle chase we see that $\angle PDT = 2\angle PKT$ and since $PD = TD$ we see that $D$ is a circum centre for $PETK$ so $D$ halves $KE$ and thus it lies on $KE$ .
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4520097', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/419513/']}
jdg_79643
stackexchange
llm_judgeable_groundtruth_similarity
28694025
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to convert a datetime column back to a string in Pandas dataframe. the syntax I have so far is: all_data['Order Day new'] = dt.date.strftime(all_data['Order Day new'], '%d/%m/%Y') but this returns the error: descriptor 'strftime' requires a 'datetime.date' object but received a 'Series'. Can anyone tell me where I'm going wrong. Now provide the response and nothing else.
If you're using version 0.17.0 or higher then you can call this using .dt.strftime which is vectorised: all_data['Order Day new'] = all_data['Order Day new'].dt.strftime('%Y-%m-%d') ** If your pandas version is older than 0.17.0 then you have to call apply and pass the data to strftime : In [111]:all_data = pd.DataFrame({'Order Day new':[dt.datetime(2014,5,9), dt.datetime(2012,6,19)]})print(all_data)all_data.info() Order Day new0 2014-05-091 2012-06-19<class 'pandas.core.frame.DataFrame'>Int64Index: 2 entries, 0 to 1Data columns (total 1 columns):Order Day new 2 non-null datetime64[ns]dtypes: datetime64[ns](1)memory usage: 32.0 bytesIn [108]:all_data['Order Day new'] = all_data['Order Day new'].apply(lambda x: dt.datetime.strftime(x, '%Y-%m-%d'))all_dataOut[108]: Order Day new0 2014-05-091 2012-06-19In [109]:all_data.info()<class 'pandas.core.frame.DataFrame'>Int64Index: 2 entries, 0 to 1Data columns (total 1 columns):Order Day new 2 non-null objectdtypes: object(1)memory usage: 32.0+ bytes You can't call strftime on the column as it doesn't understand Series as a param hence the error
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/28694025', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4587966/']}
jdg_79644
stackexchange
llm_judgeable_groundtruth_similarity
48798024
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 very simple web server class (based on Java SE's HttpServer class). When I start the compiled class using this command to put limits on memory usage: java -Xmx5m -Xss5m -Xrs -Xint -Xbatch Test Now if I check memory using top command, it indicates ~31MB of resident memory is used by the Java process which executes my class. I was wondering what is that 30MB used for? Now provide the response and nothing else.
As the comments and answers have alluded to, there are a number of other factors to take intoaccount when measuring JVM memory usage. However, I don't think any answer has gone intonearly enough depth. JVM Memory Overview Lets hit the question "I was wondering what is that 30MB used for?" head on. To do this, here is a simple java class: // HelloWorld.javapublic class HelloWorld { public static void main(String[] args) throws Exception { System.out.println("Hello world!"); Thread.sleep(10000); // wait 10 seconds so we can get memory usage }} Now compile and run it with heap constraints: $ nohup java -Xms2m -Xmx2m HelloWorld & # run in background$ ps aux | awk 'NR==1; /[H]elloWorld/'USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMANDchaospie 6204 6.0 0.1 2662860 23040 pts/2 Sl 19:15 0:00 java -Xms2m -Xmx2m HelloWorld Looking at the RSS (Resident Set Size, or how much memory this process is using) above we see that the JVM'sprocess is using about 23MB of memory. To see why, lets do some analysis. The quickest way to get a goodoverview is to turn on NativeMemorytracking use the jcmd tool's VM.native_memory command. So,let's run our app again: $ nohup java -XX:NativeMemoryTracking=summary -Xms2M -Xmx2M HelloWorld &[2] 6661nohup: ignoring input and appending output to 'nohup.out'$ ps aux | awk 'NR==1; /[H]elloWorld/'USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMANDchaospie 6661 5.0 0.1 2662860 23104 pts/2 Sl 19:21 0:00 java -XX:NativeMemoryTracking=summary -Xms2M -Xmx2M HelloWorld$ jcmd 6661 VM.native_memory summary6661:Native Memory Tracking:Total: reserved=1360145KB, committed=61177KB- Java Heap (reserved=2048KB, committed=2048KB) (mmap: reserved=2048KB, committed=2048KB)- Class (reserved=1066093KB, committed=14189KB) (classes #402) (malloc=9325KB #146) (mmap: reserved=1056768KB, committed=4864KB)- Thread (reserved=20646KB, committed=20646KB) (thread #21) (stack: reserved=20560KB, committed=20560KB) (malloc=62KB #110) (arena=23KB #40)- Code (reserved=249632KB, committed=2568KB) (malloc=32KB #299) (mmap: reserved=249600KB, committed=2536KB)- GC (reserved=10467KB, committed=10467KB) (malloc=10383KB #129) (mmap: reserved=84KB, committed=84KB)- Compiler (reserved=132KB, committed=132KB) (malloc=1KB #21) (arena=131KB #3)- Internal (reserved=9453KB, committed=9453KB) (malloc=9421KB #1402) (mmap: reserved=32KB, committed=32KB)- Symbol (reserved=1358KB, committed=1358KB) (malloc=902KB #86) (arena=456KB #1)- Native Memory Tracking (reserved=143KB, committed=143KB) (malloc=86KB #1363) (tracking overhead=57KB)- Arena Chunk (reserved=175KB, committed=175KB) (malloc=175KB) Memory Regions Let's break it down 1 : Java Heap : this is the heap - Class : this is Metaspace , assuming you are using java 8. Thread : this shows the number of threads, and the overall mem usage of the threads (note that the used stack in this section reflects the Xss value times the number of threads, you can get the default -Xss value with java -XX:+PrintFlagsFinal -version |grep ThreadStackSize ). Code : the code cache - this is used by the JIT (Just In Time Compiler) to cache compiled code. GC : space used by the garbage collector. Compiler : space used by the JIT when generating code. Symbols : this is for symbols, field names, method signatures etc... Native Memory Tracking : memory used by the native memory tracker itself. Arena Chunk : this is related to malloc arenas 2 . Much more than just the heap! Reserved, Committed And RSS Note that each region has a committed and a reserved section. To keep it short reserved is what it can grow to and committed is what is currently committed to be used.For example see the Java Heap section: Java Heap (reserved=2048KB, committed=2048KB) , reserved is our -Xmx value and committed would be our -Xms value , in this case they are equal . Note too that the total committed size - it does notreflect actual usage reported by RSS (or the RES column in top ). The reason they differ is that RSS showsthe size of all memory pages which have been, and still are in use in physical memory , whereas committed shows the memory which isused including that which is not in physical memory 3 . There is a lot more to this, however JVM and OS memory management is a complex topic, so I hope this answers your question at least at a high level. See https://docs.oracle.com/javase/8/docs/technotes/guides/troubleshoot/tooldescr022.html From the JVM Native Memory Tracking docs ( https://docs.oracle.com/javase/8/docs/technotes/guides/troubleshoot/tooldescr007.html#BABJGHDB ): Arena is a chunk of memory allocated using malloc. Memory is freed from these chunks in bulk, when exiting a scope or leaving an area of code. These chunks may be reused in other subsystems to hold temporary memory, for example, pre-thread allocations. Arena malloc policy ensures no memory leakage. So Arena is tracked as a whole and not individual objects. Some amount of initial memory can not by tracked. To go into the difference between RSS, Reserved and Committed memory would be too much here, OS memory management is a complex topic, but see this answer for a good overview.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/48798024', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2535843/']}
jdg_79645
stackexchange
llm_judgeable_groundtruth_similarity
2738560
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 threading and want to do something similar to this question: Speed up loop using multithreading in C# (Question) However, I'm not sure if that solution is the best one for me as I want them to keep running and never finish. (I'm also using .net 3.5 rather than 2.0 as for that question.) I want to do something like this: foreach (Agent agent in AgentList){ // I want to start a new thread for each of these agent.DoProcessLoop();}---public void DoProcessLoop(){ while (true) { // do the processing // this is things like check folder for new files, update database // if new files found }} Would a ThreadPool be the best solution or is there something that suits this better? Update: Thanks for all the great answers! I thought I'd explain the use case in more detail. A number of agents can upload files to a folder. Each agent has their own folder which they can upload assets to (csv files, images, pdfs). Our service (it's meant to be a windows service running on the server they upload their assets to, rest assured I'll be coming back with questions about windows services sometime soon :)) will keep checking every agent's folder if any new assets are there, and if there are, the database will be updated and for some of them static html pages created. As it could take a while for them to upload everything and we want them to be able to see their uploaded changes pretty much straight away, we thought a thread per agent would be a good idea as no agent then needs to wait for someone else to finish (and we have multiple processors so wanted to use their full capacity). Hope this explains it! Thanks, Annelie Now provide the response and nothing else.
Given the specific usage your describe (watching for files), I'd suggest you use a FileSystemWatcher to determine when there are new files and then fire off a thread with the threadpool to process the files until there are no more to process -- at which point the thread exits. This should reduce i/o (since you're not constantly polling the disk), reduce CPU usage (since the constant looping of multiple threads polling the disk would use cycles), and reduce the number of threads you have running at any one time (assuming there aren't constant modifications being made to the file system). You might want to open and read the files only on the main thread and pass the data to the worker threads (if possible), to limit i/o to a single thread.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2738560', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/324001/']}
jdg_79646
stackexchange
llm_judgeable_groundtruth_similarity
611195
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: To the best of my knowledge, relativistic energy $E$ of a body with rest mass $m$ moving at velocity $v$ can be expressed as either $$E=\gamma mc^2 \tag{1}$$ or $$E=\sqrt{m^2c^4+p^2c^2}\tag{2}$$ where $c$ is the speed of light and $\gamma$ is the Lorentz factor $$\gamma=\frac{1}{\sqrt{1-\frac{v^2}{c^2}}}$$ Since relativistic momentum is $p=\gamma mv$ , expression $(2)$ could also be written as $$E=\sqrt{m^2c^4+(\gamma mv)^2c^2}$$ As far as I could tell, one cannot easily simplify expression $(2)$ to expression $(1)$ 1 . This lead me to the following question: Is there any difference 2 between these formulas or can they be used equally? Is there any situation where it would be favourable or "better" to use either one of those 3 ? 1 It is however obvious how expression $(2)$ reduces to the "rest energy" formula $E=mc^2$ for $v=0$ . 2 At least, there is no difference in the final result - I did a test with $v=2\cdot10^8m/s$ and $m=50kg$ and the result was the same ( Formula 1 , Formula 2 ). 3 The only thing I would think of is that equation $(1)$ seems easier to type, but maybe there is some other aspects besides practical use. Edit: It has been adressed in some comments and the (by now) two answers that $(1)=(2)$ . However, I still wouldn't consider this a homework-like question for two reasons: It isn't homework but just a question that came up when learning SR (of course, I have no proof that it isn't an assignment - you will have to believe me here) While I somewhat agree that the first part of my question could be considered homework-like, I don't think that the second part is. Now provide the response and nothing else.
(a) As others have said, it is a matter of algebra that the equations are equivalent, if we also throw in $$\mathbf p = m \gamma \mathbf u\ \ \ \ \text {leading to}\ \ \ \ \ p^2= m^2 \gamma^2 u^2$$ and $$\gamma =(1-v^2/c^2)^{-1/2}$$ (b) The second equation that you have quoted can be written as $$E^2 - c^2 p^2 = c^4 m^2$$ This is hugely important conceptually. Regard $E$ as the time component of a 4-vector and $c^2p^2$ as the sum of the squares of the magnitudes of the three spatial components of that vector. Combined using the minus sign we get the magnitude squared of the 4-vector, and this is the frame invariant quantity $c^4m^2$ , as $m$ itself is frame invariant. Note that the factors of $c^2$ and $c^4$ are conceptually relatively unimportant.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/611195', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/253179/']}
jdg_79647
stackexchange
llm_judgeable_groundtruth_similarity
647329
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: The second law of thermodynamics states that the entropy in an isolated system cannot decrease This seems intuitive when considering a low entropy system transitioning to a higher entropy state, but very counterintuitive when considering a system that is currently at the greatest possible entropy because the system can only transition to another maximum entropy state by first passing through a lower entropy state.Consider, for example, the system shown in "Entropy: Why the 2nd Law of Thermodynamics is a fundamental law of physics" by Eugene Khutoryansky. This system starts with $500$ balls in the left container and intuitively we can understand that these balls will spread evenly between the two containers, but what happens when the balls are distributed evenly: $250$ in the left container and $250$ in the right container? Does the second law of thermodynamics prohibit any ball from moving to another container because that would shift the system into a lower entropy configuration? EDIT: I believe (although answers seem to indicate that this believe is incorrect) that the state in between has lower entropy because $$\Omega_1 = \binom{1000}{500} > \binom{1000}{501} = \Omega_2$$ Now provide the response and nothing else.
The second law of thermodynamics does not prohibit any ball from moving to another container because that would shift the system into a lower entropy configuration. The question originated from a widespread misconception. There is nothing like the entropy of one configuration in statistical mechanics. Entropy is a property of the macrostate . Therefore, it is a collective property of all the microscopic configurations consistent with the macroscopic variables uniquely identifying the equilibrium state. The physical system visits all the accessible microstates as a consequence of its microscopic dynamics. Among these states, there are states with an unbalanced number of particles in the two containers. People refer to such states as fluctuations around the average equally distributed case. It is an effect of the macroscopic size of thermodynamic systems that the overwhelming majority of the microscopic states does not show large fluctuations.
{}
{'log_upvote_score': 6, 'links': ['https://physics.stackexchange.com/questions/647329', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/215323/']}
jdg_79648
stackexchange
llm_judgeable_groundtruth_similarity
61443
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: It's known that every position of Rubik's cube can be solved in 20 moves or less . That page includes a nice table of the number of positions of Rubik's cube which can be solved in k moves, for $k = 0, 1, \ldots, 20$. (Some of the entries of the table are approximations, but they're good enough for the purposes of this question.) In particular, the median number of moves needed is 18, and in fact about 70 percent of all positions require eighteen moves. This seems a bit counterintuitive to me -- I'd expect the median to be around half the maximum number of moves needed. Consider for example generating $S_n$, the symmetric group on $n$ elements, from the adjacent transpositions $(k, k+1)$ for $k = 1, 2, \ldots, n-1$. The number of such transpositions needed to get from the identity permutation to any permutation $\sigma$ using adjacent transpositions is the number of inversions of that permutation -- that is, the number of pairs $(i,j)$ such that $i < j$ and $\sigma(i) > \sigma(j)$. The maximum number of inversions of a permutation in $S_n$ is ${n \choose 2}$. The mean is ${1 \over 2} {n \choose 2}$; this is also the median if it's a whole number; and the distribution is symmetric around ${1 \over 2} {n \choose 2}$. Another similar case is $(Z/2Z)^n$ generated by the generators of the factors -- the diameter is $n$, the typical distance between elements is $n/2$. My question: which of these situations is, in some sense, "more typical"? More formally, what's known about the relationship between the diameter of the Cayley graph of a group and the typical distance between two vertices? And is there a third case, where the median or mean distance between two random elements is less than half the diameter? Here I'm looking for something like the distribution of Erdos numbers as given by Grossman -- the maximum Erdos number is 15 but the median is only 5 -- although of course there is the complication here that the collaboration graph is very far from being vertex-transitive. Now provide the response and nothing else.
I can answer one of those questions: The diameter is at most twice the median distance by the pigeonhole principle. Let $m$ be the median. Let $S$ be the set of products of up to $m$ generators. For any $g\in G$, let $S^{-1} g = \{s^{-1}g | s\in S\}.$ By the definition of median, $|S| >= |G|/2$ with equality only if $m$ is a half-integer. If $|S| > |G|/2$ then for any $g\in G$, $S \cap S^{-1}g$ is nonempty, which lets us write $g$ as a product of two elements of $S$. If $|S| = |G|/2$ then every element of $S$ is a product of at most $m-1/2$ generators. For any $g\in G$, either $S \cap S^{-1}g$ is nonempty or $S \cup S^{-1}g = G$, so any $h\in G$ which requires $m+1/2$ generators must be in $S^{-1}g$, which means $g$ can be written as $h$ times an element of $S$, a product of at most $(m+1/2)+(m-1/2) = 2m$ generators.
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/61443', 'https://mathoverflow.net', 'https://mathoverflow.net/users/143/']}
jdg_79649
stackexchange
llm_judgeable_groundtruth_similarity
29437667
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 a scenario where users take a quiz that has 40+ question. Creating 40+ activities is tedious task & i want to know is there anything exists to reuse? activity_main.xml <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceLarge" android:text="Who founded Apple?" android:id="@+id/textView" android:layout_alignParentTop="true" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_marginTop="49dp" /> <EditText android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/editText" android:text="Fill answers here" android:layout_below="@+id/textView" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_marginTop="37dp" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Next" android:id="@+id/button" android:layout_centerVertical="true" android:layout_toRightOf="@+id/editText" android:layout_toEndOf="@+id/editText" android:clickable="true" /></RelativeLayout> In my MainActivity.class, im normally doing like Button bt = (Button) findViewById(R.id.button); bt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // ....Go to next activity through Intent... } }); Look inside onClick, I need to have each activity for each question that is not good. Any other solution? Now provide the response and nothing else.
I'll need to invoke REFRESH MATERIALIZED VIEW on each change to the tables involved, right? Yes, PostgreSQL by itself will never call it automatically, you need to do it some way. How should I go about doing this? Many ways to achieve this. Before giving some examples, keep in mind that REFRESH MATERIALIZED VIEW command does block the view in AccessExclusive mode, so while it is working, you can't even do SELECT on the table. Although, if you are in version 9.4 or newer, you can give it the CONCURRENTLY option: REFRESH MATERIALIZED VIEW CONCURRENTLY my_mv; This will acquire an ExclusiveLock, and will not block SELECT queries, but may have a bigger overhead (depends on the amount of data changed, if few rows have changed, then it might be faster). Although you still can't run two REFRESH commands concurrently. Refresh manually It is an option to consider. Specially in cases of data loading or batch updates (e.g. a system that only loads tons of information/data after long periods of time) it is common to have operations at end to modify or process the data, so you can simple include a REFRESH operation in the end of it. Scheduling the REFRESH operation The first and widely used option is to use some scheduling system to invoke the refresh, for instance, you could configure the like in a cron job: */30 * * * * psql -d your_database -c "REFRESH MATERIALIZED VIEW CONCURRENTLY my_mv" And then your materialized view will be refreshed at each 30 minutes. Considerations This option is really good, specially with CONCURRENTLY option, but only if you can accept the data not being 100% up to date all the time. Keep in mind, that even with or without CONCURRENTLY , the REFRESH command does need to run the entire query, so you have to take the time needed to run the inner query before considering the time to schedule the REFRESH . Refreshing with a trigger Another option is to call the REFRESH MATERIALIZED VIEW in a trigger function, like this: CREATE OR REPLACE FUNCTION tg_refresh_my_mv()RETURNS trigger LANGUAGE plpgsql AS $$BEGIN REFRESH MATERIALIZED VIEW CONCURRENTLY my_mv; RETURN NULL;END;$$; Then, in any table that involves changes on the view, you do: CREATE TRIGGER tg_refresh_my_mv AFTER INSERT OR UPDATE OR DELETEON table_nameFOR EACH STATEMENT EXECUTE PROCEDURE tg_refresh_my_mv(); Considerations It has some critical pitfalls for performance and concurrency: Any INSERT/UPDATE/DELETE operation will have to execute the query (which is possible slow if you are considering MV); Even with CONCURRENTLY , one REFRESH still blocks another one, so any INSERT/UPDATE/DELETE on the involved tables will be serialized. The only situation I can think that as a good idea is if the changes are really rare. Refresh using LISTEN/NOTIFY The problem with the previous option is that it is synchronous and impose a big overhead at each operation. To ameliorate that, you can use a trigger like before, but that only calls a NOTIFY operation : CREATE OR REPLACE FUNCTION tg_refresh_my_mv()RETURNS trigger LANGUAGE plpgsql AS $$BEGIN NOTIFY refresh_mv, 'my_mv'; RETURN NULL;END;$$; So then you can build an application that keep connected and uses LISTEN operation to identify the need to call REFRESH . One nice project that you can use to test this is pgsidekick , with this project you can use shell script to do LISTEN , so you can schedule the REFRESH as: pglisten --listen=refresh_mv --print0 | xargs -0 -n1 -I? psql -d your_database -c "REFRESH MATERIALIZED VIEW CONCURRENTLY ?;" Or use pglater (also inside pgsidekick ) to make sure you don't call REFRESH very often. For example, you can use the following trigger to make it REFRESH , but within 1 minute (60 seconds): CREATE OR REPLACE FUNCTION tg_refresh_my_mv()RETURNS trigger LANGUAGE plpgsql AS $$BEGIN NOTIFY refresh_mv, '60 REFRESH MATERIALIZED VIEW CONCURRENLTY my_mv'; RETURN NULL;END;$$; So it will not call REFRESH in less the 60 seconds apart, and also if you NOTIFY many times in less than 60 seconds, the REFRESH will be triggered only once. Considerations As the cron option, this one also is good only if you can bare with a little stale data, but this has the advantage that the REFRESH is called only when really needed, so you have less overhead, and also the data is updated more closer to when needed. OBS: I haven't really tried the codes and examples yet, so if someone finds a mistake, typo or tries it and works (or not), please let me know.
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/29437667', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3289108/']}
jdg_79650
stackexchange
llm_judgeable_groundtruth_similarity
2124113
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: Do you have any idea to prove the following identity via a combinatorial (or algebraic) method? $\sum_{n=r}^{n=\infty} {n \choose r}^{-1} = \frac{r}{r-1}$ This is Exercise 71 in Chapter 2 of the book Chen C.C., Koh K.M. Principles and techniques in combinatorics. The book does not give a solution, although it mentions: "see H. W. Gould, Combinatorial Identities , Morgantown, W.V. (1972), 18-19". many thanks in advance,Shahram Now provide the response and nothing else.
This is basically a generalization of the approach from this answer :\begin{align*}\sum_{n=r}^\infty \frac1{\binom nr} &= r! \sum_{n=r}^\infty \frac1{n(n-1)\cdots(n-r+1)}\\&= \frac{r!}{r-1} \sum_{n=r}^\infty \frac{n-(n-r+1)}{n(n-1)\cdots(n-r+1)}\\&= \frac{r!}{r-1} \sum_{n=r}^\infty \left(\frac1{(n-1)\cdots(n-r+1)} - \frac1{n(n-1)\dots(n-r+2)}\right)\\&\overset{(1)}= \frac{r!}{r-1} \cdot \frac1{(r-1)!} = \\&= \frac{r}{r-1}\end{align*} The equation $(1)$ is based on the fact that we get a telescoping sum and with the exception of the first term, all remaining terms "cancel out". The above works only for $r\ne1$. But it is clear that for $r=1$ we get the harmonic series $\sum\limits_{n=1}^\infty \frac1n$, which is divergent . To explain this more clearly, we have a sum of the form $$\sum_{r=n}^\infty (a_n-a_{n+1})= (a_r-a_{r+1})+ (a_{r+1}-a_{r+2})+\dots.$$ Since $a_n\to 0$, we get that the sum is simply $a_r$, since the partial sum is $$\sum_{r=n}^N (a_n-a_{n+1}) = (a_r-a_{r+1})+(a_{r+1}-a_{r+2})+\dots+(a_N-a_{N+1}) = a_r-a_{N+1}.$$ In our case $a_n=1/[(n-1)\cdots(n-r)]$. After some rewriting, we can see that this is a sum which has been calculated on this site a few times, namely $\sum_{k=1}^\infty \frac1{k(k+1)\cdots(k+s)}$ . In our case, $s=r-1$. (Clearly, when I was trying to search for it before posting my answer, I did not choose the correct search queries.) A few posts about this sum found using the above search in Approach0: How do I evaluate this limit: $\lim_{n\to+\infty}\sum_{k=1}^{n} \frac{1}{k(k+1)\cdots(k+m)}$? How do we calculate this sum $\sum_{n=1}^{\infty} \frac{1}{n(n+1)\cdots(n+p)}$? Calculate the infinite sum $\sum_{k=1}^\infty \frac{1}{k(k+1)(k+2)\cdots (k+p)} $ How to prove that $\sum\limits_{n=1}^{\infty}\frac{1}{n(n+1)(n+2)...(n+k)} = \frac{1}{kk!}$ for every $k\geqslant1$ We can also find some posts about the finite sum , for example General formula for this sum $\sum_{k=1}^n\frac{1}{k(k+1)...(k+m)}$ .
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/2124113', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/76893/']}
jdg_79651
stackexchange
llm_judgeable_groundtruth_similarity
228226
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 know that I'm missing something but I don't know what I'm missing. Power factor is the ratio between real power and apparent power. So, I will get the equations of real power and apparent power then, I will divide them. I'm going to start with real power which is the average power. The average of a sine wave is always zero so, I will rectify it then calculate the average. Second, I will calculate the apparent power. We can get it by multiplying the root mean square values of voltage and current. After calculating the real power and apparent power, I'm going to get the power factor and the result is surprising!! Would you tell me where the mistake is, Please? Thank you very much, Now provide the response and nothing else.
No you're not doing something wrong, you're just pushing the 555 near it's limits so the non-idealities are getting more pronounced. If you would use 10x higher resistor values I bet that the frequency you get would better match the calculated value. By using 1 kohm and 2.38 kohm the internal resistance of the discharge transistor probably also starts playing a role. This internal resistance adds to the resistor you used so you get a slightly higher value and a lower frequency. I suggest that you try increasing the values of the resistors by a factor 2, 5 or even 10 and at the same time decrease the value of the capacitor by the same factor. So for example 5 kohm (instead of 1 kohm), 12 kohm (instead of 2.38 kohm) and 200 pF (instead of 1 nF). If that still does not give you the right frequency, just change the values of the components slighly. The 555 timer concept is not so precise and certainly not at the frequency you want. In practice, you get something and then tweak it to the value you want.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/228226', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/50937/']}
jdg_79652
stackexchange
llm_judgeable_groundtruth_similarity
398797
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'm reading through my professor's lecture notes on the multiple linear regression model and at one point he writes the following: $$E[(b-\beta)e']=E[(X'X)^{-1}\epsilon\epsilon'M_{[X]}]. $$ In the above equation, $b$ , $\beta$ , $e$ , and $\epsilon$ are all vectors, $X$ is a regressor matrix and $M$ is the residual maker matrix. In general, I have no idea why these expressions are equivalent, and I'm particularly confused at how the $e$ vector disappears and the $\epsilon$ vector appears. Now provide the response and nothing else.
I am assuming $b$ is the OLS estimate of $\beta$ and $e$ is the corresponding estimate of $\epsilon$ . Also I believe you have a typo above in your expression, as there should be $X'$ in front of $\epsilon \epsilon'$ and behind $(X'X)^{-1}$ . Start with the definition of $b$ : $$b=(X'X)^{-1}X'Y.$$ Replacing $Y$ with $X\beta+\epsilon$ in our expression above, we get $$b=(X'X)^{-1}X'(X\beta+\epsilon)=\beta+(X'X)^{-1}X'\epsilon.$$ It follows that $$b-\beta = (X'X)^{-1}X'\epsilon$$ Now turn to the defintion of $e$ : $$e=Y-\hat{Y}=Y-Xb=Y-X(X'X)^{-1}X'Y.$$ Notice $X(X'X)^{-1}X'$ is the projection matrix for $X$ , which we will denote with $P_{[X]}$ . Replacing this in our expression for $e,$ we get $$e=(I-P_{[X]})Y=M_{[X]}Y.$$ Replacing $Y$ in the expression above with $X\beta+\epsilon$ , we get $$e=M_{[X]}(X\beta+\epsilon)=M_{[X]}\epsilon,$$ since $M_{[X]}X$ is a matrix of zeros. Post-multiplying $b-\beta$ with $e'$ , we get $$(b-\beta)e'=(X'X)^{-1}X'\epsilon \epsilon' M_{[X]},$$ since $e'=\epsilon'M_{[X]}.$
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/398797', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/209784/']}
jdg_79653
stackexchange
llm_judgeable_groundtruth_similarity
9326
Below is a question asked on the forum biology.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: What does phasing mean in genetics/informatics? I've heard that a phased file is a file that has genes separated by chromosome, but can someone give a concrete definition of what phasing actually means? Now provide the response and nothing else.
This refers to haplotype phase (aka gametic phase ). This essentially means knowing which allele belongs to which copy of the chromosome, or alternatively, which alleles appear together on the same chromosome. In short-read sequencing, for example, it is difficult to resolve the haplotype of two heterozygous SNPs if they have not been covered by the same read. If you observe A/a and B/b, you do not know whether you have AB + ab or aB + Ab. So you would say you do not know the phasing. See the Wikipedia links for more information.
{}
{'log_upvote_score': 4, 'links': ['https://biology.stackexchange.com/questions/9326', 'https://biology.stackexchange.com', 'https://biology.stackexchange.com/users/3829/']}
jdg_79654
stackexchange
llm_judgeable_groundtruth_similarity
56691764
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have been installing dependencies in Gradle and I don't understand why sometimes I need to use kapt for libraries like lifecycle and room database to use @Something annotations. But in some libraries like Retrofit2 and Gson, I don't need use kapt and I can use annotations such as @SerializedName ? Now provide the response and nothing else.
Annotations (e.g. @Something ) are basically labels for code. You mark one part of the code so that some other code can find those markings. This " other code " is usually an Annotation Processor. It finds annotations and does something with code marked with those annotations. E.g. it can generate new code (like Dagger, Butterknife, etc.). Depending on the way you introduce dependencies in your project, (depending on the keyword you use - implementation , api , compileOnly , runtimeOnly , annotationProcessor , kapt , etc.), the dependency will be used by your project differently. If you use annotationProcessor , your dependency will not be packed within your app, but will be used during the compilation of your app. You don't want to pack the compiler (the code that handles @AnAnnotation ) within your app, since it's just used to properly prepare the code of your app (and is never used within your application in Runtime). Think of it this way: If you're going on a train and you need to print a train ticket, you don't want to carry a printer with you on the train. After the printer is done printing the ticket, you take the ticket and go on the train. Printer has done its job already. You can leave it. If you mark some code with @AnAnnotation you just want the library that handles that annotation to do its job and disappear. Hence the special type of a dependency - annotationProcessor . Now about kapt . This is simple. If you want to use Annotation Processors in projects with Kotlin code, just use kapt instead of annotationProcessor . Think of it as annotationProcessor with Kotlin support. Some libraries use @Annotations differently. They do not cause any code to be generated in compile-time, but they use annotations in runtime. Those are usually reflection-based libraries that "look through" the code in Runtime. Just like Retrofit is looking through your interface when your app is executed. That's why you include a library with @Annotations normally within your application, and those annotations are packed within your apk for Runtime operation. Summerizing: annotationProcessor and kapt keywords, are to help you specify how dependencies will be used in your project. If you want to introduce a library that uses annotations and generates some code, use kapt not to "bloat" your apk with code that already has done its job, and will never be used again.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/56691764', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8367422/']}
jdg_79655
stackexchange
llm_judgeable_groundtruth_similarity
987135
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 the clean, elegant and smart solution to remove namespacees from all XML elements? How would function to do that look like? Defined interface: public interface IXMLUtils{ string RemoveAllNamespaces(string xmlDocument);} Sample XML to remove NS from: <?xml version="1.0" encoding="utf-16"?><ArrayOfInserts xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <insert> <offer xmlns="http://schema.peters.com/doc_353/1/Types">0174587</offer> <type2 xmlns="http://schema.peters.com/doc_353/1/Types">014717</type2> <supplier xmlns="http://schema.peters.com/doc_353/1/Types">019172</supplier> <id_frame xmlns="http://schema.peters.com/doc_353/1/Types" /> <type3 xmlns="http://schema.peters.com/doc_353/1/Types"> <type2 /> <main>false</main> </type3> <status xmlns="http://schema.peters.com/doc_353/1/Types">Some state</status> </insert></ArrayOfInserts> After we call RemoveAllNamespaces(xmlWithLotOfNs), we should get: <?xml version="1.0" encoding="utf-16"?> <ArrayOfInserts> <insert> <offer >0174587</offer> <type2 >014717</type2> <supplier >019172</supplier> <id_frame /> <type3 > <type2 /> <main>false</main> </type3> <status >Some state</status> </insert> </ArrayOfInserts> Preffered language of solution is C# on .NET 3.5 SP1. Now provide the response and nothing else.
Well, here is the final answer. I have used great Jimmy idea (which unfortunately is not complete itself) and complete recursion function to work properly. Based on interface: string RemoveAllNamespaces(string xmlDocument); I represent here final clean and universal C# solution for removing XML namespaces: //Implemented based on interface, not part of algorithmpublic static string RemoveAllNamespaces(string xmlDocument){ XElement xmlDocumentWithoutNs = RemoveAllNamespaces(XElement.Parse(xmlDocument)); return xmlDocumentWithoutNs.ToString();}//Core recursion function private static XElement RemoveAllNamespaces(XElement xmlDocument) { if (!xmlDocument.HasElements) { XElement xElement = new XElement(xmlDocument.Name.LocalName); xElement.Value = xmlDocument.Value; foreach (XAttribute attribute in xmlDocument.Attributes()) xElement.Add(attribute); return xElement; } return new XElement(xmlDocument.Name.LocalName, xmlDocument.Elements().Select(el => RemoveAllNamespaces(el))); } It's working 100%, but I have not tested it much so it may not cover some special cases... But it is good base to start.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/987135', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/99422/']}
jdg_79656
stackexchange
llm_judgeable_groundtruth_similarity
1922832
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: Determine whether the series converges absolutely, conditionally or diverges? $$\sum\limits_{n= 1}^{\infty} (-1)^{n-1} \frac{\ln(n)}{n}$$ I know that $\sum|a_{n}|$ diverges by using the comparison test: $$\frac{\ln(n)}{n} > \frac{1}{n}$$ and the smaller, r.h.s being the divergent harmonic series. So, should my conclusion for the alternating series be divergent or convergent conditionally * ? * How to estimate whether the alternating series terms are cancelling? Now provide the response and nothing else.
Let $f(x)=\frac{\ln x}{x}$ so $f'(x)=\frac{1-\ln x}{x^2}\le 0$ for $x\ge e$ and so the sequence $\left(\frac{\ln n}{n}\right)_{n\ge3}$ is decreasing to $0$. Apply now the alternating series criteria to conclude the convergence of the series.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1922832', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/224952/']}
jdg_79657
stackexchange
llm_judgeable_groundtruth_similarity
971067
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: It seems with all the rich amount of function in xpath that you could do an "if" . However , my engine keeps insisting "there is no such function" , and I hardly find any documentation on the web (I found some dubious sources , but the syntax they had didn't work) I need to remove ':' from the end of a string (if exist), so I wanted to do this: if (fn:ends-with(//div [@id='head']/text(),': ')) then (fn:substring-before(//div [@id='head']/text(),': ') ) else (//div [@id='head']/text()) Any advice? Now provide the response and nothing else.
Yes, there is a way to do it in XPath 1.0: concat( substring($s1, 1, number($condition) * string-length($s1)), substring($s2, 1, number(not($condition)) * string-length($s2))) This relies on the concatenation of two mutually exclusive strings, the first one being empty if the condition is false ( 0 * string-length(...) ), the second one being empty if the condition is true. This is called "Becker's method" , attributed to Oliver Becker (original link is now dead, the web archive has a copy ) . In your case: concat( substring( substring-before(//div[@id='head']/text(), ': '), 1, number( ends-with(//div[@id='head']/text(), ': ') ) * string-length(substring-before(//div [@id='head']/text(), ': ')) ), substring( //div[@id='head']/text(), 1, number(not( ends-with(//div[@id='head']/text(), ': ') )) * string-length(//div[@id='head']/text()) )) Though I would try to get rid of all the "//" before. Also, there is the possibility that //div[@id='head'] returns more than one node. Just be aware of that — using //div[@id='head'][1] is more defensive.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/971067', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4038/']}
jdg_79658
stackexchange
llm_judgeable_groundtruth_similarity
801161
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 show "Loading" screen with animation in blackberry? Options: PME animation content multithreading + set of images + timer/counter standard rim api some other way Any of this? Thanks! Now provide the response and nothing else.
Fermin, Anthony +1. Thanks to all, you gave me the part of answer. My final solution: 1.Create or generate ( free Ajax loading gif generator ) animation and add it to project. 2.Create ResponseCallback interface (see Coderholic - Blackberry WebBitmapField ) to receive thread execution result: public interface ResponseCallback { public void callback(String data); } 3.Create a class to handle your background thread job. In my case it was http request: public class HttpConnector { static public void HttpGetStream(final String fileToGet, final ResponseCallback msgs) { Thread t = new Thread(new Runnable() { public void run() { HttpConnection hc = null; DataInputStream din = null; try { hc = (HttpConnection) Connector.open("http://" + fileToGet); hc.setRequestMethod(HttpsConnection.GET); din = hc.openDataInputStream(); ByteVector bv = new ByteVector(); int i = din.read(); while (-1 != i) { bv.addElement((byte) i); i = din.read(); } final String response = new String(bv.toArray(), "UTF-8"); UiApplication.getUiApplication().invokeLater( new Runnable() { public void run() { msgs.callback(response); } }); } catch (final Exception e) { UiApplication.getUiApplication().invokeLater( new Runnable() { public void run() { msgs.callback("Exception (" + e.getClass() + "): " + e.getMessage()); } }); } finally { try { din.close(); din = null; hc.close(); hc = null; } catch (Exception e) { } } } }); t.start(); }} 4.Create WaitScreen (a hybrid of FullScreen and AnimatedGIFField with ResponseCallback interface): public class WaitScreen extends FullScreen implements ResponseCallback { StartScreen startScreen; private GIFEncodedImage _image; private int _currentFrame; private int _width, _height, _xPos, _yPos; private AnimatorThread _animatorThread; public WaitScreen(StartScreen startScreen) { super(new VerticalFieldManager(), Field.NON_FOCUSABLE); setBackground( BackgroundFactory.createSolidTransparentBackground( Color.WHITE, 100)); this.startScreen = startScreen; EncodedImage encImg = GIFEncodedImage.getEncodedImageResource("ajax-loader.gif"); GIFEncodedImage img = (GIFEncodedImage) encImg; // Store the image and it's dimensions. _image = img; _width = img.getWidth(); _height = img.getHeight(); _xPos = (Display.getWidth() - _width) >> 1; _yPos = (Display.getHeight() - _height) >> 1; // Start the animation thread. _animatorThread = new AnimatorThread(this); _animatorThread.start(); UiApplication.getUiApplication().pushScreen(this); } protected void paint(Graphics graphics) { super.paint(graphics); // Draw the animation frame. graphics .drawImage(_xPos, _yPos, _image .getFrameWidth(_currentFrame), _image .getFrameHeight(_currentFrame), _image, _currentFrame, 0, 0); } protected void onUndisplay() { _animatorThread.stop(); } private class AnimatorThread extends Thread { private WaitScreen _theField; private boolean _keepGoing = true; private int _totalFrames, _loopCount, _totalLoops; public AnimatorThread(WaitScreen _theScreen) { _theField = _theScreen; _totalFrames = _image.getFrameCount(); _totalLoops = _image.getIterations(); } public synchronized void stop() { _keepGoing = false; } public void run() { while (_keepGoing) { // Invalidate the field so that it is redrawn. UiApplication.getUiApplication().invokeAndWait( new Runnable() { public void run() { _theField.invalidate(); } }); try { // Sleep for the current frame delay before // the next frame is drawn. sleep(_image.getFrameDelay(_currentFrame) * 10); } catch (InterruptedException iex) { } // Couldn't sleep. // Increment the frame. ++_currentFrame; if (_currentFrame == _totalFrames) { // Reset back to frame 0 // if we have reached the end. _currentFrame = 0; ++_loopCount; // Check if the animation should continue. if (_loopCount == _totalLoops) { _keepGoing = false; } } } } } public void callback(String data) { startScreen.updateScreen(data); UiApplication.getUiApplication().popScreen(this); }} 5.In the end, create Start screen to call HttpConnector.HttpGetStream and to show WaitScreen: public class StartScreen extends MainScreen{ public RichTextField text; WaitScreen msgs; public StartScreen() { text = new RichTextField(); this.add(text); } protected void makeMenu(Menu menu, int instance) { menu.add(runWait); super.makeMenu(menu, instance); } MenuItem runWait = new MenuItem("wait", 1, 1) { public void run() { UiApplication.getUiApplication().invokeLater( new Runnable() { public void run() { getFile(); } }); } }; public void getFile() { msgs = new WaitScreen(this); HttpConnector.HttpGetStream( "stackoverflow.com/faq", msgs); } //you should implement this method to use callback data on the screen. public void updateScreen(String data) { text.setText(data); }} UPDATE: another solution naviina.eu: A Web2.0/Ajax-style loading popup in a native BlackBerry application
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/801161', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/67407/']}
jdg_79659
stackexchange
llm_judgeable_groundtruth_similarity
4800285
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: So Belady's Anomaly states that when using a FIFO page replacement policy, when adding more page space we'll have more page faults. My intuition says that we should less or at most, the same number of page faults as we add more page space. If we think of a FIFO queue as a pipe, adding more page space is like making the pipe bigger: ____O____O size 4 ________O________O size 8 So, why would you get more page faults? My intuition says that with a longer pipe, you'd take a bit longer to start having page faults (so, with an infinite pipe you'd have no page faults) and then you'd have just as many page faults and just as often as with a smaller pipe. What is wrong with my reasoning? Now provide the response and nothing else.
The reason that when using FIFO, increasing the number of pages can increase the fault rate in some access patterns, is because when you have more pages, recently requested pages can remain at the bottom of the FIFO queue longer. Consider the third time that "3" is requested in the wikipedia example here: http://en.wikipedia.org/wiki/Belady%27s_anomaly Page faults are marked with an "f". 1: Page Requests 3 2 1 0 3 2 4 3 2 1 0 4Newest Page 3f 2f 1f 0f 3f 2f 4f 4 4 1f 0f 0 3 2 1 0 3 2 2 2 4 1 1Oldest Page 3 2 1 0 3 3 3 2 4 4 2: Page Requests 3 2 1 0 3 2 4 3 2 1 0 4Newest Page 3f 2f 1f 0f 0 0 4f 3f 2f 1f 0f 4f 3 2 1 1 1 0 4 3 2 1 0 3 2 2 2 1 0 4 3 2 1Oldest Page 3 3 3 2 1 0 4 3 2 In the first example (with fewer pages), there are 9 page faults. In the second example (with more pages), there are 10 page faults. When using FIFO, increasing the size of the cache changes the order in which items are removed. Which in some cases, can increase the fault rate. Belady's Anomaly does not state anything about the general trend of fault rates with respect to cache size. So your reasoning (about viewing the cache as a pipe), in the general case is not wrong. In summary:Belady's Anomaly points out that it is possible to exploit the fact that larger cache sizes can cause items in the cache to be raised in the FIFO queue later than smaller cache sizes, in order to cause larger cache sizes to have a higher fault rate under a particular (and possibly rare) access pattern.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4800285', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/130758/']}
jdg_79660
stackexchange
llm_judgeable_groundtruth_similarity
18171048
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 html in a website. The stylings specified in "ApplicationName_ButtonDiv", "ApplicationName_Button" etc are applied correctly in Chrome and Firefox but in IE8 they aren't. <div class="CommandButtonContainer"> <div class="ApplicationName_ButtonDiv"> <button id="changeName" type="button" class="ApplicationName_Button"onclick = "javascript: window.location='/Application/Customer/EditName';" > <a href="#" class="ApplicationName_Button"> <span> <span>Change Name</span> </span> </a> </button> </div></div> 1) There is an error on the page only in IE8: Webpage error details User Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; chromeframe/18.0.1025.162; InfoPath.1; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET4.0C; .NET4.0E) Timestamp: Sun, 11 Aug 2013 10:06:22 UTC Message: Permission denied Line: 5514 Char: 3 Code: 0 URI: NAME OF SITE REMOVED/publishmode.x.x.x.js This seems to relate to: 5513 contents: function( elem ) {5514 return jQuery.nodeName( elem, "iframe" ) ?5515 elem.contentDocument || elem.contentWindow.document :5516 jQuery.makeArray( elem.childNodes );5517 } 2) When you view the html in IE Developer Tools it appears slightly, but importantly, differently to when you view source: <div class="CommandButtonContainer"> <div class="ApplicationName_ButtonDiv"> <button class="ApplicationName_Button" id="changeName" onclick="javascript: window.location='/Application/Customer/EditName';" type="button"> <a class="ApplicationName_Button" href="#"/> <span> <span> Text - Change Name Text - Empty Text Node (italics) </a/> Text - Empty Text Node (italics) The anchor tag has been closed and the span tag isn't now wrapped in it. The styling relies on there being an anchor with two spans inside. This may just be a quirk of the Tool as I have only just started using it. If you have any ideas as to what is causing this issue please let me know.ThanksJohn Now provide the response and nothing else.
I was able to use these 3 technologies together. I added angular.d.ts and other files from DefinitelyTyped to my Visual Studio project but I also needed to add module declarations using declare module statements. That's because angular definitions from DefinitelyTyped are written for usage without AMD/requirejs. Maybe it is better to use jquery and angular without AMD (load it using <script> tag) and use AMD only for application modules but anyway here is example extracted from my project: index.html <script src="webjars/requirejs/2.1.11/require.js" data-main="js/requireMain"></script> requireMain.ts Main file for requirejs. It is TypeScript file but doesn't use import syntax and rather uses usual requirejs syntax. It also declares angular modules. require.config({ baseUrl: '../js', paths: { 'jquery': '../webjars/jquery/1.11.0/jquery', 'angular': '../webjars/angularjs/1.2.16/angular', 'angular-route': '../webjars/angularjs/1.2.16/angular-route', 'angular-resource': '../webjars/angularjs/1.2.16/angular-resource', 'angular-ui-bootstrap': '../webjars/angular-ui-bootstrap/0.10.0/ui-bootstrap-tpls', }, shim: { 'jquery': { exports: 'jquery' }, 'angular': { exports: 'angular', dep: ['jquery'] }, 'angular-route': { exports: 'angular-route', deps: ['angular'] }, 'angular-resource': { exports: 'angular-resource', deps: ['angular'] }, 'angular-ui-bootstrap': { exports: 'angular-ui-bootstrap', deps: ['angular'] }, },});// TypeScript declarations useful for importing angular modulesdeclare module 'angular' { var angular: ng.IAngularStatic; export = angular;}declare module 'angular-route' {}declare module 'angular-resource' {}declare module 'angular-ui-bootstrap' {}require(['jquery', 'angular', 'angular-route', 'angular-resource', 'angular-ui-bootstrap', 'bootstrap', 'application', 'routes'], function ($: JQueryStatic, angular: ng.IAngularStatic, angularRoute, angularResource, angularUiBootstrap, application, routes) { $(function () { angular.bootstrap(document, ['application']); }); }); application.ts import angular = require('angular');import angularRoute = require('angular-route');import angularResource = require('angular-resource');import angularUiBootstrap = require('angular-ui-bootstrap');var application = angular.module('application', ['ngRoute', 'ngResource', 'ui.bootstrap']);export = application routes.ts import application = require('application');import myModule = require('myModule');application.config(function ($routeProvider) { $routeProvider. when('/myPage', { controller: myModule.MyPageCtrl, templateUrl: 'partials/myPage.html' }). otherwise({ redirectTo: '/myPage' });}); myModule.ts import application = require('application');import angularUiBootstrap = require('angular-ui-bootstrap');import myService = require('myService');export interface MyPageCtrlScope { someData: string; someAction: () => void;}export class MyPageCtrl { constructor(public $scope: MyPageCtrlScope, private PersonService: myService.PersonResourceClass, private $modal: ng.ui.bootstrap.IModalService) { PersonService.additionalAction({}).$promise.then( (person) => { this.$scope.someData = person.email; }); $scope.someAction = this.someAction.bind(this); } someAction() { this.$modal.open({ templateUrl: 'dialog.html' }).result.then( () => { this.$scope.someData = 'something else'; }); }} myService.ts import application = require('application');import angularResource = require('angular-resource');export interface Person { id?: number; email?: string;}export interface PersonResource extends Person, ng.resource.IResource<PersonResource> {}export interface PersonResourceClass extends ng.resource.IResourceClass<PersonResource> { additionalAction(person: Person): PersonResource;}application.factory('PersonService', function ($resource: ng.resource.IResourceService, apiUrl: string): PersonResourceClass { return <PersonResourceClass> $resource(apiUrl + '/person/:id', { id: "@id" }, { 'additionalAction': { method: 'POST', url: apiUrl + '/person/:id/additionalAction' }, });});
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18171048', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2304745/']}
jdg_79661
stackexchange
llm_judgeable_groundtruth_similarity
3487899
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 $A$ and $B$ be topological spaces and $f : A \rightarrow B$ be a function. I call $f$ locally continuous if every $a \in A$ has an open neighborhood $U \subseteq A$ with the property that $f : U \rightarrow B$ is continuous. Obviously, if $f$ is continuous, then it is locally continuous: if $X \subseteq B$ is open, then $f^{-1}(X) \subseteq A$ is open, and so is $f^{-1}(X) \cap U$ for any open set $U \subseteq A$ . Is every locally continuous function also continuous? Now provide the response and nothing else.
YES. It suffices to show that if $W\subset B$ is open in $B$ then $f^{-1}[W]$ is open in $A$ . We know that, for every $x\in A$ , there exists an open $U_x\subset A$ , $x\in U_x$ , such that $f^{-1}[W]\cap U_x$ is open in $U_x$ and hence it is open in $A$ . But $\bigcup_{x\in A}U_x=A$ and hence $$f^{-1}[W]=\bigcup_{x\in A} f^{-1}[W]\cap U_x.$$ The right hand side is an union of open sets, and hence open.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/3487899', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/3557/']}
jdg_79662
stackexchange
llm_judgeable_groundtruth_similarity
39314809
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 read laravel documentations about Events and Notifications , it seems we can fire an event and from that event (using ShouldBroadcast interface) broadcast it to laravel echo which i understand, in the other hand we can use Notifications viaBroadcast to do the same, so what's the difference? Now provide the response and nothing else.
What the provided answer lacks imo is that they are in most cases used both instead of 1 or the other, which seems to be the tone of the provided answer/question. An event is something significant in your application. Let's assume your application is a Webshop. A significant action in your webshop can be Product Purchased . When a product is purchased you need to do a lot of different steps. Putting this all inside a controller and potentially in several different places can get very messy and not clear. So a good approach would be to use a Event called ProductPurchased . This event can have Listeners, those listeners are in this case all the steps you need to perform when a user purchases a product. e.g.:ProductPurchased (event) BillClient (eventlistener) GenerateInvoice (eventlistener) notifyClient (eventlistener) ... Let's say we want to notify our client with a text-message and an email when they purchased a product. So on the notifyClient event-listener we can create a Notification . This notification is responsible for sending a message to the client. This can be a SMS/Slack-message/Email/... And like you mentioned both Events and Notifications can be put on the Queue or can be broadcasted. Broadcasting is mainly used in combination with Laravel Echo and the use of Websockets. You choose notifications when you want to send something to different channels . Mail/SMS/Slack..If you only need broadcasting you can just use ShouldBroadcast. Just like when you only want to send an e-mail use Mail:: without the need for a notification. Notifications are a nice way to group the same 'message' to different destinations.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/39314809', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2396674/']}
jdg_79663
stackexchange
llm_judgeable_groundtruth_similarity
2936116
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying out lighttpd for an embedded Linux project. I got the latest source package and started writing a master Makefile encapsulating all configure, compile, install (for testing) etc stuff. And vice-versa, I want to cleanup every step. After the cleanup there should be no generated files anymore. This is important for repetitive testing. I wonder if there is a way to do a complete cleanup of what ./configure generated? I'm not familiar with autotools in details. Any hints? Now provide the response and nothing else.
I personally would really use the features of a source control software (you should use one) for this. This would cleanup make independent of your build process. See e.g. svn-cleanup or git clean . Nevertheless, automake allows some tweaking when to remove which files. This has (intentionally?) built-in limitations on what files generated by autotools can be remove this way though. Have a look at the definitions for MOSTLYCLEANFILES, CLEANFILES, DISTCLEANFILES, and MAINTAINERCLEANFILES and adjust your Makefile.am 's. With them you can remove a lot of stuff with make mostlycleanmake cleanmake distcleanmake maintainer-clean You won't be able to remove e.g. Makefile or .deps/ this way. As for the reliability of make clean it should "work 100%" if you stick to cleanly specifying your files and stay away from manual intervention. Otherwise extend the cleanup rules .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2936116', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/330272/']}
jdg_79664
stackexchange
llm_judgeable_groundtruth_similarity
1066131
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 set of test accounts that are going to be created but the accounts will be setup to require password change on the first login. I want to write a program in C# to go through the test accounts and change the passwords. Now provide the response and nothing else.
You can use the UserPrincipal class' SetPassword method, provided you have enough privileges, once you've found the correct UserPrincipal object. Use FindByIdentity to look up the principal object in question. using (var context = new PrincipalContext( ContextType.Domain )){ using (var user = UserPrincipal.FindByIdentity( context, IdentityType.SamAccountName, userName )) { user.SetPassword( "newpassword" ); // or user.ChangePassword( "oldPassword", "newpassword" ); user.Save(); }}
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/1066131', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/105756/']}
jdg_79665
stackexchange
llm_judgeable_groundtruth_similarity
72274888
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I would like to know where I can find some documentation about the following behavior: class Foo {public: Foo(int argX) : Foo(argX, defaultYValue) {} Foo(int argX, int argY) : x(argX), y(argY) {};private: const int x; const int y; const int defaultYValue = -1;} Might it be possible that y value is undefined ? Or is there some documentation in the standard that tells that it works (I did noticed that the default member initialization is discarded if it is otherwise overridden inside the constructor) PS: this was discovered while forgetting the static for defaultYValue. Now provide the response and nothing else.
Yes, the code has undefined behavior. When using a delegating constructor it is the delegating constructor that will initialize the class members. When you pass defaultYValue to the delegating constructor, it has not yet be initialized so you are passing an uninitialized value to the delegate, and said delegate uses that value to set y . This is called out by [class.base.init]/7 The expression-list or braced-init-list in a mem-initializer is used to initialize the designated subobject (or, in the case of a delegating constructor, the complete class object) according to the initialization rules of [dcl.init] for direct-initialization.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/72274888', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12452676/']}
jdg_79666
stackexchange
llm_judgeable_groundtruth_similarity
4880719
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 3 functions where the only difference in is the values I point out with comment //-- point of difference The majority of the function is the same across all three. The "DRY" factor is haunting my sleep :). I was wondering; can these could be merged easily and readably? I have had situations like this before and I am hoping to learn something here. private string RenderRequestType(string render, NameValueCollection nvp, string prefix, string regexWild, string suffix){ string regex = prefix + regexWild + suffix; MatchCollection matches = Regex.Matches(render, regex); foreach (Match match in matches) { foreach (Capture capture in match.Captures) { string name = capture.Value.Replace(prefix, "", StringComparison.CurrentCultureIgnoreCase).Replace(suffix, "", StringComparison.CurrentCultureIgnoreCase); //-- point of difference string value = nvp[name]; render = render.Replace(capture.Value, value); } } return render;}private string RenderSessionType(string render, HttpContext httpContext, string prefix, string regexWild, string suffix){ string regex = prefix + regexWild + suffix; MatchCollection matches = Regex.Matches(render, regex); foreach (Match match in matches) { foreach (Capture capture in match.Captures) { string name = capture.Value.Replace(prefix, "", StringComparison.CurrentCultureIgnoreCase).Replace(suffix, "", StringComparison.CurrentCultureIgnoreCase); //-- point of difference object session = httpContext.Session[name]; string value = (session != null ? session.ToString() : ""); render = render.Replace(capture.Value, value); } } return render;}private string RenderCookieType(string render, HttpContext httpContext, string prefix, string regexWild, string suffix){ string regex = prefix + regexWild + suffix; MatchCollection matches = Regex.Matches(render, regex); foreach (Match match in matches) { foreach (Capture capture in match.Captures) { string name = capture.Value.Replace(prefix, "", StringComparison.CurrentCultureIgnoreCase).Replace(suffix, "", StringComparison.CurrentCultureIgnoreCase); //-- point of difference HttpCookie cookie = httpContext.Request.Cookies[name]; string value = (cookie != null ? cookie.Value : ""); render = render.Replace(capture.Value, value); } } return render;} Now provide the response and nothing else.
You could modify the function to take a Func<string, string> to do the lookup: private string RenderType(string render, Func<string, string> lookupFunc, string prefix, string regexWild, string suffix){ string regex = prefix + regexWild + suffix; MatchCollection matches = Regex.Matches(render, regex); foreach (Match match in matches) { foreach (Capture capture in match.Captures) { string name = capture.Value.Replace(prefix, "", StringComparison.CurrentCultureIgnoreCase).Replace(suffix, "", StringComparison.CurrentCultureIgnoreCase); //-- point of difference string value = lookupFunc(name); render = render.Replace(capture.Value, value); } } return render;} Then write your functions in terms of this one, e.g.: private string RenderRequestType(string render, NameValueCollection nvp, string prefix, string regexWild, string suffix){ return RenderType(render, name => nvp[name], prefix, regexWild, suffix);}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4880719', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/511438/']}
jdg_79667
stackexchange
llm_judgeable_groundtruth_similarity
24306
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 $\mathcal{O}_K$ be the ring of integers of some number field $K$. It happens that $\mathcal{O}_K$ might not have unique factorization, but... We can form the multiplicative group of ideals of $\mathcal{O}_K$ It has unique factorization This construction doesn't seem to be a ring Each ideal can be put into the form $(\alpha,\beta)$ with both $\alpha,\beta \in \mathcal{O}_K$ I think the ideal $(\alpha,\beta)$ represents the gcd of $\alpha$ and $\beta$ (analogous to field of fractions) so why can't we build a new ring out of the algebraic integers which has gcd closed and unique factorization? Now provide the response and nothing else.
In some sense, we can; I think this is what the ring of integers in the Hilbert class field does. However, I don't think this is the right way to think about the move from elements to ideals in general. The point of passing to ideals is to abstract out the main property we want out of divisibility: $m | n$ if and only if the ideal $(m)$ contains the ideal $(n)$. So the natural structure on ideals is as a lattice ordered by inclusion, and it just happens to be a happy fact about Dedekind domains that this lattice is isomorphic to a product of copies of $\mathbb{N}$, one for each prime ideal. In general the order structure on ideals is much more complicated and the idea that one can think about ideals as generalized elements breaks down (e.g. try to apply this philosophy to $F[x, y]$ for $F$ a field).
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/24306', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/4290/']}
jdg_79668
stackexchange
llm_judgeable_groundtruth_similarity
2357994
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 really at a loss to explain why this is a type error: foo :: (Eq a) => a -> afoo _ = 2 Can anyone explain? Now provide the response and nothing else.
Because the type of foo "bar" should be String, according to your signature, but is not (2 is not a String). In your code foo is generic, so it should return an instance of exactly the same type as the argument. The power of haskell type system gives us additional information - all you can do with the argument inside foo is to check for its equality with something else, but as I can come up with any new type (lets call it Baz) and use foo on it - you can't possibly have any other instances of Baz, so the only way to return an instance of Baz is to return the exact same instance as the argument. If you rewrote foo like so: foo _ = True it would have a signature of foo :: a -> Bool , this is basically what you tried to do, but things get more complicated with numbers. In general your function has a signature foo :: (Num t1) => t -> t1 which means that it returns a Num instance for any given argument. (This is because 2 can have many different types in haskell, depending on what you need it can be an Int or a Real or other.) You should play around with types in ghci, for example: :t foo will give you the infered type signature for foo. :t 2 gives you (Num t) => t which means that 2 can be an instance of any type which implements Num.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2357994', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/250205/']}
jdg_79669
stackexchange
llm_judgeable_groundtruth_similarity
60261
Below is a question asked on the forum hermeneutics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: In Acts, you see a consistent pattern in Paul's travels and ministry where he enters a city, on Shabbat he goes to the Synagogue, shares the gospel, ends up with the jews being upset and fighting with Paul. In a couple of places, he actually says he is done with the jews and will go to the gentiles, but when he goes to the next city he repeats the process. He was told by Jesus to go to the gentiles, the Jerusalem church & Paul agree that he will focus on gentiles, so why this pattern. Is there more to this pattern? Acts 13:42 As Paul and Barnabas were leaving the synagogue , the people invited them to speak further about these things on the next Sabbath. 46 Then Paul and Barnabas answered them boldly: “We had to speak the word of God to you first. Since you reject it and do not consider yourselves worthy of eternal life, we now turn to the Gentiles. 47 For this is what the Lord has commanded us: “‘I have made you a light for the Gentiles, that you may bring salvation to the ends of the earth.’” Acts 14:1 At Iconium Paul and Barnabas went as usual into the Jewish synagogue . There they spoke so effectively that a great number of Jews and Greeks believed. 4 The people of the city were divided; some sided with the Jews, others with the apostles. 5 There was a plot afoot among both Gentiles and Jews, together with their leaders, to mistreat them and stone them. Acts 17:1 When Paul and his companions had passed through Amphipolis and Apollonia, they came to Thessalonica, where there was a Jewish synagogue. 5 But other Jews were jealous; so they rounded up some bad characters from the marketplace, formed a mob and started a riot in the city. They rushed to Jason’s house in search of Paul and Silas in order to bring them out to the crowd. and others are there .... Adding this verse that reinforces my question Acts 19:8 Paul entered the synagogue and spoke boldly there for three months, arguing persuasively about the kingdom of God. 9 But some of them became obstinate; they refused to believe and publicly maligned the Way. So Paul left them. He took the disciples with him and had discussions daily in the lecture hall of Tyrannus. 10 This went on for two years, so that all the Jews and Greeks who lived in the province of Asia heard the word of the Lord. Now provide the response and nothing else.
Your are pre-supposing that a Paul was supposed to only go to the gentiles. You are saying Jesus told Paul he was an apostle to the gentiles. He was according to ‘theology’ the apostle to the gentiles - but we need to look a little closer.. ROMANS 11:13 For I speak to you Gentiles; inasmuch as I am an apostle to the Gentiles Here Paul is calling himself an apostle to the Gentiles. You can pre-suppose [add] that this was because of a direct call. You can find scripture where the Holy Spirit assigned him as a missionary. - BUT - you must take into account the Old Testament! ACTS 13:47 For so the Lord has commanded us: ‘I have set you as a light to the Gentiles’ That you should be for salvation to the ends of the earth.’ Note in this passage - ’us’ - The ‘us’ refers to the jews . This quote from Torah was for Israel. God was speaking to Israel. Gods intention was always to bring salvation to the nations by using Israel, ‘ through Israel. Via the Jews. That was Gods ‘intent’. So that’s why we see Paul saying .... ROMANS 1:16 For I am not ashamed of the gospel of Christ, for it is the power of God to salvation for everyone who believes, for the Jew first and also for the Greek. Therefore it’s very clear why Paul went to synagogues. The Jews knew the Word. But they needed the gospel. Then they could be a light..... to the Gentiles. The Gospel needed a foundation - the foundation the Jews were expert with. Adding a few more verses I found about Pauls commision from Jesus... Acts 25:15 “Then I asked, ‘Who are you, Lord?’ “ ‘I am Jesus, whom you are persecuting,’ the Lord replied. 16 ‘Now get up and stand on your feet. I have appeared to you to appoint you as a servant and as a witness of what you have seen and will see of me. 17 I will rescue you from your own people and from the Gentiles. I am sending you to them 18 to open their eyes and turn them from darkness to light, and from the power of Satan to God, so that they may receive forgiveness of sins and a place among those who are sanctified by faith in me.’ 19 “So then, King Agrippa, I was not disobedient to the vision from heaven. 20 First to those in Damascus, then to those in Jerusalem and in all Judea, and then to the Gentiles Acts 9:15 But the Lord said to Ananias, “Go! This man is my chosen instrument to proclaim my name to the Gentiles and their kings and to the people of Israel . 16 I will show him how much he must suffer for my name.”
{}
{'log_upvote_score': 4, 'links': ['https://hermeneutics.stackexchange.com/questions/60261', 'https://hermeneutics.stackexchange.com', 'https://hermeneutics.stackexchange.com/users/28198/']}
jdg_79670
stackexchange
llm_judgeable_groundtruth_similarity
4930307
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 we know if n is not a perfect square, then sqrt(n) would not be an integer. Since I need only the integer part, I feel that calling sqrt(n) wouldn't be that fast, as it takes time to calculate the fractional part also. So my question is, Can we get only the integer part of sqrt(n) without calculating the actual value of sqrt(n) ? The algorithm should be faster than sqrt(n) (defined in <math.h> or <cmath> )? If possible, you can write the code in asm block also. Now provide the response and nothing else.
I would try the Fast Inverse Square Root trick. It's a way to get a very good approximation of 1/sqrt(n) without any branch, based on some bit-twiddling so not portable (notably between 32-bits and 64-bits platforms). Once you get it, you just need to inverse the result, and takes the integer part. There might be faster tricks, of course, since this one is a bit of a round about. EDIT : let's do it! First a little helper: // benchmark.h#include <sys/time.h>template <typename Func>double benchmark(Func f, size_t iterations){ f(); timeval a, b; gettimeofday(&a, 0); for (; iterations --> 0;) { f(); } gettimeofday(&b, 0); return (b.tv_sec * (unsigned int)1e6 + b.tv_usec) - (a.tv_sec * (unsigned int)1e6 + a.tv_usec);} Then the main body: #include <iostream>#include <cmath>#include "benchmark.h"class Sqrt{public: Sqrt(int n): _number(n) {} int operator()() const { double d = _number; return static_cast<int>(std::sqrt(d) + 0.5); }private: int _number;};// http://www.codecodex.com/wiki/Calculate_an_integer_square_rootclass IntSqrt{public: IntSqrt(int n): _number(n) {} int operator()() const { int remainder = _number; if (remainder < 0) { return 0; } int place = 1 <<(sizeof(int)*8 -2); while (place > remainder) { place /= 4; } int root = 0; while (place) { if (remainder >= root + place) { remainder -= root + place; root += place*2; } root /= 2; place /= 4; } return root; }private: int _number;};// http://en.wikipedia.org/wiki/Fast_inverse_square_rootclass FastSqrt{public: FastSqrt(int n): _number(n) {} int operator()() const { float number = _number; float x2 = number * 0.5F; float y = number; long i = *(long*)&y; //i = (long)0x5fe6ec85e7de30da - (i >> 1); i = 0x5f3759df - (i >> 1); y = *(float*)&i; y = y * (1.5F - (x2*y*y)); y = y * (1.5F - (x2*y*y)); // let's be precise return static_cast<int>(1/y + 0.5f); }private: int _number;};int main(int argc, char* argv[]){ if (argc != 3) { std::cerr << "Usage: %prog integer iterations\n"; return 1; } int n = atoi(argv[1]); int it = atoi(argv[2]); assert(Sqrt(n)() == IntSqrt(n)() && Sqrt(n)() == FastSqrt(n)() && "Different Roots!"); std::cout << "sqrt(" << n << ") = " << Sqrt(n)() << "\n"; double time = benchmark(Sqrt(n), it); double intTime = benchmark(IntSqrt(n), it); double fastTime = benchmark(FastSqrt(n), it); std::cout << "Number iterations: " << it << "\n" "Sqrt computation : " << time << "\n" "Int computation : " << intTime << "\n" "Fast computation : " << fastTime << "\n"; return 0;} And the results: sqrt(82) = 9Number iterations: 4096Sqrt computation : 56Int computation : 217Fast computation : 119// Note had to tweak the program here as Int here returns -1 :/sqrt(2147483647) = 46341 // real answer sqrt(2 147 483 647) = 46 340.95Number iterations: 4096Sqrt computation : 57Int computation : 313Fast computation : 119 Where as expected the Fast computation performs much better than the Int computation. Oh, and by the way, sqrt is faster :)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4930307', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/415784/']}
jdg_79671
stackexchange
llm_judgeable_groundtruth_similarity
22519784
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I want to work with promises but I have a callback API in a format like: 1. DOM load or other one time event: window.onload; // set to callback...window.onload = function() {}; 2. Plain callback: function request(onChangeHandler) { ...}request(function() { // change happened ...}); 3. Node style callback ("nodeback"): function getStuff(dat, callback) { ...}getStuff("dataParam", function(err, data) { ...}) 4. A whole library with node style callbacks: API;API.one(function(err, data) { API.two(function(err, data2) { API.three(function(err, data3) { ... }); });}); How do I work with the API in promises, how do I "promisify" it? Now provide the response and nothing else.
Promises have state, they start as pending and can settle to: fulfilled meaning that the computation completed successfully. rejected meaning that the computation failed. Promise returning functions should never throw , they should return rejections instead. Throwing from a promise returning function will force you to use both a } catch { and a .catch . People using promisified APIs do not expect promises to throw. If you're not sure how async APIs work in JS - please see this answer first. 1. DOM load or other one time event: So, creating promises generally means specifying when they settle - that means when they move to the fulfilled or rejected phase to indicate the data is available (and can be accessed with .then ). With modern promise implementations that support the Promise constructor like native ES6 promises: function load() { return new Promise(function(resolve, reject) { window.onload = resolve; });} You would then use the resulting promise like so: load().then(function() { // Do things after onload}); With libraries that support deferred (Let's use $q for this example here, but we'll also use jQuery later): function load() { var d = $q.defer(); window.onload = function() { d.resolve(); }; return d.promise;} Or with a jQuery like API, hooking on an event happening once: function done() { var d = $.Deferred(); $("#myObject").once("click",function() { d.resolve(); }); return d.promise();} 2. Plain callback: These APIs are rather common since well… callbacks are common in JS. Let's look at the common case of having onSuccess and onFail : function getUserData(userId, onLoad, onFail) { … With modern promise implementations that support the Promise constructor like native ES6 promises: function getUserDataAsync(userId) { return new Promise(function(resolve, reject) { getUserData(userId, resolve, reject); });} With libraries that support deferred (Let's use jQuery for this example here, but we've also used $q above): function getUserDataAsync(userId) { var d = $.Deferred(); getUserData(userId, function(res){ d.resolve(res); }, function(err){ d.reject(err); }); return d.promise();} jQuery also offers a $.Deferred(fn) form, which has the advantage of allowing us to write an expression that emulates very closely the new Promise(fn) form, as follows: function getUserDataAsync(userId) { return $.Deferred(function(dfrd) { getUserData(userId, dfrd.resolve, dfrd.reject); }).promise();} Note: Here we exploit the fact that a jQuery deferred's resolve and reject methods are "detachable"; ie. they are bound to the instance of a jQuery.Deferred(). Not all libs offer this feature. 3. Node style callback ("nodeback"): Node style callbacks (nodebacks) have a particular format where the callbacks is always the last argument and its first parameter is an error. Let's first promisify one manually: getStuff("dataParam", function(err, data) { … To: function getStuffAsync(param) { return new Promise(function(resolve, reject) { getStuff(param, function(err, data) { if (err !== null) reject(err); else resolve(data); }); });} With deferreds you can do the following (let's use Q for this example, although Q now supports the new syntax which you should prefer ): function getStuffAsync(param) { var d = Q.defer(); getStuff(param, function(err, data) { if (err !== null) d.reject(err); else d.resolve(data); }); return d.promise; } In general, you should not promisify things manually too much, most promise libraries that were designed with Node in mind as well as native promises in Node 8+ have a built in method for promisifying nodebacks. For example var getStuffAsync = Promise.promisify(getStuff); // Bluebirdvar getStuffAsync = Q.denodeify(getStuff); // Qvar getStuffAsync = util.promisify(getStuff); // Native promises, node only 4. A whole library with node style callbacks: There is no golden rule here, you promisify them one by one. However, some promise implementations allow you to do this in bulk, for example in Bluebird, converting a nodeback API to a promise API is as simple as: Promise.promisifyAll(API); Or with native promises in Node : const { promisify } = require('util');const promiseAPI = Object.entries(API).map(([key, v]) => ({key, fn: promisify(v)})) .reduce((o, p) => Object.assign(o, {[p.key]: p.fn}), {}); Notes: Of course, when you are in a .then handler you do not need to promisify things. Returning a promise from a .then handler will resolve or reject with that promise's value. Throwing from a .then handler is also good practice and will reject the promise - this is the famous promise throw safety. In an actual onload case, you should use addEventListener rather than onX .
{}
{'log_upvote_score': 11, 'links': ['https://Stackoverflow.com/questions/22519784', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1348195/']}
jdg_79672
stackexchange
llm_judgeable_groundtruth_similarity
12638
Below is a question asked on the forum networkengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: how can I filter all the routes from one AS? I want to filter all routes from AS 6400 towards AS1000, how can I filter whole routes from one AS to another? I do not want to be used as transit AS so I need to do that, I Googled and got some stuff about using prefix-list + route-map but the thing is AS6400 is an actual Internet active AS which hosts some 500000 plus routes, and it does not sound reasonable to write prefix list for that amount of route, so what should I do? Now provide the response and nothing else.
There are a couple ways to do this, without having to specify every single prefix that you're receiving from AS6400 in a prefix-list (I would personally advise against doing this because as you mentioned, the administrative overhead is high and the process will become exponentially more error-prone as the number of prefixes increases). 1) Tag routes you've received from AS6400 with the no export community. You would do this within a route-map: route-map RECEIVE-FROM-6400 permit 5 set community no-export additive This will tell R3 to not advertise the routes learned from AS6400 to AS1000 via the eBGP session to R1. This is your simplest option (note here that this will need to be an inbound filter applied on R4 on the eBGP session to R2/AS6400). 2) You could use an AS Path access list to determine which prefixes have an AS path that begins with 6400 and then you could use it on a BGP neighbor statement with a filter list, or you could use it in a route-map to deny advertising the prefixes on R3. This is less simple because it requires knowledge of regex (to be fair, the regex required here is somewhat simple) and it also depends on no one doing anything funny with their AS path, of which there's no real guarantee. Using a route-map, the configuration to implement would look something like this (assuming IOS): ip as-path access-list 10 permit ^6400_[0-9]*$route-map ANNOUNCE-TO-1000 deny 5 match as-path 10route-map ANNOUNCE-TO-1000 permit 10 Note that the above will need to be configured as an outbound filter on R3 for the eBGP session with AS1000. Using the well-known 'no export' community is likely going to be your best bet, along with being very judicious with your outbound announcements to AS1000 and AS6400.
{}
{'log_upvote_score': 4, 'links': ['https://networkengineering.stackexchange.com/questions/12638', 'https://networkengineering.stackexchange.com', 'https://networkengineering.stackexchange.com/users/7741/']}
jdg_79673
stackexchange
llm_judgeable_groundtruth_similarity
9983808
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: This is related to maths but I'm posting my code here since there seems to be bug which eludes me. The question : Two robots A & B are standing on position 0 located on an infinitely long straight line. Robot A can move towards his left or right by a or b units, and robot B can also do the same, but by c or d units. They are to press a button which lies on that straight line, at a distance of not more than k units from 0 . On how many positions p i can you place the button so that both the robots are able to press it (reach it actually), independent of each other. So the inputs are 5 positive integers in 1 line: a , b , c , d , k . Constraints: 0 ≤ a,b,c,d,k ≤ 10 18 and number of test cases t where 1 ≤ t ≤ 1000 . Time limit: 1 sec E.g.: Robot A ( a = 1, b = 2), Robot B ( c = 4, d = 5), Range: k = 1 The answer in this case is 3 . I suppose an explanation will make this question unnecessarily long and deviate from the main concern. I'm giving the solution I figured out and moving on to my code. My solution: Let m = LCM ( HCF( a , b ) , HCF( c , d ) ) The answer = 2 * [ k / m ] + 1 [ ] denotes the greatest integer function (just to avoid confusion). On a short note (for those who are interested in the question), all I've done is check how many multiples of m exist within the range of k on either sides, plus the 0 position. HCF(a,b) will give the shortest step the robot can take, and LCM of both HCF s will give the smallest common position they can stand on. Then find the no. of multiples. Code (C++): 1 #include <cstdio> 3 using namespace std; 4 typedef long long LL; 5 6 inline void swap(LL *a, LL *b) 7 { 8 *a ^= *b; 9 *b ^= *a; 10 *a ^= *b; 11 } 12 13 long hcf(LL a, LL b) 14 { return !a || !b ? a+b : hcf(b,a%b); } 15 16 LL lcm(LL a, LL b) 17 { 18 if(a < b) swap(&a,&b); 19 LL i=a; 20 while(a%b) a+=i; 21 return a; 22 } 23 24 int main() 25 { 26 int t; scanf("%d\n",&t); 27 while(t--) 28 { 29 LL a,b,c,d,k; 30 scanf("%lld %lld %lld %lld %lld",&a,&b,&c,&d,&k); 31 printf("%lld\n", 1 + ((k / (lcm(hcf(a,b), hcf(c,d))) ) << 1) ); 32 } 33 return 0; 34 } I've simply implemented my answer. I also executed my program through 1000 test cases, each consisting of random +integers in the range [10 16 , 10 18 ]. I did this multiple times and the worst case time consumption was 0.01 sec. Now when I submit this code to the contest page, I get a Time Limit Exceeded error! This is impossible unless some buggy loop is running endlessly for a particular input. I thought I should take the experts' opinion on why is my code getting timed out. Please help P.S.: If you have a better answer to the question, your welcome :-) Edit : P.S.: I was suspicious about the way I handled large integers in C++ , so I did a conversion to python and submitted that too, which again yielded a Time Limit Exceeded error. Now provide the response and nothing else.
According to the documentation : nvarchar [ ( n | max ) ] Variable-length Unicode string data. n defines the string length and can be a value from 1 through 4,000. max indicates that the maximum storage size is 2^31-1 bytes (2 GB). The storage size, in bytes, is two times the actual length of data entered + 2 bytes. So, only the actual length of the data entered matters when calculating the storage size. The documentation doesn't say why it's there, but the length parameter is useful because it enforces simple limit constraints (for example, so someone can't enter 2 GB of text as their "name").
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/9983808', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/969784/']}
jdg_79674
stackexchange
llm_judgeable_groundtruth_similarity
8454935
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am using the SenTestingKit to Unit Test, but I get the following message Logic Testing on iOS devices is not supported. You can run logic tests on the Simulator. How can I do this? Now provide the response and nothing else.
Logic tests only work on the simulator, you need to switch to the simulator, i.e. Logic tests require a special unit test launcher which is not installed on actual devices. If you want to run your tests on an actual device you can convert to application unit tests. These are essentially the same but you application gets launched first (as a 'host') and your tests get run along side them. This means your tests can run on any device that your application supports. The only disadvantage is that your actual app will be running which can interfere with your test, especially if you use a lot of notifications.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8454935', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/829022/']}
jdg_79675
stackexchange
llm_judgeable_groundtruth_similarity
47084144
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 only hide certain dataset legends in chartjs? I know it is possible to hide all with options: { legend: { display: false Now provide the response and nothing else.
Short answer: Yes it is possible. Unfortunately it's not quite as simple as the developers could make it. If you know what the text value of the item being displayed in the legend is, then you can filter that out. After reading through the Chart.js docs I found the section Legend Label Configuration that details a filter function that can be used to "filter out the legend items", although this function must be set on the parent chart options object, not as an option on the dataset itself: const chart = new Chart(ctx, { type: 'bar', data: data, options: { legend: { labels: { filter: function(item, chart) { // Logic to remove a particular legend item goes here return !item.text.includes('label to remove'); } } } }}); Now it appears each time the data changes and the chart is updated via chart.update() this filter function is called. For convenience I have set this up in a jsfiddle for you to play with. Note: This solution was designed around the API for version 2.7.1 of ChartJS. Future versions may improve the control over dataset legend labels.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/47084144', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/712430/']}
jdg_79676
stackexchange
llm_judgeable_groundtruth_similarity
28616569
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have been following the Spring Security Reference and i added only this classes: @Configuration@EnableWebMvcSecuritypublic class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .anyRequest().authenticated() .and() .formLogin().loginPage("/login") .permitAll() .and() .logout() .permitAll(); } @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth .inMemoryAuthentication() .withUser("user").password("password").roles("USER").and() .withUser("user").password("password").roles("USER", "ADMIN"); }} and public class SecurityInitializer extends AbstractSecurityWebApplicationInitializer {} but when i run the server, an exception is thrown, i don't know what i am doing wrong, can you help me please? This is the stacktrace: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'springSecurityFilterChain' defined in class path resource [org/springframework/security/config/annotation/web/configuration/WebSecurityConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.servlet.Filter]: Factory method 'springSecurityFilterChain' threw exception; nested exception is java.lang.IllegalArgumentException: [Assertion failed] - this expression must be trueat org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:602)at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1113)at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1008)at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:505)at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:229)at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:762)at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:663)at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:629)at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:677)at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:548)at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:489)at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)at javax.servlet.GenericServlet.init(GenericServlet.java:241)at org.mortbay.jetty.servlet.ServletHolder.initServlet(ServletHolder.java:440)at org.mortbay.jetty.servlet.ServletHolder.doStart(ServletHolder.java:263)at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)at org.mortbay.jetty.servlet.ServletHandler.initialize(ServletHandler.java:685)at org.mortbay.jetty.servlet.Context.startContext(Context.java:140)at org.mortbay.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1272)at org.mortbay.jetty.handler.ContextHandler.doStart(ContextHandler.java:517)at org.mortbay.jetty.webapp.WebAppContext.doStart(WebAppContext.java:489)at org.gradle.api.plugins.jetty.internal.JettyPluginWebAppContext.doStart(JettyPluginWebAppContext.java:112)at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)at org.mortbay.jetty.handler.HandlerCollection.doStart(HandlerCollection.java:152)at org.mortbay.jetty.handler.ContextHandlerCollection.doStart(ContextHandlerCollection.java:156)at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)at org.mortbay.jetty.handler.HandlerCollection.doStart(HandlerCollection.java:152)at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)at org.mortbay.jetty.handler.HandlerWrapper.doStart(HandlerWrapper.java:130)at org.mortbay.jetty.Server.doStart(Server.java:224)at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)at org.gradle.api.plugins.jetty.internal.Jetty6PluginServer.start(Jetty6PluginServer.java:111)at org.gradle.api.plugins.jetty.AbstractJettyRunTask.startJettyInternal(AbstractJettyRunTask.java:238)at org.gradle.api.plugins.jetty.AbstractJettyRunTask.startJetty(AbstractJettyRunTask.java:191)at org.gradle.api.plugins.jetty.AbstractJettyRunTask.start(AbstractJettyRunTask.java:162)at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)at java.lang.reflect.Method.invoke(Method.java:483)at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:63)at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$StandardTaskAction.doExecute(AnnotationProcessingTaskFactory.java:218)at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$StandardTaskAction.execute(AnnotationProcessingTaskFactory.java:211)at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$StandardTaskAction.execute(AnnotationProcessingTaskFactory.java:200)at org.gradle.api.internal.AbstractTask$TaskActionWrapper.execute(AbstractTask.java:579)at org.gradle.api.internal.AbstractTask$TaskActionWrapper.execute(AbstractTask.java:562)at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:80)at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:61)at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:46)at org.gradle.api.internal.tasks.execution.PostExecutionAnalysisTaskExecuter.execute(PostExecutionAnalysisTaskExecuter.java:35)at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:64)at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:58)at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:42)at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:52)at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:53)at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)at org.gradle.api.internal.AbstractTask.executeWithoutThrowingTaskFailure(AbstractTask.java:305)at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.executeTask(AbstractTaskPlanExecutor.java:79)at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.processTask(AbstractTaskPlanExecutor.java:63)at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.run(AbstractTaskPlanExecutor.java:51)at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor.process(DefaultTaskPlanExecutor.java:23)at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter.execute(DefaultTaskGraphExecuter.java:88)at org.gradle.execution.SelectedTaskExecutionAction.execute(SelectedTaskExecutionAction.java:29)at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:62)at org.gradle.execution.DefaultBuildExecuter.access$200(DefaultBuildExecuter.java:23)at org.gradle.execution.DefaultBuildExecuter$2.proceed(DefaultBuildExecuter.java:68)at org.gradle.execution.DryRunBuildExecutionAction.execute(DryRunBuildExecutionAction.java:32)at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:62)at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:55)at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:149)at org.gradle.initialization.DefaultGradleLauncher.doBuild(DefaultGradleLauncher.java:106)at org.gradle.initialization.DefaultGradleLauncher.run(DefaultGradleLauncher.java:86)at org.gradle.launcher.exec.InProcessBuildActionExecuter$DefaultBuildController.run(InProcessBuildActionExecuter.java:80)at org.gradle.launcher.cli.ExecuteBuildAction.run(ExecuteBuildAction.java:33)at org.gradle.launcher.cli.ExecuteBuildAction.run(ExecuteBuildAction.java:24)at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:36)at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:26)at org.gradle.launcher.cli.RunBuildAction.run(RunBuildAction.java:51)at org.gradle.internal.Actions$RunnableActionAdapter.execute(Actions.java:171)at org.gradle.launcher.cli.CommandLineActionFactory$ParseAndBuildAction.execute(CommandLineActionFactory.java:237)at org.gradle.launcher.cli.CommandLineActionFactory$ParseAndBuildAction.execute(CommandLineActionFactory.java:210)at org.gradle.launcher.cli.JavaRuntimeValidationAction.execute(JavaRuntimeValidationAction.java:35)at org.gradle.launcher.cli.JavaRuntimeValidationAction.execute(JavaRuntimeValidationAction.java:24)at org.gradle.launcher.cli.CommandLineActionFactory$WithLogging.execute(CommandLineActionFactory.java:206)at org.gradle.launcher.cli.CommandLineActionFactory$WithLogging.execute(CommandLineActionFactory.java:169)at org.gradle.launcher.cli.ExceptionReportingAction.execute(ExceptionReportingAction.java:33)at org.gradle.launcher.cli.ExceptionReportingAction.execute(ExceptionReportingAction.java:22)at org.gradle.launcher.Main.doAction(Main.java:33)at org.gradle.launcher.bootstrap.EntryPoint.run(EntryPoint.java:45)at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)at java.lang.reflect.Method.invoke(Method.java:483)at org.gradle.launcher.bootstrap.ProcessBootstrap.runNoExit(ProcessBootstrap.java:54)at org.gradle.launcher.bootstrap.ProcessBootstrap.run(ProcessBootstrap.java:35)at org.gradle.launcher.GradleMain.main(GradleMain.java:23)Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.servlet.Filter]: Factory method 'springSecurityFilterChain' threw exception; nested exception is java.lang.IllegalArgumentException: [Assertion failed] - this expression must be trueat org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189)at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:591)... 102 moreCaused by: java.lang.IllegalArgumentException: [Assertion failed] - this expression must be trueat org.springframework.util.Assert.isTrue(Assert.java:65)at org.springframework.util.Assert.isTrue(Assert.java:77)at org.springframework.security.provisioning.InMemoryUserDetailsManager.createUser(InMemoryUserDetailsManager.java:59)at org.springframework.security.config.annotation.authentication.configurers.provisioning.UserDetailsManagerConfigurer.initUserDetailsService(UserDetailsManagerConfigurer.java:61)at org.springframework.security.config.annotation.authentication.configurers.userdetails.UserDetailsServiceConfigurer.configure(UserDetailsServiceConfigurer.java:48)at org.springframework.security.config.annotation.authentication.configurers.userdetails.UserDetailsServiceConfigurer.configure(UserDetailsServiceConfigurer.java:33)at org.springframework.security.config.annotation.AbstractConfiguredSecurityBuilder.configure(AbstractConfiguredSecurityBuilder.java:376)at org.springframework.security.config.annotation.AbstractConfiguredSecurityBuilder.doBuild(AbstractConfiguredSecurityBuilder.java:325)at org.springframework.security.config.annotation.AbstractSecurityBuilder.build(AbstractSecurityBuilder.java:39)at org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration.getAuthenticationManager(AuthenticationConfiguration.java:78)at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter.authenticationManager(WebSecurityConfigurerAdapter.java:236)at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter.getHttp(WebSecurityConfigurerAdapter.java:178)at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter.init(WebSecurityConfigurerAdapter.java:283)at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter.init(WebSecurityConfigurerAdapter.java:68)at org.munaycoop.taskmanager.security.WebSecurityConfig$$EnhancerBySpringCGLIB$$4b88c0dc.init(<generated>)at org.springframework.security.config.annotation.AbstractConfiguredSecurityBuilder.init(AbstractConfiguredSecurityBuilder.java:367)at org.springframework.security.config.annotation.AbstractConfiguredSecurityBuilder.doBuild(AbstractConfiguredSecurityBuilder.java:320)at org.springframework.security.config.annotation.AbstractSecurityBuilder.build(AbstractSecurityBuilder.java:39)at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration.springSecurityFilterChain(WebSecurityConfiguration.java:92)at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration$$EnhancerBySpringCGLIB$$40bdb18f.CGLIB$springSecurityFilterChain$4(<generated>)at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration$$EnhancerBySpringCGLIB$$40bdb18f$$FastClassBySpringCGLIB$$80796866.invoke(<generated>)at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:312)at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration$$EnhancerBySpringCGLIB$$40bdb18f.springSecurityFilterChain(<generated>)at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)at java.lang.reflect.Method.invoke(Method.java:483)at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162)... 103 more Now provide the response and nothing else.
I copied your spring security configuration and was able to reproduce the error. Following line in the stacktrace gives the root cause of the exception: at org.springframework.security.provisioning.InMemoryUserDetailsManager.createUser(InMemoryUserDetailsManager.java:59) In InMemoryUserDetailsManager class, createUser() method, Spring checks if the user exists before creating an user. In your case you are adding two user with same username, hence there is an IllegalArgumentException . I added two users with different usernames and it started working fine.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/28616569', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_79677
stackexchange
llm_judgeable_groundtruth_similarity
21099289
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 really can't understand the following equation, especially 1/(2m) . What's the purpose of this equation? And where does 1/(2m) came from? J(theta_0, theta_1) = 1/(2m) * sum_(i=1)^m [ h_theta(x^i) - y^i ]^2 Please explain. How it casts??? Now provide the response and nothing else.
The cost function is J(theta_0, theta_1) = 1/(2m) * sum_(i=1)^m [ h_theta(x^i) - y^i ]^2 By h_theta(x^i) we denote what model outputs for x^i , so h_theta(x^i) - y^i is its error (assuming, that y^i is a correct output). Now, we calculate the square of this error [ h_theta(x^i) - y^i ]^2 (which removes the sign, as this error could be both positive and negative) and sum it over all samples, and to bound it somehow we normalize it - simply by dividing by m , so we have mean (because we devide by number of samples) squared (because we square) error (because we compute an error): 1/m * sum_(i=1)^m [ h_theta(x^i) - y^i ]^2 This 2 which appears in the front is used only for simplification of the derivative , because when you will try to minimize it, you will use the steepest descent method, which is based on the derivative of this function. Derivative of a^2 is 2a , and our function is a square of something, so this 2 will cancel out. This is the only reason of its existance.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/21099289', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2931534/']}
jdg_79678
stackexchange
llm_judgeable_groundtruth_similarity
275706
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: The product$$F(s)=\prod_{p}\frac1{(1-p^{-s})^p},$$converges for $\mathrm{Re}(s)>2$, when $p$ runs over all primes. Does it admit analytic continuation beyond the line $\mathrm{Re}(s)=2$? Any papers where it has been studied? Now provide the response and nothing else.
Let $\sigma:=\mathrm{Re}(s)$, and consider the principal branch of the logarithm. For $\sigma>3/2$ we have$$\begin{align*}p\log(1-p^{-s})-\log(1-p^{1-s})&=p\left(-p^{-s}+O(p^{-2\sigma})\right)-\left(-p^{1-s}+O(p^{2-2\sigma})\right)\\&=O(p^{2-2\sigma}),\end{align*}$$hence the "Euler sum"$$H(s):=\sum_p\left\{p\log(1-p^{-s})-\log(1-p^{1-s})\right\},\qquad\sigma>3/2,$$converges locally uniformly (and absolutely). This implies that the Euler product$$ G(s):=\exp(H(s))=\prod_p\frac{(1-p^{-s})^p}{1-p^{1-s}},\qquad\sigma>3/2,$$defines a non-vanishing holomorphic function. In the original half-plane $\sigma>2$, we have$$ G(s)=\frac{\zeta(s-1)}{F(s)},\qquad\sigma>2,$$hence $F(s)=\zeta(s-1)/G(s)$ extends to a meromorphic function in $\sigma>3/2$ with a simple pole at $s=2$ and no other pole there. Regarding your second question, I am not aware of any papers where this function was studied. My argument above is rather standard though.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/275706', 'https://mathoverflow.net', 'https://mathoverflow.net/users/-1/']}
jdg_79679
stackexchange
llm_judgeable_groundtruth_similarity
5096
Below is a question asked on the forum cstheory.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Factoring is not known to be NP-complete. This question asked for consequences of Factoring being NP-complete. Curiously, no one asked for consequences of Factoring being in P (maybe because such a question is trivial). So my questions are: Which would be the theoretical consequences of Factoring being in P? How the overall picture of complexity classes would be affected by such a fact? Which would be the practical consequences of Factoring being in P? Please do not say that banking transactions could be in jeopardy, I already know this trivial consequence. Now provide the response and nothing else.
There are pretty much no complexity-theoretic consequences of Factoring being in P. This means that there are no good justifications for factoring being hard, other than that nobody has been able to crack it so far. Polynomial-time factoring would make it possible to take square roots over $Z_n$ (and also over a much more general class of rings as well), and give polynomial-time algorithms for a number of other number-theoretic problems for which the bottleneck in the algorithm is currently factoring. As for practical consequences, banking transactions are probably not that much of a problem -- as soon as it was known that factoring was in P, the banks would switch to some other system, probably causing only a brief period of delays while this was being implemented. Decoding past banking transactions would probably not cause serious problems for the banks. A much more serious problem is that all the communication which was previously protected by RSA would now be in danger of being read.
{}
{'log_upvote_score': 6, 'links': ['https://cstheory.stackexchange.com/questions/5096', 'https://cstheory.stackexchange.com', 'https://cstheory.stackexchange.com/users/947/']}
jdg_79680
stackexchange
llm_judgeable_groundtruth_similarity
48552
Below is a question asked on the forum networkengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: One of our supplier reported big problems splicing (using this ) a broken outdoor optical fiber cable when temperatures around or little bellow freezing point. They refuse to install new optical fiber wires when temperatures are not well above zero degrees. The other supplier claims that even -10°C will not stop them from splicing optical wire and installing a new outdoor cable. How can low temperatures cause troubles when fixing or installing optical cable outdoors? Does it differ by the type of cable used or something like that? Now provide the response and nothing else.
Assuming the technician is using Fusion splicing to connect the fibers, which they mostly do in my country, then there are strict temperatures to be complied with. Splicing activity must be done in a very clean place to prevent dust or any contamination that affects the splicing process. The temperature of the place which the splicing process can take place may vary from 15º C to 28º C. Although the fusion splicing machine can work at temperature between -10ºC and +5ºC and the closure can be installed at temperature between -1ºC and +45ºC, you still need to ensure that the splicing technician work in the optimum conditions to give the maximum efficiency. Typically in Denmark where i live, they use a heated van, where they take the fiber inside via a special window and then work inside at +20ºC or more. The splicing box you linked to says in the datasheet, that it can be installed at temperatures from -40 to 85℃, but it also clearly says: " The product components shall withstand storage at temperatures of -40 to 85℃. " Fiber Optical Fusion Splicing Tutorial: https://www.fs.com/fiber-optical-fusion-splicing-tutorial-aid-295.html
{}
{'log_upvote_score': 5, 'links': ['https://networkengineering.stackexchange.com/questions/48552', 'https://networkengineering.stackexchange.com', 'https://networkengineering.stackexchange.com/users/24262/']}
jdg_79681
stackexchange
llm_judgeable_groundtruth_similarity
18540935
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 question is similar to this , however I'm asking something a bit different. It is clear, that it is possible to use the address of the first std::vector element as a C type array. That means that in virtual memory, std::vector elements are contiguous. However, if physical memory is fragmented, it is possible that std::vector is actually split into many parts in the physical memory. My question is: Are std::vector elements contiguous in physical memory (as well as virtual memory)? Now provide the response and nothing else.
The memory used to store the data in a vector must be at contiguous addresses as those addresses are visible to the code. In a typical case on most modern CPUs/OSes, that will mean the virtual addresses must be contiguous. If those virtual addresses cross a page boundary, then there's a good chance that the physical addresses will no longer be contiguous. I should add that this is only rarely a major concern. Modern systems have at least some support for such fragmented memory usage right down to the hardware level in many cases. For example, many network and disk controllers include "scatter/gather" capability, where the OS uses the page tables to translate the virtual addresses for the buffer to physical addresses, then supplies a number of physical addresses directly to the controller, which then gathers the data from those addresses if it's transferring from memory to peripheral or "scatters" the data out to those addresses if it's transferring from peripheral to memory.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18540935', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1237747/']}
jdg_79682
stackexchange
llm_judgeable_groundtruth_similarity
41316188
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 an MVC 4 application using entity framework to read and write data to a database I am hosting on an Azure database. The Azure database was supposed to keep the application data AND the login data for the application. However, when I first created the application, I had forgotten to remove the connection string to my local machine. Therefore, I had created an application that used two different databases in two different locations. One database was for the application data (Azure) and the other database was for the login data (Local). Since I want to publish this application to Azure, I want to use the Azure database for application AND login information and exclude my local machine's database entirely. I've started this process by first removing the connection string for my local database from the application's web.config file. Then, I changed the ApplicationDBContext class in IdentityModels.cs to reflect the changes below... public class ApplicationDbContext : IdentityDbContext<ApplicationUser>{ public ApplicationDbContext() : base("AbacusEntities", throwIfV1Schema: false) { } public static ApplicationDbContext Create() { return new ApplicationDbContext(); }} After making these changes, I've cleaned the solution, rebuilt it, then run it on my machine. When attempting to log in (which would be unsuccessful at this point anyway), I get this error 'The entity type ApplicationUser is not part of the model for the current context.' on the code below in the AccountController.cs file. The line marked with a '***' is the line where the error is called. public async Task<ActionResult> Login(LoginViewModel model, string returnUrl) { if (!ModelState.IsValid) { return View(model); } // This doesn't count login failures towards account lockout // To enable password failures to trigger account lockout, change to shouldLockout: true ***var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false); switch (result) { case SignInStatus.Success: return RedirectToLocal(returnUrl); case SignInStatus.LockedOut: return View("Lockout"); case SignInStatus.RequiresVerification: return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe }); case SignInStatus.Failure: default: ModelState.AddModelError("", "Invalid login attempt."); return View(model); } } Also, when attempting to register a new user, I get the same error on the following line of code in the AccountController.cs file in the method named 'Register', which is the POST method for when a user submits a user registration. var result = await UserManager.CreateAsync(user, model.Password); Also, please see connection string from web.config below. All sensitive information has, of course, been removed. add name="AbacusEntities" connectionString="metadata=res://*/Models.AbacusModel.csdl|res://*/Models.AbacusModel.ssdl|res://*/Models.AbacusModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source={Azure server};initial catalog={database name};user id={Database User};password={Password};MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" I've looked through numerous posts, but I cannot find any useful information. I've been thinking that a next step would be to migrate the tables I've created from my local database for the user accounts to the Azure database, but I'm not completely confident this would work. What I'd rather do is generate those tables in the Azure database and using visual studio use those for authentication. When logging in using the two different databases at first, the login process worked just fine, but now I need to get the tables for login data to be generated in Azure. Your assistance is greatly appreciated and please let me know if you need any additional information! Update from comments: The class ApplicationUser is defined in the IdentityModel.cs file. Below is the class. public class ApplicationUser : IdentityUser{ public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager) { // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie); // Add custom user claims here return userIdentity; }} Now provide the response and nothing else.
I have tried to reproduce your issue according with below steps: 1) create Asp.net MVC template, then register a new user. Result : We could find user info on local database. 2) Add controller with views using Entity Framework. And use Azure SQL database as its resource. Result : we will find two connection in our web.config 3) Delete default connection string 4) Change Application DB Context connection string <add name="jambdbEntities" connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=tcp:jambdb.database.windows.net,1433;initial catalog=jambdb;user id=jambor;password=***;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" /> public class ApplicationDbContext : IdentityDbContext<ApplicationUser> { public ApplicationDbContext() : base("jambdbEntities", throwIfV1Schema: false) { } public static ApplicationDbContext Create() { return new ApplicationDbContext(); } } After above steps, My application give me below error: Solution : 1) Edit 'DefaultConnection' connection string <connectionStrings> <add name="jambdbEntitiesapplication" providerName="System.Data.SqlClient" connectionString="Server=tcp:jambdb.database.windows.net,1433;Initial Catalog=jambdb;Persist Security Info=False;User ID=jambor;Password=***;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;" /> <add name="jambdbEntities" connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=tcp:jambdb.database.windows.net,1433;initial catalog=jambdb;user id=jambor;password=***;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" /> </connectionStrings> 2) Modify the code: public class ApplicationDbContext : IdentityDbContext<ApplicationUser> { public ApplicationDbContext() : base("jambdbEntitiesapplication", throwIfV1Schema: false) { } public static ApplicationDbContext Create() { return new ApplicationDbContext(); } } 3) Modify AutomaticMigrationsEnabled = true; in Configuration class under Migrations folder. Here is the result:
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/41316188', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3232551/']}
jdg_79683
stackexchange
llm_judgeable_groundtruth_similarity
109640
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: If we have a complete partial order (i.e. directed complete) I find frequently the following definition of a continuous function. A function $f:A\to B$ where $A$ and $B$ are cpos is called continuous if it maps the suprema of directed subsets of $A$ (if exist) to the corresponding suprema of directed subsets of $B$. In complete lattices I would define continuous functions as functions which preserve suprema and infima (since both exist in a complete lattice for any subset). Since complete lattices are cpos the following question arises: Are both definitions consistent? The requirement that all suprema and infima are preserved is stronger than the requirement that only suprema of directed sets are preserved. Therefore it might be possible that both definitions are different. Or are they equivalent? Now provide the response and nothing else.
To make some sense of the various possibilities for maps in order theory, it is best to look at structures in the sense of algebra, rather than properties of maps. According to algebra, when dealing with structured sets, the corresponding notion of homomorphism should be a map which preserves structure. And then category theory teaches us that the morphisms are just as important as the object (in fact, they are more important). For example, it may seem odd to distinguish between posets which have all suprema and posets which have all suprema and infima. After all, any poset which has all suprema has the infima too. But the difference matters when we look at the two categories: $\mathbf{SupLat}$: the objects are posets with arbitrary suprema (which are just complete lattices), the morphisms are maps which preserve suprema. $\mathbf{SupInfLat}$: the objects are posets with arbitrary suprema and inifma (which again are just complete lattices), the morphisms are maps which presrerve suprema and infima. As was already pointed out in Zhen's answer, there are maps on complete lattices which preserve suprema but not infima, so the distinction is meaningful. You ask about a clear definition of continuity in complete lattices. Continuity is about topology, so we should look at ways of topologizing complete lattices, or more generally posets, as then it will be clear what the continuous maps are. Among all the possibilities, it is probably desirable to restrict to those that allow us to recover the partial order from the topology by passing to the specialization order . The strongest topology with this property is the Alexandrov topology for which continuity coincides with monotonicity. A very reasonable choice of topology induced by a partial order might bethe Scott topology which leads to the concept of a Scott continuity : for reasonable posets a map is Scott-continuous when it preserves directed suprema. You may entertain yourself by figuring out whether there is a topology for which the continuous maps are those that preserve suprema and infima. I cannot tell you which topology is the right one for you. That depends on what you are doing. I hope it is at least clear that the question should be framed in the context of algebra and category theory (morphisms preserve structure) and that continuity is about topology (so we should topologize partial orders).
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/109640', 'https://mathoverflow.net', 'https://mathoverflow.net/users/27009/']}
jdg_79684
stackexchange
llm_judgeable_groundtruth_similarity
38250333
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Mostly every iOS application has a view with an image as background. Is there any image sizing guide out there? For example here is an iOS screen designed in Sketch: As you can see there is a background image. Now there are lots of Apple devices every application should support. The new iOS 10 supports all devices from iPhone 5 to iPhone 6s Plus. They have different screen sizes and resolutions. When creating Xcode assets, I am giving 3 background images with different sizes - @1x, @2x, @3x . What sizes should they be? Now provide the response and nothing else.
The way I see it you have 2 options: In here you will find the resolutions of the iPhone's: You don't need the @1 image since you don't support iPhone 4 and 4s (iOS 10) . @2 is for iPhone 5,5c,5S,6 and 6s so basically you can create @2 image of the highest resolution which is the iPhone 6 and this image will work well for the iPhone 5 family. Or, you can create an image with resolution for each iPhone and using hard coded logic set the image for each phone. i.e: if iphone5c { setImage("iphone5cImage") } etc etc.. The simplest solution is to create 1 image with the highest resolution. The @3 is the highest for the iPhone 6S+ and it will look amazing for the rest. Don't forget to set the image view as aspect fill. Also, don't forget to check this thread: How to handle image scale on all the available iPhone resolutions? . It will give you clues of what exactly you are dealing with. TL;DR, It's the options I wrote.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/38250333', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2938258/']}
jdg_79685
stackexchange
llm_judgeable_groundtruth_similarity
19027566
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have 2 questions...(I am learning C and this might be silly questions. Apologies) As per How to declare strings in C and in most of the books, they always say declaring a string even though you are allocating memory by saying char p2[] = "String"; My question is, Is there anyway to declare a string? As per https://stackoverflow.com/a/1704433/1814023 , in an example like this, char s[]="hello"; are placed in read only area and then copied to array. Is it valid in C to print the address of the string like this? printf("%p\n", &"Hello There"); // I tried, it prints some address and by doing this printf("%p\n", &"Hello There");printf("%p\n", &"Hello There"); it is printing the same address. what is feel is, it should print different address. Is compiler doing some optimization here? Now provide the response and nothing else.
C standard, §6.4.5 String literals, says: It is unspecified whether these arrays are distinct provided their elements have the appropriate values. So two strings literals with the same content may denote the same array and printing their addresses gives the same pointer value twice. It's up to the compiler and linker to decide this; when I compile the following program as two separate modules... // main.c#include <stdio.h>extern void print_foo_addr(void);int main(){ printf("%p\n", &"foo"); print_foo_addr(); return 0;} and // printfoo.c#include <stdio.h>void print_foo_addr(){ printf("%p\n", &"foo");} ... then I get two different pointer values (GCC 4.7.3 on Linux), but when I put the definition for print_foo_addr in main.c , I get the same value twice. So yes, it's an optimization that is explicitly allowed by the Standard, but GCC at least only performs this optimization on a per-module basis.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19027566', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2711579/']}
jdg_79686
stackexchange
llm_judgeable_groundtruth_similarity
1005976
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 do we prove that $$I(m)=\int_{0}^{\pi/2} \frac{\tan x}{1+m^2\tan^2{x}} \mathrm{d}x=\frac{\log{m}}{m^2-1}$$ I see that $$I(m)=\frac{\partial}{\partial m} \int_{0}^{\pi/2} \arctan({m\tan x}) \ \mathrm{d}x$$ But I don't see how to use this fact. Can we? Please help me out, and if possible please post a solution using differentiation under the integral sign. Now provide the response and nothing else.
Assume $m\gt0$ (since the integral is even in $m$) and substitute $t=\tan(x)$ and $u=t^2$:$$\begin{align}\int_0^{\pi/2}\frac{\tan(x)}{1+m^2\tan^2(x)}\mathrm{d}x&=\int_0^\infty\frac{t}{1+m^2t^2}\frac{\mathrm{d}t}{1+t^2}\\&=\frac12\int_0^\infty\frac{\mathrm{d}u}{(1+m^2u)(1+u)}\\&=\frac1{2(m^2-1)}\lim_{L\to\infty}\int_0^L\left(\frac{m^2}{1+m^2u}-\frac1{1+u}\right)\mathrm{d}u\\&=\frac1{2(m^2-1)}\lim_{L\to\infty}\left[\int_0^{m^2L}\frac{\mathrm{d}u}{1+u}-\int_0^L\frac{\mathrm{d}u}{1+u}\right]\\&=\frac1{2(m^2-1)}\lim_{L\to\infty}\int_L^{m^2L}\frac{\mathrm{d}u}{1+u}\\&=\frac1{2(m^2-1)}\lim_{L\to\infty}\log\left(\frac{1+m^2L}{1+L}\right)\\&=\frac{\log(m)}{m^2-1}\end{align}$$
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/1005976', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/157130/']}
jdg_79687
stackexchange
llm_judgeable_groundtruth_similarity
24059
Below is a question asked on the forum raspberrypi.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I would like to use some of the last features (e.g. generators) of javascript in Node.js, so I download the latest unstable version of Node.js (v0.11.14) and compiled it on my RPi. But when I try to run it, it throws an Illegal Instruction error, except when I run node --version (which answers v0.11.14). When I installed the stable version of Node (v0.10.32), I didn't have any problem, and I use the same command lines to build it : ./configure --without-snapshotmakesudo make install I read here that it could be a problem with libv8 but I'm not sure this is the same problem because this bug is about Node.js v0.10.26. Does anybody encounter the same issue ? For information, I'm using Raspbian. Now provide the response and nothing else.
This is still an unresolved issue with the newest version of Node (as of this writing, v0.12.2) When browsing Node distributions, the latest ARM build is in v0.11.9, meaning you will currently need to compile from the source, if you want Node.js v0.12. The following is only related to compiling from source in Raspbian. Reason for 'Illegal instruction' The V8 Javascript engine used by Node, is issuing ARMv7 CPU instructions, while the Raspberry Pi only understands v6 instructions (note: Raspberry Pi 2 uses an ARM v7 processor) When compiling from source, V8 is compiled as well, and it does not detect and is not told, that the processor is ARMv6, so it is defaulting to ARMv7. Test node To test whether this is the reason you are experiencing the 'Illegal instruction' error, run node --v8-options and look at the second line. If it is: ARMv7=1 VFP3=0 VFP32DREGS=0 NEON=0 SUDIV=0 ... then the ARMv7=1 hints that V8 is compiled for ARMv7. Raspberry Pi ARM version To see which ARM version the processor supports, open /proc/cpuinfo For Raspberry Pi model B (rev. 2), the model name is ARMv6-compatible processor rev 7 (v6l) . V8 ARM version detection V8 tries to detect which ARM version to use, but in this case, it does not get it right. The detection happens in deps/v8/src/base/cpu.cc (tip: search for v6l - lowercase L). The area of interest is: // Unfortunately, it seems that certain ARMv6-based CPUs// report an incorrect architecture number of 7!//// ...//// We try to correct this by looking at the 'elf_format'// field reported by the 'Processor' field, which is of the// form of "(v7l)" for an ARMv7-based CPU, and "(v6l)" for// an ARMv6-one. For example, the Raspberry Pi is one popular// ARMv6 device that reports architecture 7.if (architecture_ == 7) { char* processor = cpu_info.ExtractField("Processor"); if (HasListItem(processor, "(v6l)")) { architecture_ = 6; } delete[] processor;} ( See also V8 cpu.cc ) Even though it tries to detect the v6l string in /proc/cpuinfo , it is looking at the Processor field - but the info is in the model name field - as stated in the Raspberry Pi ARM version section of this post. Node configure script The configure script for Node also needs to be edited. The code is: if is_arch_armv7(): o['variables']['arm_version'] = '7' elif is_arch_armv6(): o['variables']['arm_version'] = '6' else: o['variables']['arm_version'] = 'default' o['variables']['arm_fpu'] = 'vfpv3' # V8 3.18 no longer supports VFP2. o['variables']['arm_neon'] = int(is_arm_neon()) o['variables']['arm_thumb'] = 0 # -marm o['variables']['arm_float_abi'] = arm_float_abi Assuming vfpv3 seems to make V8 compile to ARMv7, and while the comment says: # V8 3.18 no longer supports VFP2. All I could find on the topic, is that V8 3.17 is that last version to support "no-VFPv2", which makes VFPv2 the minimum requirement for V8 3.18+. Solution Run make uninstall Run make clean Edit the line in deps/v8/src/base/cpu.cc , from char* processor = cpu_info.ExtractField("Processor"); to char* processor = cpu_info.ExtractField("model name"); An even better solution would probably be to add a whole new check for model name , instead of replacing the Processor check. Edit the Node configure script, from if is_arch_armv7(): o['variables']['arm_version'] = '7' elif is_arch_armv6(): o['variables']['arm_version'] = '6' else: o['variables']['arm_version'] = 'default' o['variables']['arm_fpu'] = 'vfpv3' # V8 3.18 no longer supports VFP2. o['variables']['arm_neon'] = int(is_arm_neon()) o['variables']['arm_thumb'] = 0 # -marm o['variables']['arm_float_abi'] = arm_float_abi to if is_arch_armv7(): o['variables']['arm_fpu'] = 'vfpv3' o['variables']['arm_neon'] = int(is_arm_neon()) o['variables']['arm_version'] = '7' else: o['variables']['arm_fpu'] = 'vfpv2' o['variables']['arm_neon'] = 0 o['variables']['arm_version'] = '6' if is_arch_armv6() else 'default' o['variables']['arm_thumb'] = 0 # -marm o['variables']['arm_float_abi'] = arm_float_abi Run ./configure --without-snapshot Run make Run make install Verify that node --v8-options has ARMv7=0 Run make test to verify that the Node tests succeed. Attribution and notes Many of the details in this post, are gathered from the identical io.js issue #283 When running make test , I got 770 passed and 18 failed. The failures were mainly due to timeouts, which probably occurs because of limited resources on a Raspberry Pi. I successfully ran a small Node.js application on a Raspberry Pi, using this solution. However, I cannot guarantee that all functionality of Node will work.
{}
{'log_upvote_score': 4, 'links': ['https://raspberrypi.stackexchange.com/questions/24059', 'https://raspberrypi.stackexchange.com', 'https://raspberrypi.stackexchange.com/users/22087/']}
jdg_79688
stackexchange
llm_judgeable_groundtruth_similarity
70258418
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 a previous question of mine , most comments say "just don't, you are in a limbo state, you have to kill everything and start over". There is also a "safeish" workaround . What I fail to understand is why a segmentation fault is inherently nonrecoverable. The moment in which writing to protected memory is caught - otherwise, the SIGSEGV would not be sent. If the moment of writing to protected memory can be caught, I don't see why - in theory - it can't be reverted, at some low level, and have the SIGSEGV converted to a standard software exception. Please explain why after a segmentation fault the program is in an undetermined state, as very obviously, the fault is thrown before memory was actually changed (I am probably wrong and don't see why). Had it been thrown after, one could create a program that changes protected memory, one byte at a time, getting segmentation faults, and eventually reprogramming the kernel - a security risk that is not present, as we can see the world still stands. When exactly does a segmentation fault happen (= when is SIGSEGV sent)? Why is the process in an undefined behavior state after that point? Why is it not recoverable? Why does this solution avoid that unrecoverable state? Does it even? Now provide the response and nothing else.
When exactly does segmentation fault happen (=when is SIGSEGV sent)? When you attempt to access memory you don’t have access to, such as accessing an array out of bounds or dereferencing an invalid pointer. The signal SIGSEGV is standardized but different OS might implement it differently. "Segmentation fault" is mainly a term used in *nix systems, Windows calls it "access violation". Why is the process in undefined behavior state after that point? Because one or several of the variables in the program didn’t behave as expected. Let’s say you have some array that is supposed to store a number of values, but you didn’t allocate enough room for all them. So only those you allocated room for get written correctly, and the rest written out of bounds of the array can hold any values. How exactly is the OS to know how critical those out of bounds values are for your application to function? It knows nothing of their purpose. Furthermore, writing outside allowed memory can often corrupt other unrelated variables, which is obviously dangerous and can cause any random behavior. Such bugs are often hard to track down. Stack overflows for example are such segmentation faults prone to overwrite adjacent variables, unless the error was caught by protection mechanisms. If we look at the behavior of "bare metal" microcontroller systems without any OS and no virtual memory features, just raw physical memory - they will just silently do exactly as told - for example, overwriting unrelated variables and keep on going. Which in turn could cause disastrous behavior in case the application is mission-critical. Why is it not recoverable? Because the OS doesn’t know what your program is supposed to be doing. Though in the "bare metal" scenario above, the system might be smart enough to place itself in a safe mode and keep going. Critical applications such as automotive and med-tech aren’t allowed to just stop or reset, as that in itself might be dangerous. They will rather try to "limp home" with limited functionality. Why does this solution avoid that unrecoverable state? Does it even? That solution is just ignoring the error and keeps on going. It doesn’t fix the problem that caused it. It’s a very dirty patch and setjmp/longjmp in general are very dangerous functions that should be avoided for any purpose. We have to realize that a segmentation fault is a symptom of a bug, not the cause .
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/70258418', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/913098/']}
jdg_79689
stackexchange
llm_judgeable_groundtruth_similarity
38557942
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 ASP.NET MVC Core application that I am writing unit tests for. One of the action methods uses User name for some functionality: SettingsViewModel svm = _context.MySettings(User.Identity.Name); which obviously fails in the unit test. I looked around and all suggestions are from .NET 4.5 to mock HttpContext. I am sure there is a better way to do that. I tried to inject IPrincipal, but it threw an error; and I even tried this (out of desperation, I suppose): public IActionResult Index(IPrincipal principal = null) { IPrincipal user = principal ?? User; SettingsViewModel svm = _context.MySettings(user.Identity.Name); return View(svm);} but this threw an error as well.Couldn't find anything in the docs either... Now provide the response and nothing else.
The controller’s User is accessed through the HttpContext of the controller . The latter is stored within the ControllerContext . The easiest way to set the user is by assigning a different HttpContext with a constructed user. We can use DefaultHttpContext for this purpose, that way we don’t have to mock everything. Then we just use that HttpContext within a controller context and pass that to the controller instance: var user = new ClaimsPrincipal(new ClaimsIdentity(new Claim[]{ new Claim(ClaimTypes.Name, "example name"), new Claim(ClaimTypes.NameIdentifier, "1"), new Claim("custom-claim", "example claim value"),}, "mock"));var controller = new SomeController(dependencies…);controller.ControllerContext = new ControllerContext(){ HttpContext = new DefaultHttpContext() { User = user }}; When creating your own ClaimsIdentity , make sure to pass an explicit authenticationType to the constructor. This makes sure that IsAuthenticated will work correctly (in case you use that in your code to determine whether a user is authenticated).
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/38557942', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/184509/']}
jdg_79690
stackexchange
llm_judgeable_groundtruth_similarity
835111
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 solutions are there for $a^{2014} +2015\cdot b! = 2014^{2015}$, with $a,b$ positive integers? This is another contest problem that I got from my friend. Can anybody help me find the answer? Or give me a hint to solve this problem? Thanks Now provide the response and nothing else.
Taking this equation mod $2015$ yields $a^{2014} \equiv -1 \pmod{2015}$. Since $2015 = 5 \cdot 13 \cdot 31$, we get the following: $a^{2014} \equiv -1 \pmod{5}$ $a^{2014} \equiv -1 \pmod{13}$ $a^{2014} \equiv -1 \pmod{31}$ By Fermat's Little Theorem, $a^{31} \equiv a \pmod{31}$. Hence, $a^4 \equiv a^{2014} \equiv -1 \pmod{31}$. We can check that $-1$ is not a quadratic residue $\pmod{31}$. Thus, there is no residue $a^2$ such that $(a^2)^2 = a^4 \equiv -1 \pmod{31}$. Therefore, there are no solutions to the original equation.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/835111', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/85092/']}
jdg_79691
stackexchange
llm_judgeable_groundtruth_similarity
27769246
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to use images in a Swift PickerView. I don't know how to get the images to actually appear in the component. I know how to do this using Strings with the titleForRow function but I don't know how to do this using images. Here is my code so far: import UIKitclass ViewController: UIViewController, UIPickerViewDelegate { @IBOutlet weak var pickerView: UIPickerView! var imageArray: [UIImage] = [UIImage(named: "washington.jpg")!, UIImage(named: "berlin.jpg")!, UIImage(named: "beijing.jpg")!, UIImage(named: "tokyo.jpg")!] override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // returns the number of 'columns' to display. func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int{ return 1 } // returns the # of rows in each component.. func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return imageArray.count }}// end of app Now provide the response and nothing else.
You will need to implement a couple more the delegate methods for the UIPickerViewDelegate protocol. In particular a rowHeight delegate method and a viewForRow delegate method. Something like: // MARK: UIPickerViewDataSourcefunc numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { return 1}func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return 2} func pickerView(pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat { return 60}// MARK: UIPickerViewDelegatefunc pickerView(pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusingView view: UIView!) -> UIView { var myView = UIView(frame: CGRectMake(0, 0, pickerView.bounds.width - 30, 60)) var myImageView = UIImageView(frame: CGRectMake(0, 0, 50, 50)) var rowString = String() switch row { case 0: rowString = “Washington” myImageView.image = UIImage(named:"washington.jpg") case 1: rowString = “Beijing” myImageView.image = UIImage(named:"beijing.jpg") case 2: default: rowString = "Error: too many rows" myImageView.image = nil } let myLabel = UILabel(frame: CGRectMake(60, 0, pickerView.bounds.width - 90, 60 )) myLabel.font = UIFont(name:some font, size: 18) myLabel.text = rowString myView.addSubview(myLabel) myView.addSubview(myImageView) return myView}func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { // do something with selected row} Note that the label layout etc is just for demonstration, would need to be tweaked, or probably better to use Auto Layout ect.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/27769246', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4417966/']}
jdg_79692
stackexchange
llm_judgeable_groundtruth_similarity
32723167
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 code where certain tests will always fail in CI environment. I would like to disable them based on an environment condition. How to programmatically skip a test in mocha during the runtime execution? Now provide the response and nothing else.
You can skip tests by placing an x in front of the describe or it block, or placing a .skip after it. xit('should work', function (done) {});describe.skip('features', function() {}); You can also run a single test by placing a .only on the test. for instance describe('feature 1', function() {});describe.only('feature 2', function() {});describe('feature 3', function() {}); Only the feature 2 block would run in this case. There doesn't appear to be a way to programmatically skip tests, but you could just do some sort of check in a beforeEach statement and only run the test if the flag was set. beforeEach(function(){ if (wrongEnvironment){ runTest = false }}describe('feature', function(){ if(runTest){ it('should work', function(){ // Test would not run or show up if runTest was false, } }}
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/32723167', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/368691/']}
jdg_79693
stackexchange
llm_judgeable_groundtruth_similarity
19887729
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 make a graphic window in PyDev (Eclipse) python 2.75. I've done few things but I'd like to make an "entrance" "blink". It's Tests the user input. If it's an integer it should blink green for a second, and then turn into white. But if it's a string of something else it should blink red, and then turn into white. I've used a time.sleep() but it doesn't work as I'd like to. Here is my code for this action: def sprawdzam(): z = e.get() try: z = int(z) e.config(bg = 'green') time.sleep(2) e.config(bg = 'white') except: l.config(bg = 'red') time.sleep(2) e.config(bg = 'white') Now provide the response and nothing else.
time.sleep blocks the execution of the program. Use after . For example: from Tkinter import *def blink(): e.config(bg='green') e.after(1000, lambda: e.config(bg='white')) # after 1000msroot = Tk()e = Entry(root)e.pack()b = Button(root, text='blink', command=blink)b.pack()root.mainloop()
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19887729', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2975769/']}
jdg_79694
stackexchange
llm_judgeable_groundtruth_similarity
390757
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I want to write a script to reference multiple arrays from another array which holds these array's variable names. Here's my code so far: #!/bin/basharray1=('array1string1' 'array1string2')array2=('array2string1' 'array2string2')array_names=('array1' 'array2')for a in ${array_names[@]}do for b in ${a[@]} do echo $b donedone I'd like the output to scan through both arrays (from the outer for loop) and print the respective strings in the inner for loop which calls echo. My current output is just showing me: array1array2 I'd be grateful for any pointers regarding this. Thank you! Now provide the response and nothing else.
Bash 4.3 and later supports "name references", or namerefs (a similar concept exists in ksh93 , but the scoping is annoyingly different ): #!/bin/basharray1=('array1string1' 'array1string2')array2=('array2string1' 'array2string2')array_names=('array1' 'array2')for a in "${array_names[@]}"; do declare -n arr="$a" for b in "${arr[@]}"; do echo "$b" donedone The variable arr is a nameref that acts like an alias for the named variable (the variable with name $a in this example). Without namerefs, in earlier Bash versions, one solution would be to create a new array that contains all the elements from the other arrays: all=( "${array1[@]}" "${array2[@]}" ) ... a bit like the array_names array in the question but with the contents of all arrays, and then iterate over "${all[@]}" . It's also possible to use eval , but the resulting code looks astoundingly awful. See glenn jackman's answer for a variation with variable indirection (introduced in its current form with Bash version 2).
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/390757', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/249958/']}
jdg_79695
stackexchange
llm_judgeable_groundtruth_similarity
2912164
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have the following (real world!) problem which is most easily described using an example. I ask my six students when the best time to hold office hours would be. I give them four options, and say that I'll hold two hours in total. The poll's results are as follows (1 means yes, 0 means no): $$\begin{array}{l|c|c|c|c} \text{Name} & 9 \text{ am} & 10 \text{ am} & 11 \text{ am} & 12 \text{ pm} \\ \hline\text{Alice} & 1 & 1 & 0 & 0 \\ \text{Bob} & 1 & 1 & 0 & 1 \\ \text{Charlotte} & 1 & 1 & 0 & 1 \\ \text{Daniel} & 0 & 1 & 1 & 1 \\\text{Eve} & 0 & 0 & 1 & 1 \\\text{Frank} & 0 & 0 & 1 & 0 \\ \hline\text{Total} & 3 & 4 & 3 & 4\end{array}$$ Naively, one might pick columns 2 and 4, which have the greatest totals. However, the solution which allows the most distinct people to attend is to pick columns 2 and 3. In practice, however, I have ~30 possible timeslots and over 100 students, and want to pick, say, five different timeslots for office hours. How do I pick the timeslots which maximise the number of distinct students who can attend? Now provide the response and nothing else.
In general, this problem is the maximum coverage problem , which is NP-hard, so you're not going to be able to find the optimal solution by any method substantially faster than brute force. (As I mentioned, for a problem of your size, brute force is still feasible.) However, a modification of your strategy (to choose the timeslots with the highest totals) performs reasonably well. It doesn't actually make sense to choose all the timeslots with the highest totals immediately: if they all have the same students in them, then this isn't any better than just choosing one of the timeslots. Instead, we can: Choose one timeslot with the highest total number of students. Remove all students that can make it to that timeslot from consideration. Recalculate the totals for the remaining students. Repeat steps 1-2 until you have chosen $k=5$ timeslots. According to the wikipedia article, this algorithm achieves an approximation ratio of $1 - \frac1e$; that is, if you can reach $N$ students with the optimal choice of timeslots, this algorithm will reach at least $(1 - \frac1e)N$ students. There are other possible approximate solutions out there; for example, there is the big step heuristic, which considers all choices of $p$ timeslots in each step, as opposed to all individual timeslots. (When $p=1$, it is the algorithm above; when $p=k$, it is just brute force.) No fast algorithm has guaranteed performance better than $(1 - \frac1e)N$, but they may perform better in some cases.
{}
{'log_upvote_score': 7, 'links': ['https://math.stackexchange.com/questions/2912164', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/70984/']}
jdg_79696
stackexchange
llm_judgeable_groundtruth_similarity
53479942
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 validate a checkbox in a Flutter Form ? Every other validation works fine, but the checkbox doesn't show an Error.Here is my code: FormField( validator: (value) { if (value == false) { return 'Required.'; } }, builder: (FormFieldState<dynamic> field) { return CheckboxListTile( value: checkboxValue, onChanged: (val) { if (checkboxValue == false) { setState(() { checkboxValue = true; }); } else if (checkboxValue == true) { setState(() { checkboxValue = false; }); } }, title: new Text( 'I agree.', style: TextStyle(fontSize: 14.0), ), controlAffinity: ListTileControlAffinity.leading, activeColor: Colors.green, ); },), Now provide the response and nothing else.
A cleaner solution to this problem is to make a class that extends FormField<bool> Here is how I accomplished this: class CheckboxFormField extends FormField<bool> { CheckboxFormField( {Widget title, FormFieldSetter<bool> onSaved, FormFieldValidator<bool> validator, bool initialValue = false, bool autovalidate = false}) : super( onSaved: onSaved, validator: validator, initialValue: initialValue, builder: (FormFieldState<bool> state) { return CheckboxListTile( dense: state.hasError, title: title, value: state.value, onChanged: state.didChange, subtitle: state.hasError ? Builder( builder: (BuildContext context) => Text( state.errorText, style: TextStyle(color: Theme.of(context).errorColor), ), ) : null, controlAffinity: ListTileControlAffinity.leading, ); });}
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/53479942', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10312066/']}
jdg_79697
stackexchange
llm_judgeable_groundtruth_similarity
270814
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: Is there anyway to extract a tar.gz file faster than tar -zxvf filenamehere ? We have large files, and trying to optimize the operation. Now provide the response and nothing else.
pigz is a parallel version of gzip. Although it only uses a single thread for decompression, it starts 3 additional threads for reading, writing, and check calculation. Your results may vary but we have seen significant improvement in decompression of some of our datasets. Once you install pigz, the tar file can be extracted with: pigz -dc target.tar.gz | tar xf -
{}
{'log_upvote_score': 7, 'links': ['https://serverfault.com/questions/270814', 'https://serverfault.com', 'https://serverfault.com/users/65061/']}
jdg_79698
stackexchange
llm_judgeable_groundtruth_similarity
1477044
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm using the WPF DataGrid from CodePlex and I need to get Virtualization to work with grouping. This question is on topic and points to an MSDN Example but it only covers ListControls with with simple (i.e. single 'column') DataTemplates. Grouping and Virtualization seems like a pretty common use case for a Grid. Is there a standard/recommended/simple way of getting this going? Now provide the response and nothing else.
I realize I'm late to the party here... but I ran into this problem recently (using the DataGrid built into .NET 4). Unfortunately, there still is no virtualization of the rows once Grouping is used on the DataGrid... but a I found a very slick performance enhancement trick that hopefully somebody else will find useful as well. Assuming you're using an ItemsPresenter within an expander of your GroupItem's template and by default your expander is not expanded, then try simply binding the visibility of your ItemsPresenter to the Expander's IsEnabled property with the default BooleanToVisibilityConverter: <BooleanToVisibilityConverter x:Key="bool2vis" /><DataGrid.GroupStyle> <GroupStyle> <GroupStyle.ContainerStyle> <Style TargetType="{x:Type GroupItem}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type GroupItem}"> <Expander x:Name="exp"> <ItemsPresenter Visibility="{Binding ElementName=exp, Path=IsExpanded, Converter={StaticResource bool2vis}}" /> </Expander> </ControlTemplate> </Setter.Value> </Setter> </Style> </GroupStyle.ContainerStyle> </GroupStyle></DataGrid.GroupStyle> If you're running into the problem where your DataGrid takes really long to load (because it's essentially drawing out every record in your datagrid even though it's in a collapsed expander)... then using the above code will cause the datagrid to not draw your records until you expand a group, and then, it will only draw out the records for that particular group. The down side is that this only helps if your expanders are collapsed by default, and still the rows do not get virtualized (if you have 100 items in an expanded group, but only 20 fit on the screen, all 100 will be drawn at the time you expanded the group). The upside is that you've essentially implemented lazy loading of your DataGrid records, so you're not performing the drawing work until you actually need to view the items (you choose to expand the group). For my product, my group header had buttons built in to perform operations on all items within its group, so more often the user never expanded a group unless they needed to perform an operation on an individual item within a group. *One thing to note if you use this trick is that you should probably set some explicit widths or minimum widths to your column headers (because the items are not being drawn when the DataGrid first loads, so the column headers cannot autosize to fit the largest item). Hopefully true virtualization gets implemented in a future service pack, but if not, I hope this will help somebody else! Update It appears this issue will be fixed in .NET 4.5 with a new attached property VirtualizingPanel.IsVirtualizingWhenGrouping .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1477044', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/460845/']}
jdg_79699
stackexchange
llm_judgeable_groundtruth_similarity
71870
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 thought I understood transistors but now I'm confused again. I have a basic opamp circuit to amplify the input of a electret microphone. The output of the opamp will vary within 1-4V. Now I want to connect this output to a load (laser) and this modulate the light intensity via the mic. The driver of the laser is not a constant current one, and output does change if input changes, thus modulation is possible. The thing is that I cannot connect the laser directly to the output of the opamp circuit because the current flow will be to high (+-300mA), so this means I need to use a transistor right? So I thought I can just connect this output to the base pin of the transistor(2n2222), the load from +5V to collector, and emitter to ground. The base input then controls the current over the proportionality. So basicly a input of 1-4V on base must control the collector current also from 1-4V but allowing a larger current to flow. I read that the base-collector current must not be the same and this shuts down the transistor. I tried a basic circuit and obviously it didn't work. Now provide the response and nothing else.
A couple of circuits that spring to mind. The first was actually for controlling the light output from a laser (amongst other things). Incidentally the laser was used to shine at a turbine blade spinning in a turbine and the optical cable had a return path for reflections back to a photodiode to monitor the timing of the blades: - The crux of this circuit is the emitter resistor and the feedback control from the op-amp. If you have 1V on your +Vin input (5V before pot divider) then providing you have a collector load, the current will be 100mA. If you have 2V, the current through the laser will be 200mA. With 4V on the +Vin input there will be 400mA through the laser. Make the emitter resistor bigger for lesser currents and of course dispence with the pot-divider on the +Vin input. The 2nd circuit is this; it's a power output stage to an op-amp based arounf an NPN BJT transistor and feedback to the opamp to provide regulation: - Quite simply the feedback on the op-amp tries to maintain the emitter at precisely the same voltage as Vin. This will give you the power for driving your laser. Things to watch - the laser forward voltage needs to be accounted for as does the heat dissipation in the BJT and the emitter resistor in the 1st example.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/71870', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/24682/']}
jdg_79700
stackexchange
llm_judgeable_groundtruth_similarity
12166956
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Does the style of the formatter in the parse method of the DateTime class have to match the exact style of the string? For instance, I'm getting a TimeStamp object from the database (Oracle) and converting it to a string. In the database the TimeStamp is stored like this 08-AUG-12 12.00.00.000000000 AM I set my formatter to this style String pattern = "dd-MMM-yy"; I get this exception java.lang.IllegalArgumentException: Invalid format: "08-AUG-12 12.00.00 AM" is malformed at " 12.00.00 AM"org.joda.time.format.DateTimeFormatter.parseDateTime(DateTimeFormatter.java:866)org.joda.time.DateTime.parse(DateTime.java:144) What exactly does this mean and how would I go about fixing it? When I set my formatter to "yy-MMM-dd hh.mm.ss aa" I don't get an exception but it prints in the browser like this: 2008-08-12T00:00:00.000-04:00 , but I need for it to print out as "dd-MMM-yy hh:mm:ss aa" Now provide the response and nothing else.
Use LocalDateTime instead: String input = "08-AUG-12 12.00.00 AM";String pattern = "dd-MMM-yy hh.mm.ss aa";LocalDateTime localDateTime = LocalDateTime.parse(input, DateTimeFormat.forPattern(pattern)); EDIT As a matter of fact you can do it with DateTime also: private static String parseDateTime(String input){ String pattern = "dd-MMM-yy hh.mm.ss aa"; DateTime dateTime = DateTime.parse(input, DateTimeFormat.forPattern(pattern)); return dateTime.toString("dd-MMM-yy hh:mm:ss aa");}
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/12166956', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/868591/']}
jdg_79701
stackexchange
llm_judgeable_groundtruth_similarity
2533800
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: Q. Let $V$ denote the (complex) vector space of complex polynomials of degree at most $9$ and consider the linear operator $T:V \to V$ defined by $$T(a_0+a_1 x+a_2 x^2+\cdots+a_9 x^9)=a_0 +(a_2 x +a_1 x^2)+(a_4 x^3+ a_5 x^4 + a_3 x^5)+(a_7 x^6 + a_8 x^7 + a_9 x^8 + a_6 x^9).$$ (a) What is the trace of $T^4$? (b) What is the trace of $T^2$? My approach : First off we form matrix of $T$ under the standard basis $\{1,x,x^2,...,x^9\}.$ We get, $$ \left(\begin{matrix} 1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 1 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 1 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 1 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 1 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 1 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 1 \\ 0 & 0 & 0 & 0 & 0 & 0 & 1 & 0 & 0 & 0 \\\end{matrix}\right)$$ Now $\text {tr}(T)=1$. We calculate $\det T$ by observing number of row exchanges that convert it to an identity matrix. Number of such exchanges is $6$. Thus $\det T=(-1)^6=1.$ We have relation of eigenvalues with trace and determinants as follows,$\lambda_1+\lambda_2+...+\lambda_{10}=\text {tr} (T)=1$ and $\lambda_1 \lambda_2 \cdots \lambda_{10}=\det T=1.$ Also eigenvalues of $T^4$ and $T^2$ are ${\lambda_1}^4,{\lambda_2}^4,...,{\lambda_{10}}^4$ and ${\lambda_1}^2,{\lambda_2}^2,...,{\lambda_{10}}^2$ respectively. In the $3 \times 3$ and $4 \times 4$ cases of this problem, I found $1$ as a common eigenvalue and other eigenvalues to be either $-1$ or $\pm i$ or $\frac {-1 \pm \sqrt 3i}2.$ So eigenvalues are coming out to be $n-$th roots of unity but I am not able to find a pattern among them. My plan is using $\text {tr} (T^2)={\lambda_1}^2 + {\lambda_2}^2 +...+{\lambda_{10}}^2$ and $\text {tr}(T^4)={\lambda_1}^4+{\lambda_2}^4+...+{\lambda_{10}}^4.$ Knowing all these things is not helping me to find a way to tackle the problem. Is there some concept that I am missing to apply? Moreover are there any shorter elegant ways to approach this problem? Now provide the response and nothing else.
Notice that $T$ just acts as $x^i \mapsto x^{\sigma(i)}$, where $\sigma$ is a permutation on $\{0, \ldots, 9\}$ given as: $$\sigma = (1\,2)(3\,5\,4)(6\,9\,8\,7)$$ So $T^2$ acts as $x^i \mapsto x^{\sigma^2(i)}$, where $$\sigma^2 = \sigma \circ \sigma = (1\,2)^2(3\,5\,4)^2(6\,9\,8\,7)^2 = (3\,5\,4)^2(6\,9\,8\,7)^2$$ so $$T^2(a_0+a_1 x+a_2 x^2+\cdots+a_9 x^9)=a_0 +a_1 x +a_2 x^2+(a_5 x^3+ a_3 x^4 + a_4 x^5)+ (a_8 x^6 + a_9 x^7 + a_6x^8 + a_7 x^9)$$ The trace in this case is just the number of elements $x_i$ such that $x^i \mapsto x^{i}$, that is the fixed points of our permutation $\sigma^2$. So, $\operatorname{Tr} T^2 = 3$, since the fixed points of $\sigma^2$ are $0$, $1$, $2$. Similarly $T^4$ acts as $x^i \mapsto x^{\sigma^4(i)}$, where $$\sigma^4 = (1\,2)^4(3\,5\,4)^4(6\,9\,8\,7)^4 = (3\,5\,4)$$ so $$T^4(a_0+a_1 x+a_2 x^2+\cdots+a_9 x^9)=a_0 +a_1 x +a_2 x^2+(a_4 x^3+ a_5 x^4 + a_3 x^5)+a_6 x^6 + a_7 x^7 + a_8 x^8 + a_9 x^9$$ We read $\operatorname{Tr} T^4 = 7$, since the fixed points of $\sigma^4$ are $0, 1, 2, 6, 7, 8, 9$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2533800', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/206726/']}
jdg_79702
stackexchange
llm_judgeable_groundtruth_similarity
9541
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: In a script I get in $0 the possible relative path to it. For converting it to absolute I've found this solution which I don't understand: abspath=$(cd ${0%/*} && echo $PWD/${0##*/}) My problem is the magic inside of ${0%/*} and ${0##*/} . It looks like the former extracts the dirname and the latter extracts the filename, I just don't get how. Now provide the response and nothing else.
Definitions: ${string%substring} deletes shortest match of $substring from the end of $string . ${string##substring} deletes longest match of $substring from the start of $string . Your example: abspath=$(cd ${0%/*} && echo $PWD/${0##*/}) ${0%/*} deletes everything after the last slash, giving you the directory name of the script (which might be a relative path). ${0##*/} deletes everything upto the last slash, giving you just the name of the script. So, this command changes to the directory of the script and concatenates the current working directory (given by $PWD ) and the name of the script giving you the absolute path. To see what is going on try: echo ${0%/*}echo ${0##*/}
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/9541', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/5116/']}
jdg_79703
stackexchange
llm_judgeable_groundtruth_similarity
130968
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: So, I have 50+ words and I have to match the numbers in them. These numbers can be 3 or 4 digit numbers. I think I tried every way there is, but nothing seems to work (I need to remember the number as a pattern).My attempts: '/\(.*\)\([0-9][0-9]?[0-9][0-9]\)\(.*\)/''/\(.*\)\([0-9]\{3,4\}\)\(.*\)/''/\(.*\)\(([0-9][0-9][0-9][0-9]|[0-9][0-9][0-9])\)\(.*\)/'... It always matches only 3 numbers, or the whole word. INPUT: 1844-PAL.Bak IMG_1959.bak ZER_1940.BAK PEN225.bakword-1943.BAK NEED TO REMEMBER AS A PATTERN: 1844195919402251943 Now provide the response and nothing else.
There are many ways to do this. The following commands assume that each input line can only have one number. I am using this file as a test: 1844-PAL.Bak IMG_1959.bak ZER_1940.BAK PEN225.bakword-1943.BAK sed $ sed -r 's/([^0-9]*)([0-9]*)([^0-9]*)/1:"\1", 2:"\2", 3:"\3"/' file1:"", 2:"1844", 3:"-PAL.Bak "1:"IMG_", 2:"1959", 3:"bak "1:"ZER_", 2:"1940", 3:"BAK "1:"PEN", 2:"225", 3:"bak"1:"word-", 2:"1943", 3:"BAK" perl $ perl -lpe 's/([^\d]*)(\d*)([^\d])/1:"$1", 2:"$2", 3:"$3"/' file1:"", 2:"1844", 3:"-"PAL.Bak 1:"IMG_", 2:"1959", 3:"."bak 1:"ZER_", 2:"1940", 3:"."BAK 1:"PEN", 2:"225", 3:"."bak1:"word-", 2:"1943", 3:"."BAK grep $ grep -oP '\d+' file1844195919402251943 If you only have one pattern of interest per line, you can simplify to $ sed -r 's/[^0-9]*([0-9]*).*/Matched: \1/' fileMatched: 1844Matched: 1959Matched: 1940Matched: 225Matched: 1943 or $ perl -lpe 's/.*?(\d+).*/Matched $1/' fileMatched 1844Matched 1959Matched 1940Matched 225Matched 1943 In general, with regular expressions, less is more. You should always try and use the simplest regular expression necessary. If you don't want to capture or match the non-number characters, then leave them out of the regex.
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/130968', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/66407/']}
jdg_79704
stackexchange
llm_judgeable_groundtruth_similarity
3453281
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 $S=1/2+2/2^2+3/2^3+...+n/2^n$ I try searching on the internet and see only the version of $k=1$ to infinity. I put this equation on Wolfram Alpha and get $(2^{n+1}-n-2)/2^n$ but I dunno how to do that. Please help Now provide the response and nothing else.
This is an example of what is called an arithmetico-goemetric series . We can write it more compactly as $$S_n = \displaystyle\sum\limits_{k=1}^n \frac{k}{2^k}$$ The common ratio for the denominators is $2$ , so we will multiply the entire series by $2$ : \begin{align}S_n &= \,\qquad\frac{1}{2} +\frac{2}{4} +\frac{3}{8} +\frac{4}{16} + \cdots + \frac{n-1}{2^{n-1}} + \frac{n}{2^n}\tag{1}\\\\2S_n&=\,\,1 +\frac{2}{2} + \frac{3}{4} + \frac{4}{8} +\frac{5}{16} +\cdots +\frac{n}{2^{n-1}} \qquad\tag{2}\\\end{align} Subtract $(1)$ from $(2)$ : $$2S_n - S_n = \left(1 + \frac{1}{2} + \frac{1}{4} + \frac{1}{8} + \frac{1}{16} + \cdots + \frac{1}{2^{n-1}} \right) - \frac{n}{2^n}$$ Everything on the right hand side, except the last term, is a finite geometric series with common ratio $1/2$ . \begin{align}S_n &= \left(2-\frac{1}{2^{n-1}}\right) - \frac{n}{2^n}\\\\S_n &= \left(\frac{2^{n+1}}{2^{n}}-\frac{2}{2^{n}}\right) - \frac{n}{2^{n}}\\\\\displaystyle\sum\limits_{k=1}^n \frac{k}{2^k} &= \boxed{\frac{2^{n+1}-n-2}{2^{n}}}\\\\\end{align} The exact same method works even more cleanly for the corresponding infinite series. We can also take the limit of the partial sums: $$S = \displaystyle\sum\limits_{k=1}^\infty \frac{k}{2^k} = \lim_{n\to\infty} S_n = \lim_{n\to\infty}\left(\frac{2^{n+1}-n-2}{2^{n}}\right) = 2$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3453281', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/635988/']}
jdg_79705
stackexchange
llm_judgeable_groundtruth_similarity
18652554
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 kanban view in a module, I set the default_group_by property in kanban with the state field.The state contains: [('new','Waiting Queue'),('in_progress','In Progress'),('done','Finished')] but where's there's no data in specific state,the column for the state will not appear until I create a data with that state. is there any way to workaround this problem guy ?thanks.. Now provide the response and nothing else.
Assuming this is ASP.Net MVC, you should be returning an ActionResult from your action (or at least something that derives from it). The next issue is that returning true will mean toString() will be called on the bool value, resulting in the string "True" or "False" . Note that both of these equate to true in javascript. Instead, return JSON containing a result flag. In the jQuery code you've also set async: false which is really bad practice to use. In fact, if you check the console you'll see browsers warnings about its use. You should remove that property so that the AJAX request is made asynchronously. You've also set dataType to JSON in the ajax() call, but are actually returning a string. Try this instead: function SendPreview() { var value = CKEDITOR.instances['Source'].getData(); var model = { EmailBody: value.toString(), EmailTo: $("#SendTo").val(), EmailSubject: $("#Subject").val() }; var request = $.ajax({ url: '/Campaign/SendPreviewEmail', type: 'POST', dataType: 'JSON', data: { model: JSON.stringify(model) }, cache: false, success: function (data) { if (data.emailSent) { // note the object parameter has changed alert("Message Sent"); } else { alert("Message Not Sent, Please check details"); } } });} [HttpPost][ValidateInput(false)]public ActionResult SendPreviewEmail(string model){ var e = new EmailPreview(); var result = false; JavaScriptSerializer objJavascript = new JavaScriptSerializer(); e = objJavascript.Deserialize<EmailPreview>(model); if (!string.IsNullOrEmpty(e.EmailTo) && !string.IsNullOrEmpty(e.EmailSubject) && !string.IsNullOrEmpty(e.EmailBody)) { if (IsValidEmail(e.EmailTo)) { _mailService.SendMail(account.Email, e.EmailTo, e.EmailSubject, e.EmailBody, true); result = true; } } return Json(new { emailSent = result });}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18652554', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2424235/']}
jdg_79706
stackexchange
llm_judgeable_groundtruth_similarity
42828664
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to access vue instance data inside filter function like this.JS:- new Vue({ data:{ amount: 10, exchangeRate:50 }, el:"#app", filters:{ currency: function(amount){ console.log(this); //return amount * this.exchangeRate; return amount *50; } }}) HTML: <div id="app"> {{ amount | currency}}</div> My goal is to use return amount * this.exchangeRate; but this is equal to window here.How can I do this ? Thanks. jsfiddle Now provide the response and nothing else.
According to Evan, the creator of Vue: Use methods primarily for triggering state alterations. When you call a method, it generally implies some side effect. Use filters primarily for simple text formatting that needs to be reused all across your app. Filters should be pure - no side effects, just data in and data out. Use computed properties for local, component-specific data transforms. Similar to filters, computed getters should be pure. There is a special case where you want to compute something using a scope variable that is only available in the template (e.g. a v-for alias), in such cases it's okay to use "helper methods" so that you can compute something by passing it arguments. (source: https://forum-archive.vuejs.org/topic/830/method-vs-computed-vs-filter/2 ) So, since the filter depends on the component, I think you should use a computed property in this case instead of a filter.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/42828664', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3473663/']}
jdg_79707
stackexchange
llm_judgeable_groundtruth_similarity
2335883
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm developing a 2D overhead shooter game using C# and XNA. I have a class that I'll call "bullet" and need to update many of these instances every fraction of a second. My first way to do this was to have a generic List of bullets and simply remove and add new bullets as needed. But in doing so the GC kicks in often and my game had some periodic jerky lag. (Alot of code cut out, but just wanted to show a simple snippet) if (triggerButton){ bullets.Add(new bullet());}if (bulletDestroyed){ bullets.Remove(bullet);} My second and current attempt is to have a separate generic Stack of bullets that I push to when I'm done with a bullet, and pop off a bullet when I need a new one if there's anything in the stack. If there's nothing in the stack then I add a new bullet to the list. It seems to cut the jerky lag but then again, sometimes there's still some jerky lag springing up (though I don't know if it's related). if (triggerButton){ if (bulletStack.Count > 0) { bullet temp = bulletStack.Pop(); temp.resetPosition(); bullets.Add(temp); } else { bullets.Add(new bullet()); }}if (bulletDestroyed){ bulletStack.Push(bullet); bullets.Remove(bullet);} So, I know premature optimization is the root of all evil, but this was very noticeable inefficiency that I could catch early (and this was before even having to worry about enemy bullets filling the screen). So my questions are: Will pushing unused objects to a stack invoke the garbage collection? Will the references by kept alive or are objects still being destroyed? Is there a better way to handle updating many different objects? For instance, am I getting too fancy? Would it be fine to just iterate through the list and find an unused bullet that way? Now provide the response and nothing else.
There are a lot of issues here, and it's tricky to tell. First off, is bullet a struct or a class? If bullet is a class, any time you construct one, then unroot it (let it go out of scope or set it to null), you're going to be adding something the GC needs to collection. If you're going to be making many of these, and updating them every frame, you may want to consider using a List<bullet> with bullet being a struct, and the List being pre-allocated (generate it with a size large enough to hold all of your bullets, so it's not being recreated as you call List.Add ). This will help dramatically with the GC pressure. Also, just because I need to rant: So, I know premature optimization is the root of all evil, but this was very noticeable inefficiency Never, ever, be afraid to optimize a routine that you know is causing problems . If you're seeing a performance issue (ie: your lags), this is no longer premature optimization. Yes, you don't want to be optimizing every line of code, but you do need to optimize code , especially when you see a real performance issue. Optimizing it as soon as you see it's a problem is much easier than trying to optimize it later, as any design changes required will be much more easily implemented before you've added a lot of other code that uses your bullet class.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2335883', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/259579/']}
jdg_79708
stackexchange
llm_judgeable_groundtruth_similarity
9488
Below is a question asked on the forum earthscience.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Up until recently, I was under a (wrong) impression that the amount of planetary cumulative water resources was finite as I believed its escape from the atmosphere was impossible. I believed that, unlike other planetary resources, it was impossible to "waste" water as any waste would simply recycle itself in nature, i.e. municipal waste would be treated and get into the oceans from where it would eventually evaporate and precipitate back into continental waters renewing our water supply. Recently, I learned I was wrong and that there is such a phenomenon called sequestration and that it is indeed possible for the total water resources on the planet to vary. I am curious if there are metrics on how much water the planet has been losing (or gaining in case of a reverse phenomenon). Additionally, is there anything we can do to reduce this effect? This article says that we've lost a quarter of our water total but I was looking for more granular statistics. Now provide the response and nothing else.
It is not actual water what is lost to space, because in the high atmosphere water usually dissociate into other molecules or ions. The oxygen ion outflow is frequently assumed to be a proxy for the loss of water from the planetary atmosphere. In terms of global outflow rates for the Earth the rate varies from $10^{25}$ to $10^{26} s^{-1}$ , depending on geomagnetic activity ( reference ). On the poster of the reference (sent to me by the author) we can read: If we assume oxygen corresponds to water loss (self-regulation, Hunten and McElroy [1970]), then an oxygen loss rate of ~ $10^{25} s^{-1}$ corresponds to ~300 $\text{g s}^{-1}$ of water loss. Over the age of the solar system (4.5 billion years ~ $1.4 \times 10^{17}$ s) this loss rate gives $4.2 \times 10^{19}$ g of water. The current loss figure is equivalent ~25,920 liters per day, or 9,467 $\text{m}^3$ per year. And the reference of that figure seem to be the paper Escape of O+ through the distant tail plasma sheet , that used measurements from the STEREO‐B (Solar Terrestrial Relations Observatory) spacecraft . That would correspond to a total loss over Earth's history of 42,000 $\text{km}^3$ of water, equivalent to about 12 cm of sea level change. However, that's a straightforward extrapolation of the current rate, because they acknowledge that they don't know how to model how Earth's magnetosphere would have behaved in the past when the Sun was weaker. Although, for a weaker Sun it would be reasonable expect smaller losses. This value is radically different to that of the article you pointed to . In that case they use the loss of hydrogen instead of oxygen as proxy for water loss: Knowing how much hydrogen had disappeared from the oceans over the last four billion years enabled the researchers to calculate that the oceans have lost about a quarter of their water since the Earth’s early days. They the say: Today the atmosphere is rich in oxygen, which reacts with both hydrogen and deuterium to recreate water, which falls back to the Earth's surface. So the vast bulk of the water on Earth is held in a closed system that prevents the planet from gradually drying out. That suggests that the limiting factor for the existence of water is now the abundance atmospheric oxygen (although oxygen in rocks if very abundant). So it would make sense to use now Oxygen loss as proxy for water loss, but in the past, before the atmosphere was flooded with oxygen, maybe hydrogen loss was a better proxy. They suggests that methanogenesis can free hydrogen atoms and make them liable to be loss to space, but when it is part of a water molecule it is safe. Methanogenesis would have been much more common in the past when the atmosphere was rich in methane (50 to 500 richer than today). To wrap up, it seem that there is no consensus about the actual amount of water loss trough Earth's history. Different proxies give different values. Some proxies might be representative to some periods in Earth's past, but other proxies are more representative of other periods. And unfortunately we don't have yet a good reconstruction of the composition and density of the atmosphere throughout Earth's history. But we do know with some confidence, that while you where reading this answer, one or two liters of water were loss to space.
{}
{'log_upvote_score': 5, 'links': ['https://earthscience.stackexchange.com/questions/9488', 'https://earthscience.stackexchange.com', 'https://earthscience.stackexchange.com/users/7323/']}
jdg_79709
stackexchange
llm_judgeable_groundtruth_similarity
2162525
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: Solve the diffusion equation on the positive half-line $\frac{∂u}{∂t}−a^2\frac{∂^2u}{∂x^2}=0,0≤x<∞$subject to the initial and the boundary condition $u(x,0)=Qδ(x−x_0),u_x(0,t)=0.$ Where $Q≠0$ and $x_0>0$ are given constants, and $δ(⋅)$ is the Dirac delta-function. I think that The equation is invariant with respect to $x → −x$ and $v → −v$, and the initial condition is odd in $x$, hence the solution is even in $x$. Would I be correct in saying this? Also I am stuck at this point and unsure where to go from here. Now provide the response and nothing else.
For simplicity I will assume $a=1$. Extend the initial value to make it even as $u_0(x)=Q(\delta(x-x_0)+\delta(x+x_0))$. The solution is then$$u(x,t)=\frac{1}{\sqrt{4\,\pi\,t}}\int_{-\infty}^\infty e^{-\tfrac{(x-y)^2}{4t}}u_0(y)\,dy=\frac{Q}{\sqrt{4\,\pi\,t}}\Bigl(e^{-\tfrac{(x-x_0)^2}{4t}}+e^{-\tfrac{(x+x_0)^2}{4t}}\Bigr).$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2162525', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/381064/']}
jdg_79710
stackexchange
llm_judgeable_groundtruth_similarity
2110308
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I've been trying to solve this limit without application of L'Hospital's rule for some time now, but with no success, tried a couple of approaches but all end up in dead end. $$\lim_{x\to0} \frac{\ln(e+x)-e^x}{\cos^2x-e^x}$$ any kind of hint would be appreciated. Now provide the response and nothing else.
$$\dfrac{\ln(x+e)-e^x}{\cos^2x-e^x}$$ $$=\dfrac{1+\ln(1+x/e)-e^x}{(\cos x+e^{x/2})(\cos x-e^{x/2})}$$ $$=\dfrac{-\dfrac1e\cdot\dfrac{\ln(1+x/e)}{x/e}-\dfrac{e^x-1}x}{(\cos x+e^{x/2})\left(-\dfrac12\cdot\dfrac{e^{x/2}-1}{x/2}-\dfrac{1-\cos x}x\right)}$$ Now $\dfrac{1-\cos x}x=\dfrac x{1+\cos x}\cdot\left(\dfrac{\sin x}x\right)^2$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2110308', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/139345/']}
jdg_79711
stackexchange
llm_judgeable_groundtruth_similarity
32854
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: I've been looking at some thick subcategories in $K^b(R-proj)$ (the homotopy category of bounded chain complexes of projective modules), and, as expected, I'm running into the question of when chain complexes split quite often. I'm wondering what sorts of useful criteria there are for determining when chain complexes split. By "split" I mean decompose as two nontrivial complexes as $A = A_1 \oplus A_2$. Feel free to strengthen the hypotheses a bit if you need to- these can be complexes of free modules, if you like. I'm just trying to get a sense of how to look at a chain complex and think, "That probably splits..." or, "That probably doesn't..." Also remember that I'm working in the homotopy category, so if the question becomes easier when homotopy equivalent objects are identified, please feel free to use this hypothesis. Now provide the response and nothing else.
One result that guarantees such a decomposition comes from looking at the homological support of such complexes (assuming that $R$ is commutative so we have a tensor product). The homological support of a complex $A$ is just the union of the supports of the $H^i(A)$ as $R$-modules. Then it is a result of Balmer, in the paper Supports and Filtrations in Algebraic Geometry and Modular Representation Theory which is available on his website, that if the homological support of $A$ can be written as a disjoint union of closed subsets $Y_1\cup Y_2$ of $\mathrm{Spec} \;R$ whose complements are quasi-compact then $A\cong A_1\oplus A_2$ in $K^b(R\text{-}\mathrm{proj})$ where the homological support of $A_i$ is $Y_i$. Another method which works for any triangulated category is if $f\colon A\to B$ is a morphism then the triangle one gets by completing splits giving $B\cong A\oplus \mathrm{cone}(f)$ if and only if the map $\mathrm{cone}(f) \to \Sigma A$ is zero. A reference for this is Corollary 1.2.5 of Neeman's book on triangulated categories (I think I've also put the proof on MO before but I can't remember in which answer, maybe I can hunt it down later).
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/32854', 'https://mathoverflow.net', 'https://mathoverflow.net/users/6936/']}
jdg_79712
stackexchange
llm_judgeable_groundtruth_similarity
20266098
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am working on an asp.net mvc web application , and on my advance search page i want to have three html.dropdownlist which contain static values:- Exact match Start With and i need the dropdownlists to be beside any of the search field. so can any one advice how i can create such static html.dropdownlist , as all the current dropdownlists which i have are bing populated with dynamic data from my model ? Thanks Now provide the response and nothing else.
Your first option is to include the html within your view: <select id="selection"> <option>Exact match</option> <option>Starts with</option></select> Second option is to use a hard-coded built in html helper: @Html.DropDownList("selection", new List<SelectListItem>() {new SelectListItem { Text="Exact match", Value = "Match"}, new SelectListItem { Text="Starts With", Value = "Starts"}}) The third option which I would prefer if it is used a lot on your site is to create an html helper extension and you can simply use it like this: @Html.SearchSelectionList() Here is the code for this: public static MvcHtmlString SearchSelectionList(this HtmlHelper htmlHelper){ return htmlHelper.DropDownList("selection", new List<SelectListItem>() { new SelectListItem { Text = "Exact match", Value = "Match" }, new SelectListItem { Text = "Starts With", Value = "Starts" } });}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20266098', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1146775/']}
jdg_79713
stackexchange
llm_judgeable_groundtruth_similarity
13057432
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Really not sure what stack site to place this on. Feel free to move it to the correct one. My question isn't really related to programming, but I have a ton of power points with these "Worksheet Objects" embedded in the slides. Some appear to be graphs from excel as well as other chart type items from Visio. I need to convert all these "Worksheet Objects" to just images within the slide. My process right now is copy the object > Paste as Image > Move to the correct location > Delete the "Worksheet Object". It's a very time consuming and tedious process. Is there a macro I can write or something that can convert all these objects automatically? I tried googling and no luck so far Now provide the response and nothing else.
This should get you started: Sub ConvertAllShapesToPic() Dim oSl As Slide Dim oSh As Shape For Each oSl In ActivePresentation.Slides For Each oSh In oSl.Shapes ' modify the following depending on what you want to ' convert Select Case oSh.Type Case msoChart, msoEmbeddedOLEObject, msoLinkedOLEObject ConvertShapeToPic oSh Case msoPlaceholder If oSh.PlaceholderFormat.ContainedType = msoEmbeddedOLEObject _ Or oSh.PlaceholderFormat.ContainedType = msoLinkedOLEObject _ Or oSh.PlaceholderFormat.ContainedType = msoChart _ Then ConvertShapeToPic oSh End If Case Else End Select Next NextEnd SubSub ConvertShapeToPic(ByRef oSh As Shape) Dim oNewSh As Shape Dim oSl As Slide Set oSl = oSh.Parent oSh.Copy Set oNewSh = oSl.Shapes.PasteSpecial(ppPasteEnhancedMetafile)(1) With oNewSh .Left = oSh.Left .Top = oSh.Top Do .ZOrder (msoSendBackward) Loop Until .ZOrderPosition < oSh.ZOrderPosition End With oSh.DeleteEnd Sub
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13057432', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/736967/']}
jdg_79714
stackexchange
llm_judgeable_groundtruth_similarity
47112642
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 question has been posed numerous times on many websites, but not definitive solution. I am trying to run Opencv with a video using function: import cv2cap = cv2.VideoCapture('video.mp4')if(cap.isOpened()==False):print "Error opening camera" But it fails every time. I have tried almost all steps from various sites, but couldn't get it to work (including rebuilding ffmpeg separately). Any help would be much appreciated. My platform is Ubuntu17 and Python3. Now provide the response and nothing else.
This answer is written with Linux and Python in mind, but the general idea can be applied to any OS and language supported by OpenCV. The VideoCapture class not opening the video file can have many causes, but the following three applies to most cases. OpenCV FFMPEG support: By default OpenCV uses ffmpeg to read video files. OpenCV may not have been built with FFMPEG support. To find out if OpenCV was built with FFMPEG support, in terminal enter: python -c "import cv2; print(cv2.getBuildInformation())" | grep -i ffmpeg The output should be something like: FFMPEG: YES If the output is No then follow an online guide to build OpenCV from source with ffmpeg support. FFMPEG Codec: It's possible that FFMPEG does not have codec for your specific file. We are going to use this video as an example, to show if FFMPEG has decoding capability for this file. First, we need to find the encoding format used in this video file. We will be using the mediainfo program. In terminal, enter: mediainfo video_file.mp4 In the output, under the video heading, look for format . In this case the video encoding used is AVC , which is another name for H264. Now, we try to find if FFMPEG supports codec for decoding AVC encoded files. In terminal: ffmpeg -codecs | grep -i avc On my machine, the output is: DEV.LS h264 H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (decoders: h264 h264_crystalhd h264_vdpau ) (encoders: libx264 libx264rgb ) We are interested in DEV , which stands for Decoding, Encoding and Video. This means that AVC is a video encoding format and FFMPEG supports both encoding and decoding capabilities for this format. File PATH Lastly, check if the file path is correct or even if the file exists.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/47112642', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5950615/']}
jdg_79715
stackexchange
llm_judgeable_groundtruth_similarity
1913098
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: What exactly is the difference between an interface and an abstract class? Now provide the response and nothing else.
Interfaces An interface is a contract : The person writing the interface says, " hey, I accept things looking that way ", and the person using the interface says " OK, the class I write looks that way ". An interface is an empty shell . There are only the signatures of the methods, which implies that the methods do not have a body. The interface can't do anything. It's just a pattern. For example (pseudo code): // I say all motor vehicles should look like this:interface MotorVehicle{ void run(); int getFuel();}// My team mate complies and writes vehicle looking that wayclass Car implements MotorVehicle{ int fuel; void run() { print("Wrroooooooom"); } int getFuel() { return this.fuel; }} Implementing an interface consumes very little CPU, because it's not a class, just a bunch of names, and therefore there isn't any expensive look-up to do. It's great when it matters, such as in embedded devices. Abstract classes Abstract classes, unlike interfaces, are classes. They are more expensive to use, because there is a look-up to do when you inherit from them. Abstract classes look a lot like interfaces, but they have something more: You can define a behavior for them. It's more about a person saying, " these classes should look like that, and they have that in common, so fill in the blanks! ". For example: // I say all motor vehicles should look like this:abstract class MotorVehicle{ int fuel; // They ALL have fuel, so lets implement this for everybody. int getFuel() { return this.fuel; } // That can be very different, force them to provide their // own implementation. abstract void run();}// My teammate complies and writes vehicle looking that wayclass Car extends MotorVehicle{ void run() { print("Wrroooooooom"); }} Implementation While abstract classes and interfaces are supposed to be different concepts, the implementations make that statement sometimes untrue. Sometimes, they are not even what you think they are. In Java, this rule is strongly enforced, while in PHP, interfaces are abstract classes with no method declared. In Python, abstract classes are more a programming trick you can get from the ABC module and is actually using metaclasses, and therefore classes. And interfaces are more related to duck typing in this language and it's a mix between conventions and special methods that call descriptors (the __method__ methods). As usual with programming, there is theory, practice, and practice in another language :-)
{}
{'log_upvote_score': 12, 'links': ['https://Stackoverflow.com/questions/1913098', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/139459/']}
jdg_79716
stackexchange
llm_judgeable_groundtruth_similarity
22235
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: This question follows on from my earlier question Can Wolfram's Player Pro Use Proprietary Packages . That question appeared to have established that, yes, PlayerPro can use proprietary packages. Hmmm....? I've got two problems (to start) one of which I'll describe here and the second in a separate question. I purchased a PlayerPro license ($200 USD) for OS X to evaluate what it really can and does do. I installed it on a machine that had no other Mathematica installation. I tested its installation and functionality by running a couple of simple completely self-contained CDF s on it without any trouble. I then transferred copies of three files to the PlayerPro equipped machine and located them in the following directories: /Users/username/Library/MathematicaPlayerPro/Applications. myPackage.m /Users/username/Library/MathematicaPlayerPro/Applications. myNotebook.nb /Users/username/Library/MathematicaPlayerPro/Kernel. init.m myPackage.m holds proprietary functions. myNotebook.nb provides a Grid of InputField s and a Button to execute code contained in myPackage.m . All of its code resides in an initialization cell (but that starts to get into my next question). init.m contains the following code: (** User Mathematica initialization file **)Get["myPackage`"] The comparable deployment on my machine running Mathematica works perfectly. On the PlayerPro machine, not so much. I have shut down and restarted PlayerPro and the problem persists. I have rebooted the machine, launched PlayerPro and the problem persists. Upon opening myNotebook.nb , I can see plainly that none of the function names from myPackage.m have run. They all remain blue. The package has not loaded automatically. As the notebook depends almost entirely on the code in the package nothing in it executes. Neither does it appear that the initialization cell runs. I then went into: PlayerPro >>> Preferences >>> System >>> Edit Trusted Directories and specifically added the: .../MathematicaPlayerPro/Applications .../MathematicaPlayerPro/Kernel directories, restarted, rebooted, still nothing. Does anyone have any ideas of how to get this working? I've actually phoned Premier Support about this. The did not have a ready answer. If I hear anything useful from them I'll post it. Update 1 : I have used Encode to encode the package in question. I have made the assumption that the init.m package would not require encoding. Perhaps that assumption needs reexamination. Update 2 : Encoding init.m has no affect. Update 3 : I created a notebook to test the following two lines of code for loading the package: Get["myPackage`"]$FailedGet["Users/username/Library/MathematicaPlayerPro/Applications/myPackage`"]Get::noopen : Cannot open Users/username/Library/MathematicaPlayerPro/Applications/myPackage`$Failed I have also tried: Needs["myPackage`"]Needs::nocont : Context myPackage` was not created when Needs was evaluated.$Failed Needs["myPackage ,"Users/username/Library/MathematicaPlayerPro/Applications/myPackage`"] Get::noopen : Cannot open Users/username/Library/MathematicaPlayerPro/Applications/myPackage`Needs::nocont : Context myPackage` was not created when Needs was evaluated. $Failed Update 4 : Premier Support suggested some of the same things that Albert does in his answer below (still working through all of Albert's suggestions). They did discover something peculiar with PlayerPro: I know that the main difference between this procedure and what youmay have been doing with your package is that you have your Needs/Getstatement inside of the PlayerPro init.m file. I did try doing thesame, and found that it did not load the package. I will check on thisissue with our developers to get more information. Update 5 : Sorry for all these updates, but this now appears like a bug in (at least) PlayerPro 9.0.1.0. The init.m file whether encoded or not simply doesn't do its job, at least not in anyway similar to how it works in full blown Mathematica. I have successfully found a workaround (but not a happy one), with the generous assistance of both answers made to this question. Still, having Wolfram provide either a fix or at least a readily available explanation of why it differs in PlayerPro from Mathematica would save a lot time and frustration. Now provide the response and nothing else.
The general requirements for a package file to be loaded in PlayerPro are listed in this answer which I think you already know about. My suspection is that your problems are in some detail in your package that might or might not have to do with the fact you are running this in PlayerPro. As usual you should start with something very simple and then add things step by step until your real problem works or you can exactly tell which step led to a problem, otherwise there is just too many small details that can go wrong. I see some potential problems with your calls to Get and Needs , especially you can't mix full path names and context names as in Get["Users/username/Library/MathematicaPlayerPro/Applications/myPackage`"] But the return value of Get["myPackage`"] and the message of Needs["myPackage`"] indicate that you rather have a problem in the content of your package file, maybe some piece of code that doesn't work on PlayerPro as expected. Here is my suggestion for finding out what actually goes wrong: Load Trivial Example: Get with Full Path start with something very simple. Create a text file with this content: BeginPackage["test`"]testfun::usage="testfun does nothing";EndPackage[]; naming it, e.g. "C:\\Users\\albert.retey\\Desktop\\test.txt" (of course adopt the path name to something valid on your computer). Then evaluate the following in Mathematica: Encode[ "C:\\Users\\albert.retey\\Desktop\\test.txt", "C:\\Users\\albert.retey\\Desktop\\test.m"] This should create an encoded package, check that it exists and contains something like: (*!1N!*)mcmj<hTJue'P+lKh]7t>X#r/N5>m^c0Q )K,<@X>.5bPbTY_m,n@1#W5cPbTYS)Q6i.XXJ.p12!rF:tH|qLWBuA`Ua' Now create a new notebook with the following content: Get["C:\\Users\\albert.retey\\Desktop\\test.m"]?testfun Evaluating this should show the usage message of testfun as defined in the package. Once that works in Mathematica, open the same notebook with PlayerPro and see whether that works there, too. If you are running PlayerPro on another machine than Mathematica, then don't forget to change the path to the correct value on the target machine before saving the the notebook. Load Trivial Example: Needs with adjusted $Path For Needs to work, the package file must create the correct Context , that means the name of the package file and the context given in BeginPackage need to agree, otherwise you'll get the Needs::nocont message. Here is how you can test whether that works for your encoded package file: Create a notebook with this content and save it in the same directory as your encoded package file: Quit[]AppendTo[$Path, NotebookDirectory[]];Needs["test`"] Evaluating this should now work both in Mathematica and PlayerPro. Load Trivial Package from $UserAddOnsDirectory For the final deployment, you usually want to put the package file in one of those directories that Mathematica or PlayerPro search for packages instead of tweaking $Path . Basically you can copy your file to any directory listed in $Path , but by convention you should either use the Applications subdirectory of either $UserAddOnsDirectory (for installation for single user) or $AddOnsDirectory (for system wide installation). To do so, copy the encoded package file into the "Applications" subdirectory of e.g. $UserAddOnsDirectory directory. Doing so, we can load it without giving the full path name of the package file and just use the context name of the package in either Get or Needs .Make sure you use the exact outcome of what $UserAddOnsDirectory gives you evaluated in PlayerPro on the target machine . For me $UserAddOnsDirectory is: "C:\\Users\\albert.retey\\AppData\\Roaming\\MathematicaPlayerPro" and the path to the package file then needs to be: "C:\\Users\\albert.retey\\AppData\\Roaming\\MathematicaPlayerPro\\Applications\\test.m" . To test this, create another notebook with the following content: Quit[];Get["test`"]?testfun And evaluate it in PlayerPro. Again, you should now see the given usage message. If this doesn't work, make sure the file can be found, e.g. with: FileNames["test.m", $Path] Again, you need to create a notebook with this content in Mathematica, open that with PlayerPro and evaluate it in PlayerPro. This will also show whether there are more than the expected instances of the test.m file in your $Path , loading a different package than what you think is also a very common source of errors. Add actual Content of your Package File If you have the above running, start with a new file with the name of your own package. Start again with just the trivial content but the correct filename and context. Once that works, add the content. If the loading then doesn't work, restart with an empty package file and add the definitions for your function one by one and check whether each works. That way you should find the insulting code. If you don't see why that piece of code doesn't work in PlayerPro, come back and add that to your question or create a new one... Final note: I tested this with PlayerPro 8.0.4, I can hardly imagine that these things have changed for version 9 of PlayerPro that came out a few days ago, but if the above doesn't work and you are actually using version 9 of PlayerPro, you might want to add that information.
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/22235', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/571/']}
jdg_79717
stackexchange
llm_judgeable_groundtruth_similarity
31169259
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: using version 0.3 of visual studio code and I'm not sure how to enable sourcemaps and debug the ts file I get the following error can't launch program '/Projects/app-server/server.ts'; enabling source maps might help how do I enable sourcemaps and typescript debugging. Sourcemap is set to true in my tsconfig.json { "compilerOptions": { "target": "ES5", "module": "commonjs", "sourceMap": true }} launch.json { "version": "0.1.0", // List of configurations. Add new configurations or edit existing ones. // ONLY "node" and "mono" are supported, change "type" to switch. "configurations": [ { // Name of configuration; appears in the launch configuration drop down menu. "name": "Launch server.ts", // Type of configuration. Possible values: "node", "mono". "type": "node", // Workspace relative or absolute path to the program. "program": "server.ts", // Automatically stop program after launch. "stopOnEntry": true, // Command line arguments passed to the program. "args": [], // Workspace relative or absolute path to the working directory of the program being debugged. Default is the current workspace. "cwd": ".", // Workspace relative or absolute path to the runtime executable to be used. Default is the runtime executable on the PATH. "runtimeExecutable": null, // Environment variables passed to the program. "env": { } }, { "name": "Attach", "type": "node", // TCP/IP address. Default is "localhost". "address": "localhost", // Port to attach to. "port": 5858 } ]} Now provide the response and nothing else.
This configuration is working fine for me: Project distribution |-- .vscode |----- launch.json|-- bin |----- app.js |----- app.js.map|-- src |----- app.ts|-- node_modules |-- [..]|-- tsconfig.json|-- [...] The idea is compile the typescript under src folder and place it under bin folder. tsconfig.json It's important to active sourceMap option. { "compilerOptions": { "emitDecoratorMetadata": true, "module": "commonjs", "target": "ES5", "outDir": "bin", "rootDir": "src", "sourceMap": true }} launch.json ==== EDIT ==== This is the configuration I'm currently using at Visual Studio Code v1: { "version": "0.2.0", "configurations": [ { "args": [], "cwd": "${workspaceRoot}", "env": { "NODE_ENV": "development" }, "externalConsole": false, "name": "DEBUG", "outDir": "${workspaceRoot}/bin", "preLaunchTask": "compile", "program": "${workspaceRoot}/src/app.ts", "request": "launch", "runtimeArgs": [ "--nolazy" ], "runtimeExecutable": null, "sourceMaps": true, "stopOnEntry": false, "type": "node" }, { "name": "Attach", "type": "node", "request": "attach", "port": 5858 } ]} Note the key preLaunchTask is extremely helpful if you're using any task runner as gulp because the IDE is able to detect its tasks by name. Running Compile your ts (typing in a terminal rm -r bin/ ; tsc or executing your compiling task) In visual Code play Launch type (our configuration name) Enjoy!
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/31169259', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/611750/']}
jdg_79718
stackexchange
llm_judgeable_groundtruth_similarity
16043761
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I've got a following Java class which is also a Hibernate entity: @Entity@Table(name = "category")public class Category { @ManyToOne @JoinColumn(name="parent_id") private Category parent; public Category getParent() { return parent; } public void setParent(Category parent) { this.parent = parent; } The category represents a node in a category tree. I'm implementing a webservice which allows to CRUD categories. For instance, the interface has the ability to create a category tree node and it passes the category id as a parameter. I want just to create a new Category object and persist it into the database without fetching the parent object. My data provider class looks like this: public void createCategory(int parent_id, String name, CategoryType type) { Category category = new Category(); category.setName(name); // category.setParent(?); <- I don't have this object here // category.setParentId(id); <- but I do have the id category.setType(type); this.categoryDao.save(category);} My question is: what can I do to create a new Category object with the parent_id set if assuming I won't call hibernate to fetch the parent for me (this would be stupid)? Can I provide a setParentId/getParentId method for Category class? What hibernate annotations would it have? Now provide the response and nothing else.
Hibernate provides a method called (quite confusingly) Session.load() for this scenario. Session.load() returns a lazy proxy with the given identifier without querying the database (if object with the given identifier is already loaded in the current Session , it returns an object itself). You can use that proxy to initialize relationships in your entities being saved: category.setParent(session.load(Category.class, parent_id)); Note that this code doesn't check existence of Category with the given id. However, if you have a foreign key constraint in your DB schema, you'll get a constraint violation error when invalid id is passed in. JPA equivalent of this method is called EntityManager.getReference() .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16043761', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/769384/']}
jdg_79719
stackexchange
llm_judgeable_groundtruth_similarity
40418804
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 Ionic 2, I would like to access the $colors variables from the file "[my project]\src\theme\variables.scss". This file contains: $colors: ( primary: #387ef5, secondary: #32db64, danger: #f53d3d, light: #f4f4f4, dark: #222, favorite: #69BB7B); In a component, I draw a canvas. It looks like that: import {Component, Input, ViewChild, ElementRef} from '@angular/core';@Component({ selector: 'my-graph',})@View({ template: `<canvas #myGraph class='myGraph' [attr.width]='_size' [attr.height]='_size'></canvas>`,})export class MyGraphDiagram { private _size: number; // get the element with the #myGraph on it @ViewChild("myGraph") myGraph: ElementRef; constructor(){ this._size = 150; } ngAfterViewInit() { // wait for the view to init before using the element let context: CanvasRenderingContext2D = this.myGraph.nativeElement.getContext("2d"); // HERE THE COLOR IS DEFINED AND I D LIKE TO ACCESS variable.scss TO DO THAT context.fillStyle = 'blue'; context.fillRect(10, 10, 150, 150); }} As one can see, at some point in this code the color of the shape is defined: context.fillStyle = 'blue' , I would like to use instead something like context.fillStyle = '[variables.scss OBJECT].$colors.primary ' . Has anyone an idea? Now provide the response and nothing else.
Unfortunately, there is no way to access SASS variable directly from typescript/javascript code. However, we can make a workaround to access those variables. Let me describe briefly the steps to access SASS variables from within typescript source code: 1. Creating a SASS Helper Component Create ../providers/sass-helper/sass-helper.component.scss : $prefix: "--"; //Prefix string for custom CSS properties//Merges a variable name with $prefix@function custom-property-name($name) { @return $prefix + $name;}// Defines a custom property@mixin define-custom-property($name, $value) { #{custom-property-name($name)}: $value;}body { // Append pre-defined colors in $colors: @each $name, $value in $colors { @include define-custom-property($name, $value); } // Append SASS variables which are desired to be accesible: @include define-custom-property('background-color', $background-color);} In this SCSS file, we simply create custom properties inside the body section of the DOM. You should add each SASS variable that you want to be accessible into this SCSS file by using the mixin called define-custom-property which expects two parameters: variable name and variable value. As an example, I have added entries for all the colors defined in $colors as well as an entry for the SASS variable $background-color defined in my theme/variables.scss file. You can add as many variables as you wish. Create ../providers/sass-helper/sass-helper.component.ts : import { Component } from '@angular/core';export const PREFIX = '--';@Component({ selector: 'sass-helper', template: '<div></div>'})export class SassHelperComponent { constructor() { } // Read the custom property of body section with given name: readProperty(name: string): string { let bodyStyles = window.getComputedStyle(document.body); return bodyStyles.getPropertyValue(PREFIX + name); }} 2. Integrating SASS Helper Component From now on, we can follow standard Ionic2 framework principles for component integration and usage. Add the component class name ( SassHelperComponent ) into the declarations section of your NgModule in app.module.ts Insert the following HTML code into the HTML template of your page from where you want to access those magic variables: <sass-helper></sass-helper> 3. Using Helper Component In your page's TS file, you should insert the following lines into your page class: @ViewChild(SassHelperComponent)private sassHelper: SassHelperComponent; Finally, you can read the value of any SASS variable by just calling the child class method as follows: // Read $background-color:this.sassHelper.readProperty('background-color');// Read primary:this.sassHelper.readProperty('primary');
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/40418804', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3811726/']}
jdg_79720
stackexchange
llm_judgeable_groundtruth_similarity
24142350
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 might sound silly but when i'm working with sizes in Xcode, the total frame size is equal to 320 * 568 ( width * height ). I'm fine with that. But the resolution of the phone is actually different. The iphone 4S is 640*960 & the 5 and next generations are 640*1136. I know the last one is exactly double of what xcode is using as units, so my question is : What unit of measurement does XCode use? If it pixels, why not use the phone size/resolution as reference? Now provide the response and nothing else.
It uses points.In retina devices, 1 point equals four pixels. In non-retina devices, 1 points equals 1 pixel. Check out apple's documentation on drawing and printing on ios. https://developer.apple.com/library/ios/documentation/2ddrawing/conceptual/drawingprintingios/GraphicsDrawingOverview/GraphicsDrawingOverview.html#//apple_ref/doc/uid/TP40010156-CH14-SW7 Specially the section "Points Versus Pixels" Edit To answer your iphone 4S vs 5 and next generation question. These are actual screen sizes. The resolutions are different. The iPhone 4S and 4 screens are 320x480 points, or 640x960 pixels. iPhone 5, 5C and 5S screens are 320x568 points, or 640x1136 pixels. If you are working with xibs, you may be seeing one of the previous sizes because xibs have a size defined. That's where auto layout constraints come in. You tell in the xib or storyboard how you want the elements to be resized/relocated in the screen. You may be using struts and springs to decide how to relocate items in your view instead of auto layout. It's ok.Even if your xib / storyboard is iphone5 size, if you check the size of the screen in your viewDidAppear methods when running the app on a iPhone4/4S simulator or device, you will see that your view bounds have the size of the corresponding device.It's better to use points instead of pixels because it helps the developer abstract from resolutions. You don't have to bother about how many pixels are a point, you just locate items at points in the screen and let the system take care of the resolution for you.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/24142350', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3603502/']}
jdg_79721
stackexchange
llm_judgeable_groundtruth_similarity
4116658
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 array of 3 million data points from a 3-axiz accellerometer (XYZ), and I want to add 3 columns to the array containing the equivalent spherical coordinates (r, theta, phi). The following code works, but seems way too slow. How can I do better? import numpy as npimport math as mdef cart2sph(x,y,z): XsqPlusYsq = x**2 + y**2 r = m.sqrt(XsqPlusYsq + z**2) # r elev = m.atan2(z,m.sqrt(XsqPlusYsq)) # theta az = m.atan2(y,x) # phi return r, elev, azdef cart2sphA(pts): return np.array([cart2sph(x,y,z) for x,y,z in pts])def appendSpherical(xyz): np.hstack((xyz, cart2sphA(xyz))) Now provide the response and nothing else.
This is similar to Justin Peel 's answer, but using just numpy and taking advantage of its built-in vectorization: import numpy as npdef appendSpherical_np(xyz): ptsnew = np.hstack((xyz, np.zeros(xyz.shape))) xy = xyz[:,0]**2 + xyz[:,1]**2 ptsnew[:,3] = np.sqrt(xy + xyz[:,2]**2) ptsnew[:,4] = np.arctan2(np.sqrt(xy), xyz[:,2]) # for elevation angle defined from Z-axis down #ptsnew[:,4] = np.arctan2(xyz[:,2], np.sqrt(xy)) # for elevation angle defined from XY-plane up ptsnew[:,5] = np.arctan2(xyz[:,1], xyz[:,0]) return ptsnew Note that, as suggested in the comments, I've changed the definition of elevation angle from your original function. On my machine, testing with pts = np.random.rand(3000000, 3) , the time went from 76 seconds to 3.3 seconds. I don't have Cython so I wasn't able to compare the timing with that solution.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4116658', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/434008/']}
jdg_79722
stackexchange
llm_judgeable_groundtruth_similarity
12883861
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 plain java class in a web application and want to read a configuration file under WEB-INF folder. I know the way to access the file if its in the classpath ( WEB-INF/classes folder). Since WEB-INF/classes folder is meant for .class files, I want to keep my configuration file under WEB-INF folder only. Can anyone tell me how I can access it from my java class? Now provide the response and nothing else.
ServletContext.getResourceAsStream() will load a file from a given path relative to the root of the WAR file. Something like: ServletContext ctx;InputStream configStream = ctx.getResourceAsStream("/WEB-INF/config.properties"); The major issue here is that you need access to the servlet context to be able to do this. You have that in a servlet or a filter, but not in a non-web component further back in the application. You have a few options: Make the servlet context available from the web layer to the service layer, via an application-scoped variable, or injection, or some other way Put the resource-loading code in the web layer, and expose that to the service layer Load the configuration in the web layer, and pass it on to the service layer
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12883861', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/390186/']}
jdg_79723
stackexchange
llm_judgeable_groundtruth_similarity
44183480
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to use Dialog API of Office Add-ins. According to the doc, we could use Office.context.ui.messageParent to send a message from the Dialog box to the host page (eg, task pane). Whereas, I don't see how we could send a message from the host page to the Dialog box. Does anyone know how to do this? Now provide the response and nothing else.
The variable you call video actually holds the playlist information , not the video information. You can find a list of the individual video information in the playlist's entries attribute. See below for a possible fix. I renamed your video variable to playlist and took the freedom to rewrite it a bit and add output: import textwrapimport youtube_dlplaylists = [ "https://www.youtube.com/playlist?list=PLRQGRBgN_EnrPrgmMGvrouKn7VlGGCx8m"]for playlist in playlists: with youtube_dl.YoutubeDL({"ignoreerrors": True, "quiet": True}) as ydl: playlist_dict = ydl.extract_info(playlist, download=False) # Pretty-printing the video information (optional) for video in playlist_dict["entries"]: print("\n" + "*" * 60 + "\n") if not video: print("ERROR: Unable to get info. Continuing...") continue for prop in ["thumbnail", "id", "title", "description", "duration"]: print(prop + "\n" + textwrap.indent(str(video.get(prop)), " | ", lambda _: True) )
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/44183480', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/702977/']}
jdg_79724
stackexchange
llm_judgeable_groundtruth_similarity
38270089
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I would like to use the reduce function instead of doing this: var result = '';authors.forEach( function(author) { result += author.name + ', '; });console.log(result); So in the array authors there are several names. Now I want to build a string with this names, separated by comma (except the last one). var result = authors.reduce(function (author, index) { return author + ' ';}, '');console.log(result); Now provide the response and nothing else.
A flurry of answers just came in and here is one more! The first option is using the native js join method which eliminates the need for reduce. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join var authors = ['some author', 'another author', 'last author'];var authorString = authors.join(",");console.log(authorString); IMPORTANT - if you're array contains objects, then you might want to map it before joining: var authors = [{name: 'some author'},{name: 'another author'},{name: 'last author'}]var authorString = authors.map(function(author){ return author.name;}).join(",");console.log(authorString); or, if you're really fired up about using reduce, just make sure you use the previous value, current value and index when passing in the callback. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce var authorString = authors.reduce(function(prevVal,currVal,idx){ return idx == 0 ? currVal : prevVal + ', ' + currVal;}, '')console.log(authorString); IMPORTANT - again if your array contains objects then you will want to make sure you are using the 'name property': var authors = [{name: 'some author'},{name: 'another author'},{name: 'last author'}];var authorString = authors.reduce(function(prevVal,currVal,idx){ return idx == 0 ? currVal.name : prevVal + ', ' + currVal.name;}, '')console.log(authorString);
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/38270089', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3142695/']}
jdg_79725
stackexchange
llm_judgeable_groundtruth_similarity
20802163
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I use bootstrap 3.0.3 in my web page and add html5shiv lib and respond lib for fix it this but it is not worked on internet explorer 8. my html code: <div class="container"> <div class="row"> <div class="col-sm-4" style="background:red;">&nbsp;</div> <div class="col-sm-4" style="background:green;">&nbsp;</div> <div class="col-sm-4" style="background:blue;">&nbsp;</div> </div></div> Its worked good in FF and Webkits browsers but result in IE : Now demo is here , how can I fix it? Now provide the response and nothing else.
Based on the solution in the thread : Must Bootstrap container elements include row elements? , your markup should be : <div class="container"> <div class="row"> <div class="col-sm-4" style="background:red;">&nbsp;</div> <div class="col-sm-4" style="background:green;">&nbsp;</div> <div class="col-sm-4" style="background:blue;">&nbsp;</div> </div></div> and use this CSS to achieve it in IE8: .container{ display:table; width: 100%;}.row{ height: 100%; display: table-row;}.col-sm-4{ display: table-cell;} here is the working demo The .row class is not required inside a .container , but if you include then, container > row is the order not row > container ( which you code )! EDIT It might be worth noting that respond.js only works for local files. So if you have got css files of bootstrap from CDN for your website on IE8, it won't work, instead, try with a local copy of bootstrap.css Internet Explorer 8 and Respond.js Beware of the following caveats when using Respond.js in yourdevelopment and production environments for Internet Explorer 8. Respond.js and cross-domain CSS Using Respond.js with CSS hosted on a different (sub)domain (forexample, on a CDN) requires some additional setup. See the Respond.jsdocs for details. Respond.js and file:// Due to browser security rules, Respond.js doesn't work with pagesviewed via the file:// protocol (like when opening a local HTML file).To test responsive features in IE8, view your pages over HTTP(S). Seethe Respond.js docs for details. Respond.js and @import Respond.js doesn't work with CSS that's referenced via @import. Inparticular, some Drupal configurations are known to use @import. Seethe Respond.js docs for details. IE Compatibility modes Bootstrap is not supported in the old Internet Explorer compatibilitymodes. To be sure you're using the latest rendering mode for IE,consider including the appropriate tag in your pages: Source : Getbootstrap
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20802163', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1823003/']}
jdg_79726
stackexchange
llm_judgeable_groundtruth_similarity
42726870
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: We're working on an application that uses the new firebase cloud functions. What currently is happening is that a transaction is put in the queue node. And then the function removes that node and puts it in the correct node. This has been implemented because of the ability to work offline. Our current problem is the speed of the function. The function itself takes about 400ms, so that's alright. But sometimes the functions take a very long time (around 8 seconds), while the entry was already added to the queue. We suspect that the server takes time to boot up, because when we do the action once more after the first. It takes way less time. Is there any way to fix this problem? Down here i added the code of our function. We suspect there's nothing wrong with it, but we added it just in case. const functions = require('firebase-functions');const admin = require('firebase-admin');const database = admin.database();exports.insertTransaction = functions.database .ref('/userPlacePromotionTransactionsQueue/{userKey}/{placeKey}/{promotionKey}/{transactionKey}') .onWrite(event => { if (event.data.val() == null) return null; // get keys const userKey = event.params.userKey; const placeKey = event.params.placeKey; const promotionKey = event.params.promotionKey; const transactionKey = event.params.transactionKey; // init update object const data = {}; // get the transaction const transaction = event.data.val(); // transfer transaction saveTransaction(data, transaction, userKey, placeKey, promotionKey, transactionKey); // remove from queue data[`/userPlacePromotionTransactionsQueue/${userKey}/${placeKey}/${promotionKey}/${transactionKey}`] = null; // fetch promotion database.ref(`promotions/${promotionKey}`).once('value', (snapshot) => { // Check if the promotion exists. if (!snapshot.exists()) { return null; } const promotion = snapshot.val(); // fetch the current stamp count database.ref(`userPromotionStampCount/${userKey}/${promotionKey}`).once('value', (snapshot) => { let currentStampCount = 0; if (snapshot.exists()) currentStampCount = parseInt(snapshot.val()); data[`userPromotionStampCount/${userKey}/${promotionKey}`] = currentStampCount + transaction.amount; // determines if there are new full cards const currentFullcards = Math.floor(currentStampCount > 0 ? currentStampCount / promotion.stamps : 0); const newStamps = currentStampCount + transaction.amount; const newFullcards = Math.floor(newStamps / promotion.stamps); if (newFullcards > currentFullcards) { for (let i = 0; i < (newFullcards - currentFullcards); i++) { const cardTransaction = { action: "pending", promotion_id: promotionKey, user_id: userKey, amount: 0, type: "stamp", date: transaction.date, is_reversed: false }; saveTransaction(data, cardTransaction, userKey, placeKey, promotionKey); const completedPromotion = { promotion_id: promotionKey, user_id: userKey, has_used: false, date: admin.database.ServerValue.TIMESTAMP }; const promotionPushKey = database .ref() .child(`userPlaceCompletedPromotions/${userKey}/${placeKey}`) .push() .key; data[`userPlaceCompletedPromotions/${userKey}/${placeKey}/${promotionPushKey}`] = completedPromotion; data[`userCompletedPromotions/${userKey}/${promotionPushKey}`] = completedPromotion; } } return database.ref().update(data); }, (error) => { // Log to the console if an error happened. console.log('The read failed: ' + error.code); return null; }); }, (error) => { // Log to the console if an error happened. console.log('The read failed: ' + error.code); return null; }); });function saveTransaction(data, transaction, userKey, placeKey, promotionKey, transactionKey) { if (!transactionKey) { transactionKey = database.ref('transactions').push().key; } data[`transactions/${transactionKey}`] = transaction; data[`placeTransactions/${placeKey}/${transactionKey}`] = transaction; data[`userPlacePromotionTransactions/${userKey}/${placeKey}/${promotionKey}/${transactionKey}`] = transaction;} Now provide the response and nothing else.
firebaser here It sounds like you're experiencing a so-called cold start of the function. When your function hasn't been executed in some time, Cloud Functions puts it in a mode that uses fewer resources so that you don't pay for compute time that you're not using. Then when you hit the function again, it restores the environment from this mode. The time it takes to restore consists of a fixed cost (e.g. restore the container) and a part variable cost (e.g. if you use a lot of node modules, it may take longer ). We're continually monitoring the performance of these operations to ensure the best mix between developer experience and resource usage. So expect these times to improve over time. The good news is that you should only experience this during development. Once your functions are being frequently triggered in production, chances are they'll hardly ever hit a cold start again, especially if they have consistent traffic. If some functions tend to see spikes of traffic, however, you'll still see cold starts for every spike. In that case, you may want to consider the minInstances setting to keep a set number of instances of a latency-critical function warm at all times.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/42726870', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5568288/']}
jdg_79727
stackexchange
llm_judgeable_groundtruth_similarity
24948356
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 currently working on a new project which required a slider. I have implemented slick JS for one of my project. Now I need to add thumbnails which will appear when we hover the dots which will link to the slider For example, click on first thumb and slider will advance to first slide,....click on third and slides to third slide. HTML <html> <head> <title>My Now Amazing Webpage</title> <link rel="stylesheet" type="text/css" href="slick/slick.css"/> <link rel="stylesheet" type="text/css" href="slick/style.css"/> </head> <body><!-- THis is the slider code --> <div class="center"> <div><img alt="slide 2" src="images/img1.jpg"></div> <div><img alt="slide 2" src="images/img2.jpg"></div> <div><img alt="slide 2" src="images/img3.jpg"></div> <div><img alt="slide 2" src="images/img4.jpg"></div> <div><img alt="slide 2" src="images/img5.jpg"></div> </div> <script type="text/javascript" src="slick/jquery-1.11.0.min.js"></script> <script type="text/javascript" src="slick/jquery-migrate-1.2.1.min.js"></script> <script type="text/javascript" src="slick/slick.min.js"></script> <script type="text/javascript"> $('.center').slick({ centerMode: true, centerPadding: '60px', slidesToShow: 1, dots: !0, /* It is for the navigation dots */ draggable: !1, responsive: [ { breakpoint: 768, settings: { arrows: false, centerMode: true, centerPadding: '40px', slidesToShow: 1 } }, { breakpoint: 480, settings: { arrows: false, centerMode: true, centerPadding: '40px', slidesToShow: 1 } } ] }); </script> </body></html> Now provide the response and nothing else.
You may replace dots with custom thumbnails. You would need to add thumbnails somewhere (for example, in a hidden div inside the image slide wrapper. See the code for reference: $('.slideme').slick({ dots: true, customPaging: function(slider, i) { // this example would render "tabs" with titles return '<button class="tab">' + $(slider.$slides[i]).find('.slide-title').text() + '</button>'; },}); You would also need tweak up the native Slick pager css to remove dots and add more space and styles for your thumbnails
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/24948356', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3173001/']}
jdg_79728
stackexchange
llm_judgeable_groundtruth_similarity
1058783
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Using regular expressions in C#, is there any way to find and remove duplicate words or symbols in a string containing a variety of words and symbols? Ex. Initial string of words: "I like the environment. The environment is good." Desired string: "I like the environment. is good" Duplicates removed: "the", "environment", "." Now provide the response and nothing else.
As said by others, you need more than a regex to keep track of words: var words = new HashSet<string>();string text = "I like the environment. The environment is good.";text = Regex.Replace(text, "\\w+", m => words.Add(m.Value.ToUpperInvariant()) ? m.Value : String.Empty);
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1058783', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/98672/']}
jdg_79729
stackexchange
llm_judgeable_groundtruth_similarity
182046
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: Given the data below: {x, {y, z}} = {{0.1, {0.013070604, 1.00015}}, {0.6, {0.078698955, 1.0054247}}, {1.1, {0.14552025, 1.0184426}}, {1.6, {0.21458577, 1.0398293}}, {2.1, {0.28706229,1.0712175}}, {2.6, {0.3643249, 1.1155575}}} How can I plot column x with column z and z with y ? Now provide the response and nothing else.
This is a good place to apply patterns to re-arrange the elements of the data. list = {{0.1, {0.013070604, 1.00015}}, {0.6, {0.078698955,1.0054247}}, {1.1, {0.14552025, 1.0184426}}, {1.6, {0.21458577,1.0398293}}, {2.1, {0.28706229, 1.0712175}}, {2.6, {0.3643249,1.1155575}}};ListPlot[{list /. {{x_, {y_, z_}} -> {x, z}}, list /. {{x_, {y_, z_}} -> {z, y}}}]
{}
{'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/182046', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/58233/']}
jdg_79730
stackexchange
llm_judgeable_groundtruth_similarity
29381496
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 a function like this to extract a few data from a form: $(document).ready(function() { $('#btnEnviar').click(function() { var email = $('#email').val(); It's working, but now I also need to extract the content of a list box, which is a mark sign. So I put the list box inside a span with id "idaevolta": <ul class="ui-autocomplete ui-menu ui-widget ui-widget-content ui-corner-all" role="listbox" aria-activedescendant="ui-active-menuitem" style="z-index: 1; top: 0px; left: 0px; display: none;"></ul><ul class="ui-autocomplete ui-menu ui-widget ui-widget-content ui-corner-all" role="listbox" aria-activedescendant="ui-active-menuitem" style="z-index: 1; top: 0px; left: 0px; display: none;"></ul> <input id="cbIdaVolta" type="hidden" name="cbIdaVolta" /> So far so good, but when I try to extract the data: var idaevolta = $("#idaevolta").html(); It is simply not working. UPDATE WHILE LOOKING AT THE HTML OUPUT, WITH CHROME CONSOLE, LOOK WHAT I FOUND: <input type="checkbox" id="cbIdaVolta" name="cbIdaVolta" style="width: 35px; height: 35px; margin-left: 10px;"> Does it make things easier to find a solution? UDPATE 2 It is actually a check box. Now provide the response and nothing else.
You have to draw the circle view, and after that you should create an animation to it. Creating the circle view: public class Circle extends View { private static final int START_ANGLE_POINT = 90; private final Paint paint; private final RectF rect; private float angle; public Circle(Context context, AttributeSet attrs) { super(context, attrs); final int strokeWidth = 40; paint = new Paint(); paint.setAntiAlias(true); paint.setStyle(Paint.Style.STROKE); paint.setStrokeWidth(strokeWidth); //Circle color paint.setColor(Color.RED); //size 200x200 example rect = new RectF(strokeWidth, strokeWidth, 200 + strokeWidth, 200 + strokeWidth); //Initial Angle (optional, it can be zero) angle = 120; } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); canvas.drawArc(rect, START_ANGLE_POINT, angle, false, paint); } public float getAngle() { return angle; } public void setAngle(float angle) { this.angle = angle; }} Creating the animation class to set the new angle: public class CircleAngleAnimation extends Animation { private Circle circle; private float oldAngle; private float newAngle; public CircleAngleAnimation(Circle circle, int newAngle) { this.oldAngle = circle.getAngle(); this.newAngle = newAngle; this.circle = circle; } @Override protected void applyTransformation(float interpolatedTime, Transformation transformation) { float angle = oldAngle + ((newAngle - oldAngle) * interpolatedTime); circle.setAngle(angle); circle.requestLayout(); }} Put circle into your layout: <com.package.Circle android:id="@+id/circle" android:layout_width="300dp" android:layout_height="300dp" /> And finally starting the animation: Circle circle = (Circle) findViewById(R.id.circle);CircleAngleAnimation animation = new CircleAngleAnimation(circle, 240);animation.setDuration(1000);circle.startAnimation(animation); The result is:
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/29381496', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3692451/']}
jdg_79731
stackexchange
llm_judgeable_groundtruth_similarity
6659351
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I want to strip script tags out of this HTML at Pastebin: http://pastebin.com/mdxygM0a I tried using the below regular expression: html.replace(/<script.*>.*<\/script>/ims, " ") But it does not remove all of the script tags in the HTML. It only removes in-line scripts. I'm looking for some regex that can remove all of the script tags (in-line and multi-line). It would be highly appreciated if a test is carried out on my sample http://pastebin.com/mdxygM0a Now provide the response and nothing else.
Attempting to remove HTML markup using a regular expression is problematic. You don't know what's in there as script or attribute values. One way is to insert it as the innerHTML of a div, remove any script elements and return the innerHTML, e.g. function stripScripts(s) { var div = document.createElement('div'); div.innerHTML = s; var scripts = div.getElementsByTagName('script'); var i = scripts.length; while (i--) { scripts[i].parentNode.removeChild(scripts[i]); } return div.innerHTML; }alert( stripScripts('<span><script type="text/javascript">alert(\'foo\');<\/script><\/span>')); Note that at present, browsers will not execute the script if inserted using the innerHTML property, and likely never will especially as the element is not added to the document.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/6659351', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/140477/']}
jdg_79732
stackexchange
llm_judgeable_groundtruth_similarity
28574
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: A MS SQL Server - Database that worked fine for the last weeks suddenly threw the following error: System.Data.SqlClient.SqlException: Warning: Fatal error 823 occurred at date / time Note the error and time, and contact your system administrator. What does this error mean, and what can i do about it? I tried DBCC CHECKDB('mydatabase') but i only got more error messages. Thanks in advance! Now provide the response and nothing else.
As Splattne said, 823 means there's an I/O subsystem problem. An 823 message is what I call a 'hard I/O error'. SQL Server asks the OS to read a page and it says no - this means the I/O subsystem couldn't read the page in question. The CHECKDB output means that it couldn't create the internal database snapshot that it uses to get a transactionally-consistent point-in-time view of the database. There are a number of different causes of this: There may not be any free space on the volume(s) storing the data files for the database The SQL service account might not have create-file permissions in the directory containing the data files for the database If neither of these are the case, you can create your own database snapshot and run DBCC CHECKDB on that. One you have, run the following: DBCC CHECKDB (yourdbname) WITH NO_INFOMSGS, ALL_ERRORMSGS If you post the results, I'll interpret them for you (I wrote DBCC CHECKDB for SQL 2005) Whatever the results are, you're looking at either restoring from a backup, extracting data to a new database, or running repair. Each involves varying amounts of downtime and data-loss. You're also going to have to do some root-cause analysis to figure out what happened to cause the corruption in the first place. Btw - do you have page checksums enabled? Have you looked in the SQL error log or Windows application event log for any signs of corruption or things going wrong with the I/O subsystem? Hope this helps.
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/28574', 'https://serverfault.com', 'https://serverfault.com/users/10082/']}
jdg_79733
stackexchange
llm_judgeable_groundtruth_similarity
15093
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm working on a (non high security) project that currently isn't live but might go live at some point. We have a REST API (implemented using Restlet and Neo4j) running on a server and an Android client app. To keep things stateless, we need to send auth information together with each request. We decided to use a MAC-based approach: We sign a set of header values as well as the entity body of each HTTP request using the HMAC-SHA256 algorithm. We then put that hash together with the username in the Authorization header of the request. For the HMAC secret, we use a password that is chosen by the user. To make things more secure, we hash the password before using it and storing it in the client. Of course, in order for the server to be able to validate the HMAC-SHA256 header, we need to transmit the secret once. But as this only happens a single time, it's not that much of a security risk. The problem with this setup is the secure storage of the user passwords. I know that passwords should never be hashed without using a salt to prevent rainbow table attacks. But when I generate a secure/random salt, a client that logs a user in for the first time has no way to get access to that salt in order to generate the correct hash. What would be the best decision in this case? Should I simply store the passwords using a "conventional" hashing algorithm like SHA256 without using a salt? I guess that would be very negligent. I could also use a more secure algorithm like bcrypt or PBKDF2 with a "dummy salt" like the username a MD5 hash of the username and a higher iteration count. Even though the salt is known, it would be very slow and painful to generate rainbow tables. Would bcrypt with a "security-by-obscurity" salt be secure enough? Or is the entire setup insecure and should be exchanged with another authentication method? Now provide the response and nothing else.
The most important thing you should be doing is: use SSL . Use HTTPS, not HTTP. Justification: If you use SSL, your approach is reasonable. Tactical detail: I suggest using PBKDF2 with a large iteration count to generate the HMAC key from the password. You can use a fixed value (or a hash of the username) as the salt. This will admittedly have some weaknesses: since you store a hash of the password on the client device, someone who gains access to the mobile device can use dictionary attacks to try to recover the password, and they might or might not be successful, depending upon how strong the password is. Also, anyone who gains access to the mobile device can learn the crypto key, which is all that is needed to submit authenticated HTTP requests. In many settings, this weakness might be an acceptable risk. If you don't use SSL, your scheme will probably have major security problems. Anyone who can sniff the wire will be able to learn a hash of the password, and if the password is not strong, they may be able to recover the user's password using dictionary search. If you want even better security, then here is a slightly stronger approach: Use SSL throughout. Don't mess around with unencrypted HTTP; use HTTPS for everything. Use a full-strength crypto key. Have the server generate a full-strength 128-bit cryptographically-random crypto key for use with HMAC. The server can store this key. The first time the client connects, it will need to learn this crypto key. To do that, have a special request where the client supplies its username and password, and receives the crypto key in response if the password is correct. (The server can rate-limit these requests, to deter dictionary attacks.) When the client receives the crypto key, it stores it locally. For every subsequent request, the client can look up its locally-stored copy of the crypto key and use that to compute the HMAC. If the user logs onto the web site from a new device, no problem, that device just goes through the initialization step mentioned above to retrieve the crypto key, then everything continues to work. This avoids the need to store the user's password or a hash of the user's password on the end device. It also prevents dictionary-search attacks against the crypto key; since the crypto key is a fully-random value that's chosen randomly independent of the password, off-line dictionary search attacks against the password are not going to be successful at retrieving the key. However, it does retain the weakness that if a bad guy gets their hands on the client device, they will be able to learn the crypto key and thus issue forged requests. I suspect that's about as good as you can do, given your goals.
{}
{'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/15093', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/9819/']}
jdg_79734
stackexchange
llm_judgeable_groundtruth_similarity
5468710
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 think this question has been asked before but i havent been able to deduce a clear answer. I am trying to find the best way (or a way) to intersect two completely different ienumerable collections. class A: int z1 int z2 int z3 string z4 class B: int j5 int j6 T j7 T j8 string j9 ..I want to intersect List<A> with List<B> on z2 == j6 . can this be done? Now provide the response and nothing else.
The question doesn't really make sense - what would the result type be? Intersections have to be performed on two sequences of the same type. It sounds like you don't so much want an intersection between two sets, as a filter of the first sequence based on possible values of z2. For example: HashSet<int> validZ2 = new HashSet<int>(listB.Select(x => x.j6));var filtered = listA.Where(x => validZ2.Contains(x.z2)); Or possibly as Gabe suggests, you want a join. For example: var query = from a in listA join b in listB on a.z2 equals b.j6 select new { a, b }; That will give you all pairings of values from the two lists which match on z2/j6.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5468710', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/96854/']}
jdg_79735
stackexchange
llm_judgeable_groundtruth_similarity
1215651
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 wanting to prove that the following recursive sequence is monotonic decreasing via proof by induction. Let $ S_1 = 1, ~ S_{n+1} = \frac{n}{n+1} (S_n)^2;~ n \geq 1. $ Here is what I have so far but I feel the proof fails at my last statement and I am unsure how to correct it. $$ \text{Base:} ~ S_1 = 1 > \frac{1}{2} = S_2 \\ $$ $$ \text{Assumption:} ~ S_{k+1} > S_{k+2} \\ $$ $$ \text{Proof for:} ~ k+2: $$ $$ \text{ie:} ~ S_{k+1} > S_{k+2} \\ \Rightarrow S_{k+2} = \frac{k+1}{k+2} (S_{k+1})^2 \\ \Rightarrow S_{k+2} =\frac{k+1}{k+2}(\frac{k}{k+1})^2S_{k}^4 \\ \Rightarrow S_{k+2} = \frac{k^2}{(k+1)(k+2)}S_{k}^4 < \frac{k^2}{(k+1)(k+1)}S_{k}^4 = [(\frac{k}{k+1})S_k^2]^2 = S_{k+1}^2 \\ \text{Since}~ S_{k+1}^2 > S_{k+2} \Rightarrow S_{k+1} > S_{k+2} $$ Is this fine or have I messed up badly? Any help/hints is/are appreciated. Now provide the response and nothing else.
You were on the good track at the beginning. There were other simplifications you could have done, though. Start from : $$r_k(n) := \frac{{kn+k \choose n+1}}{{kn \choose n}}= \frac{\frac{(kn+k)!}{(n+1)!(kn+k-n-1)!}}{\frac{(kn)!}{n!(kn-n)!}} = \frac{(kn+k)!n!(kn-n)!}{(n+1)!(kn+k-n-1)!kn!} =\frac{(kn+k-n)(kn+k-n+1)\cdots(kn+k)}{(n+1)(kn-n+1)\cdots(kn-n)}$$ However, let's change the way we simplify at the last step. We then get : $$r_k(n) = \frac{1}{n+1} \frac{(kn+1)\cdots (kn+k)}{(kn-n+1)\cdots(kn+k-n-1)} = \frac{kn+k}{n+1} \prod_{j=1}^{k-1} \frac{kn+j}{(k-1)n+j}$$ Now, the magic is that the number of terms in the product is constant in $n$ (which was not the case with your simplifications). In addition, for all $j$, $$\lim_{n \to + \infty} \frac{kn+j}{kn-n+j} = \frac{k}{k-1},$$ whence: $$\lim_{n \to + \infty} r_k(n) = k \left( \frac{k}{k-1} \right)^{k-1} = \frac{k^k}{(k-1)^{k-1}},$$ and we are done.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1215651', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/224562/']}
jdg_79736
stackexchange
llm_judgeable_groundtruth_similarity
55485
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 $H$ and $K$ be subgroups of a finite group $G$, at least one of which is normal. Show that if $|H|$ and $[G:K]$ are relatively prime, then $H \leq K$. In the case that $K$ is normal, let $\pi : G \rightarrow G/K$ be the quotient map. Then $\pi(H)$ is a subgroup of $G/K$ and so $|\pi(H)|$ must divide both $|G/K|=[G:K]$ and $|H|$. These are relatively prime, so that $|\pi(H)|=1$, or $H \leq \ker \pi = K$. If $H$ is normal, I'm not sure what to try. A hint would be perfect. This question is similar, but omits the normality hypothesis. Now provide the response and nothing else.
Hint : $HK$ is a subgroup of $G$ and $[HK:K]$ divides $[G:K]$. Here's a reasonably complete answer, so look away if you don't want that yet: Also $|HK|/|K| = [H:H \cap K]$ divides $|H|$. Thus $[HK:K]$ divides two relatively prime integers, so divides $1$.Hence $[H:H \cap K] = 1$ and $H \leq K$. You don't really need normality, just that $HK=KH$ is a subgroup ( by the way, whether or not $HK$ is a subgroup, its cardinality is$|H| |K|/|H \cap K|$).
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/55485', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/1761/']}
jdg_79737
stackexchange
llm_judgeable_groundtruth_similarity
24648610
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 code gives me an exception in node js saying: "need to remove or update" var args = { query: { _id: _id }, update: { $set: data }, new: true, remove: false};db.collection(COLLECTION.INVENTORY_LOCATION) .findAndModify(args, function (err, results) { if (err) { return callback(err); } else { console.log(results); callback(null, results); } }); Not able to figure out the issue as I have specified the update operation. Now provide the response and nothing else.
The syntax is different in the node driver than for the shell, which is the syntax you are using. db.collection("collection_name").findAndModify( { _id: _id }, // query [], // represents a sort order if multiple matches { $set: data }, // update statement { new: true }, // options - new to return the modified document function(err,doc) { }); There is a separate function for .findAndRemove()
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/24648610', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/368957/']}
jdg_79738
stackexchange
llm_judgeable_groundtruth_similarity
1019434
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 experimenting some difficulties trying to use Connection String Builders (ADO.NET) within LINQ to SQL. Let me show you guys what I'm trying to do: the app.config file: <?xml version="1.0" encoding="utf-8" ?><configuration> <configSections> </configSections> <connectionStrings> <add name="LoremIpsum" connectionString="Data Source=SomeServer;Initial Catalog=SomeDB;User ID=joe;" providerName="System.Data.SqlClient" /> </connectionStrings></configuration> and a snippet of the form: ConnectionStringSettings settings = ConfigurationManager.ConnectionStrings["LoremIpsum"];if (null != settings){ string connection = settings.ConnectionString; SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(connection); // passwordTextBox being the control where joe the user actually // enters his credentials builder.Password = passwordTextBox.Text;}LINQTOSQLDataClassDataContext db = new LINQTOSQLDataClassDataContext();// finally some rather anecdotic LINQ sentence here:var foo = db.Table.Single(bar => bar.Table == whatever); On the other hand checking the Immediate Window : ?builder.ConnectionString"Data Source=SomeServer;Initial Catalog=SomeDB;User ID=joe;Password=swordfish" I'm always getting an exception: Login failed for user 'joe'. Any ideas? Thanks much in advance. Now provide the response and nothing else.
It seems like you are trying to modify the connection string that is stored in the app.config file. When you use a no argument constructor for your data context, it reads what was configured at design time. Try injecting your modified connection string into the constructor of the DataContext: ConnectionStringSettings settings = ConfigurationManager.ConnectionStrings["LoremIpsum"];SqlConnectionStringBuilder builder;LINQTOSQLDataClassDataContext db;if (null != settings) { string connection = settings.ConnectionString; builder = new SqlConnectionStringBuilder(connection); // passwordTextBox being the control where joe the user actually enters his credentials builder.Password =passwordTextBox.Text; db = new LINQTOSQLDataClassDataContext(builder.ConnectionString); } }
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1019434', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6992/']}
jdg_79739
stackexchange
llm_judgeable_groundtruth_similarity
2596275
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Prove that the Jacobson radical of a ring $R$ contains no idempotents other than $0$ . Could anyone give me a hint please? Now provide the response and nothing else.
If $e$ is an idempotent and in the Jacobson radical, $e^2=e$ and $(1-e)$ is invertible, ($x$ is in the Jacobsoon radical if and only if $1+ax$ is invertible for every $a$) $(1-e)^2=1-2e+e^2=1-e$ implies that $(1-e)^{-1}(1-e)^2=1$ implies that $1-e=1$ and $e=0$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2596275', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/417020/']}
jdg_79740