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 | 21901368 |
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 verify if a methodOne is called before methodTwo in Mockito? public class ServiceClassA { public void methodOne(){} }public class ServiceClassB { public void methodTwo(){} } public class TestClass { public void method(){ ServiceClassA serviceA = new ServiceClassA(); ServiceClassB serviceB = new ServiceClassB(); serviceA.methodOne(); serviceB.methodTwo(); }}
Now provide the response and nothing else.
| InOrder helps you to do that. ServiceClassA firstMock = mock(ServiceClassA.class);ServiceClassB secondMock = mock(ServiceClassB.class);Mockito.doNothing().when(firstMock).methodOne(); Mockito.doNothing().when(secondMock).methodTwo(); //create inOrder object passing any mocks that need to be verified in orderInOrder inOrder = inOrder(firstMock, secondMock);//following will make sure that firstMock was called before secondMockinOrder.verify(firstMock).methodOne();inOrder.verify(secondMock).methodTwo(); | {} | {'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/21901368', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1319542/']} | jdg_78741 |
stackexchange | llm_judgeable_groundtruth_similarity | 13956158 |
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 sample class with these two methods: Process.java: public class Process { public Process() { } public static void countRecursive(int num) { System.out.println("countRecursive: " + num++); if (num <= 10) countRecursive(num); else return; } public static void countWhile(int num) { do System.out.println("countWhile: " + num++); while (num <= 10); }} Main class: public static void main(String[] args) { Process.countRecursive(0); Process.countWhile(0);} Output: countRecursive: 0countRecursive: 1countRecursive: 2countRecursive: 3countRecursive: 4countRecursive: 5countRecursive: 6countRecursive: 7countRecursive: 8countRecursive: 9countRecursive: 10countWhile: 0countWhile: 1countWhile: 2countWhile: 3countWhile: 4countWhile: 5countWhile: 6countWhile: 7countWhile: 8countWhile: 9countWhile: 10 But I want to know which "technique" is recommended to use and why. Thanks in advance.
Now provide the response and nothing else.
| Recursion will be slower because of the method call overhead and call stack usage. Java isn't performing tail call optimization either so don't count on it. (Although there are languages on the JVM which do have tail call optimization including Clojure and Kotlin) Another drawback might be the risk of a StackOverflowError in case you are filling up the stack. If you are doing this just to try things out I suggest using VisualVM which can be found in the java JDK. It is a profiler which can be used to benchmark this kind of situation (or you can ask for an open source YourKit license if you're working on OSS). Please note that I do not recommend using recursion just to be fancy. Use it if you really need it (traversing trees for example). | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/13956158', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1178686/']} | jdg_78742 |
stackexchange | llm_judgeable_groundtruth_similarity | 54173634 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am implementing the coroutine for first time. I am following MVP pattern for a simple login app. Here is my code flow - The login button clicked will follow this direction - LoginFragment -> LoginPresenter -> Repository -> APIRepository -> RetrofitInterface The login response will follow this direction - RetrofitInterface -> APIRepository -> Repository -> LoginPresenter -> LoginFragment Here is the code - RetrofitInterface.kt @POST("login") fun loginAPI(@Body loginRequest: LoginRequest): Deferred<LoginResponse>? Here is my Result.kt sealed class Result<out T : Any> { class Success<out T : Any>(val data: T) : Result<T>() class Error(val exception: Throwable, val message: String = exception.localizedMessage) : Result<Nothing>()} APIRepository.kt override suspend fun loginAPICall(loginRequest: LoginRequest) : Result<LoginResponse>? { try { val loginResponse = apiInterface?.loginAPI(loginRequest)?.await() return Result.Success<LoginResponse>(loginResponse!!) } catch (e : HttpException) { return Result.Error(e) } catch (e : Throwable) { return Result.Error(e) } } Repository.kt override suspend fun loginUser(loginRequest: LoginRequest): Result<LoginResponse> { if (isInternetPresent(context)) { val result = apiRepositoryInterface?.loginAPICall(loginRequest) if (result is Result.Success<LoginResponse>) { val loginData = result.data cache?.storeData(loginData) } return result!! } else { return Result.Error(Exception()) } } How do I launch a coroutine now in my presenter? I need to execute this API call on a background thread and publish the results on UI thread?
Now provide the response and nothing else.
| You need to launch a coroutine in a Presenter using local scope and injected CoroutineContext to be able to change it, for example in Unit Tests: class Presenter( private val repo: Repository, private val uiContext: CoroutineContext = Dispatchers.Main) : CoroutineScope { // creating local scope private var job: Job = Job() // or SupervisorJob() - children of a supervisor job can fail independently of each other // To use Dispatchers.Main (CoroutineDispatcher - runs and schedules coroutines) // in Android add dependency: implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.0.1' override val coroutineContext: CoroutineContext get() = uiContext + job fun detachView() { // cancel the job when view is detached job.cancel() } fun login(request: LoginRequest) = launch { // launching a coroutine val result = repo.loginUser(request) // calling 'loginUser' function will not block the Main Thread, it suspends the coroutine //use result, update UI when (result) { is Success<LoginResponse> -> { /* update UI when login success */ } is Error -> { /* update UI when login error */ } } }} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/54173634', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10656024/']} | jdg_78743 |
stackexchange | llm_judgeable_groundtruth_similarity | 63221463 |
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 method which fetches some values from Firebase as below: void getTable(Action<IDictionary> callBack) { // function & data initialized here function.CallAsync(data).ContinueWith((callTask) => { if (callTask.IsFaulted) callBack(null); else if (callTask.IsCompleted) { Debug.Log("I am being executed when done"); var result = (IDictionary) callTask.Result.Data; callBack(result); } }); } I call this method from another method as like: public void GetTable(ref string valueReturned) { string val = null; getTable((dictionary => { Debug.Log("Done getting values"); val = (string) dictionary["someValue"]; // returns "testValue" to val })); valueReturned = val; Debug.Log("Value is:" + valueReturned); Debug.Log("Completed Execution"); } Expected Output: I am being executed when done Done getting values Value is: testValue Completed Execution What output I am getting is: I am being executed when done Value is: (null) Completed Execution Done getting values I tried to assign "valueReturned" within the lambda expression of GetTable method. But it gave error : "Cannot user ref parametre inside a lambda expression"
Now provide the response and nothing else.
| I'm assuming you actually had int status outside of the loop body, otherwise the code wouldn't compile. (Not even with the do in place.) With that fixed, the code you wrote is still valid without do , but does something differrent, as you already correctly noted. Let me rewrite it slightly to show how it is interpreted: int main () { int status; { // anonymous braced block that just creates a new scope status = foo(); } while (status) { // empty loop body }} A stand-alone block like that does have its uses , for example to utilize RAII - it could contain a local variable with an object whose destructor frees some resource when it goes out of scope (for example a file handle), among other things. The reason that the while (status); is the same as while (status) {} is because you are allowed to put either a single statement or a block, and ; is a valid statement that does nothing. And writing something like while (someVariable); isn't even nonsensical in general (although of course in this case it is) because it is essentially a spinlock, a form of busy waiting - it would leave the loop if another processor core, some I/O component or an interrupt would modify the value of someVariable so that the condition is no longer fulfilled, and it would do so without any delay. You would probably not write such code on a desktop platform where "hogging CPU" is a bad thing (except in specific scenarios in kernel-mode code), but on an embedded device like a microcontroller (where your code is the only code that runs) it can be a perfectly valid way of implementing code that waits for some external change. As pointed out by Acorn in the comments, this would of course only make sense if someVariable were volatile (or otherwise non-predictable), but I'm talking about busy loops on a variable in general. | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/63221463', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5846499/']} | jdg_78744 |
stackexchange | llm_judgeable_groundtruth_similarity | 7716455 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
What is the best way to remove the first occurrence of an object from a list in Scala? Coming from Java, I'm accustomed to having a List.remove(Object o) method that removes the first occurrence of an element from a list. Now that I'm working in Scala, I would expect the method to return a new immutable List instead of mutating a given list. I might also expect the remove() method to take a predicate instead of an object. Taken together, I would expect to find a method like this: /** * Removes the first element of the given list that matches the given * predicate, if any. To remove a specific object <code>x</code> from * the list, use <code>(_ == x)</code> as the predicate. * * @param toRemove * a predicate indicating which element to remove * @return a new list with the selected object removed, or the same * list if no objects satisfy the given predicate */def removeFirst(toRemove: E => Boolean): List[E] Of course, I can implement this method myself several different ways, but none of them jump out at me as being obviously the best. I would rather not convert my list to a Java list (or even to a Scala mutable list) and back again, although that would certainly work. I could use List.indexWhere(p: (A) ⇒ Boolean) : def removeFirst[E](list: List[E], toRemove: (E) => Boolean): List[E] = { val i = list.indexWhere(toRemove) if (i == -1) list else list.slice(0, i) ++ list.slice(i+1, list.size)} However, using indices with linked lists is usually not the most efficient way to go. I can write a more efficient method like this: def removeFirst[T](list: List[T], toRemove: (T) => Boolean): List[T] = { def search(toProcess: List[T], processed: List[T]): List[T] = toProcess match { case Nil => list case head :: tail => if (toRemove(head)) processed.reverse ++ tail else search(tail, head :: processed) } search(list, Nil)} Still, that's not exactly succinct. It seems strange that there's not an existing method that would let me do this efficiently and succinctly. So, am I missing something, or is my last solution really as good as it gets?
Now provide the response and nothing else.
| You can clean up the code a bit with span . scala> def removeFirst[T](list: List[T])(pred: (T) => Boolean): List[T] = { | val (before, atAndAfter) = list span (x => !pred(x)) | before ::: atAndAfter.drop(1) | }removeFirst: [T](list: List[T])(pred: T => Boolean)List[T]scala> removeFirst(List(1, 2, 3, 4, 3, 4)) { _ == 3 }res1: List[Int] = List(1, 2, 4, 3, 4) The Scala Collections API overview is a great place to learn about some of the lesser known methods. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7716455', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/255836/']} | jdg_78745 |
stackexchange | llm_judgeable_groundtruth_similarity | 9478085 |
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 learn type of argument at function in Haskell ? In python, we have type ( ) function. Ex: in func; if type ( a ) == Int do <something> But, I don't know how I can manage that wish in Haskell ?
Now provide the response and nothing else.
| You don't need this since Haskell is statically typed and all types are known at compile time. In case of polymorphic functions like length :: [a] -> Int (Calculate the length of a list of elements of type a ), there is no way to find out about the type of the argument, since you specified with the type that any argument type fits. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9478085', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']} | jdg_78746 |
stackexchange | llm_judgeable_groundtruth_similarity | 26815 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
What is the idea behind deformation to the normal cone and what are examples of its applications?
Now provide the response and nothing else.
| Here's a place to see the normal cone side-by-side with other familiar constructions, that I learned from Fulton's "Intersection Theory". Here $X \subset Y$. Start with the space $Y \times {\mathbb P}^1$, thought of as a trivial family over ${\mathbb P}^1$. Blow up the subscheme $X \times \infty$. Now we still have a flat family over ${\mathbb P}^1$, in which all the fibers except the one over $\infty$ are still copies of $Y$. The fiber over $\infty$ is reducible: one piece $Z_1$ is the blowup of $Y$ along $X$, and the other is the projective completion $Z_2$ of the normal cone to $X$ inside $Y$. These intersect along the projectivization of the normal cone, which appears in $Z_1$ as the exceptional divisor, and in $Z_2$ as the stuff added in projective completion. (An example, for people who like polytopal pictures of toric varieties: let $Y$ be ${\mathbb P}^2$, pictured as a triangle, and $X$ be a point, pictured as a vertex. Then $Y \times {\mathbb P}^1$ is pictured as a triangular prism, and its blowup by cutting a corner off that prism. The fiber over $\infty$ is then pictured as cutting that triangle into a trapezoid $Z_1$ union a small triangle $Z_2$, glued along an interval, matching the decomposition above.) So, if perhaps you don't like degenerating $Y$ (which may be complete) to something noncomplete, you can complete it by including $Z_1$. The normal cone is $Z_2 \setminus Z_1$. Two other comments. On $Y \times {\mathbb P}^1$ there is a circle action, dilating the ${\mathbb P}^1$. It acts trivially on the $0$ and $\infty$ fibers, moving the rest around. When we blow up $X \times \infty$, the circle action on the new $\infty$ fiber $Z_1 \cup Z_2$ is nontrivial on $Z_2$; it is the dilation of the cone fibers. This is one place to lay blame for the existence of this "cone" structure. Finally, there's a conformally equivalent way to think about the $Y$ to $Z_1 \cup Z_2$ degeneration, at least when $X$ and $Y$ are smooth. Pick a small tubular neighborhood (nonalgebraic!) around $X$, with boundary $S$, a sphere bundle over $X$. Let the metric on $Y$ get very looong nearby $S$, in directions passing through $S$. You might say that $X$ is falling into a black hole, with $S$ the Schwarzschild boundary. In the limit, it gets infinitely long, and $X$ has bubbled off into its own universe. | {} | {'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/26815', 'https://mathoverflow.net', 'https://mathoverflow.net/users/-1/']} | jdg_78747 |
stackexchange | llm_judgeable_groundtruth_similarity | 42605769 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm having issues installing OpenAI Gym Atari environment on Windows 10. I have successfully installed and used OpenAI Gym already on the same system. It keeps tripping up when trying to run a makefile. I am running the command pip install gym[atari] Here is the error: and here is what I currently have on my system... cmake and make are both clearly installed.
Now provide the response and nothing else.
| A while ago I have created a fork with Windows support (devs of original repository do not merge or even comment PRs and issues). It does not require neither MSYS/Cygwin nor CMake or Zlib. To simply install atari-py wheels (binaries) use this command: pip install -f https://github.com/Kojoley/atari-py/releases atari_py If you have any distutils supported compiler you can install from sources: pip install git+https://github.com/Kojoley/atari-py.git Test your installation with a simple example: import gymenv = gym.make('SpaceInvaders-v0')env.reset()for _ in range(1000): env.step(env.action_space.sample()) env.render('human')env.close() # https://github.com/openai/gym/issues/893 If your got a 'scrambled' output that's most likely because your gym is outdated . | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/42605769', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6446734/']} | jdg_78748 |
stackexchange | llm_judgeable_groundtruth_similarity | 1002 |
Below is a question asked on the forum cs.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
The Existential Theory of the Reals is in PSPACE , but I don't know whether it is PSPACE-Complete . If I believe that it is not the case, how could I prove it? More generally, given a problem in some complexity class X , how can I show that it is not X-Complete ? For example, X could be NP , PSPACE , EXPTIME .
Now provide the response and nothing else.
| Actually proving $X$ is not $PSPACE$-complete (under, say, polynomial-time reductions) would be extremely hard to do. If $P=PSPACE$, then all non-trivial (i.e., not $\varnothing$ and not $\Sigma^{\star}$) and infinite problems in $PSPACE$ are $PSPACE$-complete under polynomial-time reductions. Since the existential theory of the reals has this non-trivial and infinite property, proving that it isn't $PSPACE$-complete would imply $P \neq PSPACE$. (See the answer to this question on CSTheory.SE for a sketch of the proof.) | {} | {'log_upvote_score': 5, 'links': ['https://cs.stackexchange.com/questions/1002', 'https://cs.stackexchange.com', 'https://cs.stackexchange.com/users/31/']} | jdg_78749 |
stackexchange | llm_judgeable_groundtruth_similarity | 59111 |
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:
Many statistical packages provide a "F statistic" and the corresponding p value in their output of a multiple linear regression. I don't find that in the parameters of the Mathematica function LinearModelFit . All I can find are the t-statistics for the individual coefficients but no general statistic related to the regression as a whole. I also don't find how to test interactions between predictor variables. Where can I find the general F statistic and see the interactions between my predictor variables?
Now provide the response and nothing else.
| Assume that you have assigned the variable "model" as your LinearModelFit result. Then you can get the F statistic and its p-value with: model[{"ANOVATableFStatistics", "ANOVATablePValues"}] For interactions, you can include them when you build your data. For example, assume that you have two independent variables. Build your data list as: data = Table[{x1[[i]], x2[[i]], x1[[i]] x2[[i]], y[[i]]}, {i, 1, Length[y]}] Now, run your regression: model = LinearModelFit[data, {x1, x2, x3}, {x1, x2, x3}] and examine the results: model["ParameterTable"] You can calculate the overall F statistic for the model by averaging the individual F statistics: Mean[model["ANOVATableFStatistics"]] To get the p value is a bit of a hassle, but this will do it: 1 - CDF[FRatioDistribution[Total[model["ANOVATableDegreesOfFreedom"][[1;;Length[model["ANOVATableFStatistics"]]]]], model["ANOVATableDegreesOfFreedom"][[-2]]], Mean[model["ANOVATableFStatistics"]]] and here is a function to give both the F statistic and its p value as a list {f,p} : fStat[m_FittedModel] := {Mean[m["ANOVATableFStatistics"]], 1 - CDF[ FRatioDistribution[ Total[m["ANOVATableDegreesOfFreedom"][[1 ;; Length[m["ANOVATableFStatistics"]]]]], m["ANOVATableDegreesOfFreedom"][[-2]]], Mean[m["ANOVATableFStatistics"]]]}; , There may be easier ways to get these values, and I'd love to see them, but this is what I was able to figure out. I don't understand why MMA doesn't have these as properties. | {} | {'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/59111', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/5305/']} | jdg_78750 |
stackexchange | llm_judgeable_groundtruth_similarity | 4575689 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Possible Duplicate: How can I compare two dates, return a number of days I have two dates (as NSString in the form "yyyy-mm-dd"), for example: NSString *start = "2010-11-01";NSString *end = "2010-12-01"; I'd like to implement: - (int)numberOfDaysBetween:(NSString *)startDate and:(NSString *)endDate {}
Now provide the response and nothing else.
| NSString *start = @"2010-09-01";NSString *end = @"2010-12-01";NSDateFormatter *f = [[NSDateFormatter alloc] init];[f setDateFormat:@"yyyy-MM-dd"];NSDate *startDate = [f dateFromString:start];NSDate *endDate = [f dateFromString:end];NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];NSDateComponents *components = [gregorianCalendar components:NSCalendarUnitDay fromDate:startDate toDate:endDate options:0]; components now holds the difference. NSLog(@"%ld", [components day]); | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/4575689', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/412082/']} | jdg_78751 |
stackexchange | llm_judgeable_groundtruth_similarity | 25327168 |
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 created a swift class with string optionals (String?) and instantiated the class in a different swift file and got a compile error. When I instantiate the class within the same file, there is no error. Is there something wrong I am doing? I double checked the behaviour and this behaviour is consistent even with the class definition given in the swift documentation: class ShoppingListItem { var name: String? var quantity = 1 var purchased = false}var item = ShoppingListItem() Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks. https://itun.es/in/jEUH0.l If the var item = ShoppingListItem() is done in the appDelegate.swift , from the function application:didFinishLaunchingWithOptions we get the error: <class> cannot be initialised because it has no accessible initializers OTOH, if we keep the instantiation as soon as the class declaration ends, there is no problem. Edit: This issue is not a showstopper, the current default initialiser behaviour seems inconsistent or I need to understand it better
Now provide the response and nothing else.
| Chances are it's an issue with the Swift compiler and access control (not pointing fingers, just trying to troubleshoot). Add an explicit initializer to the class and see if that works: class ShoppingListItem { var name: String? var quantity = 1 var purchased = false init() { }} If that doesn't work, then set the class to public, along with the initializer public class ShoppingListItem { var name: String? var quantity = 1 var purchased = false public init() { } } | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/25327168', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3944596/']} | jdg_78752 |
stackexchange | llm_judgeable_groundtruth_similarity | 1597093 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a problem with this limit, I don't know what method to use. I have no idea how to compute it. Can you explain the method and the steps used? $$\lim\limits_{x \to +\infty} \frac{(x+2)!+4^x}{((2x+1)^2+\ln x)x!}$$
Now provide the response and nothing else.
| The answer is 1/4 and you can calculate it by without a pen/paper. At infinity $(x + 2)!$ grows way faster than $4^x$ also $(2x + 1)^2$ grows way faster than $\ln x$. So you can rewrite your limit as: $$\lim\limits_{x \to +\infty} \frac{(x+2)!}{(2x+1)^2 \cdot x!} = \lim\limits_{x \to +\infty} \frac{(x+2)(x+1)}{(2x+1)^2 } = 1/4$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1597093', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/245227/']} | jdg_78753 |
stackexchange | llm_judgeable_groundtruth_similarity | 31485660 |
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 my working script that generates a plot, saves it locally to disk, uploads to S3 and deletes the file: plt.figure(figsize=(6,6))plt.plot(x, y, 'bo')plt.savefig('file_location')conn = boto.s3.connect_to_region( region_name=AWS_REGION, aws_access_key_id=AWS_ACCESS_KEY_ID, aws_secret_access_key=AWS_SECRET_ACCESS_KEY, calling_format=boto.s3.connection.OrdinaryCallingFormat() )bucket = conn.get_bucket('bucket_name')k = Key(bucket)k.key = 'file_name'k.set_contents_from_filename('file_location')os.remove(file_location) What I want is to skip the disk writing and upload the plot directly from memory. Any suggestions how to achieve that?
Now provide the response and nothing else.
| Putting it all together: img_data = io.BytesIO()plt.savefig(img_data, format='png')img_data.seek(0)s3 = boto3.resource('s3')bucket = s3.Bucket(BUCKET_NAME)bucket.put_object(Body=img_data, ContentType='image/png', Key=KEY) Thanks @padraic-cunningham and @guyb7 for the tips! | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/31485660', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1349341/']} | jdg_78754 |
stackexchange | llm_judgeable_groundtruth_similarity | 34794 |
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm setting up some new Ubuntu servers, and I'd like to secure the data on them against theft. The threat model is attackers desiring the hardware or rather naïve attackers desiring the data. Please take note of this section. The threat model does not include smart attackers desiring the data; I presume they will do one or more of the following: Splice a UPS into power cable in order to keep the machine running continuously. Insert a pair of Ethernet bridges between the computer and the network termination point that will bridge the traffic over a wireless network of sufficient range that the host will maintain network connectivity. Open the box and use a probe on the memory bus to grab interesting stuff. Use TEMPEST devices to probe what the host is doing. Use legal means (such as a court order) to force me to disclose the data Etc. Etc. So what I want is to have some, or ideally all, of the data on the disk on an encrypted partition, with the key material necessary to access it on external media of some sort. Two methods I can think of for storing the key material are: Store it on a remote host accessible via the network, and configure enough of the network to retrieve it during the boot process. Retrieval would be allowed only to the IP address assigned to the secured host (thus not allowing access to the encrypted data if it were booted on another network connection) and could be disabled by administrators if the machine were discovered to be stolen. Store it on a USB storage device that is made in some way significantly more difficult to steal than the host itself. Locating it remote from the host, such as at the end of a five meter USB cable leading off into another corner of the room, or even another room, would probably significantly decrease the chances of attackers taking it. Securing it in some way, such as by chaining it to something immobile, or even putting it into a safe, would work even better. So what are my options for setting this up? As I said before, I'd prefer to have everything (aside from perhaps a small boot partition that does not contain /etc) encrypted, so that I don't have to worry about where I'm putting files, or where they're accidentally landing. We're running Ubuntu 9.04, if it makes any difference.
Now provide the response and nothing else.
| I know of a clever variant of Option 1 called Mandos. It uses a combination of a GPG key pair, Avahi, SSL and IPv6 all added to your initial RAM disk to securely retrieve its root partition's key password. If the Mandos server isn't present on the LAN your server is an encrypted brick or the Mandos server hasn't seen a heartbeat from the Mandos client software for a given period of time it will ignore future requests for that key pair and the server is an encrypted brick next time it boots. Mandos Homepage Mandos README | {} | {'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/34794', 'https://serverfault.com', 'https://serverfault.com/users/7408/']} | jdg_78755 |
stackexchange | llm_judgeable_groundtruth_similarity | 431476 |
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:
In mathematics, the multinomial theorem describes how to expand a power of a sum in terms of powers of the terms in that sum. It is the generalization of the binomial theorem from binomials to multinomials. which means not each multinomial distribution is necessarily a binomial distribution, such as rolling dice. this post is using the Binomial Theorem to analyze the problem of rolling dice, is it appropriate? in other words, is rolling dice a multinomial distribution that is not a binomial distribution?
Now provide the response and nothing else.
| Short answer: this should be no problem. I'm pretty sure you'll have somewhat lower power than if you had a perfectly balanced design, but there is no fundamental difficulty. Here's an example where I subsample the (complete/balanced) sleepstudy data set and show that it works fine (and the results don't change very much). The only specific issue that I can think of is that if you are fitting a model with autoregressive structure (e.g. in lme with the correlation argument), you'll have to switch from an "AR1" specification to a "continuous AR" or "Ornstein-Uhlenbeck" or "exponential correlation" specification (in lme from corAR1 to corCAR : in glmmTMB from ar() to ou() ). This analysis of carbon exchange in tundra ecosystems shows an example of mixed models applied to an unevenly sampled time series. subsample data set library(lme4)set.seed(101)table(sleepstudy $Subject)ss <- do.call("rbind", lapply(split(sleepstudy,sleepstudy$ Subject), function(x) { x[sort(sample(1:10, size=rbinom(1,size=10,prob=0.7), replace=FALSE)),] }))lapply(split(ss,ss $Subject), function(x) x$ Days) fit unbalanced/subsampled data set lmer(Reaction~Days+(Days|Subject), data=ss)## Linear mixed model fit by REML ['lmerMod']## Formula: Reaction ~ Days + (Days | Subject)## Data: ss## REML criterion at convergence: 1130.586## Random effects:## Groups Name Std.Dev. Corr## Subject (Intercept) 22.634## Days 6.303 0.15## Residual 21.628## Number of obs: 119, groups: Subject, 18## Fixed Effects:## (Intercept) Days## 250.30 10.44 fit full data set lmer(Reaction~Days+(Days|Subject), data=sleepstudy)## Linear mixed model fit by REML ['lmerMod']## Formula: Reaction ~ Days + (Days | Subject)## Data: sleepstudy## REML criterion at convergence: 1743.628## Random effects:## Groups Name Std.Dev. Corr## Subject (Intercept) 24.737 ## Days 5.923 0.07## Residual 25.592 ## Number of obs: 180, groups: Subject, 18## Fixed Effects:## (Intercept) Days ## 251.41 10.47 | {} | {'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/431476', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/250190/']} | jdg_78756 |
stackexchange | llm_judgeable_groundtruth_similarity | 42868 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
Studying a specific quantum cluster algebra, I have come across the following sequence of polynomials : $$X_1$$$$q^{-1/2}(X_1X_2-1)$$$$q^{-1/2}(X_1X_2X_3-X_3-X_1)$$$$q^{-1}(X_1X_2X_3X_4-X_3X_4-X_1X_2-X_1X_4+1)$$$$q^{-1}(X_1X_2X_3X_4X_5 - X_1X_4X_5 - X_1X_2X_3 - X_1X_2X_5 - X_3X_4X_5 + X_1 + X_3 + X_5)$$ Either finding a simple expression, or just other places where these polynomials occur would be interesting. They differ only from a $q$ factor from their commutative analogues, which can be caracterized as determinants of the following matrix: $$\begin{pmatrix}x_n & 1 & 0 & \cdots & 0 \\\\1 & x_{n-1} & 1 & \cdots & 0\\\\0 & 1 & x_{n-2} & \cdots & 0\\\\\vdots & \vdots & \vdots & \ddots & \vdots \\\\0 & 0 & 0 & \cdots & x_1\end{pmatrix}$$ I read about a quantum analog of determinants, but it involves quantum matrices and this is not a quantum matrix since it would need to satisfy $X_1 = qX_1$.
Now provide the response and nothing else.
| Given that you want to know the structure of the Galois group and ramification, I think that you are best off working with the kernel of the norm map between connected components of idele class groups, as you yourself suggest. These groups are very explicit: for $K := \mathbb Q(i)$, one obtains $\hat{\mathcal O}_K^{\times}/\{\pm 1,\pm i\}$,and for $\mathbb Q$ one obtains $\hat{\mathbb Z}.$ (Here $\hat{}$ denotes the profinitecompletion.) Apart from the diagonally embedded $\{\pm 1,\pm i\}$ quotient in thegroup for $K$, both groups factor as a product over primes, and the norm map is givencomponent wise. So the kernel of the norm map is equal to$$\bigl(\prod_p (\mathcal O_K\otimes_{\mathbb Z}\mathbb Z_p)^{\times, \text{Norm } = 1}\bigr)/\{\pm 1,\pm i\}.$$ This should be explicit enough to answer any particular question you have. | {} | {'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/42868', 'https://mathoverflow.net', 'https://mathoverflow.net/users/1619/']} | jdg_78757 |
stackexchange | llm_judgeable_groundtruth_similarity | 715069 |
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:
Integrate the following : $$\int \frac{\sin x}{\sin4x}dx$$ My approach : $$=\int \frac{\sin x}{2\sin2x \cos2x}dx$$ $$= \int \frac{\sin x}{4\sin x \cos x \cos2x}dx$$$$= \int \frac{1}{4\cos x \cos2x}dx $$ [ didn't get the hint here ] then I did the following way. $$= \int \frac{\sin x}{4\sin x \cos x (\cos2x) }dx$$ Now putting $\cos x =t$ $\Rightarrow -\sin x \, dx = dt $ $$= \int \frac{-dt}{4\sqrt{1-t^2} t(2t^2-1)}$$ [Using : $ \cos2x = 2\cos^2x-1]$
Now provide the response and nothing else.
| From the step before the last step you had it as: $$\eqalign{\int\frac{dx}{\cos x\cos2x} &= \int\frac{dx}{\cos x(2(\cos x)^2 - 1))}\cr & =\int\frac{1}{\cos x} - \frac{2\cos x}{(2(\cos x)^2 - 1)}dx\cr & = \int\frac{1}{\cos x} - \frac{2\cos x}{1 - 2(\sin x)^2}dx\ .\cr}$$ From now you can integrate 1/cosx = secx and its antiderivative is well known. The second term: let u = sinx, then du = cosxdx, and use fration decomposition to continue. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/715069', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/68597/']} | jdg_78758 |
stackexchange | llm_judgeable_groundtruth_similarity | 1869 |
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a disk with some pending unreadable sectors, according to smartd. What would be the easiest way to make the disk remap them and stop smartd from complaining? Today, I get two of these every hour: Sep 10 23:15:35 hylton smartd[3353]: Device: /dev/sdc, 1 Currently unreadable (pending) sectors The system is an x86 system running Ubuntu Linux 9.10 (jaunty). The disk is part of an LVM group. This is how smartctl identifies the disk: Model Family: Western Digital Caviar Second Generation Serial ATA familyDevice Model: WDC WD5000AAKS-00TMA0Serial Number: WD-WCAPW4207483Firmware Version: 12.01C01User Capacity: 500,107,862,016 bytes
Now provide the response and nothing else.
| A pending unreadable sector is one that returned a read error and which the drive has marked for remapping at the first possible opportunity. However, it can't do the remapping until one of two things happens: The sector is reread successfully The sector is rewritten Until then, the sector remains pending. So you have two corresponding ways to deal with this: Keep trying to reread the sector until you succeed Overwrite that sector with new data Obviously, (1) is non-destructive, so you should probably try it first, although keep in mind that if the drive is starting to fail in a serious way then continual reading from a bad area is likely to make it fail much more quickly. If you have a lot of pending sectors and other errors, and you care about the data on the drive, I recommend taking it out of service and using the excellent tool ddrescue to recover as much data as possible. Then discard the drive. If the sector in question contains data you don't care about, or can restore from a backup, then overwriting it is probably the quickest and simplest solution. You can then view the reallocated and pending counts for the drive to make sure the sector was taken care of. How do you find out what the sector corresponds to in the filesystem? I found an excellent article on the smartmontools web site, here , although it's fairly technical and is specific to ext2/3/4 and reiser file systems. A simpler approach, which I used on one of my own (Mac) drives, is to use find / -xdev -type f -print0 | xargs -0 ... to read every file on the system. Make a note of the pending count before running this. If the sector is inside a file, you will get an error message from the tool you used to read the files (eg md5sum) showing you the path to it. You can then focus your attentions on re-reading just this file until it reads successfully. Often this will solve the problem, if it's an infrequently-used file which just needed to be reread a few times. If the error goes away, or you don't encounter any errors in reading all the files, check the pending count to see if it's decreased. If it has, the problem was solved by reading. If the file cannot be read successfully after multiple tries (eg 20) then you need to overwrite the file, or the block within the file, to allow the drive to reallocate the sector. You can use ddrescue on the file (rather than the partition) to overwrite just the one sector, by copying to a temporary file and then copying back again. Note that just removing the file at this point is a bad idea, because the bad sector will go into the free list where it will be harder to find. Completely overwriting it is bad too, because again the sectors will go into the free list. You need to rewrite the existing blocks. The notrunc option of dd is one way to do this. If you encounter no errors, and the pending count did not decrease, then the sector must be in the freelist or in part of the filesystem infrastructure (eg an inode table). You can try filling up all the free space with cat /dev/zero >tempfile , and then check the pending count. If it goes down, the problem was in the free list and has now gone away. If the sector is in the infrastructure, you have a more serious problem, and you will probably encounter errors just walking the directory tree. In this situation, I think the only sensible solution is to reformat the drive, optionally using ddrescue to recover data if necessary. Keep a very close eye on the drive. Sector reallocation is a very good canary in the coal mine , potentially giving you early warning of a drive that is failing. By taking early action you can prevent a later catastrophic and very painful landslide. I'm not suggesting that a few sector reallocations are an indication that you should discard the drive. All modern drives need to do some reallocation. However, if the drive isn't very old (< 1 yr) or you are getting frequent new reallocations (> 1/month) then I recommend you replace it asap. I don't have empirical evidence to prove it, but my experience suggests that disk problems can be reduced by reading the whole disk once in a while, either by a dd of the raw disk or by reading every file using find . Almost all the disk problems I've experienced in the past several years have cropped up first in rarely-used files, or on machines that are not used much. This makes sense heuristically, too, in that if a sector is being reread frequently the drive has a chance to reallocate it when it first detects a minor problem with that sector rather than waiting until the sector is completely unreadable. The drive is powerless to do anything with a sector unless the host accesses it somehow, either by reading or writing it or by conducting one of the SMART tests. I'd like to experiment with the idea of a nightly or weekly cron job that reads the whole disk. Currently I'm using a "poor man's RAID" in which I have a second hard drive in the machine and I back up the main disk to it every night. In some ways, this is actually better than RAID mirroring, because if I goof and delete a file by mistake I can get yesterday's version immediately from the backup disk. On the other hand, I believe a hardware RAID controller does a lot of good work in the background to monitor, report and fix disk problems as they emerge. My current backup script uses rsync to avoid copying data that hasn't changed, but in view of the need to reread all sectors maybe it would be better to copy everything, or to have a separate script that reads the entire raw disk every week. | {} | {'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/1869', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/1623/']} | jdg_78759 |
stackexchange | llm_judgeable_groundtruth_similarity | 9313189 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a problem with cookies in MVC3. I want to create a cookie, that stores informations whether the user is logged in. I have never used cookies before and don't know what is the proper way to do it and I am new to MVC3.Please, can somebody tell me if the approach I used to store cookie is proper or if there is some security risk (the password is encrypted)?If the cookies are set correctly, how can I use them in other views to check if the user is logged in and set the session for him?If the approach I use to log in user is wrong, just tell me. public ActionResult Login(string name, string hash, string keepLogged) { if (string.IsNullOrWhiteSpace(hash)) { Random random = new Random(); byte[] randomData = new byte[sizeof(long)]; random.NextBytes(randomData); string newNonce = BitConverter.ToUInt64(randomData, 0).ToString("X16"); Session["Nonce"] = newNonce; return View(model: newNonce); } User user = model.Users.Where(x => x.Name == name).FirstOrDefault(); string nonce = Session["Nonce"] as string; if (user == null || string.IsNullOrWhiteSpace(nonce)) { return RedirectToAction("Login", "Users"); } string computedHash; using (SHA256 sha256 = SHA256.Create()) { byte[] hashInput = Encoding.ASCII.GetBytes(user.Password + nonce); byte[] hashData = sha256.ComputeHash(hashInput); StringBuilder stringBuilder = new StringBuilder(); foreach (byte value in hashData) { stringBuilder.AppendFormat("{0:X2}", value); } computedHash = stringBuilder.ToString(); } if (computedHash.ToLower() == hash.ToLower()) { Session["IsAdmin"] = user.IsAdmin == 1; Session["IDUser"] = user.IDUser; ViewBag.IdUser = IDUser; ViewBag.IsAdmin = IsAdmin; ViewBag.UserName = model.Users.Where(x => x.IDUser == IDUser).First().Name; if (keepLogged == "keepLogged") { //Set user's cookies - is this correct? Response.Cookies.Add(new HttpCookie("UserCookie", user.IDUser.ToString())); Response.Cookies.Add(new HttpCookie("PassCookie", user.Password.ToString())); } } return RedirectToAction("Index", "Posts"); }
Now provide the response and nothing else.
| This code creates an encrypted cookie with the username FormsAuthenticationTicket ticket = new FormsAuthenticationTicket( 1, user.UserName, DateTime.Now, DateTime.Now.AddMinutes(10), false, null);string encryptedTicket = FormsAuthentication.Encrypt(ticket);HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);this.Response.Cookies.Add(cookie); To enable forms authentication add the following to the system.web section of the web.config: <authentication mode="Forms"> <forms loginUrl="~/Logon" timeout="2880" /></authentication> | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9313189', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1028038/']} | jdg_78760 |
stackexchange | llm_judgeable_groundtruth_similarity | 22591179 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
$date_show1 = "01-".$date2;$date = date($date)."-01";$date_char = date($date);$eee2 = mysqli_query($database->connection,"SELECT * FROM bon_info WHERE date_day = '$date' AND creditcart != '8' AND creditcart != '6' AND kassa_id = '$kassa_id'") or die(mysqli_error());$num1 = mysqli_num_rows($eee2); I tried the following script with a while loop but how can i also change the names of the variables also like $date_show1 ..2 ..3 ..4 ..5 ..6 ..7 ..8 ..9 ..10 ..11 ..12$num1 $num2 $num3......
Now provide the response and nothing else.
| As you can see, the AND operator drops every row in which at least one value equals -1. On the other hand, the OR operator requires both values to be equal to -1 to drop them. That's right. Remember that you're writing the condition in terms of what you want to keep , not in terms of what you want to drop. For df1 : df1 = df[(df.a != -1) & (df.b != -1)] You're saying "keep the rows in which df.a isn't -1 and df.b isn't -1", which is the same as dropping every row in which at least one value is -1. For df2 : df2 = df[(df.a != -1) | (df.b != -1)] You're saying "keep the rows in which either df.a or df.b is not -1", which is the same as dropping rows where both values are -1. PS: chained access like df['a'][1] = -1 can get you into trouble. It's better to get into the habit of using .loc and .iloc . | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/22591179', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3105443/']} | jdg_78761 |
stackexchange | llm_judgeable_groundtruth_similarity | 20232991 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am trying to create a Waveform Control Panel to change the properties of its components. I attempted to apply the example in the Redhawk documentation for a Component Control Panel, but for some reason I get a java.lang.NullPointerException when running the plugin. The error occurs when I attempt to bind the text field to a component property, the exact line where the error occurred is in the comments of the code (at the very bottom). public class TestControlPanel extends AbstractScaContentEditor<ScaWaveform> { private ScaWaveform waveform; private ScaComponent myComponent; private Text propertyValueField; private EMFDataBindingContext context; /** * {@inheritDoc} */ @Override public void createPartControl(final Composite main) { main.setLayout(new GridLayout(2, false)); Group controlGroup = new Group(main, SWT.SHADOW_ETCHED_OUT); controlGroup.setLayoutData(GridDataFactory.fillDefaults().grab(true, true).create()); controlGroup.setText("Controls"); createControlGroup(controlGroup); } private void createControlGroup(Composite parent) { parent.setLayout(new GridLayout(2, false)); EObject input = getInput(); if (input instanceof ScaWaveform) { // make local copy of waveform waveform = (ScaWaveform) input; try { waveform.refresh(null, RefreshDepth.FULL); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } label = new Label(parent,SWT.None); label.setText("Property Value:"); propertyValueField = new Text(parent, SWT.BORDER | SWT.FILL); myComponent = waveform.getScaComponent("myComponent_1"); if(myComponent != null) { IObservableValue observable = SCAObservables.observeSimpleProperty(myComponent, "propertyId"); IObservableValue targetObservable = WidgetProperties.text(SWT.Modify).observeDelayed(5000,propertyValueField); if(observable != null && targetObservable != null) { // ***** THE BELOW LINE CAUSES A java.lang.NullPointerException ERROR ***** context.bindValue(targetObservable, observable); // ***** THE ABOVE LINE CAUSES A java.lang.NullPointerException ERROR ***** } } } } My original guess for the reason for this error was that one of the IObservableValue variables (e.g. targetObservable or observable) was null, which is why I check to make sure the values are not null before binding them. However, this didn't fix the problem and I still got the same error.
Now provide the response and nothing else.
| Doing this is astoundingly convoluted. You can see my solution in action here : the methodology is described below (getting the HTML elements, by ID or otherwise, is left as an exercise for the reader). In the HTML Make sure your SVG element includes the attribute xmlns="http://www.w3.org/2000/svg" , as you're going to need to take the source of the element as its own file, and the XMLNS declaration is required for standalone SVG files. (Also note that this means your SVG will need to be self-contained and can't refer to elements in its parent document with something like <use> .) Optionally, wrap the element in a <div> or <span> , which you may use to get the content of the <svg> element using .innerHTML . (Neither the innerHTML nor the outerHTML attributes are present on SVG elements in the current HTML standard.) Include a <link rel="icon"> in your page's <head> . In JavaScript Get the source of the SVG element you want to set as your favicon by getting the innerHTML attribute of the HTML element you've wrapped it in, or by calling new XMLSerializer().serializeToString() on the SVG element. Create a DataURL for this element as a document by prepending the string "data:image/svg+xml," to the source. (If most browsers supported SVGs for favicons, we'd be done here, but since, at time of writing, they don't, we must go deeper .) Create an <img> element that you'll be routing the image through, add an event listener to it for the load event that will draw the image once control returns to the event loop (as spec-compliant browsers won't let you read the image synchronously - see this crbug ), and set the DataURL of your SVG source as its src attribute. (The steps between this and step 8 can happen either in sync now, or as part of the listener callback; they just need to happen before you draw the image.) Decide what resolution you want to render your favicon to - My examples will use 64x64, for compatibility with high-DPI (Retina and Super Retina) displays. Create a <canvas> element (heretofore referred to as canvasElement ) and set its dimensions (by setting canvasElement.width = 64 and canvasElement.height = 64 ). Create a drawing context for the canvas using canvasElement.getContext('2d') (heretofore referred to as ctx ). If you're re-using a canvas you've created beforehand, set ctx.globalCompositeOperation = "copy" , or clear it with ctx.clearRect(0, 0, 64, 64) . Somewhere in the execution sequence following from the load listener you added to the <img> element you created in step 3, draw the image onto the canvas using ctx.drawImage(svgImg, 0, 0, 64, 64) (where svgImg is the <img> element you set the src to the SVG DataURL). Create a PNG DataURL from the canvas using canvasElement.toDataURL() , and set that to the href attribute of the <link rel="icon"> element in your HTML. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20232991', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2933643/']} | jdg_78762 |
stackexchange | llm_judgeable_groundtruth_similarity | 12286613 |
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 the book Programming Interviews Exposed it says that the complexity of the program below is O(N), but I don't understand how this is possible. Can someone explain why this is? int var = 2;for (int i = 0; i < N; i++) { for (int j = i+1; j < N; j *= 2) { var += var; }}
Now provide the response and nothing else.
| You need a bit of math to see that. The inner loop iterates Θ(1 + log [N/(i+1)]) times (the 1 + is necessary since for i >= N/2 , [N/(i+1)] = 1 and the logarithm is 0, yet the loop iterates once). j takes the values (i+1)*2^k until it is at least as large as N , and (i+1)*2^k >= N <=> 2^k >= N/(i+1) <=> k >= log_2 (N/(i+1)) using mathematical division. So the update j *= 2 is called ceiling(log_2 (N/(i+1))) times and the condition is checked 1 + ceiling(log_2 (N/(i+1))) times. Thus we can write the total work N-1 N ∑ (1 + log (N/(i+1)) = N + N*log N - ∑ log ji=0 j=1 = N + N*log N - log N! Now, Stirling's formula tells us log N! = N*log N - N + O(log N) so we find the total work done is indeed O(N) . | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12286613', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1556240/']} | jdg_78763 |
stackexchange | llm_judgeable_groundtruth_similarity | 2180910 |
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 tried to solve this ODE, but I couldn't find the particular solution. With $x\in\mathbb{R}$,$$y'(x) + y(x) = \frac{1}{1+ e^{-x}} $$ So far I got the homogeneous one:$$ y_h(x)= C e^{-x} $$ Unfortunately I don't know the technical terms in English. I would really appreciate if you could write down what to do instead of telling me to try "this" or "that" method. The answer is $$y(x)=Ce^{-x} +1 -e^{-x} \ln(1+e^{x}) $$
Now provide the response and nothing else.
| Just like in the homogeneous case, multiply both sides by $e^{x}$ to get$$(e^{x}y(x))'=\frac{e^{x}}{1+e^{-x}}$$Integrate both sides,$$e^{x}y(x)=c+\int^{x}\frac{e^{s}}{1+e^{-s}}ds=c+\int^{x}\frac{e^{2s}}{1+e^{s}}ds$$$$=c+\int^{x}\left(e^{s}-\frac{e^{s}}{1+e^{s}}\right)ds=c+e^{x}-\ln{(1+e^{x})}$$ So $y(x)=ce^{-x}+1-e^{-x}\ln(1+e^{x})$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2180910', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/406966/']} | jdg_78764 |
stackexchange | llm_judgeable_groundtruth_similarity | 4605325 |
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 beating my head against a wall here, and I'm fairly certain I'm doing something stupid, so time to make my stupidity public. I'm trying to take two images, blend them together into a third image using standard blending algorithms (Hardlight, softlight, overlay, multiply, etc). Because Android does not have such blend properties build in, I've gone down the path of taking each pixel and combine them using an algorithm. However, the results are garbage. Below is the results of a simple multiply blend (images used, and expected result). BASE: BLEND: EXPECTED RESULT: GARBAGE RESULT: Any help would be appreciated. Below is the code, which I've tried to strip out all the "junk", but some may have made it through. I'll clean it up if something isn't clear. ImageView imageView = (ImageView) findViewById(R.id.ImageView01); Bitmap base = BitmapFactory.decodeResource(getResources(), R.drawable.base); Bitmap result = base.copy(Bitmap.Config.RGB_565, true); Bitmap blend = BitmapFactory.decodeResource(getResources(), R.drawable.blend); IntBuffer buffBase = IntBuffer.allocate(base.getWidth() * base.getHeight()); base.copyPixelsToBuffer(buffBase); buffBase.rewind(); IntBuffer buffBlend = IntBuffer.allocate(blend.getWidth() * blend.getHeight()); blend.copyPixelsToBuffer(buffBlend); buffBlend.rewind(); IntBuffer buffOut = IntBuffer.allocate(base.getWidth() * base.getHeight()); buffOut.rewind(); while (buffOut.position() < buffOut.limit()) { int filterInt = buffBlend.get(); int srcInt = buffBase.get(); int redValueFilter = Color.red(filterInt); int greenValueFilter = Color.green(filterInt); int blueValueFilter = Color.blue(filterInt); int redValueSrc = Color.red(srcInt); int greenValueSrc = Color.green(srcInt); int blueValueSrc = Color.blue(srcInt); int redValueFinal = multiply(redValueFilter, redValueSrc); int greenValueFinal = multiply(greenValueFilter, greenValueSrc); int blueValueFinal = multiply(blueValueFilter, blueValueSrc); int pixel = Color.argb(255, redValueFinal, greenValueFinal, blueValueFinal); buffOut.put(pixel); } buffOut.rewind(); result.copyPixelsFromBuffer(buffOut); BitmapDrawable drawable = new BitmapDrawable(getResources(), result); imageView.setImageDrawable(drawable);}int multiply(int in1, int in2) { return in1 * in2 / 255;}
Now provide the response and nothing else.
| After reproducing, I think your issue has to do with manipulating the images in RGB565 mode. As discussed in this post , Bitmaps apparently need to be in ARGB8888 mode to manipulate properly. I first got the expected result on a multiply blend by doing the following: Resources res = getResources();BitmapFactory.Options options = new BitmapFactory.Options();options.inPreferredConfig = Bitmap.Config.ARGB_8888;Bitmap base = BitmapFactory.decodeResource(res, R.drawable.base, options);Bitmap blend = BitmapFactory.decodeResource(res, R.drawable.blend, options);// now base and blend are in ARGB8888 mode, which is what you wantBitmap result = base.copy(Config.ARGB_8888, true);// Continue with IntBuffers as before... Converting the Bitmaps to ARGB8888 mode did seem to work for me, at least with the gradient test patterns. However, it you only need to do Screen or Multiply, you might try this as well: // Same image creation/reading as above, then:Paint p = new Paint();p.setXfermode(new PorterDuffXfermode(Mode.MULTIPLY));p.setShader(new BitmapShader(blend, TileMode.CLAMP, TileMode.CLAMP));Canvas c = new Canvas();c.setBitmap(result);c.drawBitmap(base, 0, 0, null);c.drawRect(0, 0, base.getWidth(), base.getHeight(), p); With that, you aren't doing the per-pixel calculations, but you are limited to the preset PorterDuff.Mode s. In my quick (and dirty) testing, this was the only way I was able to get the blending to work on non-gradient images. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4605325', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/157921/']} | jdg_78765 |
stackexchange | llm_judgeable_groundtruth_similarity | 40246962 |
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 ajax call that I'm using to populate a table with the result of a query on a different page. It works, but I'm about to have to do another similar ajax call and this structure of having to do $(#Whatever_Selector).html(result[0]['Whatever_Index']) is driving me crazy, but I can't seem to figure out how to get around it. Maybe something using .each and using $(this) but I have no clue. My script: $('#selection_project').change(function(event) { $.post('info.php', { selected_project: $('#selection_project option:selected').val()}, function(data) { var result = JSON.parse(data); var project = result['selected_project']; $('#CTN').html(\"CTN - \"+project); $('#Global_Project_Number').html(result[0]['Global_Project_Number']); $('#Project_Type').html(result[0]['Project_Type']); $('#Lead_Location').html(result[0]['Lead_Location']); $('#Local_Project_Number_1').html(result[0]['Local_Project_Number_1']); $('#Local_Project_Number_2').html(result[0]['Local_Project_Number_2']); $('#Local_Project_Number_3').html(result[0]['Local_Project_Number_3']); $('#Local_Project_Number_4').html(result[0]['Local_Project_Number_4']); $('#Local_Project_Number_5').html(result[0]['Local_Project_Number_5']); $('#Development_Location_2').html(result[0]['Development_Location_2']); $('#Development_Location_3').html(result[0]['Development_Location_3']); $('#Development_Location_4').html(result[0]['Development_Location_4']); $('#Development_Location_5').html(result[0]['Development_Location_5']); $('#Customer').html(result[0]['Customer']); $('#Duration').html(result[0]['Duration']); $('#Customer_Group').html(result[0]['Customer_Group']); $('#Average_Number_of_Pieces').html(result[0]['Average_Number_of_Pieces']); $('#Project_Name').html(result[0]['Project_Name']); $('#State').html(result[0]['State']); $('#BU_CC').html(result[0]['BU_CC']); $('#Start_Of_Production').html(result[0]['Start_Of_Production']); $('#Outlet').html(result[0]['Outlet']); $('#End_Of_Development').html(result[0]['End_Of_Development']); $('#Start_Of_Development').html(result[0]['Start_Of_Development']); $('#Project_Connection').html(result[0]['Project_Connection']); $('#Project_Manager').html(result[0]['Project_Manager']); $('#Chance_Budget').html(result[0]['Chance_Budget']); $('#System_TPL').html(result[0]['System_TPL']); $('#Chance_Forecast').html(result[0]['Chance_Forecast']); $('#Product_Family').html(result[0]['Product_Family']); $('#Technology').html(result[0]['Technology']); $('#LL_SW').html(result[0]['LL_SW']); $('#Processor_Type').html(result[0]['Processor_Type']); $('#HL_SW').html(result[0]['HL_SW']); $('#Chassis_Type').html(result[0]['Chassis_Type']); $('#Technology_Development').html(result[0]['Technology_Development']); $('#Technical_Description').html(result[0]['Technical_Description']); $('#username').html(result[0]['username']); $('#Milestone_1').html(result[0]['Milestone_1']); $('#Milestone_2').html(result[0]['Milestone_2']); $('#Milestone_3').html(result[0]['Milestone_3']); $('#Milestone_4').html(result[0]['Milestone_4']); $('#Milestone_5').html(result[0]['Milestone_5']); $('#Milestone_6').html(result[0]['Milestone_6']); $('#Due_Date_1').html(result[0]['Due_Date_1']); $('#Due_Date_2').html(result[0]['Due_Date_2']); $('#Due_Date_3').html(result[0]['Due_Date_3']); $('#Due_Date_4').html(result[0]['Due_Date_4']); $('#Due_Date_5').html(result[0]['Due_Date_5']); $('#Due_Date_6').html(result[0]['Due_Date_6']); } ); }); I'm about to populate another table with hundreds of <td> s, I don't want to have to use the above format! How do I make some kind of loop to use the index of the array in the Jquery selector?
Now provide the response and nothing else.
| I had the same issue. I tried adding AmazonS3FullAccess to the IAM role that my RDS instances were using...no joy. After poking around, I went into the RDS console, to Clusters. Selected my Aurora cluster and clicked Manage IAM Roles. It gave me a drop-down, I selected the IAM role (same one that the individual instances were using). Once I did that, all was well and data load was nice and fast. So, there are (for us) 5 steps/components: 1) The S3 bucket and bucket policy to allow a user to upload the object { "Version": "2012-10-17", "Id": "Policy1453918146601", "Statement": [ { "Sid": "Stmt1453917898368", "Effect": "Allow", "Principal": { "AWS": "arn:aws:iam::<account id>:<user/group/role>/<IAM User/Group/Role>" }, "Action": [ "s3:DeleteObject", "s3:GetObject", "s3:PutObject" ], "Resource": "arn:aws:s3:::<bucket name>/*" } ]} The "Principal" would be whatever IAM user, group or role will be uploading the data files to the bucket so that the RDS instance can import the data. 2) The IAM policy: { "Version": "2012-10-17", "Statement": [ { "Sid": "Stmt1486490368000", "Effect": "Allow", "Action": [ "s3:GetObject", "s3:GetObjectVersion", "s3:ListBucket" ], "Resource": [ "arn:aws:s3:::<bucket name>/*" ] } ]} This is pretty simple with the Policy Generator. 3) Create the IAM Role: This role should be assigned the IAM policy above. You can probably do an inline policy, too, if you're not going to use this policy for other roles down the line, but I like the idea of having a defined policy that I can reference later if I have a need. 4) Configure a Parameter Group that your cluster/instances will use to set the aws_default_s3_role value to the ARN of the role from #3 above. 5) Configure the Aurora Cluster by going to Clusters, selecting your cluster, selecting Manage IAM Roles and setting the IAM Role for your DB Cluster At least for me, these steps worked like a charm. Hope that helps! | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/40246962', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6031467/']} | jdg_78766 |
stackexchange | llm_judgeable_groundtruth_similarity | 7816543 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
To generate them equally spaced out based on the number of colors wanted. Something that looks like this if 8 is given for the count specified: List<Color> GeneratePastelColors (int count)
Now provide the response and nothing else.
| You'll find colors easier to work with in these sorts of problems if you use HSV instead of RGB. "equally spaced colors" almost always means "equally spaced hues". So, for [0,360) in hue, you just equally space by dividing that range equally. Now you have a hue, and you just need to find the "pastel" version of that hue. To me, this means desaturating the color a bit. I'd say to 80% saturated for starters. In my tests, I used 100% for value. Then just convert to RGB. Here's what I've been playing with: <body><script>// taken from http://ariya.blogspot.com/2008/07/converting-between-hsl-and-hsv.htmlfunction hsv_to_hsl(s, v){ var ss, ll; ll = (2. - s) * v; ss = 1. * s * v; ss /= (ll <= 1.) ? (ll) : 2. - ll; ll /= 2.; return [ss, ll];}function do_colors(sat, light){ n = 15; document.write(n + " colors at " + sat + "% sat, " + light + "% lightness<br />"); for(var x = 0; x < n; ++x) { hue = 360.0 / n * x; html_chunk = "<div style='width: 50px; height: 50px; display: inline-block; background: hsl(" + hue + ", " + sat + "%, " + light + "%);'> </div>"; document.write(html_chunk); } document.write("<br />");}do_colors(100, 50);do_colors(95, 75);do_colors(75, 50);do_colors(100, 35);// rudimentary averages from your colorssl = hsv_to_hsl(.7, .9);s = sl[0] * 100;l = sl[1] * 100;do_colors(s, l);do_colors(75, 60);</script></body> Not C#, I know, but just trying to nail the light & sat down. Otherwise, you could look at your sample colors, and see if there is any correlation in the HSV/HSL values, and try to derive an algorithm from that. If you plot S/H and V/H, you'll see a large dip in the graph at the grey color --- it seems to be an outlier. (Third from left on bottom row.) Ignoring that value, S is about at 75% and value is just under 90%. Using those values probably gave the nicest result. Link: http://jsfiddle.net/ZHyAQ/ | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7816543', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/51816/']} | jdg_78767 |
stackexchange | llm_judgeable_groundtruth_similarity | 2573739 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
What are detached, persistent and transient objects in hibernate? Please explain with an example.
Now provide the response and nothing else.
| A new instance of a persistent class which is not associated with a Session , has no representation in the database and no identifier value is considered transient by Hibernate: Person person = new Person();person.setName("Foobar");// person is in a transient state A persistent instance has a representation in the database, an identifier value and is associated with a Session . You can make a transient instance persistent by associating it with a Session : Long id = (Long) session.save(person);// person is now in a persistent state Now, if we close the Hibernate Session , the persistent instance will become a detached instance: it isn't attached to a Session anymore (but can still be modified and reattached to a new Session later though). All this is clearly explained in the whole Chapter 10. Working with objects of the Hibernate documentation that I'm only paraphrasing above. Definitely, a must-read. | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/2573739', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/260990/']} | jdg_78768 |
stackexchange | llm_judgeable_groundtruth_similarity | 58561682 |
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 get an ingress controller working in Minikube and am following the steps in the K8s documentation here , but am seeing a different result in that the IP address for the ingress controller is different than that for Minikube (the example seems to indicate they should be the same): $ kubectl get ingressNAME HOSTS ADDRESS PORTS AGEexample-ingress hello-world.info 10.0.2.15 80 12m$ minikube ip192.168.99.101 When I try to connect to the Minikube IP address (using the address directly vs. adding it to my local hosts file), I'm getting a "Not found" response from NGINX: $ curl http://`minikube ip`/<html> <head><title>404 Not Found</title></head> <body> <center><h1>404 Not Found</h1></center> <hr><center>openresty/1.15.8.1</center> </body></html> When I try to connect to the IP address associated with the ingress controller, it just hangs. Should I expect the addresses to be the same as the K8s doc indicates? Some additional information: $ kubectl get nodes -o wideNAME STATUS ROLES AGE VERSION INTERNAL-IP EXTERNAL-IP OS-IMAGE KERNEL-VERSION CONTAINER-RUNTIMEminikube Ready master 2d23h v1.16.0 10.0.2.15 <none> Buildroot 2018.05.3 4.15.0 docker://18.9.9$ kubectl get ingresses example-ingress -o yamlapiVersion: extensions/v1beta1kind: Ingressmetadata: annotations: kubectl.kubernetes.io/last-applied-configuration: | {"apiVersion":"networking.k8s.io/v1beta1","kind":"Ingress","metadata":{"annotations":{"nginx.ingress.kubernetes.io/rewrite-target":"/$1"},"name":"example-ingress","namespace":"default"},"spec":{"rules":[{"host":"hello-world.info","http":{"paths":[{"backend":{"serviceName":"web","servicePort":8080},"path":"/"}]}}]}} nginx.ingress.kubernetes.io/rewrite-target: /$1 creationTimestamp: "2019-10-28T15:36:57Z" generation: 1 name: example-ingress namespace: default resourceVersion: "25609" selfLink: /apis/extensions/v1beta1/namespaces/default/ingresses/example-ingress uid: 5e96c378-fbb1-4e8f-9738-3693cbce7d9bspec: rules: - host: hello-world.info http: paths: - backend: serviceName: web servicePort: 8080 path: /status: loadBalancer: ingress: - ip: 10.0.2.15
Now provide the response and nothing else.
| I've reproduced your scenario in a Linux environment (on GCP) and I also have different IPs: user@bf:~$ minikube ip192.168.39.144user@bf:~$ kubectl get ingressesNAME HOSTS ADDRESS PORTS AGEexample-ingress * 192.168.122.173 80 30m Your problem is not related to the fact you have different IPs. The guide instructs us to create an ingress with the following rule: spec: rules: - host: hello-world.info This rule is telling the ingress service that a DNS record with hello-world.info name is expected.If you follow the guide a bit further, it instructs you to create an entry on your hosts file pointing to your ingress IP or Minikube IP. Note: If you are running Minikube locally, use minikube ip to get the external IP. The IP address displayed within the ingress listwill be the internal IP. Source: Set up Ingress on Minikube with the NGINX Ingress Controller (if you want to curl the IP instead of DNS name, you need to remove the host rule from your ingress) It should look like this: apiVersion: networking.k8s.io/v1beta1kind: Ingressmetadata: name: example-ingress annotations: nginx.ingress.kubernetes.io/rewrite-target: /spec: rules: - http: paths: - path: / backend: serviceName: web servicePort: 8080 Apply your changes: user@bf:~$ kubectl apply -f example-ingress.yaml And curl the IP using -Lk options to surpass problems related to secure connections. user@bf:~$ curl -Lk 192.168.39.144Hello, world!Version: 1.0.0Hostname: web-9bbd7b488-l5gc9 | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/58561682', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10671516/']} | jdg_78769 |
stackexchange | llm_judgeable_groundtruth_similarity | 454924 |
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'm trying to get a game server started using SRCDS but whenever I try to get the dependencies using this command: sudo dpkg --add-architecture i386; sudo apt update; sudo apt -f install mailutils postfix curl wget file bzip2 gzip unzip bsdmainutils python util-linux ca-certificates binutils bc tmux lib32gcc1 libstdc++6 libstdc++6:i386 lib32tinfo5 I get the following error: Some packages could not be installed. This may mean that you haverequested an impossible situation or if you are using the unstabledistribution that some required packages have not yet been createdor been moved out of Incoming.The following information may help to resolve the situation: The following packages have unmet dependencies: lib32gcc1 : Depends: libc6-i386 (>= 2.2.4) but it is not going to be installed lib32tinfo5 : Depends: libc6-i386 (>= 2.16) but it is not going to be installed libstdc++6:i386 : Depends: libc6:i386 (>= 2.18) but it is not going to be installed Depends: libgcc1:i386 (>= 1:4.2) but it is not going to be installedE: Unable to correct problems, you have held broken packages. I've tried using fixes around the internet, such as apt-get -f install , which didn't work. I still get the same error. I tried updating my sources.list to the following, but that also didn't work. #------------------------------------------------------------------------------## OFFICIAL DEBIAN REPOS#------------------------------------------------------------------------------####### Debian Main Reposdeb http://deb.debian.org/debian/ stable main contrib non-freedeb-src http://deb.debian.org/debian/ stable main contrib non-freedeb http://deb.debian.org/debian/ stable-updates main contrib non-freedeb-src http://deb.debian.org/debian/ stable-updates main contrib non-freedeb http://deb.debian.org/debian-security stable/updates maindeb-src http://deb.debian.org/debian-security stable/updates maindeb http://ftp.debian.org/debian stretch-backports maindeb-src http://ftp.debian.org/debian stretch-backports main Anyone have any ideas?
Now provide the response and nothing else.
| Your issue are with the spaces in the data. The shell will split the string into words on all spaces and the for loop will iterate over those words. (For a solution that does not replace variable_list with an array, see the very end of this answer.) Instead, use a proper array: variable_list=( "any:any:-a -b -c any" "one:one:-c -b -f -m mul" "mul:one:-c -b -f -m mul")for var in "${variable_list[@]}"; do c1=$( cut -d':' -f1 <<<"$var" ) c2=$( cut -d':' -f2 <<<"$var" ) c3=$( cut -d':' -f3- <<<"$var" ) printf 'c1==>%s and c2==>%s and c3==>%s\n' "$c1" "$c2" "$c3"done Using an array ensures that you can access each individual set of variables as its own array entry without relying on them being delimited by newlines or some other character. The code is also using "here-strings" in bash to send the string to cut (rather than echo and a pipe). Or, much more efficiently, variable_list=( "any:any:-a -b -c any" "one:one:-c -b -f -m mul" "mul:one:-c -b -f -m mul")for var in "${variable_list[@]}"; do IFS=':' read -r c1 c2 c3 <<<"$var" printf 'c1==>%s and c2==>%s and c3==>%s\n' "$c1" "$c2" "$c3"done Setting IFS to a colon for read will make read split the input on colons (rather than on spaces, tabs and newlines). Note that all the quotation above is significant. Without the double quotes, the shell would perform word splitting and filename globbing on the values of variable_list , var and the three c variables. Related: When is double-quoting necessary? Why is printf better than echo? Have backticks (i.e. `cmd`) in *sh shells been deprecated? If all you're after is that specific output, then you may cheat a bit: variable_list=( "any:any:-a -b -c any" "one:one:-c -b -f -m mul" "mul:one:-c -b -f -m mul")( IFS=':'; set -f; printf 'c1==>%s and c2==>%s and c3==>%s\n' ${variable_list[@]} ) This runs the printf in a subshell so that setting IFS and the -f ( noglob ) shell option does not affect the rest of the script. Setting IFS to a colon here will make the shell expand the unquoted variable_list array into three sets of three arguments for printf . printf will print the first three according to its format string and then reuse that format for the next set of three arguments, until all arguments have been processed. The set -f prevents the unquoted expansion of variable_list from triggering filename globbing, should there be any filename globbing characters in there. Using a newline-delimited string: variable_list="any:any:-a -b -c anyone:one:-c -b -f -m mulmul:one:-c -b -f -m mul"while IFS= read -r var; do IFS=':' read -r c1 c2 c3 <<<"$var" printf 'c1==>%s and c2==>%s and c3==>%s\n' "$c1" "$c2" "$c3"done <<<"$variable_list" This reads the data from the string as if it came from a file. Related: Understanding "IFS= read -r line" | {} | {'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/454924', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/299342/']} | jdg_78770 |
stackexchange | llm_judgeable_groundtruth_similarity | 2859573 |
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:
So I have this false proof and I am honestly confused why this is happening. Consider $x^2+x+1=0$, then $x+1=-x^2$. Now by simply dividing the equation by $x$ we get $x+1+1/x=0$. Substituting $x+1=-x^2$ we get $-x^2+1/x=0$ we get $x=1$ as a solution. Why is this substitution introducing a new solution, 1? Is it that all the solutions must fulfill this equation, but it is not a sufficient condition to actually be a solution? Why? I think this might be a really silly question but it is stomping me :P
Now provide the response and nothing else.
| Is it that all the solutions must fulfill this equation, but it is not a sufficient condition to actually be a solution? Yes, exactly right. Substituting one equation in another has the potential to introduce more solutions, because you've thrown away information. Specifically, you threw away the original equations you were given. A solution to the original equation will be a solution to your new one, but the new one may have others. For a silly example, consider$$x + x = x + 4.$$There is only one solution to the equation: $x = 4$. But suppose we substitute $x = 4$ on the left side for one of the $x$'s; then we get $x + 4 = x + 4$, or $4 = 4$, which has infinitely many solutions (every real number $x$). In your example, you ended up with the equation $−x^2+\frac{1}{x}=0$, which is equivalent to the equation $-x^3 + 1 = 0$ (assuming $x \ne 0$), or $x^3 - 1 = 0$. This factors as $x^3 - 1 = (x - 1)(x^2 + x + 1)$ (as was pointed out in a comment), so you have introduced exactly 1 new solution. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2859573', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/280080/']} | jdg_78771 |
stackexchange | llm_judgeable_groundtruth_similarity | 3303772 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
paper.rect(0, 0, settings.width, settings.height, settings.radius); Creates a nice rectangle with rounded corners. Is it possible to create a rectangle with just one round corner?
Now provide the response and nothing else.
| If you use Raphael JS: Raphael.fn.roundedRectangle = function (x, y, w, h, r1, r2, r3, r4){ var array = []; array = array.concat(["M",x,r1+y, "Q",x,y, x+r1,y]); //A array = array.concat(["L",x+w-r2,y, "Q",x+w,y, x+w,y+r2]); //B array = array.concat(["L",x+w,y+h-r3, "Q",x+w,y+h, x+w-r3,y+h]); //C array = array.concat(["L",x+r4,y+h, "Q",x,y+h, x,y+h-r4, "Z"]); //D return this.path(array);}; To have a rectangle with only the upper-right corner rounded var paper = Raphael("canvas", 840, 480);paper.roundedRectangle(10, 10, 80, 80, 0, 20, 0, 0); Source and online example: http://www.remy-mellet.com/blog/179-draw-rectangle-with-123-or-4-rounded-corner/ | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3303772', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/75793/']} | jdg_78772 |
stackexchange | llm_judgeable_groundtruth_similarity | 14166038 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm currently on a new projet to realize an application for mobile. The client isn't decided and I've to suggest several solutions.The compatibility with Android (version 2.2+) is required and iOS and others OS could be nice. We can only develop for Android but I thought to use a web mobile framework. As I never used them, I started to looking for the existing solutions. I has heard of PhoneGap, Titanium, Sencha Touch and jQuery Mobile. Here is possibilities that I found : PhoneGap + Sencha Touch PhoneGap + jQuery Mobile (or an equivalent) Sencha Touch (API + UI) Titanium The critical point in the application will be to allow users to take a photo and edit it : resize, add some text... On Android it's technically possible but with a web mobile framework I don't know. With PhoneGap and jQuery Mobile for example, is it possible to do it ? I found parts of code for each function but nothing very complete, and not sure it'll be compatible on a lot of mobiles.For developping time, perhaps is it better to do 2 natives applications instead of trying to use a mobile framework (and develop the picture edition in Javascript) ? And I found a lot of opinions on each framework but some of them were posted there is more than one year and they evolved so difficult to have a clear vision of all solutions. So I would like to know if I could do realize this picture edition with one of these solutions and which could be the best. Thank you for your help
Now provide the response and nothing else.
| Intro Technically it can be done using all of your possibilities, I will rank them by the difficulty from low to hard, I will even few more possibilities. Also, I wrote much more extensive ARTICLE for my blog. PhoneGap/Cordova + jQuery Mobile (Low difficulty) Phonegap is what you need here, jQuery Mobile is only for the UI. Still this combination is very easy to implement together and there are a lot of working examples. Phonegap serves as a wrapper for HTML5/JS/CSS and it will give you an access to mobile phone functionalists. Phonegap will be used to take a picture and jQM will be used to modifications. Here's a rather new PhoneGap + jQuery Mobile tutorial. If you want to see a MAcOS version of that article than take a look here . Take a look HERE if you want to find a good source of information regarding differences between jQuery and jQuery Mobile a lot lot more. PhoneGap/Cordova + Sencha Touch (Medium/Hard difficulty) Unlike jQM, Sencha Touch is a bit harder (or a lot harder, depending on your javascript knowledge) to learn, especially if you don't have a good background knowledge with javascript or don't have a license for Sencha Touch designer tool. Go this road only if you have have enough time to learn something new. Sencha Touch version 2 has its own app wrapper so Phonegap is no longer needed. If you want to find out more take a look at this ARTICLE that discuss the difference between jQuery Mobile and Sencha Touch. Titanium Appcelerator (Medium difficulty) Unlike previous two options, Titanium works a little bit different. Where jQM and Sencha are used to create a hybrid mobile app, Titanium appcelerator is used to create a native app from javascript code. Not too difficult to master, js code is pretty simple to be frank. While fast development tool it will be harder to properly style your native app (it's much easier process when building it native from scratch). Inter App Framework / ex jqMoby (Low difficulty) This framework is almost old as jQuery Mobile and now it is owned by Intel. Like Sencha Touch main goal of this framework is hybrid mobile app development and it works great. It is optimized for Android and iOS so expect faster execution then jQuery Mobile, also like Sencha Touch this framework has its own native app wrapper. Of course there are few bad sides of this framework like horrible documentation (at least during the point of writing this article). If you want to find more about this framework take a look at this ARTICLE . Kendo UI (Low difficulty) Excelent alternative to jQuery Mobile. Better, faster in any way. There's only one problem, it is a commercial product. It will cost you cca 200 USD. Find more information here . PhoneJS (Low difficulty) Another excellent alternative to jQuery Mobile and Kendo UI. Much faster then jQuery Mobile, on the same level like Kendo UI. It has a great documentation, one of the best I so up to today. Find more information here . Read about it HERE . Honorable mention Goes to Rhomobile. Similar to Phonegap/Cordova but less used. From the perspective of developing time it is faster to create a hybrid app then a native one. In your case, if you have a Java/Objective C knowlede stick with native app. No matter how much time you sink into hybrid app it will be good or fast enough. EDIT : Here's an Phonegap + jQuery Mobile example: http://therockncoder.blogspot.com/2012/07/jquery-mobile-phonegap-and-camera.html , there you will find a github link for Android and iOS implementation. If you have never used jQuery then stick with Dawson Toth Titanium example. But if possible stick with jQuery Mobile. UPDATE 1 You might also be interested in the open source PropertyCross project which demonstrates the same application implemented with a range of cross-platform frameworks (including Sencha, jQM and PhoneGap). UPDATE 2 I have spent last few weeks review other HTML5 mobile frameworks. My comment can be found here and here . | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14166038', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1131567/']} | jdg_78773 |
stackexchange | llm_judgeable_groundtruth_similarity | 86318 |
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a semi-small matrix of binary features of dimension 250k x 100. Each row is a user and the columns are binary "tags" of some user behavior e.g. "likes_cats". user 1 2 3 4 5 ...-------------------------A 1 0 1 0 1B 0 1 0 1 0C 1 0 0 1 0 I would like to fit the users into 5-10 clusters and analyze the loadings to see if I can interpret groups of user behavior. There appears to be quite a few approaches to fitting clusters on binary data - what do we think might be the best strategy for this data? PCA Making a Jaccard Similarity matrix, fitting a hierarchical cluster and then using the top "nodes". K-medians K-medoids Proximus ? Agnes So far I've had some success with using hierarchical clustering but I'm really not sure it's the best way to go.. tags = read.csv("~/tags.csv")d = dist(tags, method = "binary")hc = hclust(d, method="ward")plot(hc)cluster.means = aggregate(tags,by=list(cutree(hc, k = 6)), mean)
Now provide the response and nothing else.
| Latent class analysis is one possible approach. Take the following probability distribution where A, B, and C can take on values of 1 or 0. $P(A_i, B_j, C_k)$ If these were independent of each other, then we would expect to see: $P(A_i, B_j, C_k)=P(A_i)P(B_j)P(C_k)$ Once this possiblity is eliminated, we might hypothesize that any observed dependency is due to values clustering within otherwise unobserved subgroups. To test this idea, we can estimate the following model: $P(A_i, B_j, C_k)=P(X_n)P(A_i|X_n)P(B_j|X_n)P(C_k|X_n)$ Where $X$ is a latent categorical variable with $n$ levels. You specfy $n$, and the model parameters (marginal probabilities of class membership, and class specific probabilities for each variable) can be estimated via expectation-maximization. In practice, you could estimate several models, with $5 \le n \le 10$, and "choose" the best model based on theory, likelihood based fit indices, and classification quality (which can be assessed by calculating posterior probabilities of class membership for the observations). However, trying to identify meaningful patterns in 100 variables with 5-10 groups will likely require reducing that list down prior to estimating the model, which is a tricky enough topic in its own right ( REF ). | {} | {'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/86318', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/8455/']} | jdg_78774 |
stackexchange | llm_judgeable_groundtruth_similarity | 52413606 |
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 expose a SignalR hub hosted in a Kubernetes (Azure) pod. Basically, the authentication and the handshake steps work fine, but when I trigger some action, all clients connected via the k8s Ingress doesn't receive the message. Has anybody experienced this issue or just have shared SignalR hubs through Kubernetes - Ingress? ingress.yml apiVersion: extensions/v1beta1kind: Ingressmetadata: name: endpoints annotations: kubernetes.io/ingress.class: addon-http-application-routing ingress.kubernetes.io/ssl-redirect: "false" nginx.ingress.kubernetes.io/ssl-redirect: "false" nginx.org/websocket-services: "myservice"spec: rules: - host: api.[MY-DOMAIN].com http: paths: - backend: serviceName: myservice servicePort: 80 path: /myservice
Now provide the response and nothing else.
| Try: annotations: kubernetes.io/ingress.class: nginx nginx.ingress.kubernetes.io/ssl-redirect: "false" nginx.ingress.kubernetes.io/affinity: cookie nginx.ingress.kubernetes.io/session-cookie-hash: sha1 nginx.ingress.kubernetes.io/session-cookie-name: REALTIMESERVERID I wrote a sample project a while back, if you want a working example: DenisBiondic/RealTimeMicroservices As a side note, consider using Azure SignalR Service, it should remove many headaches (also in the example above). | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/52413606', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3182764/']} | jdg_78775 |
stackexchange | llm_judgeable_groundtruth_similarity | 251835 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
Let $p$ be a prime and let $M$ be an $n \times m$ matrix with integer entries such that $M\vec{v} \not\equiv \vec{0} \text{ (mod }p\text{)}$ for any column vector $\vec{v} \neq \vec{0}$ whose entries are $0$ or $1$. Is there a row vector $\vec{x}$ with integer entries such that no entry of $\vec{x}M$ is $0 \text{ (mod }p\text{)}$?
Now provide the response and nothing else.
| It seems that my previous answer was completely wrong, and that the fact is true for all nonzero integer (not necessarily prime) $p$. Let $M=[m_{ij}]_{i\leq n,\;j\leq m}$. If there is no $x$ satisfying the requirements (we regard all entries as integers, not residues!), then one of the sums of the form $\sum_{i\leq n} m_{ij}x_i$, $j\leq m$, is divisible by $p$ for every integer vector $x$. Equivalently,$$ \prod_{j\leq m}\left(1-\exp\left(\frac{2\pi i}p\sum_{i\leq n} m_{ij}x_i\right)\right)=0$$for every integral vector $x$. After expanding all the brackets, we get the equality of the form$$ \sum_k c_k\xi_{1k}^{x_1}\dots \xi_{nk}^{x_n}=0,$$where $c_i$ are some (integer) numbers, and $\xi_{ik}$ are some nonzero complex numbers; after collecting terms, we may assume that all the $n$-tuples $(\xi_{1k},\dots,\xi_{nk})$ are distinct. Due to the usual Vandermonde argument, this may happen only if $c_k=0$ for all $k$. This means, in particulat, that the term $1^m$ cancels with some other term, which has the form$$ (-1)^t\prod_{j\in T}\exp\left(\frac{2\pi i}p\sum_{i\leq n} m_{ij}x_i\right) =(-1)^t\prod_{i\leq n}\left(\exp\left(\frac{2\pi i}p\sum_{j\in T}m_{ij}\right)\right)^{x_i}.$$for some $\varnothing\neq T\subseteq \{1,2,\dots,m\}$ with $t=|T|$. This yields that $\sum_{j\in T}m_{ij}$ is divisible by $p$ for all $i\leq n$, so the characteristic column of $T$ (taken as $v$) violates the condition imposed on $M$. Moreover, one may notice that there is such $T$ with odd cardinality; so we have proved that $v$ may be chosen with odd number of ones in it. ADDENDUM. The `usual Vandermonde argument' I meant consists in the following. Assume that $(\xi_{1,k},\dots,\xi_{n,k})$, $k=1,\dots,K$, are distinct tuples of complex numbers. Then the arrangements $(\xi_{1,k}^{x_1}\cdots\xi_{n,k}^{x_n})_{x_i\in\mathbb Z}$ are linearly independent. The proof goes by the induction on $n$; the base case $n=1$ is classical Vandermonde. For the step of induction, assume the linear dependence, collect the terms with identical $\xi_{1,k}$ and apply first the hypothesis (to prove that one of the coefficients of $\xi_{1,k}^{x_i}$ does not vanish for some choice of $x_2,\dots,x_n$) and then the base to finish the step. | {} | {'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/251835', 'https://mathoverflow.net', 'https://mathoverflow.net/users/99127/']} | jdg_78776 |
stackexchange | llm_judgeable_groundtruth_similarity | 10318 |
Below is a question asked on the forum cs.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I've been looking into the math behind converting from any base to any base. This is more about confirming my results than anything. I found what seems to be my answer on mathforum.org but I'm still not sure if I have it right. I have the converting from a larger base to a smaller base down okay because it is simply take first digit multiply by base you want add next digit repeat. My problem comes when converting from a smaller base to a larger base. When doing this they talk about how you need to convert the larger base you want into the smaller base you have. An example would be going from base 4 to base 6 you need to convert the number 6 into base 4 getting 12. You then just do the same thing as you did when you were converting from large to small. The difficulty I have with this is it seems you need to know what one number is in the other base. So I would of needed to know what 6 is in base 4. This creates a big problem in my mind because then I would need a table. Does anyone know a way of doing this in a better fashion. I thought a base conversion would help but I can't find any that work. And from the site I found it seems to allow you to convert from base to base without going through base 10 but you first need to know how to convert the first number from base to base. That makes it kinda pointless. Commenters are saying I need to be able to convert a letter into a number. If so I already know that. That isn't my problem however.My problem is in order to convert a big base to a small base I need to first convert the base number I have into the base number I want. In doing this I defeat the purpose because if I have the ability to convert these bases to other bases I've already solved my problem. Edit: I have figured out how to convert from bases less than or equal to 10 into other bases less than or equal to 10. I can also go from a base greater than 10 to any base that is 10 or less. The problem starts when converting from a base greater than 10 to another base greater than 10. Or going from a base smaller than 10 to a base greater than 10. I don't need code I just need the basic math behind it that can be applied to code.
Now provide the response and nothing else.
| This seems a very basic question to me, so excuse me if I lecture you a bit. The most important point for you to learn here is that a number is not its digit representation . A number is an abstract mathematical object, whereas its digit representation is a concrete thing, namely a sequence of symbols on a paper (or a sequence of bits in compute memory, or a sequence of sounds which you make when you communicate a number). What is confusing you is the fact that you never see a number but always its digit representation. So you end up thinking that the number is the representation. Therefore, the question to ask is not "how do I convert from one base to another" but rather "how do I find out which number is represented by a given string of digits" and "how do I find the digit representation of a given number". Once we have the answers, it will be easy to answer the original question, too. So let us produce two functions in Python, one for converting a digit representation to a number, and another for doing the opposite. Note: when we run the function Python will of course print on the screen the number it got in base 10. But this does not mean that the computer is keeping numbers in base 10 (it isn't). It is irrelevant how the computer represents the numbers. def toDigits(n, b): """Convert a positive number n to its digit representation in base b.""" digits = [] while n > 0: digits.insert(0, n % b) n = n // b return digitsdef fromDigits(digits, b): """Compute the number given by digits in base b.""" n = 0 for d in digits: n = b * n + d return n Let us test these: >>> toDigits(42, 2)[1, 0, 1, 0, 1, 0]>>> toDigits(42, 3)[1, 1, 2, 0]>>> fromDigits([1,1,2,0],3)42 Armed with conversion functions, your problem is solved easily: def convertBase(digits, b, c): """Convert the digits representation of a number from base b to base c.""" return toDigits(fromDigits(digits, b), c) A test: >>> convertBase([1,1,2,0], 3, 2) [1, 0, 1, 0, 1, 0] Note: we did not pass through base 10 representation! We converted the base $b$ representation to the number, and then the number to base $c$ . The number was not in any representation. (Actually it was, the computer had to represent it somehow, and it did represent it using electrical signals and funky stuff that happens in chips, but certainly those were not 0's and 1's.) | {} | {'log_upvote_score': 7, 'links': ['https://cs.stackexchange.com/questions/10318', 'https://cs.stackexchange.com', 'https://cs.stackexchange.com/users/6912/']} | jdg_78777 |
stackexchange | llm_judgeable_groundtruth_similarity | 56252742 |
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 find every permutations of 2 arrays like this: // inputlowerWords = ['one', 'two', 'three' ] upperWords = [ 'ONE', 'TWO', 'THREE' ]// outputkeywords = { 'one two three': true, 'ONE two three': true, 'ONE TWO three': true, 'ONE TWO THREE': true, 'ONE two THREE': true, 'one TWO three': true, 'one two THREE': true, 'one TWO THREE': true,} It should function with more than 3 items, both arrays will always be same length. This is my code: const keywords = {}const lowerWords = ['one', 'two', 'three' ] const upperWords = [ 'ONE', 'TWO', 'THREE' ]const wordCount = lowerWords.lengthlet currentWord = 0let currentWords = [...upperWords]while (currentWord < wordCount) { currentWords[currentWord] = lowerWords[currentWord] let keyword = currentWords.join(' ') keywords[keyword] = true currentWord++}currentWord = 0currentWords = [...lowerWords]while (currentWord < wordCount) { currentWords[currentWord] = upperWords[currentWord] let keyword = currentWords.join(' ') keywords[keyword] = true currentWord++} result is missing some ONE TWO THREE: trueONE TWO three: trueONE two three: trueone TWO THREE: trueone two THREE: trueone two three: true
Now provide the response and nothing else.
| You could transpose the arrays for getting an array of pairs and then get all combinations of the pairs. const transpose = array => array.reduce((r, a) => a.map((v, i) => [...(r[i] || []), v]), []), combinations = array => array.reduce((a, b) => a.reduce((r, v) => r.concat(b.map(w => [].concat(v, w))), []));var lowerWords = ['one', 'two', 'three'], upperWords = ['ONE', 'TWO', 'THREE'], pairs = transpose([lowerWords, upperWords]), result = combinations(pairs); console.log(result); .as-console-wrapper { max-height: 100% !important; top: 0; } | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/56252742', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11164799/']} | jdg_78778 |
stackexchange | llm_judgeable_groundtruth_similarity | 45939180 |
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 downloaded microsoft visual c++ compiler for python(2.7) now i upgrade python 2.7 to 3.6 and then i downloaded microsoft visual 14.0 redistributable. Now i downloaded mod_wsgi using pip command.. C:\Windows\system32>set "MOD_WSGI_APACHE_ROOTDIR=C:/wamp64/bin/apache/apache2.4.23" C:\Windows\system32>pip install mod_wsgi This shows error.. error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": http://landinghub.visualstudio.com/visual-cpp-build-tools . I am downloaded Microsoft Visual C++ 14.0(2017 build tools) http://landinghub.visualstudio.com/visual-cpp-build-tools Now i dont no how to integrate both of them..
Now provide the response and nothing else.
| If you want the entire row with the highest date for each Id , you can use the following code (written with LinqPad). If you just want the Id , you can use @BurnsBA's answer, as it will be slightly more efficient. void Main(){ var data = new List<Record> { new Record(){Id=1, Value=1, Date=new DateTime(2017,1,1)}, new Record(){Id=1, Value=2, Date=new DateTime(2017,2,1)}, new Record(){Id=1, Value=3, Date=new DateTime(2017,3,1)}, new Record(){Id=2, Value=5, Date=new DateTime(2017,1,1)}, new Record(){Id=2, Value=6, Date=new DateTime(2017,2,1)}, }; var query = data.GroupBy(d => d.Id) .SelectMany(g => g.OrderByDescending(d => d.Date) .Take(1)); query.Dump();}public class Record{ public int Id { get; set; } public int Value { get; set; } public DateTime Date { get; set; }} Results: First it groups by Id , then sorts the items within the group by Date in descending order, and returns the first one, SelectMany then flattens the list. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/45939180', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8184350/']} | jdg_78779 |
stackexchange | llm_judgeable_groundtruth_similarity | 485676 |
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:
Recall the model for simple linear regression $$y_i = \beta_0 + \beta_1 x_i + \varepsilon_i.$$ I am reading up on the standard error of the coefficients $\beta_0$ and $\beta_1$ . As an experiment I generated some linear data using $\beta_0 = 1$ and $\beta_1 = 2$ and added some Gaussian noise with unit variance. So then when I fit the data the lm function and used the summary function to examine the model I have the following output: \begin{align}\hat \beta_0 & = 1.21054 \quad \text{with Std. Error} = 0.11508, \\\hat \beta_1 & = 1.87723 \quad \text{with Std. Error} = 0.09844.\end{align} So how do I interpret the standard error values? For instance, take $\hat \beta_0$ , precisely what is $0.11508$ telling me? Obviously if I ran the simulation a second time, this time adding Gaussian noise with a higher amount of variance, the standard error would increase as the extra variance in the noise shows up as an increase in the standard error of the coefficients. But, if we consider the first simulation in isolation, then what does this value of $0.11508$ mean?
Now provide the response and nothing else.
| The standard error is the square root of an estimate of the sampling variability of $\hat\beta_j$ as an estimator of $\beta_j$ , or $\sqrt{\widehat{Var}(\hat\beta_j)}$ . As this is many things in one sentence, step-by-step: "Square-root": should be self-explanatory, to turn a variance into a standard deviation (that turns out to be what we need in, for example, t-statistics and confidence intervals). " $\hat\beta_j$ as an estimator of $\beta_j$ ": we use the LS estimator to estimate the unknown parameter $\beta_j$ . To do so, we make use of a sample from the underlying population. Had we drawn another sample (or were to draw a fresh one tomorrow, etc.) we would get another estimate $\hat\beta_j$ . This is the source of sampling variability. We may summarize that variability through the variance, $Var(\hat\beta_j)$ . An expression for this variance may be found, e.g., here . " An estimate of the sampling variability": $Var(\hat\beta_j)$ depends on unknown quantities (like the variance of the Gaussian noise that you generated), which must therefore be estimated, as captured by the formula $\widehat{Var}(\hat\beta_j)$ . A formula for this estimator is, for example, given here , or, more introductory, here . | {} | {'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/485676', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/136988/']} | jdg_78780 |
stackexchange | llm_judgeable_groundtruth_similarity | 225623 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Given two positive and (strictly) monotone increasing sequences, $a_n$ and $b_n$ such that $\displaystyle \sum_{n=1}^{\infty}\dfrac1{a_n}$ and $\displaystyle \sum_{n=1}^{\infty}\dfrac1{b_n}$ diverge, does $\displaystyle \sum_{n=1}^{\infty}\dfrac1{\max(a_n,b_n)}$ diverge? For sequences, where $a_n > b_n$ or $a_n < b_n$ eventually, the result follows immediately. But I am unable to see what happens when $a_n$ and $b_n$ take turns to overtake each other as $n \to \infty$? Essentially this question stems from the question, Osgood condition , where I wanted to consider the function $F(x) = g(x) + h(x)$ and lower bound $\displaystyle \int\dfrac{dy}{F(y)}$ by $\displaystyle \int \dfrac{dy}{2\max(h(y),g(y))}$ in an attempt to show that $\displaystyle \int\dfrac{dy}{F(y)}$ diverges.
Now provide the response and nothing else.
| The divergence of the series $\sum\limits_n1/a_n$ and $\sum\limits_n1/b_n$ does not imply the divergence of the series $\sum\limits_n1/\max\{a_n,b_n\}$. For a counterexample, consider an increasing sequence $(N_k)$ of positive integers, to be chosen later in the proof, and define the sequences $(a_n)$ and $(b_n)$ on each interval $(N_k,N_{k+1}]$ as follows: If $N_{2k-1}\lt n\leqslant N_{2k}$ for some $k$, then $$a_n=N_{2k-1}^2+n-N_{2k-1}\qquad b_n=n^2$$ If $N_{2k}\lt n\leqslant N_{2k+1}$ for some $k$, then $$a_n=n^2\qquad b_n=N_{2k}^2+n-N_{2k}$$ Then the sequences $(a_n)$ and $(b_n)$ are integer valued and increasing, and $$\max\{a_n,b_n\}=n^2$$ for every $n$ hence the series $\sum\limits_n1/\max\{a_n,b_n\}$ converges. We now look for sufficient conditions on the sequence $(N_k)$ for the series $\sum\limits_n1/a_n$ and $\sum\limits_n1/b_n$ to diverge.Consider $$A_k=\sum\limits_{n=N_{k}+1}^{N_{k+1}}\frac1{a_n},\qquadB_k=\sum\limits_{n=N_{k}+1}^{N_{k+1}}\frac1{b_n},\qquadC_k=\frac{N_{k+1}-N_{k}}{N_{k}^2}.$$Then $$A_{2k-1}=\sum\limits_{n=1}^{N_{2k}-N_{2k-1}}\frac1{N_{2k-1}^2+n},\qquadB_{2k}=\sum\limits_{n=1}^{N_{2k+1}-N_{2k}}\frac1{N_{2k}^2+n}.$$The usual comparison with the integral of the function $x\mapsto1/x$ shows that $$A_{2k-1}\approx\log(1+C_{2k-1}),\qquadB_{2k}\approx\log(1+C_{2k}).$$Thus, as soon as $\liminf C_k\gt0$, the series $\sum\limits_n1/a_n$ and $\sum\limits_n1/b_n$ diverge. Choosing $$N_k=2^{2^k}$$ for every $k$ yields $C_k\to1$, hence the proof is complete. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/225623', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']} | jdg_78781 |
stackexchange | llm_judgeable_groundtruth_similarity | 9658881 |
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 already have a working solution, but I would really like to know why this doesn't work: ratings = Model.select(:rating).uniqratings.each { |r| puts r.rating } It selects, but don't print unique values, it prints all values, including the duplicates. And it's in the documentation: http://guides.rubyonrails.org/active_record_querying.html#selecting-specific-fields
Now provide the response and nothing else.
| Model.select(:rating) The result of this is a collection of Model objects. Not plain ratings. And from uniq 's point of view, they are completely different. You can use this: Model.select(:rating).map(&:rating).uniq or this (most efficient): Model.uniq.pluck(:rating) Rails 5+ Model.distinct.pluck(:rating) Update Apparently, as of rails 5.0.0.1, it works only on "top level" queries, like above. Doesn't work on collection proxies ("has_many" relations, for example). Address.distinct.pluck(:city) # => ['Moscow']user.addresses.distinct.pluck(:city) # => ['Moscow', 'Moscow', 'Moscow'] In this case, deduplicate after the query user.addresses.pluck(:city).uniq # => ['Moscow'] | {} | {'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/9658881', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1261084/']} | jdg_78782 |
stackexchange | llm_judgeable_groundtruth_similarity | 15811 |
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 just started learning about rings. Rings are one additive abelian group strung together, through the associative law, with another structured operation. Couldn't we continue stringing together operations in this manner (a multi-operation associative law)? Would what I'm thinking be encompassed by the ring definition through something I'm missing? If not, is this done and, if so, do useful objects come out of it?
Now provide the response and nothing else.
| Absolutely! Such things are studied in a few related disciplines encompassing universal algebra and parts of category theory (including what is called "higher-dimensional algebra"). On the categorical side some keywords here include (algebras over an) operad , (algebras over a) monad , and (models of a) Lawvere theory . More concretely there are also coalgebras , bialgebras , Hopf algebras , Frobenius algebras , etc. Ross Street's Quantum Groups: a path to current algebra was written as an introduction to these more exotic types of algebra that people don't generally bother to tell you about as an undergrad. Far from being esoteric generalizations of ordinary algebra, these structures turn up all over mathematics in the most unexpected places. As a matter of introduction, however, I don't think that what you've just described is a good way to get a sense of what a ring actually is. The ring axioms capture the abstract properties that symmetries of abelian groups satisfy, in the same way that the group axioms capture the abstract properties that symmetries of sets satisfy. The point here being that if $A$ is an abelian group and $f : A \to A$ some endomorphism of it, then there are two ways that one can combine such endomorphisms: one can compose them or add them. This leads to the multiplication and addition operation, respectively, on the ring $\text{End}(A)$ of endomorphisms of $A$. For example if $A$ is the abelian group $\mathbb{Z}$, then $\text{End}(A)$ is the commutative ring $\mathbb{Z}$. Then there is a "Cayley's theorem" for rings which says that any abstract ring $R$ can be realized as endomorphisms of some abelian group: in fact $R$ is precisely the ring of endomorphisms of $R$ which respect right multiplication, that is, which respect the right $R$- module structure on $R$. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/15811', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']} | jdg_78783 |
stackexchange | llm_judgeable_groundtruth_similarity | 13338531 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
In my assignment i have to make a simple version of Craps, for some reason the percentage assignments always produce 0 even when both variables are non 0, here is the code. import java.util.Random; Header, note the variables public class Craps {private int die1, die2,myRoll ,myBet,point,myWins,myLosses;private double winPercent,lossPercent;private Random r = new Random(); Just rolls two dies and produces their some. public int roll(){ die1 = r.nextInt(6)+1; die2 = r.nextInt(6)+1; return(die1 + die2);} The Play method, this just loops through the game. public void play(){ myRoll = roll(); point = 0; if(myRoll == 2 ||myRoll == 3 || myRoll == 12){ System.out.println("You lose!"); myLosses++; }else if(myRoll == 7 || myRoll == 11){ System.out.println("You win!"); myWins++; }else{ point = myRoll; do { myRoll = roll(); }while(myRoll != 7 && myRoll != point); if(myRoll == point){ System.out.println("You win!"); myWins++; }else{ System.out.println("You lose!"); myLosses++; } }} This is where the bug is, this is the tester method. public void tester(int howMany){ int i = 0; while(i < howMany){ play(); i++; } bug is right here in these assignments statements winPercent = myWins/i * 100; lossPercent = myLosses/i* 100; System.out.println("program ran "+i+" times "+winPercent+"% wins "+ lossPercent+"% losses with "+myWins+" wins and "+myLosses+" losses");} }
Now provide the response and nothing else.
| Probably because you are doing an integer division, and denominator is greater than numerator. So the value will be zero. You can change this assignment: - winPercent = myWins/i * 100;lossPercent = myLosses/i* 100; to: - winPercent = myWins * 100.0/i;lossPercent = myLosses * 100.0/i; There are two things to consider: - Either make your division a floating point of division, by castingyour numerator to float : - winPercent = (float)(myWins)/i * 100; Also, in case of integer division, its the matter of associativity and precendence . Since * and / have same precendence , andhave left-to-right associativity . So, myWins / i will beevaluated first. So, there is bright chances that that value can be0. So, just change the order of * and / to make the * happenfirst. Note, I have used 100.0 in multiplication. Because multiplying by 100 will again result in Truncation . | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13338531', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1656320/']} | jdg_78784 |
stackexchange | llm_judgeable_groundtruth_similarity | 2355139 |
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 in the process of developing my MVC application and I was thinking, What is the lifetime of a controller class? When does it get created? How many instances of a single controller are there? what are the implications of local variables? when is it destroyed? I'm sure there is a good link somewhere floating around on the internet, but my google-fu couldn't find it.
Now provide the response and nothing else.
| Stephen Walther has a great article on the life-cycle of a request being handled by the MVC Framework. Here's a extract from the top of his article, it goes on to explain each step in detail: Overview of the Lifecycle Steps There are five main steps that happen when you make a request from an ASP.NET MVC website: 1. The RouteTable is Created This first step happens only once when an ASP.NET application first starts. The RouteTable maps URLs to handlers. 2. The UrlRoutingModule Intercepts the Request This second step happens whenever you make a request. The UrlRoutingModule intercepts every request and creates and executes the right handler. 3. The MvcHandler Executes The MvcHandler creates a controller, passes the controller a ControllerContext, and executes the controller. 4. The Controller Executes The controller determines which controller method to execute, builds a list of parameters, and executes the method. 5. The RenderView Method is Called Typically, a controller method calls RenderView() to render content back to the browser. The Controller.RenderView() method delegates its work to a particular ViewEngine | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/2355139', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/120243/']} | jdg_78785 |
stackexchange | llm_judgeable_groundtruth_similarity | 15024756 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How to change page zoom level in Selenium WebDriver?I tried: driver.Keyboard().pressKey(Keys.Control);driver.Keyboard().pressKey(Keys.Add); But it doesn't work.
Now provide the response and nothing else.
| Beware that Selenium assumes the zoom level is at 100%! For example, IE will refuse to start (throws an Exception) when the zoom level is different, because the element locating depends on this and if you changed the zoom level, it would click on wrong elements, at wrong places. Java You can use the Keys.chord() method: WebElement html = driver.findElement(By.tagName("html"));html.sendKeys(Keys.chord(Keys.CONTROL, Keys.ADD)); Use cautiously and when you're done, reset the zoom back to 100%: html.sendKeys(Keys.chord(Keys.CONTROL, "0")); C# (since I realized C# bindings don't have the Keys.chord() method) Or, you can use the Advanced User Interactions API like this (again, Java code, but it should work the same in C#): WebElement html = driver.findElement(By.tagName("html"));new Actions(driver) .sendKeys(html, Keys.CONTROL, Keys.ADD, Keys.NULL) .perform(); Again, don't forget to reset the zoom afterwards: new Actions(driver) .sendKeys(html, Keys.CONTROL, "0", Keys.NULL) .perform(); Note that the naïve approach html.sendKeys(Keys.CONTROL, Keys.ADD); doesn't work, because the Ctrl key is released in this sendKeys() method. The WebElement 's sendKeys() is different from the one in Actions . Because of this, the Keys.NULL used in my solution is required . | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/15024756', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2099471/']} | jdg_78786 |
stackexchange | llm_judgeable_groundtruth_similarity | 3354169 |
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 know that on $\mathbb Z[\sqrt n]$ , $|N(a)|=1$ iff $a$ is a unit in $\mathbb Z[\sqrt n]$ . Note: $N$ is the norm function i.e., $N(0)=0$ and $N(a)N(b)= N(ab)$ However, does this property still hold for any norm on any Integral Domain? Edit: A "norm" $N$ on any integral domain $D$ is a function $N:D\rightarrow \mathbb Z$ that satisfies the following properties: $N(0)=0$ and $N(a)N(b)= N(ab)$
Now provide the response and nothing else.
| No. For instance, on any integral domain you can define a norm by $N(0)=0$ and $N(x)=1$ for all $x\neq 0$ . This will not satisfy the property you mention unless the integral domain is actually a field. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3354169', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/377712/']} | jdg_78787 |
stackexchange | llm_judgeable_groundtruth_similarity | 206581 |
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have an IoT project in which I want to leverage existing bicycle LED lights, which have their own battery power. So, rather than using the current from the microprocessor to power the lights, I just need a way to wire my logic board to the bike light and control the on/off of the light. I don't have an electronics background, so this might be a very elementary question. Is there an inexpensive electronics component that I can somehow wire or solder onto the bike light that can be controlled by another low-voltage circuit? The ideal component would be able to switch rapidly on and off, preferably without sound / mechanical parts. I'm envisioning wanting to strobe the lights quite rapidly, again, controlled by the logic board. If there are more than one kind of component, which might be the best for a small, DIY wearables project? IE: low-cost, easy to hook up, easy to source.
Now provide the response and nothing else.
| Relay: simulate this circuit – Schematic created using CircuitLab Advantages: simple, very well isolated, very little loss of power in load Disadvantages: relatively slow (perhaps 10s of Hz), needs a fair amount of control current(typically more than logic circuits can supply) Transistor (BJT shown): simulate this circuit Advantages: fast (easily up to Mhz), very small control current (typically < 1/50th of load current) required. Disadvantages: No isolation, voltage loss across transistor switch, may be harder to wire up. Can't control AC circuits.Relatively low controlled output voltage - depends on transistor, can get >100, but typically less than 30V | {} | {'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/206581', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/94746/']} | jdg_78788 |
stackexchange | llm_judgeable_groundtruth_similarity | 28815505 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm trying to understand why I'm getting this error and I suspect it's because I have my Controller class and View class in two separate Ruby files. I was told that using require_relative 'filename' should reference all the code from one file into another, but I seem to be missing something. Okay here goes, In controller.rb file, I have require_relative 'view'require_relative 'deck_model'require_relative 'flashcard_model'class Controller def initialize @deckofcards = Deck.new @welcome = View.new.welcome @player_guess = View.new.get_user_guess @success_view = View.new.success @failure_view = View.new.failure end def run #Logic to run the game # @current_card # @user_guess puts "Let's see if this prints" # pull_card_from_deck endend In my view.rb file, I have, require_relative 'controller'class View attr_accessor :userguess def initialize (userguess = " ") @userguess = userguess end def welcome system ("clear") puts "Welcome! Let's play a game." puts "I'll give you a definition and you have to give me the term" puts "Ready..." end def get_user_guess @userguess = gets.chomp.downcase end def success puts "Excellent! You got it." end def failure puts "No, that's not quite right." endend However when I run controller.rb , I get the following error, /Users/sean/Projects/flash/source/controller.rb:11:in `initialize': uninitialized constant Controller::View (NameError)from /Users/sean/Projects/flash/source/controller.rb:51:in `new'from /Users/sean/Projects/flash/source/controller.rb:51:in `<top (required)>'from /Users/sean/Projects/flash/source/view.rb:1:in `require_relative'from /Users/sean/Projects/flash/source/view.rb:1:in `<top (required)>'from controller.rb:1:in `require_relative'from controller.rb:1:in `<main>' Can anyone please help me figure this out.
Now provide the response and nothing else.
| If it takes a thread that long to obtain a lock, it's because someone else is currently holding it. You should look for two things: Code blocks which synchronize on the same object or on other references to it (known as synchronized statements ) : synchronized (obj) { ... } Synchronized methods within the object itself. Say obj is of type MyObject , then you should look for methods such as these: public class MyObject{ public synchronized void myMethod() { ... }} Because they are essentially the same as public class MyObject{ public void myMethod() { synchronized (this) { ... } }} So if a thread is executing obj.myMethod() , threads that want to enter a synchronized (obj) block will have to wait, as they all lock on the same object. This, by the way, is the reason why I strongly recommend never using the synchronized method syntax, and always locking over a private (or protected) class member. If another thread is currently executing code within such a block, the current thread will be locked out until the other thread finishes. You can use jvisualvm's Threads tab or Jstack to take snapshots of the current execution state of all threads and the locks they're holding. If you're on android, see this answer on how to get a thread dump on there. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/28815505', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/655073/']} | jdg_78789 |
stackexchange | llm_judgeable_groundtruth_similarity | 2630199 |
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 say I want to find a formula for the following expression given $n$ number of threes$$\ldots(3(3(3(3(3(3+1)+2)+4)+8)+16)+\ldots$$If $A_0=1$, then$$A_{n+1}=3A_n+2^n$$Plugging in values to see the pattern,$$A_2 = 3+1$$$$A_3 = 3^2+3+2^1$$$$A_4 = 3^3+3^2+3\cdot2+2^2$$But I don't know how to condense something like this into an explicit formula.
Now provide the response and nothing else.
| One way to see the correct answer is to use that: $$x^n-y^n=(x-y)\left(x^{n-1}+x^{n-2}y+\cdots+xy^{n-2}+y^{n-1}\right)$$ Putting in $x=3,y=2$ you get that: $$3^n-2^n = 3^{n-1}+3^{n-2}\cdot2+\cdots+3\cdot 2^{n-2}+2^{n-1}$$ Now add $3^n$ to both sides, and you get: $$2\cdot 3^n -2^n = 3^{n}+3^{n-1}+3^{n-2}\cdot2+\cdots+3\cdot 2^{n-2}+2^{n-1}$$ There are more advanced techniques to solve this sort of equation generally, but this is a good "eyeball" solution without appeal to generating functions. The generating function approach is to write: $$f(z)=\sum_{n=0}^{\infty} A_nz^n = A_0 + z\sum_{n=1}^{\infty} (3A_{n-1}+2^{n-1})z^{n-1} = 1+z\left(3f(z)+\frac{1}{1-2z}\right)$$ Solving for $f(z)$ gives us $$f(z)=\frac{1}{1-3z}\left(1+\frac{z}{1-2z}\right)=\frac{1-z}{(1-2z)(1-3z)}$$ You can then use partial fractions to get that: $$f(z)=\frac{2}{1-3z}-\frac{1}{1-2z}$$ Thus giving $A_n=2\cdot 3^n-2^n.$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2630199', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/405572/']} | jdg_78790 |
stackexchange | llm_judgeable_groundtruth_similarity | 52696251 |
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 save all api logs in db.For example whenever a api gets hit, its request and response get saved in a table. Is there settings in Lavavel to enable logs of Rest apis into db. For example in codeigniter:Request param logs as :a:12:{s:13:"session_token";s:20:"OiCtWkqBLm6ScaSHOmQR";s:12:"Content-Type";s:16:"application/json";s:13:"cache-control";s:8:"no-cache";s:13:"Postman-Token";s:36:"0d13fe2e-9986-4ef2-ba46-8207dd28cd44";s:10:"User-Agent";s:20:"PostmanRuntime/7.1.1";s:6:"Accept";s:3:" / ";s:4:"Host";s:9:"localhost";s:6:"cookie";s:81:"PHPSESSID=ho1oa4gjll59u4vq9usct3lev7; ci_session=ruttt4i5144hob6feq3mrv080nh2n74o";s:15:"accept-encoding";s:13:"gzip, deflate";s:14:"content-length";s:2:"19";s:10:"Connection";s:10:"keep-alive";s:7:"user_id";i:13;}
Now provide the response and nothing else.
| If you want to build something yourself, terminable middleware is a great solution in Laravel. This type of middleware is executed after all the heavy work is done (request & reponses handled, etc.). Add a new model to store your LogEntries in. Create your migrations, etc. This is basis Laravel stuff I will not explain... :-) Then, to start off with the middleware, create a middleware class like this: $ php artisan make:middleware RequestLoggerMiddleware Add a body to the new class: class RequestLoggerMiddleware{ public function handle($request, Closure $next) { return $next($request); } public function terminate(Request $request, Response $response) { $logEntry = new LogEntry(); $logEntry->attribute = VALUE; $logEntry->attribute = VALUE; $logEntry->attribute = VALUE; $logEntry->attribute = VALUE; $logEntry->save(); }} Add the middleware to your Kernel.php: protected $middleware = [ ... RequestLoggerMiddleware::class, ...]; In the Middleware you can add tons of stuff to your attributes. The injected reponse and request have a lot of information in them: request start time >> date('Y-m-d H:i:s', LARAVEL_START) URL >> request->fullUrl() request HTTP method >> $request->method() request body >> json_decode($request->getContent(), true); request header >> $request->header(); ip >> $request->ip() status code >> $response->getStatusCode() request body >> json_decode($response->getContent(), true); BTW this is an EXAMPLE of a code structure you could use, to give you an basic idea about the solution. Obviously, you need to add the correct attributes to the model, the migrations, etc. But I am sure you can handle that part... And: inject the Model in the constructor instead the above example... :-) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/52696251', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8956012/']} | jdg_78791 |
stackexchange | llm_judgeable_groundtruth_similarity | 8762096 |
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 aware that we can integrate in-app purchases with storekit. but i want to integrate payments using credit card. will apple allow to integrate such libraries? Are there any such libraries available where users can use their credit card for payment of products with in my app?
Now provide the response and nothing else.
| Depending on what users are purchasing*, you should be just fine accepting payments in your app. Instead of trying to incorporate some type of payment library into the app I would recommend using a payment API that offloads the work. Take a look at http://stripe.com/ for an example of an excellent payment system designed for ease of integration. Their API reference even mentions integration with iPhone apps . *If you are trying to sell features or services of the app itself you will almost definitely be running afoul of Apple's guidelines, but based on the fact that you said "products" I am assuming this is not the case. In fact, while you must use the in-app purchase system for "content, functionality, or services in an app" you are specifically forbidden from using it for "physical goods or goods and services used outside of the application" (item 11.3 of Apple's App Store Review Guidelines). | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/8762096', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/265341/']} | jdg_78792 |
stackexchange | llm_judgeable_groundtruth_similarity | 67368 |
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:
For example:I want to select elements from a list {1,4,3,2,5} that are bigger than its previous element .{4,5} satisfies the criteria: 4 is greater than 1 and 5 is greater than 2(Ignore the first element). In general,Is there any simple way to select elements from a list that are satisfied a criteria which need to compare with other elements in the list?
Now provide the response and nothing else.
| @belisarius comment is pure genius, but if you need more flexibility for your criteria take a look at v10's amazing MovingMap list={1,4,3,2,5};(* Find elements greater than the one before *)Pick[Rest@list, MovingMap[#[[1]]<#[[2]]&,{1,4,3,2,5}, {2}]](* {4,5} *)(* Find elements smaller than the next one *)Pick[Most@list, MovingMap[#[[1]]<#[[2]]&,{1,4,3,2,5}, {2}]](* {1,2} *)(* Find a valley *)Pick[Rest@*Most@list, MovingMap[#[[1]]>#[[2]]<#[[3]]&,{1,4,3,2,5}, {3}]](* {2} *)(* Find a peak *)Pick[Rest@*Most@list, MovingMap[#[[1]]<#[[2]]>#[[3]]&,{1,4,3,2,5}, {3}]](* {4} *) You just have to mind the edges. You can either use a sensible padding or create a function that handles the special cases! | {} | {'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/67368', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/22018/']} | jdg_78793 |
stackexchange | llm_judgeable_groundtruth_similarity | 196161 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Here, $\mathbb{R}_l$ is the lower limit topology on $\mathbb{R}$ and $\mathbb{R}_K$ is the K-topology on $\mathbb{R}$. I understand the proof that these topologies are strictly finer than $\mathbb{R}$, but I am at a loss to begin how to show they aren't comparable. This is from Munkres book.
Now provide the response and nothing else.
| To show that they are not comparable, you just need to find an open set in each that is not open in the other. (As in Munkres, I will denote the set $\{ \frac{1}{n} : n \in \mathbb{Z}_+ \}$ by $K$.) The set $[2,3)$ is open in $\mathbb{R}_l$, but not in $\mathbb{R}_K$. $\mathbb{R} \setminus K$ is open in $\mathbb{R}_K$, but not in $\mathbb{R}_l$. (Every open set in $\mathbb{R}_l$ containing $0$ meets the set $K$.) | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/196161', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/39990/']} | jdg_78794 |
stackexchange | llm_judgeable_groundtruth_similarity | 610059 |
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:
Consider a set of five arbitrary 2x2 matrices. Can you always write one as a linear combination of the others? Explain. Repeat for five arbitrary 3x3 matrices. For each of the following sets explain whether or not the set is/could be a basis for the space mentioned.a) Four vectors in that form a loop when end-to-end connected. ............... Problem is i didnt understand the questions. For the first question : i know what linear combination is, but Do i have to find that five matrices? which can be linear combination of one another ? or is asking that whether any 5 matrices can be linear combination of one another or cant? For the second question: i have learned Standard basis of matrix, (actually learning) but there is no standard . Im just started learning and bit confused if any1 explain it little bit i will figure it out. Thanks
Now provide the response and nothing else.
| Recall that a function is supposed to be (properly) Riemann integrable if for all $\epsilon>0$ there exists a partition such that $U-L<\epsilon$. Suppose $f$ becomes unbounded (say, unbounded above) near the point $x_0$. How are we to make sense of the upper sum $U$ when one of the intervals in the partition (the one containing $x_0$) has no supremum? The definition only makes sense when $f$ is bounded. Nonetheless, if $f$ becomes unbounded near $x_0$, it still may be (improperly) Riemann integrable on an interval containing $x_0$. This is because we define the improper integral to be the limit of the proper integrals over the regions where we delete an open neighborhood of $x_0$, as we let that neighborhood get smaller and smaller. If someone describes a function as "Riemann integrable" on a set $S$, it may be ambiguous if they mean properly or improperly (technically they should mean the former), and one has to infer from context whether they are implying that the function is bounded. | {} | {'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/610059', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/116049/']} | jdg_78795 |
stackexchange | llm_judgeable_groundtruth_similarity | 28232945 |
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 CoffeeScript, Clojure, ES6 and many other languages we have destructuring of objects/maps/etc somewhat like this: obj = {keyA: 'Hello from A', keyB: 'Hello from B'}{keyA, keyB} = obj I've found the list function in php which lets you destructure arrays like so: $info = array('coffee', 'brown', 'caffeine');list($drink, $color, $power) = $info; Is there a way to destructure objects or associative arrays in PHP? If not in the core libs maybe someone wrote some smart helper function?
Now provide the response and nothing else.
| For PHP 7.0 and below that is beyond the functionality of list . The docs state: list only works on numerical arrays and assumes the numerical indices start at 0. One of the things that could suit your purpose would be the extract() function which imports variables from an array into the current symbol table. While with list you are able to define variable names explicitly, extract() does not give you this freedom. Extracting an associative array With extract you could do something like that: <?php$info = [ 'drink' => 'coffee', 'color' => 'brown', 'power' => 'caffeine' ];extract($info);var_dump($drink); // string(6) "coffee"var_dump($color); // string(5) "brown"var_dump($power); // string(8) "caffeine" Extracting an Object Extracting an object works almost the same. Since extract only takes an array as an argument we need to get the objects properties as an array. get_object_vars does that for you. It returns an associative array with all public properties as key and their values as value. <?phpclass User { public $name = 'Thomas';}$user = new User();extract( get_object_vars($user) );var_dump($name); // string(6) "Thomas" Pitfalls extract() is not the same as list since it does not allow you to explicitly define the variable names that get exported to the symbol table. The variable names correspond the array keys by default. list is a language construct while extract() is a function It might happen that you overwrite variables that you have defined beforehand unintentionally Your array keys might be invalid as variable names With the $flags parameter that you can pass as second argument to extract() you can influence the behavior in case of colliding or invalid variables. But still it's important to know how extract() works and to use it with cauton. Edit: As of PHP 7.1 this is possible: http://php.net/manual/en/migration71.new-features.php#migration71.new-features.support-for-keys-in-list You can now specify keys in list(), or its new shorthand [] syntax. This enables destructuring of arrays with non-integer or non-sequential keys. https://php.net/manual/en/migration71.new-features.php#migration71.new-features.symmetric-array-destructuring The shorthand array syntax ([]) may now be used to destructure arrays for assignments (including within foreach), as an alternative to the existing list() syntax, which is still supported. For example this: $test_arr = ['a' => 1, 'b' => 2];list('a' => $a, 'b' => $b) = $test_arr;var_dump($a);var_dump($b); Will output the following as of 7.1.0 int(1) int(2) | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/28232945', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/416797/']} | jdg_78796 |
stackexchange | llm_judgeable_groundtruth_similarity | 5614572 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Say I get this line of JSON [{u'status': u'active', u'due_date': None, u'group': u'later', u'task_id': 73286}] How can I convert those separate values to strings? So I can say Print Status And it returns active
Now provide the response and nothing else.
| That is NOT a "line of JSON" as received from an external source. It looks like the result of json.loads(external_JSON_string) . Also Print Status won't work; you mean print status . >>> result = [{u'status': u'active', u'due_date': None, u'group': u'later', u'task_id': 73286}]>>> print result[0]['status']active This is what a "line of JSON" looks like: >>> import json>>> json.dumps(result)'[{"status": "active", "due_date": null, "group": "later", "task_id": 73286}]'>>> EDIT: If using Python 2.5, use import simplejson as json instead of import json . Make your code a bit more future-proof by doing this: try: import jsonexcept ImportError: import simplejson as json | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5614572', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/585510/']} | jdg_78797 |
stackexchange | llm_judgeable_groundtruth_similarity | 1045334 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
The title is self-explanatory. Prove that $AB-BA = I$ has no solution in $M_{n\times n}(\mathbb R)$ without using matrix trace. A,B are both from $M_{n\times n}(\mathbb R)$ and $AB$ is matrix multiplication. I am aware that these matrices' traces coincide and hence $tr(AB-BA) = 0$, while $tr(I) = n$ but are there other ways to solve this?
Now provide the response and nothing else.
| We prove by induction that we have $A^nB-BA^n=nA^{n-1}$ for $n\geq 1$. (For $n=0$, we get $B-B=0$)For $n=1$ this is clear. Suppose that we have the result for $0\leq k\leq n$. By multipling by $A$ we get $A^{n+1}B-ABA^n=nA^n$ and $A^nBA-BA^{n+1}=nA^n$. Hence adding the two, we get$$A^{n+1}B-BA^{n+1}+A(A^{n-1}B-BA^{n-1})A=2nA^n$$and we finish easily. Now Let $M(x)$ the minimal polynomial of $A$, of degree $d\geq 1$. We get immediately that$$M(A)B-BM(A)=M^{\prime}(A)=0$$But this is a contradiction with the definition of the minimal polynomial. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1045334', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/26153/']} | jdg_78798 |
stackexchange | llm_judgeable_groundtruth_similarity | 31089265 |
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 wrestling with the Fish-Eye Camera Model used in OpenCV 3.0.0.dev . I have read the documentation in this link several times, especially the "Detailed Description" part and formulas modeling fish-eye distortion. By now I have two concerns: Based on the projection models listed here and their conceptual explanations in " Accuracy of Fish-Eye Lens Model " By Hughes, I can't figure out which projection model has been used in the OpenCV implementation. Since the description is so concise, I need to know the main reference papers used by OpenCV developers for implementing fish-eye namespace, so that I could be on the ball and get through more details. P.S. I checked OpenCV 3.0.0-dev documentation and did not find anything useful.
Now provide the response and nothing else.
| Short answer: OpenCV 3.0.0 Fisheye camera model doesn't use the Brown model nor any of the models that the OP refers from Panotools, it uses a Generic Camera Model by Juho Kannala and Sami S. Brandt. Detailed answer: As Cfr points in his answer, this comment from Ilya Krylov (who implemented the fisheye model in OpenCV) says they ported the Camera Calibration Toolbox for Matlab of Jean-Yves Bouguet: Jean-Yves Bouguet website ( link ), in turn, mentions the paper A Generic Camera Model and Calibration Method for Conventional, Wide-Angle, and Fish-Eye Lenses , and says : The "undocumented" fisheye model contained in the calibration toolbox follows the equidistance projection model described by equation (3) in this very nice paper. The distortion model follows equation (6), to the exception that k1=1 (otherwise indistinguishable from f). Which in my opinion is a misleading statement or a plain misconception as equation(3) and equation(6) correspond to different models: equation (6) is the actual model introduced in this paper which the authors refer as the Generic Camera Model (hence the name of the paper).To be more precise, equation (6) was meant to be used as the camera model and equation (8) and (9) as the "distortion" or deviation from this model. But the odyssey is not over. OpenCV's implementation (according to its documentation ) first computes the pinhole projection to find the field angle (the angle between the 3D point, the center of projection and the optical axis). This means you can't use their fisheye model to project rays at 90º (or you would divide by 0) or close to 90º (numerical stability problems, like overflow could happen if z is small enough).Moreover I'm not sure whether it will work for rays for more than 90º.All this makes me really wonder the "usefulness" of their fisheye camera model for fisheye or wide angle lenses. In case you're skeptic about that you can take a look at OpenCV's source code, concretely at sources\modules\calib3d\src\fisheye.cpp (I added some comments) void cv::fisheye::projectPoints(InputArray objectPoints, OutputArray imagePoints, InputArray _rvec,InputArray _tvec, InputArray _K, InputArray _D, double alpha, OutputArray jacobian){ ... Rodrigues(om, R, dRdom); Affine3d aff(om, T); ... Vec3d Xi = objectPoints.depth() == CV_32F ? (Vec3d)Xf[i] : Xd[i]; Vec3d Y = aff*Xi; /* To transform to camera reference frame*/ Vec2d x(Y[0]/Y[2], Y[1]/Y[2]); /* <- The root of all evil (division by z) */ double r2 = x.dot(x); double r = std::sqrt(r2); // Angle of the incoming ray: double theta = atan(r); double theta2 = theta*theta, theta3 = theta2*theta, theta4 = theta2*theta2, theta5 = theta4*theta, theta6 = theta3*theta3, theta7 = theta6*theta, theta8 = theta4*theta4, theta9 = theta8*theta; double theta_d = theta + k[0]*theta3 + k[1]*theta5 + k[2]*theta7 + k[3]*theta9; double inv_r = r > 1e-8 ? 1.0/r : 1; double cdist = r > 1e-8 ? theta_d * inv_r : 1; Vec2d xd1 = x * cdist; Vec2d xd3(xd1[0] + alpha*xd1[1], xd1[1]); Vec2d final_point(xd3[0] * f[0] + c[0], xd3[1] * f[1] + c[1]); ...} Update : This pull request fixes the problem with rays at angles ≥ 90º. As of April 2018 it hasn't been merged into master yet but is being considered for OpenCV 4.x Calibration Module (check calibration module discussion too) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/31089265', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5056004/']} | jdg_78799 |
stackexchange | llm_judgeable_groundtruth_similarity | 2461858 |
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 heard this problem from my friend today, but unfortunately we could not figure out what's happening here. $$x^{x^{\large x^{x^{\unicode{x22F0}}}}}=2$$$$x^2=2$$$$x=\sqrt2$$ but $$x^{x^{\large x^{x^{\unicode{x22F0}}}}}=4$$$$x^4=4$$$$x=\sqrt2$$ I have a feeling that this might be a duplicate, but I could not find this problem (basically I couldn't figure out what to search). So what's happening here, and what's the real value of$$\sqrt2^{\sqrt2^{\large \sqrt2^{\sqrt2^{\unicode{x22F0}}}}}$$ ?
Now provide the response and nothing else.
| Finding the value of an infinitely iterated function can be tricky. Usually, if $z$ is a fixed point of a function $f$ (that is, if $f(z)=z$), then it often happens that$$\lim_{n\to\infty} f^n(x)=z, \forall x$$...however, things tend to get a little bit complicated when $f$ has more than one fixed point, which is the case with your function$$f(x)=\sqrt 2^x$$that has fixed points$$f(2)=2$$$$f(4)=4$$In this case, the value of $f^\infty(x)$ depends on $x$, which doesn't really make sense given the way you wrote it. Basically this means that its value depends on the number "on top" of your power tower. For example, if you start with $4$, and observe the sequence$$a_0=4$$$$a_{n+1}=\sqrt 2^{a^n}$$then each $a_n=4$, and so$$a_{\infty}=\lim_{n\to\infty}a_n=\sqrt2^{\sqrt2^{\sqrt2^{\sqrt2^{\cdots}}}}=4$$However, if you take $a_0=1$,$$a_{\infty}=\lim_{n\to\infty}a_n=\sqrt2^{\sqrt2^{\sqrt2^{\sqrt2^{\cdots}}}}=2$$However, things are a little bit less complicated in this case, since $x=2$ turns out to be something called an "attracting fixed point". Basically, we end up with$$f^\infty\left(x\right) = \left\{ \begin{array}{lr} 2 & : x \lt 4\\ 4 & : x = 4\\ \infty & : x \gt 4\\ \end{array} \right.\\$$ | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/2461858', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/142634/']} | jdg_78800 |
stackexchange | llm_judgeable_groundtruth_similarity | 315033 |
Below is a question asked on the forum meta.stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I made one of my occasional forays into the review queues and failed this audit: https://stackoverflow.com/review/reopen/10929687 The question had 8 up votes but had been migrated and showed up as being migrated in the review. As such my natural inclination was to hit the "leave closed" option. However, this was "wrong" (in the eyes of the audit) because of the question score. So either: Migrated questions should be excluded from the audit process. or: The "[migrated]" in the title should be replaced by "[on hold]" and another reason substituted. or: Change the rules so that "leave closed" is the correct behaviour in this case.
Now provide the response and nothing else.
| Near as I can tell, this is a caching issue. The criteria for a "known-good" audit in the reopen queue are: Score between 5 and 15 (inclusive) Recently created No recent downvotes No bounties No close votes, ever Lots of views Not locked Not migrated Not closed Not deleted Items in bold are criteria that were met... Until two days ago when George migrated it to Code Review. That action immediately resulted in four changes to the state of the post which should've disqualified it. However, post IDs for audits are cached. It's possible that this particular post was cached prior to George closing it, and managed to stay in the cache for another day after it should've been disqualified. That... Seems pretty unlikely, but it's the only plausible cause I can come up with here. The solution would be to perform a sanity-check on audits prior to assigning them to a reviewer, similar to what's done for normal posts assigned in the reopen queue, discarding those that no longer qualify. | {} | {'log_upvote_score': 6, 'links': ['https://meta.stackoverflow.com/questions/315033', 'https://meta.stackoverflow.com', 'https://meta.stackoverflow.com/users/59303/']} | jdg_78801 |
stackexchange | llm_judgeable_groundtruth_similarity | 63469458 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Laziness is what kept Haskell pure. If it had been strict, purity would soon go out the window. I fail to see the connection between the evaluation strategy of a language and its purity. Considering the reputation of the tweet's author I am most certainly overlooking something. Maybe someone can shed some light.
Now provide the response and nothing else.
| You're right, from a modern POV this doesn't really make sense. What is true is that lazy-by-default would make reasoning about side-effectful code a nightmare, so lazyness does require purity – but not the other way around. What does require lazyness though is the way Haskell in versions 1.0–1.2, following its predecessor Miranda , emulated IO without monads. Short of any explicit notion of side-effect sequencing, the type of executable programs was main :: [Response] -> [Request] which would, for a simple interactive program, work something like this: main would at first just ignore its input list. So thanks to lazyness, the values in that list wouldn't actually need to exist, at that point. In the meantime it would produce a first Request value, e.g. a terminal prompt for the user to type something. What was typed would then come back as a Response value, which only now actually needed to be evaluated, giving rise to a new Request , etc. etc.. https://www.haskell.org/definition/haskell-report-1.0.ps.gz In version 1.3 they then switched to the monadic-IO interface that we all know and love today, and at that point lazyness wasn't really necessary anymore. But before that, common wisdom was that the only way to interact with the real world without lazyness was to allow side-effectful functions, thus the statement that without lazyness, Haskell would just have gone down the same path as Lisp and ML before it. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/63469458', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5536315/']} | jdg_78802 |
stackexchange | llm_judgeable_groundtruth_similarity | 2614809 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
What is the default values for members of a struct and members of a class in c++, and how do these rules differ (e.g. between classes/structs/primitives/etc) ? Are there circumstances where the rules about the default values differs ?
Now provide the response and nothing else.
| There are no differences between structs and classes in this regard in C++. They all are called just class types . Members of class types have no default values in general case. In order to for a class member to get a deterministic value it has to be initialized , which can be done by Default constructor of the member itself Constructor initializer list of the enclosing class Explicitly specified initializer for object of the enclosing class (that includes value-initialization and initialization with aggregate initializer). Additionally, all objects with static storage duration are zero-initialized at the program startup. Aside from the above cases, class members, once again, have no default values and will initially contain unpredictable garbage values. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/2614809', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/157404/']} | jdg_78803 |
stackexchange | llm_judgeable_groundtruth_similarity | 2454214 |
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 find smart pointers to be a lot more comfortable than raw pointers. So is it a good idea to always use smart pointers? ( Please note that I am from Java background and hence don't much like the idea of explicit memory management. So unless there are some serious performance issues with smart pointers, I'd like to stick with them. ) Note: Though I come from Java background, I understand the implementation of smart pointers and the concepts of RAII quite well. So you can take this knowledge for granted from my side when posting an answer. I use static allocation almost everywhere and use pointers only when necessary. My question is merely: Can I always use smart pointers in place of raw pointers???
Now provide the response and nothing else.
| Given the several edits, I have the impression that a comprehensive summary would be useful. 1. When not to There are two situations where you should not use smart pointers. The first is the exact same situation in which you should not use a C++ class in fact. IE: DLL boundary if you do not offer the source code to the client. Let say anecdotal. The second happens much more often: smart manager means ownership . You may use pointers to point at existing resources without managing their lifetime, for example: void notowner(const std::string& name){ Class* pointer(0); if (name == "cat") pointer = getCat(); else if (name == "dog") pointer = getDog(); if (pointer) doSomething(*pointer);} This example is constrained. But a pointer is semantically different from a reference in that it may point to an invalid location (the null pointer). In this case, it's perfectly fine not to use a smart pointer in its stead, because you don't want to manage the lifetime of the object. 2. Smart managers Unless you are writing a smart manager class, if you use the keyword delete you are doing something wrong. It is a controversial point of view, but after having reviewed so many example of flawed code, I don't take chances any longer. So, if you write new you need a smart manager for the newly allocated memory. And you need it right now. It does not mean you are less of a programmer! On the contrary, reusing code that has been proved to work instead of reinventing the wheel over and over is a key skill. Now, the real difficulty start: which smart manager ? 3. Smart pointers There are various smart pointers out of there, with various characteristics. Skipping std::auto_ptr which you should generally avoid (its copy semantic is screwed). scoped_ptr : no overhead, cannot be copied or moved. unique_ptr : no overhead, cannot be copied, can be moved. shared_ptr / weak_ptr : some overhead (reference counting), can be copied. Usually, try to use either scoped_ptr or unique_ptr . If you need several owners try to change the design. If you can't change the design and really need several owners, use a shared_ptr , but beware of references cycles that ought to be broken using a weak_ptr somewhere in the midst. 4. Smart containers Many smart pointers are not meant to be copied, therefore their use with the STL containers are somewhat compromised. Instead of resorting to shared_ptr and its overhead, use smart containers from the Boost Pointer Container . They emulate the interface of classic STL containers but store pointers they own. 5. Rolling your own There are situations when you may wish to roll your own smart manager. Do check that you did not just missed some feature in the libraries your are using beforehand. Writing a smart manager in the presence of exceptions is quite difficult. You usually cannot assume that memory is available ( new may fail) or that Copy Constructor s have the no throw guarantee. It may be acceptable, somewhat, to ignore the std::bad_alloc exception and impose that Copy Constructor s of a number of helpers do not fail... after all, that's what boost::shared_ptr does for its deleter D template parameter. But I would not recommend it, especially for a beginner. It's a tricky issue, and you're not likely to notice the bugs right now. 6. Examples // For the sake of short code, avoid in real code ;)using namespace boost;// Example classes// Yes, clone returns a raw pointer...// it puts the burden on the caller as for how to wrap it// It is to obey the `Cloneable` concept as described in // the Boost Pointer Container library linked abovestruct Cloneable{ virtual ~Cloneable() {} virtual Cloneable* clone() const = 0;};struct Derived: Cloneable{ virtual Derived* clone() const { new Derived(*this); }};void scoped(){ scoped_ptr<Cloneable> c(new Derived);} // memory freed here// illustration of the moved semanticsunique_ptr<Cloneable> unique(){ return unique_ptr<Cloneable>(new Derived);}void shared(){ shared_ptr<Cloneable> n1(new Derived); weak_ptr<Cloneable> w = n1; { shared_ptr<Cloneable> n2 = n1; // copy n1.reset(); assert(n1.get() == 0); assert(n2.get() != 0); assert(!w.expired() && w.get() != 0); } // n2 goes out of scope, the memory is released assert(w.expired()); // no object any longer}void container(){ ptr_vector<Cloneable> vec; vec.push_back(new Derived); vec.push_back(new Derived); vec.push_back( vec.front().clone() // Interesting semantic, it is dereferenced! );} // when vec goes out of scope, it clears up everything ;) | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/2454214', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/288133/']} | jdg_78804 |
stackexchange | llm_judgeable_groundtruth_similarity | 23700941 |
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 do a full responsive navbar with specified height in Twitter Bootstrap 3.1.1, where the brand could consists of image (logo) or text. html: <nav class="navbar navbar-inverse navbar-fixed-top" role="navigation"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#"> <img src="http://placehold.it/150x50&text=Logo" alt=""> </a> </div> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav navbar-right"> <li><a href="#">About</a></li> <li><a href="#">Services</a></li> <li><a href="#">Contact</a></li> </ul> </div> </div></nav> css: body { margin-top: 125px;}.navbar-fixed-top .nav { padding: 15px 0;} The problem is that after the browser's window size is decreased and menu is collapsed, navbar returns to its original height and logo image is as below: The other problem is that changing <img src="http://placehold.it/150x50&text=Logo" alt=""> into <h3>AppName</h3> makes that AppName is not in the middle: Currently it is centered by setting padding values, but I do not know how to make it independent from it. Does anyone could help me solve this problem? Regards EDIT: Here are prepared images of effect that I want to achieve: not collapsed navbar with logo image: collapsed navbar (the same height of navbar, the same size of image, but different width od navbar): not collapsed navbar with brand name text: collapsed navbar (everything is the same except width of navbar caused by changing browser's window width):
Now provide the response and nothing else.
| If you want to achieve this (you can resize the window to see how it will look for mobile version), all you have to do is to have 2 logo images (1 for desktop and one for mobile) and display them depending of the enviroment using visible-xs and hidden-xs classes. So i used something like this: <img class="hidden-xs" src="http://placehold.it/150x50&text=Logo" alt=""><img class="visible-xs" src="http://placehold.it/120x40&text=Logo" alt=""> And ofcourse, i styled the mobile logo using: @media (max-width: 767px) { .navbar-brand { padding: 0; } .navbar-brand img { margin-top: 5px; margin-left: 5px; }} You can see all the code here . In case you need a text on mobile version insted of the logo, it's not a big deal. Just replace the logo with a <h1 class="visible-xs">AppName</h3> and change the style inside the media query like this: @media (max-width: 767px) { .navbar-brand { padding: 0; } .navbar-brand h1{ //here add your style depending of the position you want the text to be placed }} EDIT: You need this conditions to make it work: .navbar-toggle { margin: 23px 0; }.navbar-nav, .navbar-nav li, .navbar-nav li a { height: 80px; line-height: 80px;}.navbar-nav li a { padding-top: 0; padding-bottom:0;} | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/23700941', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2199497/']} | jdg_78805 |
stackexchange | llm_judgeable_groundtruth_similarity | 17438475 |
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 my function to return both an error code and a string value, so plan to use return to return the error code and use a parameter to return the string value. But it doesn't work. Looks like we can't return a value from function parameter. Any idea how to return it from function parameter? Below is a sample code. I hope to get the retVal from sayHello's parameter. function sayHello(name, retVal) { retVal = "hello " + name; return 1;}
Now provide the response and nothing else.
| You can probably do this way, pass an object back. function sayHello(name) { retVal = "hello " + name; return {code: 1, message: retVal};}//And while callingvar returnVal= sayHello("something");var code = returnVal.code;var msg= returnVal.message; Reason why retVal is nt available outside is because of variable hoisting in the scope inside the function. But you can also work around that by not passing it in as argument. var retVal; //Define it in an outer scope.function sayHello(name) { retVal = "hello " + name; return 1;}var returnVal= sayHello("something");alert(returnVal);alert(retVal); //Now get it here. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17438475', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1865603/']} | jdg_78806 |
stackexchange | llm_judgeable_groundtruth_similarity | 54641021 |
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 reduced my code to this simple example that just returns a promise function. The error TypeScript 3.2 gives me is: Error:(1, 7) TS2739: Type '() => Promise<{}>' is missing the following properties from type 'Promise<{ hasErrored: boolean; }>': then, catch, [Symbol.toStringTag] The associated code is const fetchUserInfoPromise1: Promise<{ hasErrored: boolean }> = () => { return new Promise(function(resolve) { resolve({ id: 1, name: 'peter' }); });};export default fetchUserInfoPromise1;
Now provide the response and nothing else.
| Firstly, fetchUserInfoPromise1 is a function that returns a Promise , not a Promise itself. const fetchUserInfoPromise1 = (): Promise<{ hasErrored: boolean }> => { /* ... */ } Secondly, the type parameter used in your return type definition must match the one that is being resolved. The returned Promise is supposed to resolve with an object { hasErrored: boolean } , yet it resolves with { id: number, name: string } . You need to decide what you want to accomplish. Example: const fetchUserInfoPromise1 = (): Promise<{ id: number, name: string }> => { return new Promise(function (resolve) { resolve({ id: 1, name: 'peter' }); });}; | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/54641021', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/46942/']} | jdg_78807 |
stackexchange | llm_judgeable_groundtruth_similarity | 4055339 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Ok, this should be easy... I'm new to groovy and I'm looking to implement the following logic: def testFiles = findAllTestFiles(); So far, I've come up with the code below which successfully prints all files names. However, instead of printing, I just need to put them into a collection. Of course, I could do this the old java way: just instantiate a collection, add all the elements and return it. However, that wouldn't teach me anything. So how do you do this the cool, "Groovy" way? static File[] findAllTestFiles() { def directory = new File("src/test/java"); def closure = {File f -> if(f.name =~ /Test\.java$/) println f } directory.eachFileRecurse FileType.FILES, closure return null;} I'm looking to implement findAlltestFiles() in Groovy using as little code as possible while still being readable.
Now provide the response and nothing else.
| I'd try to avoid building the collection entirely. Using closures, you can separate the logic to select the files from what you actually want to do with them, like so: import groovy.io.FileTypedef withEachTestFile(Closure closure) { new File("src/test/java").eachFileRecurse(FileType.FILES) { if (it.name =~ /Test\.java$/) { closure.call(it) } }} Then if you want to do something on the test files, you can do it directly without building up a list in memory: withEachTestFile() { println it } or if you really want the list, you can easily generate it, using whatever collection makes sense: def files = []withEachTestFile() { files << it } | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4055339', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/178433/']} | jdg_78808 |
stackexchange | llm_judgeable_groundtruth_similarity | 2534630 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm having some trouble passing a number as an argument for a method: - (void)meth2:(int)next_int; And to call that method I need this: int next_int = 1;[self performSelectorOnMainThread:@selector(meth2:) withObject:next_int waitUntilDone:NO];//update next_int and call meth2 again at this point, I get a "pointer from integer without a cast" error and would happen the same with a NSInteger . An NSNumber is not useful because it's immutable and I need to change the value constantly.Any idea how can I do this? Thanks.
Now provide the response and nothing else.
| If you're just trying to call the method, you could use the standard syntax: [self meth2:next_int]; If you really need to use the performSelectorOnMainThread: you could wrap the number in an NSNumber for the call. You say you can't do this because you need to change the number, but you can just pull an int out and change that: [self performSelectorOnMainThread:@selector(meth2:) withObject:[NSNumber numberWithInt:next_int] waitUntilDone:NO];// ... later ...- (void)meth2:(NSNumber *)number { int myInt = [number intValue]; // do stuff with myInt} But maybe you mean that you want to get the value of the number as an output from your call to meth2 . If that's what you mean, then you could pass in a double pointer so you can receive a new object back: - (void)meth2:(NSNumber **)number { int myInt = [*number intValue]; // do stuff with myInt *number = [NSNumber numberWithInt:myInt];}// The caller can now operate like this:NSNumber *number = [NSNumber numberWithInt:next_int];[self performSelectorOnMainThread:@selector(meth2:) withObject:&number waitUntilDone:YES];int returnInt = [*number intValue]; Of course, that's not really thread-safe, so if you're doing stuff with multiple threads, I would advise using the @synchronized keyword for access to multi-thread-accessed variables, or setting up atomic properties (i.e. properties not declared as nonatomic ). Also, meth is bad for you!! haha | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2534630', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/301431/']} | jdg_78809 |
stackexchange | llm_judgeable_groundtruth_similarity | 839608 |
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 I continue from $A(AB) = (BA)A = I$ and how can we justify it if we don't know that $AB=BA$? EDIT: Also, how can we prove that if $AB=I$ then $ BA = I$? This is seperate from the question above but I felt it didn't need a new post.
Now provide the response and nothing else.
| The thing is that for matrices over a field, $XY=I_n$ implies $YX=I_n$. You've already seen that $A$ is a left inverse for $AB$, and that implies it is also a right inverse ( the inverse) for $AB$. Added: For a complete explanation of this, check out this question: If $AB = I$ then $BA = I$ Another way to do it would be completely with determinants, if you're willing. Supposing you are happy to conclude a nonzero determinant means a matrix is invertible, then $\det(A^2B)=\det(A)^2\det(B)=1$ should convince you $\det(AB)\neq 0$, so that $AB$ is invertible. Thus the one sided inverse $A$ is twosided. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/839608', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/157655/']} | jdg_78810 |
stackexchange | llm_judgeable_groundtruth_similarity | 7223359 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Reading through the ECMAScript 5.1 specification , +0 and -0 are distinguished. Why then does +0 === -0 evaluate to true ?
Now provide the response and nothing else.
| JavaScript uses IEEE 754 standard to represent numbers. From Wikipedia : Signed zero is zero with an associated sign. In ordinary arithmetic, −0 = +0 = 0. However, in computing, some number representations allow for the existence of two zeros, often denoted by −0 (negative zero) and +0 (positive zero) . This occurs in some signed number representations for integers, and in most floating point number representations. The number 0 is usually encoded as +0, but can be represented by either +0 or −0. The IEEE 754 standard for floating point arithmetic (presently used by most computers and programming languages that support floating point numbers) requires both +0 and −0. The zeroes can be considered as a variant of the extended real number line such that 1/−0 = −∞ and 1/+0 = +∞, division by zero is only undefined for ±0/±0 and ±∞/±∞. The article contains further information about the different representations. So this is the reason why, technically, both zeros have to be distinguished. However, +0 === -0 evaluates to true. Why is that (...) ? This behaviour is explicitly defined in section 11.9.6 , the Strict Equality Comparison Algorithm (emphasis partly mine): The comparison x === y , where x and y are values, produces true or false . Such a comparison is performed as follows: (...) If Type(x) is Number, then If x is NaN, return false. If y is NaN, return false. If x is the same Number value as y, return true. If x is +0 and y is −0, return true. If x is −0 and y is +0, return true. Return false. (...) (The same holds for +0 == -0 btw.) It seems logically to treat +0 and -0 as equal. Otherwise we would have to take this into account in our code and I, personally, don't want to do that ;) Note: ES2015 introduces a new comparison method, Object.is . Object.is explicitly distinguishes between -0 and +0 : Object.is(-0, +0); // false | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/7223359', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/707381/']} | jdg_78811 |
stackexchange | llm_judgeable_groundtruth_similarity | 97602 |
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:
How can I list all dotfiles in a directory using zsh.?
Now provide the response and nothing else.
| The classic way we used to do it back in the day was: ls .??* This would list all dotfiles but not include . or .. . Of course, whomever came up with this assumed that all dotfiles would be named with two or more characters after the . . The other weakness is if you have directories that start with . then that command will list the contents of it. That aspect can be fixed by using the -d flag for ls . That tells ls to just show any directories specified on the command line without delving into them. Nowadays, most versions of ls include the -A flag which will list all dotfiles in the directory but excluding . or .. . And you don't have to worry about putting a -d flag on there. | {} | {'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/97602', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/49953/']} | jdg_78812 |
stackexchange | llm_judgeable_groundtruth_similarity | 429217 |
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 think I understand the amount of homomorphisms $C_6$ to $S_5$: Because $C_6$ is cyclic, we only have to look where we can send $\langle a\rangle$, because $f(\langle a\rangle)$ must have order $1, 2, 3$, or $6$ we have: -for $1$: trivial homomorphism. -for $2$: the ten $(xy)$ cycles in $S_5$, the fifteen $(xy)(ab)$ cycles in $S_5$ -for $3$: the twenty $(xyz)$ cycles in $S_5$ -for $6$: the twenty $(xyz)(ab)$ cycles in $S_5$ so total $= 66$ the other way around I find more difficult. Can anyone help? Bonus question: is the size of the conjugacy class of an element in the group always the amount of elements of the same shape? so in $S_5$, $(12)$ has conjugacy class size 10, so there are ten $(xy)$ in $S_5$?
Now provide the response and nothing else.
| The kernel of a homomorphism $f: S_5 \rightarrow C_6$ must be a normal subgroup of $S_5$. There are only three such: $S_5, A_5$ and $\{1\}$. Since $|S_5| > |C_6|$ we cannot have $\ker f = \{1\}$. If $\ker f = S_5$ then $f$ just sends everything to the identity. If $\ker f = A_5$ then by first isomorphism theorem im$f \cong C_2$, which there is only one copy of inside $C_6$, so we have $f(a) = g^3$ if $a \notin A_5$, $f(a) = 1$ if $a \in A_5$. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/429217', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/79915/']} | jdg_78813 |
stackexchange | llm_judgeable_groundtruth_similarity | 4537994 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a string like: $Order_num = "0982asdlkj"; How can I split that into the 2 variables, with the number as one element and then another variable with the letter element? The number element can be any length from 1 to 4 say and the letter element fills the rest to make every order_num 10 characters long in total. I have found the php explode function...but don't know how to make it in my case because the number of numbers is between 1 and 4 and the letters are random after that, so no way to split at a particular letter.
Now provide the response and nothing else.
| You can use preg_split using lookahead and lookbehind : print_r(preg_split('#(?<=\d)(?=[a-z])#i', "0982asdlkj")); prints Array( [0] => 0982 [1] => asdlkj) This only works if the letter part really only contains letters and no digits. Update: Just to clarify what is going on here: The regular expressions looks at every position and if a digit is before that position ( (?<=\d) ) and a letter after it ( (?=[a-z]) ), then it matches and the string gets split at this position. The whole thing is case-insensitive ( i ). | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4537994', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/533617/']} | jdg_78814 |
stackexchange | llm_judgeable_groundtruth_similarity | 17055199 |
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 URI that contains ## (e.g. http://foo.com/bar##baz ) . Ruby's URI.parse function throws an error when I try to parse it. Are double hash marks forbidden in URIs? Or is the Ruby Parser too strict?
Now provide the response and nothing else.
| Fragment Identifiers may not contain a hash sign. The parser is correct. The syntax for a fragment identifier is defined as follows: fragment = *( pchar / "/" / "?" ) pchar is defined as : pchar = unreserved / pct-encoded / sub-delims / ":" / "@" unreserved , pct-encoded and sub-delims are defined as: unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"pct-encoded = "%" HEXDIG HEXDIGsub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "=" | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17055199', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/654619/']} | jdg_78815 |
stackexchange | llm_judgeable_groundtruth_similarity | 38371 |
Below is a question asked on the forum astronomy.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
When you check an entry of the Gaia DR2 stellar catalogue in Vizier, for example this one , you can see that there is a value for the G magnitude (in our case 18.0733 mag) and a value for the uncertainty on that (in our case 0.0023 mag). The thing is that the G value is part of Gaia DR2 but the uncertainty is not, it was calculated by the CDS for Vizier (using the values presented for the flux as far as I can understand). I have two small related questions: How does the CDS calculate the value from the uncertainty exactly? at least so that the one given by the CDS and the calculated one agree to the fourth decimal. Is there a way in astropy or astroquery to retrieve the photometric uncertainty value from the catalog? Or do I have to calculate it as in the first question? Thank you in advance.
Now provide the response and nothing else.
| That is because what is measured is a flux and the flux errors are in the DR2 catalogue. Since magnitudes are based on the logarithm of the flux, then there is no straightforward correspondence (although it matters little if the error bars are less than a few hundredths if a magnitude). Simple error propagation formulae give $$|\Delta G| \simeq \frac{2.5}{\ln 10} \left(\frac{\Delta f}{f}\right),$$ where $f$ is the flux in the G band. This gives $\Delta G= 0.0023(1)$ for your example. Other algorithms give almost the same result, e.g. taking the average of the $\pm \Delta G$ from using $\pm \Delta f$ to calculate the magnitude. If the difference between the algorithms (they do give differing results when the flux error exceeds $\sim 10$ %), or the fact that the true error is asymmetric in magnitude are important, then you shouldn't be using the symmetric magnitude error bar from CDS. | {} | {'log_upvote_score': 4, 'links': ['https://astronomy.stackexchange.com/questions/38371', 'https://astronomy.stackexchange.com', 'https://astronomy.stackexchange.com/users/28496/']} | jdg_78816 |
stackexchange | llm_judgeable_groundtruth_similarity | 12236743 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Can anyone point me to an example of how to use a Map in Groovy which has a String as its key and a List as value?
Now provide the response and nothing else.
| Groovy accepts nearly all Java syntax, so there is a spectrum of choices, as illustrated below: // Java syntax Map<String,List> map1 = new HashMap<>();List list1 = new ArrayList();list1.add("hello");map1.put("abc", list1); assert map1.get("abc") == list1;// slightly less Java-esquedef map2 = new HashMap<String,List>()def list2 = new ArrayList()list2.add("hello")map2.put("abc", list2)assert map2.get("abc") == list2// typical Groovydef map3 = [:]def list3 = []list3 << "hello"map3.'abc'= list3assert map3.'abc' == list3 | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/12236743', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/555825/']} | jdg_78817 |
stackexchange | llm_judgeable_groundtruth_similarity | 4345285 |
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 <div> in my page which contains a <table> of varying number of rows, i.e varying height: <html><head></head><body><div> <table> <tr>... <tr>... ... </table></div></body></html> At the moment if the table content is long enough, the div extends below the bottom of the page (view port). I want to stop the div extending below the bottom of the page, and add a scroll bar. I can add scroll bars if the div height is fixed no problem with overflow: scroll . But I want the div height to fit to however the user has sized his browser window. Any ideas how to achieve this? I do not care or need the div to extend to the bottom of the page if there is no table content. Preferably a pure css solution as opposed to using javascript to fix the div height. Thanks
Now provide the response and nothing else.
| How about a wrapper with overflow auto and some 100% trickery. I.e. some variant of this: <!DOCTYPE HTML> <html lang="en"> <head> <meta charset="utf-8"/> <title>100% thing</title> <style> * { margin: 0; padding: 0; } html, body { height: 100%; overflow: hidden; } #wrapper { height: 100%; width: 200px; overflow: auto; } </style> </head> <body> <div id="wrapper"> <div id="content"> <p>To Sherlock Holmes she is always <i>the</i> woman. I have seldom heardhim mention her under any other name. In his eyes she eclipsesand predominates the whole of her sex. It was not that he feltany emotion akin to love for Irene Adler. All emotions, and thatone particularly, were abhorrent to his cold, precise butadmirably balanced mind. He was, I take it, the most perfectreasoning and observing machine that the world has seen, but as alover he would have placed himself in a false position. He neverspoke of the softer passions, save with a gibe and a sneer. Theywere admirable things for the observer—excellent for drawing theveil from men’s motives and actions. But for the trained reasonerto admit such intrusions into his own delicate and finelyadjusted temperament was to introduce a distracting factor whichmight throw a doubt upon all his mental results. Grit in asensitive instrument, or a crack in one of his own high-powerlenses, would not be more disturbing than a strong emotion in anature such as his. And yet there was but one woman to him, andthat woman was the late Irene Adler, of dubious and questionablememory.<p> I had seen little of Holmes lately. My marriage had drifted usaway from each other. My own complete happiness, and thehome-centred interests which rise up around the man who firstfinds himself master of his own establishment, were sufficient toabsorb all my attention, while Holmes, who loathed every form ofsociety with his whole Bohemian soul, remained in our lodgings inBaker Street, buried among his old books, and alternating fromweek to week between cocaine and ambition, the drowsiness of thedrug, and the fierce energy of his own keen nature. He was still,as ever, deeply attracted by the study of crime, and occupied hisimmense faculties and extraordinary powers of observation infollowing out those clues, and clearing up those mysteries whichhad been abandoned as hopeless by the official police. From timeto time I heard some vague account of his doings: of his summonsto Odessa in the case of the Trepoff murder, of his clearing upof the singular tragedy of the Atkinson brothers at Trincomalee,and finally of the mission which he had accomplished sodelicately and successfully for the reigning family of Holland.Beyond these signs of his activity, however, which I merelyshared with all the readers of the daily press, I knew little ofmy former friend and companion.<p> One night—it was on the twentieth of March, 1888—I wasreturning from a journey to a patient (for I had now returned tocivil practice), when my way led me through Baker Street. As Ipassed the well-remembered door, which must always be associatedin my mind with my wooing, and with the dark incidents of theStudy in Scarlet, I was seized with a keen desire to see Holmesagain, and to know how he was employing his extraordinary powers.His rooms were brilliantly lit, and, even as I looked up, I sawhis tall, spare figure pass twice in a dark silhouette againstthe blind. He was pacing the room swiftly, eagerly, with his headsunk upon his chest and his hands clasped behind him. To me, whoknew his every mood and habit, his attitude and manner told theirown story. He was at work again. He had risen out of hisdrug-created dreams and was hot upon the scent of some newproblem. I rang the bell and was shown up to the chamber whichhad formerly been in part my own. </div> </div> </body> </html> See a demonstration at jsFiddle . | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/4345285', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/183579/']} | jdg_78818 |
stackexchange | llm_judgeable_groundtruth_similarity | 1734618 |
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 CSS, when text has text-decoration:underline applied, is it possible to increase the distance between the text and the underline?
Now provide the response and nothing else.
| No, but you could go with something like border-bottom: 1px solid #000 and padding-bottom: 3px . If you want the same color of the "underline" (which in my example is a border), you just leave out the color declaration, i.e. border-bottom-width: 1px and border-bottom-style: solid . For multiline, you can wrap you multiline texts in a span inside the element. E.g. <a href="#"><span>insert multiline texts here</span></a> then just add border-bottom and padding on the <span> - Demo | {} | {'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/1734618', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/35026/']} | jdg_78819 |
stackexchange | llm_judgeable_groundtruth_similarity | 388439 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Java 5 introduced generics, and they were added to many interfaces in the java.lang package. However, Cloneable did not get generics. I wonder why? Edit: In reply to the answers of @Jon and @litb, and the comment of @Earwicker, I was thinking Cloneable might be: public interface Cloneable<T> { public T clone();} Here T clone(); overrides Object.clone() , giving it a covariant type. I believe this would still be backwards compatible and increase type safety. So why not? Edit 2: As can be seen in the answers (and comments) below, the interface suggested above would break backwards-compatibility. Since Object.clone() is protected , rewriting it in the interface would force all implementers to provide a public implementation, which class designers might not want to (i.e. they might opt to keep it protected ).
Now provide the response and nothing else.
| The Cloneable interface doesn't contain any members. What would be the point of making it generic? (If Cloneable contained the clone() method, it would make sense - but that's declared in java.lang.Object.) EDIT: clone() is in java.lang.Object as it has an implementation (which does a field-by-field copy). A better design would be to have something like .NET's MemberwiseClone() as a protected method in Object, and then a public clone() method within the interface itself. I don't know why that design wasn't chosen. (In .NET, ICloneable isn't generic because it existed before generics - the different nature of .NET generics prevents a previously non-generic type from becoming generic.) In both Java and .NET, however, the "normal" cloning API is generally regarded as a bad thing, as it says nothing about what depth of cloning should be performed. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/388439', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/41283/']} | jdg_78820 |
stackexchange | llm_judgeable_groundtruth_similarity | 42270278 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am trying to create a pod with 2 containers each having different images! Am not sure how to expose the two different containers to the client. Following is my yaml file for deployment. apiVersion: extensions/v1beta1kind: Deploymentmetadata: name: checkdifimagespec: replicas: 1 template: metadata: labels: app: checkdifimagelabspec: containers: - name: checkallcont1 image: <dockerimage> ports: - containerPort: 32030 - name: checkall1cont2 image: <dockerimage2> ports: - containerPort: 32031 What am currently doing is after I have the deployment up. I run the following command to expose the service : kubectl expose pod checkdifimage --port=8080 --type=NodePort --name=diffimage This works for a single container and am able to hit the service from a rest client. But when I use 2 containers, i am only able to hit one container. How should I proceed to hit both the containers? Also, if someone can please guide on what are the advantages and disadvantages of using one pod having one image vs one pod having multiple images!
Now provide the response and nothing else.
| You have multiple Options: Create multiple services exposing one port each, on the same deployment. Create single service exposing multiple ports: ---kind: ServiceapiVersion: v1metadata: name: my-servicespec: selector: app: MyApp ports: - name: http protocol: TCP port: 80 targetPort: 9376 - name: https protocol: TCP port: 443 targetPort: 9377 Using kubectl expose: kubectl expose service nginx --port=443 --target-port=8443 --name=nginx-https Note that if no port is specified via –port and the exposed resource has multiple ports, all will be re-used by the new service. Also if no labels are specified, the new service will re-use the labels from the resource it exposes. Source When to use multi container pods:A pod is a group of one or more containers, the shared storage for those containers, and options about how to run the containers. Pods are always co-located and co-scheduled , and run in a shared context. A pod models an application-specific “logical host” - it contains one or more application containers which are relatively tightly coupled — in a pre-container world, they would have executed on the same physical or virtual machine. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/42270278', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4915693/']} | jdg_78821 |
stackexchange | llm_judgeable_groundtruth_similarity | 1863158 |
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 could I create similar structure to handle Win32 Messages like it is in MFC? In MFC; BEGIN_MESSAGE_MAP(CSkinCtrlTestDlg, CDialog) //{{AFX_MSG_MAP(CSkinCtrlTestDlg) ON_BN_CLICKED(IDC_BROWSE, OnBrowse) ON_BN_CLICKED(IDC_DEFAULTSKIN, OnChangeSkin) ON_WM_DRAWITEM() ON_WM_MEASUREITEM() ON_WM_COMPAREITEM() ON_BN_CLICKED(IDC_CHECK3, OnCheck3) //}}AFX_MSG_MAPEND_MESSAGE_MAP() BEGIN_MESSAGE_MAP macro handles this behaviour. What to do for pure Win32?
Now provide the response and nothing else.
| Here is a breif summary of the code I use to do this in the Zeus programmer's editor: Step 1: Define a couple of message structure to hold the Windows message details: typedef struct{ MSG msg; LRESULT lResult;} xMessage;struct xWM_COMMAND{ HWND hwnd; UINT Msg; WORD ItemID; WORD NotifyCode; HWND Ctl; LRESULT lResult;};//-- unpack a message buffer#define MSG_UNPACK(var, id, msg) x##id *var = (x##id *)(msg); Step 2: Define a base window class with a few special methods: class xWindow{protected: //-- windows callback function static LRESULT CALLBACK wndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam); //-- a message dispatch method void dispatch(HWND hwnd, UINT uMessageID, WPARAM wParam, LPARAM lParam, LRESULT &Result); //-- method for command message dispatching virtual void dispatchToCmdMap(xMessage *pMessage); //-- method for windows message dispatching virtual void dispatchToMsgMap(xMessage *pMessage);}; Step 3: Define a few macros to do the dispatching of the Windows messages: #define BEGIN_MSG_MAP \ protected: \ virtual void dispatchToMsgMap(xMessage *msg)\ { \ if (msg->msg.message == WM_NULL) \ { \ return; \ }#define MSG_HANDLER(meth, wm_msg) \ else if (msg->msg.message == wm_msg) \ { \ this->meth(msg); \ return; \ }#define END_MSG_MAP(base) \ else if (msg->msg.message == WM_COMMAND) \ { \ this->dispatchToCmdMap(msg); \ return; \ } \ else if (msg->msg.message == WM_NOTIFY) \ { \ this->dispatchToNotifyMap(msg); \ return; \ } \ \ base::dispatchToMsgMap(msg); \ };#define BEGIN_CMD_MAP \ virtual void dispatchToCmdMap(xMessage *msg)\ { \ MSG_UNPACK(Cmd, WM_COMMAND, msg); \ \ if (Cmd->ItemID == 0) \ { \ /* not allowed */ \ } #define CMD_HANDLER(meth, cmd_id) \ else if (Cmd->ItemID == cmd_id) \ { \ this->meth(Cmd->ItemID); \ } #define END_CMD_MAP(base) \ else \ { \ base::dispatchToCmdMap(msg); \ } \ }; Step 4: Define the dispatcher method: void xWindow::dispatch(HWND, UINT uMessageID, WPARAM wParam, LPARAM lParam, LRESULT &Result){ xMessage message; //-- build up a message packet message.msg.message = uMessageID; message.msg.wParam = wParam; message.msg.lParam = lParam; message.lResult = 0; //-- dispatch the message this->dispatchToMsgMap(&message);} Step 5: Define the static window procedure method ( NOTE: this method will need to be used as the Window procedure of the window class when the class is first registered): LRESULT CALLBACK xWindow::wndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam){ LRESULT lResult = 0; //-- look for the creation message if (msg == WM_NCCREATE) { CREATESTRUCT *pCreateData = (CREATESTRUCT*)lParam; //-- get the window object passed in xWindow *pWindow = (xWindow)pCreateData->lpCreateParams; if (pWindow) { //-- attach the window object to the hwnd SetWindowLong(hwnd, pWindow); //-- let the window object dispatch the message pWindow->dispatch(hwnd, msg, wParam, lParam, lResult); } else { //-- leave the message to windows lResult = DefWindowProc(hwnd, msg, wParam, lParam); } } else if (hwnd) { //-- get the object attached to the hwnd xWindow *pWindow = (xWindow *)GetWindowLong(hwnd); //-- check to see if we have an object window attached to the handle if (pWindow) { //-- let the window object dispatch the message pWindow->dispatch(hwnd, msg, wParam, lParam, lResult); } else { //-- leave the message to windows lResult = ::DefWindowProc(hwnd, msg, wParam, lParam); } } return lResult;} Now, using this base class it is possible to define a new window class that will look like this: class MyWindow : public xWindow{protected: //-- the WM_COMMAND message handlers virtual void onAdd(int); virtual void onDelete(int); //-- the WM_CLOSE message handler virtual void onClose(xMessage *pMessage); //-- the WM_SIZE message handler virtual void onSize(xMessage *pMessage);public: //-- ctor and dtor MyWindow(); virtual ~MyWindow(); BEGIN_MSG_MAP //-- command message handlers CMD_HANDLER(onAdd , IDPB_ADD ) CMD_HANDLER(onDelete, IDPB_DELETE) //-- other message handling MSG_HANDLER(onClose , WM_CLOSE) MSG_HANDLER(onSize , WM_SIZE ) END_MSG_MAP(xWindow)}; Edit: How this code works. The secret to understanding how this code works is to remember the wndProc in the xWindow class is nothing but a Win32 Window procedure passed to RegisterClassEx when the Win32 Window is registered. Now if you look at the wndProc code you will see it does a bit of setting up and checking but generally it does nothing more than send the Windows message to the dispatch method. The dispatch method is even simpler as it does nothing more than pack the Windows message into an easy to move structure and then sends it off to the dispatchToMsgMap method. Now look at the MyWindow class an you will see this code: BEGIN_MSG_MAP //-- command message handlers CMD_HANDLER(onAdd , IDPB_ADD ) CMD_HANDLER(onDelete, IDPB_DELETE) //-- other message handling MSG_HANDLER(onClose , WM_CLOSE) MSG_HANDLER(onSize , WM_SIZE ) END_MSG_MAP(xWindow) This code is just using the macros defined earlier. If you take a close look at these macros you will see the code above is in fact creating a dispatchToMsgMap method. This is the exact same dispatchToMsgMap method that was called by the dispatch method. I know this method of handling Windows messages does work as I use this exact same approach in the Zeus for Windows editor. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1863158', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/186479/']} | jdg_78822 |
stackexchange | llm_judgeable_groundtruth_similarity | 56679 |
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:
I have the following question confused, we suppose: in my lab I have 10 linux servers and one layer-2 switch, I tried to separate them to 5 groups: Group one: 10.1.1.0/24 include server1(10.1.1.2), server2(10.1.1.3)Group two: 10.1.2.0/24 include server3(10.1.2.2), server4(10.1.2.3)Group three: 10.2.0.0/16 include server5(10.2.2.2), server6(10.2.2.3)Group four: 10.3.0.0/16 include server7(10.3.2.2), server8(10.3.2.3)Group five: 10.0.0.0/8 include server7(10.5.2.2), server8(10.5.2.3) So, in each group the two servers should be able to communicate very well? and also, all of the 10 servers can talk to each other very well, right?
Now provide the response and nothing else.
| So, in each group the two servers should be able to communicate? Yes. And also, all of the 10 servers can talk to each other, right? No. Because your groups are in different subnets, they will not be able to communicate. In order to communicate from one subnet to another, you need a router. The problem has less to do with the switch, and more with your addressing plan. | {} | {'log_upvote_score': 4, 'links': ['https://networkengineering.stackexchange.com/questions/56679', 'https://networkengineering.stackexchange.com', 'https://networkengineering.stackexchange.com/users/49203/']} | jdg_78823 |
stackexchange | llm_judgeable_groundtruth_similarity | 32425886 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
For my iOS app I have a model something like class Person { var Id: Int var Name: String init(id: Int, name: String?) { self.Id = id self.Name = name ?? "" }} Then later on in my ViewController when I load data from the server I add some people to an array class ViewController: UIViewController { var people:[Person] = [] override func viewDidLoad() { self.loadPeople() } func loadPeople() { // This data will be coming from a server request // so is just sample. It could have users which // already exist in the people array self.people.append(Person(id: "1", name: "Josh")) self.people.append(Person(id: "2", name: "Ben")) self.people.append(Person(id: "3", name: "Adam")) }} What I am now trying todo is turn the people array into a Set<Person> so it will not add duplicates. Is this possible to do or do I need to change my logic?
Now provide the response and nothing else.
| To make set of Person you need to make it conform to Equatable and Hashable protocols: class Person: Equatable, Hashable { var Id: Int var Name: String init(id: Int, name: String?) { self.Id = id self.Name = name ?? "" } var hashValue: Int { get { return Id.hashValue << 15 + Name.hashValue } }}func ==(lhs: Person, rhs: Person) -> Bool { return lhs.Id == rhs.Id && lhs.Name == rhs.Name} Then you can use set of persons like this: var set = Set<Person>()set.insert(Person(id: 1, name: "name")) | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/32425886', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']} | jdg_78824 |
stackexchange | llm_judgeable_groundtruth_similarity | 200637 |
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a question that would be trivial in OOP, but I am a newbie to programming in Mathematica, so I'm wondering how to deal with it. Basically, I want to create a package which basically involves a bunch of matrix transformations to a vector. So I have a bunch of functions to create a bunch of different matrices, e.g. CreateMatrix1[size, param1, param2], CreateMatrix2[size, param], ... For any given application, the matrix size is constant, but these functions are called many times, and it becomes a hassle to have to pass in the same size parameter every time. In OOP I would solve this by creating an manager object taking in size and implementing the various matrix operations as methods. In Mathematica, is there some way to make it so all these functions already know what the matrix size is for the given application, thus saving the end-user from having to pass it in all the time? Is it possible to create a temporary context of some kind, but still allow for different contexts in the same notebook, i.e. not a global variable?
Now provide the response and nothing else.
| The idea If you adhere to the convention that the size argument is always first in all your functions, then what you ask for can be achieved with some metaprogramming / dynamic environments. A dynamic environment is a function that takes your code, and generally modifies some definitions locally, only for the code that runs inside it. Preparation As a simple example, consider these 3 functions: diag[size_, diagElement_] := DiagonalMatrix[ConstantArray[diagElement, size]]identity[size_] := IdentityMatrix[size];norms[size_, genF_, dotF_] := Outer[dotF, #, #] &[genF /@ Range[size]] They take the matrix size and sometimes other parameters, and generate various matrices. For example: diag[2, 10](* {{10, 0}, {0, 10}} *)identity[2](* {{1, 0}, {0, 1}} *)norms[ 2, Function[x, HermiteH[#, x]] &, Function[{l, r}, Integrate[l[y]*r[y]* Exp[-y^2], {y, -Infinity, Infinity}]]](* {{2 Sqrt[\[Pi]], 0}, {0, 8 Sqrt[\[Pi]]}} *) where the last matrix is made of dot products of Hermite polynomials. Automating redefinitions What I suggest to do is to create a dynamic environment in which all these functions will be redefined to automatically assume the first (in this case) argument size to some fixed value. Here is the code: redefine[syms:{___Symbol}, f_]:= Module[{inSym}, Scan[ Function[sym, With[{protected = Unprotect[sym]}, sym[args___] /; !TrueQ[inSym[sym]] := Internal`InheritedBlock[{inSym}, inSym[sym] = True; f[sym, {args}] ]; Protect[protected] ] ], syms ] ]withCurried[fixedParams__][affectedFunctions___Symbol] := Function[ code , Internal`InheritedBlock[{affectedFunctions}, redefine[ {affectedFunctions}, Function[{s, a}, s[fixedParams, Sequence @@ a]] ]; code ] , HoldAll] The first function takes a number of symbols and a function, that takes the symbol, the argument passed to that symbol, and then uses that to do arbitrary computation with those. The second function takes a number of fixed argument values in the first group of arguments, and a number of symbols in the second, and creates a dynamic environment where all these symbols are redefined such that these fixed arguments are automatically prepended to the list of passed arguments when these functions are called. Illustration Let's assume we want to fix the size argument value to be 3 , and we want all 3 functions from the example above, to be affected. We create a dynamic environment, and save it in a variable: dynenv = withCurried[3][diag, identity, norms] We are now ready to use it: dynenv[{ diag[10], identity[], norms[ Function[x, HermiteH[#, x]] &, Function[{l, r}, Integrate[l[y]*r[y]* Exp[-y^2], {y, -Infinity, Infinity}] ]}](* { {{10, 0, 0}, {0, 10, 0}, {0, 0, 10}}, {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}}, {{2 Sqrt[\[Pi]], 0, 0}, {0, 8 Sqrt[\[Pi]], 0}, {0, 0, 48 Sqrt[\[Pi]]}} }*) You can see that now we have omitted the first parameter ( size ) in the calls to all these functions, yet they got the value 3 automatically passed to them. You can create as many dynamic environments as you want, with different values of parameters ( size in this case) embedded into them. The enviroments only affect the code that runs inside them. The global definitions of functions diag, identity, norms did not change. This seems to be a more economical solution that creating new symbols in some new contexts. The only problematic case I can see for this approach is when you need to use these functions with different settings of size within the same piece of code. | {} | {'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/200637', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/16270/']} | jdg_78825 |
stackexchange | llm_judgeable_groundtruth_similarity | 34758746 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Suppose I have a lens like at _ that needs some Maybe a : import Data.Map as Mm = M.fromList [(1,(2,3))]--set 2nd elementm ^. at 1 .~ Just (4,5) --gives fromList [(1,(4,5))]m ^. at 1 .~ Nothing--gives fromList () Now suppose I want to compose it with another lens. The fact that this lens returns some Maybe a prevents me from doing it directly. m ^. at 1 . _2 .~ Just 4--error-- I want to get M.fromList [(1,(2,4))] What's the right way to do this?
Now provide the response and nothing else.
| Use the _Just prism to set values in a Map conditional on whether the key exists. That's what prisms are for! λ> let m = fromList [(1, (2, 3))]λ> m & at 1 . _Just . _2 .~ 4fromList [(1,(2,4))]λ> m & at 100 . _Just . _2 .~ 4fromList [(1,(2,3))] | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/34758746', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2430739/']} | jdg_78826 |
stackexchange | llm_judgeable_groundtruth_similarity | 38935904 |
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 I'd like to do is this: Consume records from a numbers topic (Long's) Aggregate (count) the values for each 5 sec window Send the FINAL aggregation result to another topic My code looks like this: KStream<String, Long> longs = builder.stream( Serdes.String(), Serdes.Long(), "longs");// In one ktable, count by key, on a five second tumbling window.KTable<Windowed<String>, Long> longCounts = longs.countByKey(TimeWindows.of("longCounts", 5000L));// Finally, sink to the long-avgs topic.longCounts.toStream((wk, v) -> wk.key()) .to("long-counts"); It looks like everything works as expected, but the aggregations are sent to the destination topic for each incoming record. My question is how can I send only the final aggregation result of each window?
Now provide the response and nothing else.
| In Kafka Streams there is no such thing as a "final aggregation". Windows are kept open all the time to handle out-of-order records that arrive after the window end-time passed. However, windows are not kept forever. They get discarded once their retention time expires. There is no special action as to when a window gets discarded. See Confluent documentation for more details: http://docs.confluent.io/current/streams/ Thus, for each update to an aggregation, a result record is produced (because Kafka Streams also update the aggregation result on out-of-order records). Your "final result" would be the latest result record (before a window gets discarded). Depending on your use case, manual de-duplication would be a way to resolve the issue (using lower lever API, transform() or process() ) This blog post might help, too: https://timothyrenner.github.io/engineering/2016/08/11/kafka-streams-not-looking-at-facebook.html Another blog post addressing this issue without using punctuations: http://blog.inovatrend.com/2018/03/making-of-message-gateway-with-kafka.html Update With KIP-328 , a KTable#suppress() operator is added, that will allow to suppress consecutive updates in a strict manner and to emit a single result record per window; the tradeoff is an increase latency. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/38935904', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2153265/']} | jdg_78827 |
stackexchange | llm_judgeable_groundtruth_similarity | 799584 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
By definition (at least from what I've seen) sargable means that a query is capable of having the query engine optimize the execution plan that the query uses. I've tried looking up the answers, but there doesn't seem to be a lot on the subject matter. So the question is, what does or doesn't make an SQL query sargable? Any documentation would be greatly appreciated. For reference: Sargable
Now provide the response and nothing else.
| The most common thing that will make a query non-sargable is to include a field inside a function in the where clause: SELECT ... FROM ...WHERE Year(myDate) = 2008 The SQL optimizer can't use an index on myDate, even if one exists. It will literally have to evaluate this function for every row of the table. Much better to use: WHERE myDate >= '01-01-2008' AND myDate < '01-01-2009' Some other examples: Bad: Select ... WHERE isNull(FullName,'Ed Jones') = 'Ed Jones'Fixed: Select ... WHERE ((FullName = 'Ed Jones') OR (FullName IS NULL))Bad: Select ... WHERE SUBSTRING(DealerName,4) = 'Ford'Fixed: Select ... WHERE DealerName Like 'Ford%'Bad: Select ... WHERE DateDiff(mm,OrderDate,GetDate()) >= 30Fixed: Select ... WHERE OrderDate < DateAdd(mm,-30,GetDate()) | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/799584', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/95710/']} | jdg_78828 |
stackexchange | llm_judgeable_groundtruth_similarity | 12341791 |
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 buildin method or property in Yii to check if page is homepage? I know i can use something like this: $controller = Yii::app()->getController();$isHome = $controller->getAction()->getId() === 'index' ? true : false; Or put it in a method in main controller, but i am looking for something cleaner. Thanks.
Now provide the response and nothing else.
| If You want to check the current page, ie action is the default of the current controller.. $controller = Yii::app()->getController();$isHome = $controller->action->id === $controller->defaultAction->id ? true : false; dafeultaction may not always be 'index', it can be changed, so you need to compare it with defaultAction instead.. And by homepage if you mean the defult page of site, then you need to compare your controller also with defaultController .. $controller = Yii::app()->getController();$default_controller = Yii::app()->defaultController;$isHome = (($controller->id === $default_controller->id) && ($controller->action->id === $controller->defaultAction->id)) ? true : false; In Yii2: $controller = Yii::$app->controller;$default_controller = Yii::$app->defaultRoute;$isHome = (($controller->id === $default_controller) && ($controller->action->id === $controller->defaultAction)) ? true : false; | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12341791', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/558134/']} | jdg_78829 |
stackexchange | llm_judgeable_groundtruth_similarity | 5379349 |
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 entity with a property referencing other entity (ReferenceEntity in examples). With HQL i can do this: select e.ReferenceEntity from Entity e where e.Id = :entityId NHibernate will give me the ReferenceEntity instance without lazy. With query over im trying do this: Session.QueryOver<Entity>().Where(e => e.Id == entityId).Select(e => e.ReferenceEntity).SingleOrDefault<ReferenceEntity>() With QueryOver Nhibernate is giving me the ReferenceEntity but lazy. I wanna get ReferenceEntity with eager loading using queryover like i do with hql. Thanks
Now provide the response and nothing else.
| Suggestion #1 You could do a little bit of LINQ manipulation after you execute the query to grab the data you want. var result = Session.QueryOver<Entity>() .Where(e => e.Id == entityId) // Filter, .Fetch(e => e.ReferenceEntity).Eager // join the desired data into the query, .List() // execute database query, .Select(e => e.ReferenceEntity) // then grab the desired data in-memory with LINQ. .SingleOrDefault();Console.WriteLine("Name = " + result.Name); It's simple and gets the job done. In my test, it resulted in a single query. Here's the output: SELECT this_.Id as Id0_1_, this_.Name as Name0_1_, this_.ReferenceEntity_id as Referenc3_0_1_, q5379349_r2_.Id as Id1_0_, q5379349_r2_.Name as Name1_0_FROM [Entity] this_ left outer join [ReferenceEntity] q5379349_r2_ on this_.ReferenceEntity_id=q5379349_r2_.IdWHERE this_.Id = @p0; Suggestion #2 Another approach would be to use an EXISTS subquery, which would be slightly more complex, but would return the right result the first time without any need for post-database manipulation: ReferenceEntity alias = null;var result = Session.QueryOver(() => alias) .WithSubquery.WhereExists(QueryOver.Of<Entity>() .Where(e => e.Id == entityId) // Filtered, .Where(e => e.ReferenceEntity.Id == alias.Id) // correlated, .Select(e => e.Id)) // and projected (EXISTS requires a projection). .SingleOrDefault();Console.WriteLine("Name = " + result.Name); Tested - results in single query: SELECT this_.Id as Id1_0_, this_.Name as Name1_0_FROM [ReferenceEntity] this_WHERE exists ( SELECT this_0_.Id as y0_ FROM [Entity] this_0_ WHERE this_0_.Id = @p0 and this_0_.ReferenceEntity_id = this_.Id); | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5379349', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/669622/']} | jdg_78830 |
stackexchange | llm_judgeable_groundtruth_similarity | 5677379 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
The documentation I've run across researching this indicates that the way to do it for other databases is to use multiple statements in your query, a la: >>> cursor = connection.cursor()>>> cursor.execute("set session transaction isolation level read uncommitted; select stuff from table; set session transaction isolation level repeatable read;") Unfortunately, doing that yields no results, as apparently the Python DB API (or maybe just this implementation of it?) doesn't support multiple recordsets within a single query. Has anyone else had success with this in the past?
Now provide the response and nothing else.
| I don't think this works for the MySQLdb driver; you'll have to issue separate queries: cur = conn.cursor()cur.execute("SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED")cur.execute("SELECT @@session.tx_isolation")print cur.fetchall()[0]cur.execute("SELECT * FROM bar")print cur.fetchall()cur.execute("SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ")cur.execute("SELECT @@session.tx_isolation")print cur.fetchall()[0]# output('READ-UNCOMMITTED',)(('foo',), ('bar',))('REPEATABLE-READ',) The MySQLdb cursor's execute() method only sees the first query up to the semicolon: cur.execute("SELECT * FROM bar WHERE thing = 'bar'; SELECT * FROM bar")print cur.fetchall()# output(('bar',),) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5677379', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4223/']} | jdg_78831 |
stackexchange | llm_judgeable_groundtruth_similarity | 5163088 |
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 return the value of my array plus the return value of the recursive call. However, for some reason, Java does not want to have the method name after the constructor. In addition, when I tried to convert the method into another method, I get an error when I use isPalindrome. I change my program around but I'm still getting errors. public class isPalindrome { /** * This is the main entry point for the application * @return */ public static boolean main(String[] args) { String[] word = {"KayaK", "Desserts, I stressed"}; boolean isPalindrome(String[] array, String s, String I) { if(i.charAt(0) == s.charAt(0)) { System.out.println("You entered a Palindrome"); return true; } else { System.out.println("You didn't entered a Palindrome"); } } try { System.in.read(); } catch (Throwable t) { } }}
Now provide the response and nothing else.
| You can't use the class name as the name for a method. The only "methods" that can share a name with the class are constructors. One fix would be to rename your class from isPalindrome to PalindromeFinder or something. That would also better align with Java naming conventions. EDIT: Note that you never actually called your method in main; you tryed to assign a local variable to isPalindrome . That does not actually call the method. You would need to invoke the method with isPalindrome(...put your parameters here...) and store the result in a variable with a name that isn't being used. Also note that a method can only return a single value (a single primitive or a single object). If you really want to return an array AND a boolean (and I'm not sure you do), you would have to store those in an object and return that object. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5163088', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/516805/']} | jdg_78832 |
stackexchange | llm_judgeable_groundtruth_similarity | 41991574 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
For example, when we add a new button to a pane, we need to write the following code: StackPane pane = new StackPane(); pane.getChildren().add(new Button("OK")); Why do we need to call "getChildren()?" what does it even do? Why can't we say: StackPane pane = new StackPane(); pane.add(new Button("OK")); We're adding the button to the pane. We're not adding it to its children,
Now provide the response and nothing else.
| The short answer is simply "you have to do it that way, because that's how the API was written". Of course, what you are probably really asking is why the API was written like that. I think that really amounts to two (related) questions. One is about the method name, and what that method does, and one is about the actual API design. In general, in computing, it is often beneficial to reuse existing solutions to problems. (Knowing when it is beneficial to do this is something of an art, but in both the cases here it's pretty clearly a benefit.) In two somewhat different ways, this API design reuses existing solutions to well-known problems, and consequently makes it easier to understand and use for programmers who have encountered those solutions before. The Scene Graph For the big picture, think about the overall structure of a general user interface. There is a large container of some kind (think of the root of the scene in JavaFX), which contains various UI components. Some of those might be simple controls, such as buttons and labels, etc, and some of them might be other containers, which in turn contain various UI components. And some of those, of course, may also be containers, and so on. Without imposing some kind of structure, this could get complex and difficult to use. To understand the structure, we make it abstract. There is a root node, which has a collection of zero or more other nodes. Each of those has a collection of zero or more other nodes, and so on. This is a very well known abstract structure in computing, called a "tree", which basically every computer programmer (no matter which language they program in) is familiar with. So if we think of it as a tree structure, because we are already familiar with that, we can make the complexity easier to work with. In order to think of it as a tree structure, we use standard names for the tree-like aspects. Each node (except the root node) has exactly one "parent" (the container to which it belongs): so you'll find a method in the Node class ("node" is another piece of terminology from tree structures) called getParent() , which gives access to the parent node (the container containing the current node). Similarly, UI elements (nodes) that contain other nodes have a method called getChildren() that returns a collection of all the nodes contained in the current node. The Oracle JavaFX tutorial has a section on the Scene graph describing this, with lots of nice diagrams and related code. So, in short, the reason there is a method called getChildren() is because we think of the collection of all the things in the UI as a tree structure, and this method name describes exactly what that method does in the context of the collection of all the UI elements being a tree. The terms "node", "parent" and "child" are instantly recognizable to programmers with a little bit of experience, and help them to understand the overall structure and to work with it. They can basically instantly infer that getChildren() returns a list of all the UI elements immediately contained in that container (the container is the StackPane in your example). API design of Pane s (such as StackPane ) To think about the API design, think about all the things you might want to do in terms of manipulating what is contained in your StackPane . As you observe, you might want to add a new UI element ("node") to the StackPane , so you might want a method called add(...) that accepts a Node . But there are a whole bunch of other things you might need or want to do too: Remove a node from the StackPane Add a whole collection of nodes to the StackPane Remove a whole collection of nodes from the StackPane Remove all the nodes from (clear) the StackPane Since the order of nodes in the stack pane is important (it defines the z-order, i.e. if the nodes overlap it defines which are drawn in front and which behind), you might want to insert a node at a specific position (in front of something but behind something else) Remove the node at the "back", or at the front, or at some specified position and many, many others So the designers of the StackPane class could have just written all these methods, but there's a better way. If you think about implementing StackPane , you need some way to keep track of the nodes (UI elements) it contains. The order of these nodes is important, so we must keep track of that, and we need to have a nice way to define all the functionality listed above. The authors of the StackPane class (or its superclass, Pane ) could have built a data structure to do this from scratch, but one already exists in the standard libraries. A data structure that holds a collection of objects of some specific type, and keeps track of their order, is called a List 1 , and the List interface is one that every single Java programmer is familiar with . So if you think of the actual implementation of the StackPane , you could define methods for all the functionality listed above in the stack pane itself. This would end up looking something (really it would be more complex than this, I just want enough here to make the point) like public class StackPane { private final List<Node> children = new ArrayList<>(); // or some other list implementation... public void add(Node node) { children.add(node); } public boolean remove(Node node) { return children.remove(node); } public void add(int index, Node node) { children.add(index, node); } public boolean remove(int index) { return children.remove(index); } public void addAll(Collection<Node> nodes) { children.addAll(nodes); } // lots more methods like this... // lots of layout code omitted...} I think you get the point. All this code is not really doing anything; it is simply invoking behavior that is already defined. So instead of this bloated API, it's possible to provide exactly the same functionality to the user of StackPane simply by providing access to the list itself 2 : public class StackPane { private final List<Node> children = new ArrayList<>(); public List<Node> getChildren() { return children ; } // layout code omitted...} Now the class is much less bloated, the API is less bloated, and additionally, the user receives a List , which as pointed out earlier is a very well known type of object. The new programmer to JavaFX, assuming they have some (any) Java experience, will already be familiar with the API for List and will not need to learn much that is new in order to use it. So the programmer can now do (with code laid out unconventionally and the thoughts of the programmer inserted): StackPane pane = new StackPane();Button button = new Button("OK");pane.getChildren() // oooh, a List, I know how those work .add(button);List<Label> lotsOfLabels = Arrays.asList(new Label("One"), new Label("Two"), new Label("Three"));pane.getChildren() // still a list, I know more things I can do here: .addAll(lotsOfLabels);pane.getChildren().remove(button);pane.getChildren().clear(); and we have a happy programmer who immediately knows the API, and is instantly productive on a first encounter with managing the scene graph in JavaFX, and consequently a happy boss who sees great productivity from the programming team. So in summary, by simply exposing the List of child nodes, the API can expose all the functionality it needs for manipulating the contents of the StackPane , without adding a huge list of methods to the StackPane class and do it in a way that leverages the existing knowledge of every Java programmer. Footnotes Actually, Pane s require a little more functionality than is defined in List : they need a convenient way of knowing when the list changes, by nodes being added or removed (because the pane needs to recompute its layout when this happens). So the JavaFX team defined a subinterface of List , called ObservableList , which has all the functionality of List and adds functionality for "observing" the list. There is one thing that the JavaFX team will have had to think hard about here: is all the functionality defined by List appropriate for the collection of child nodes? If the List interface defined some methods that really didn't make sense here, it would probably be a bad idea to use this implementation, and the more bloated API suggested in the first code block might actually be a better choice. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/41991574', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6707111/']} | jdg_78833 |
stackexchange | llm_judgeable_groundtruth_similarity | 38303012 |
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 thread called T1 for reading a flat file and parsing it. I need to create a new thread called T2 for parsing some part of this file and later this T2 thread would need to update the status of the original entity, which is also being parsed and updated by the original thread T1 .How can I handle this situation? I receive a flat file having the below sample records: AAAABBBBAACCBBCCAADDBBDD First this file is saved in database in Received status. Now all the records starting with BB or with AA need to be processed in a separate thread. Once it's successfully parsed, both threads will try to update the status of this file object in a database to Parsed . In some cases, I get staleObjectException . Edit: And the work done by any thread before the exception is lost. We are using optimistic locking. What is the best way of avoiding this problem? Possible hibernate exceptions when two threads update the same Object? The above post helps to understand some part of it, but it does not help to resolve my problem.
Now provide the response and nothing else.
| Part 1 - Your problem The main reason for you receiving this exception is that you are using Hibernate with optimistic locking . This basically tells you that either thread T1 or thread T2 have already updated the state to PARSED and now the other thread is holding old version of the row with smaller version than the one held in the database and trying to update the state to PARSED as well. The question here is " Are the two threads trying to preserve the same data ?". If the answer is yes then even if the last update succeed there shouldn't be any problem, because eventually they are updating the row to the same state. In that case you don't need Optimistic locking because your data will, in any case be in sync. The main problem comes if after the state is set to RECIEVED if the two threads T1 and T2 actually depending on one another when reseting to the next status. In that case you need to ensure that if T1 has executed first(or vice versa) T2 needs to refresh the data for the updated row and re-apply its changes based on the changes already pushed by T1. In this case the solution is the following. If you encounter staleObjectException you basically need to refresh your data from the database and restart your operation. Part 2 analysis on the link posted Possible hibernate exceptions when two threads update the same Object? Approach 1 , this is more or less the last to update Wins situation. It more or less avoids the optimistic locking (the version counting). In case you don't have dependency from T1 to T2 or reverse in order to set status PARSED . This should be good. Aproach 2 Optimistic Locking This is what you have now. The solution is to refresh the data and restart your operation. Aproach 3 Row level DB lock The solution here is more or less the same as for approach 2 with the small correction that the Pessimistic lock dure. The main difference is that in this case it may be a READ lock and you might not be even able to read the data from the database in order to refresh it if it is PESSIMISTIC READ. Aproach 4 application level synchronization There are many different ways to do synchronization. One example would be to actually arrange all your updates in a BlockingQueue or JMS queue(if you want it to be persistent) and push all updates from a single thread. To visualize it a bit T1 and T2 will put elements on the Queue and there will be a single T3 thread reading operations and pushing them to the Database server. If you use application level synchronization you should be aware that no all structures can be distributes in a multi-server deployment. Well I can't think of anything else for now :) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/38303012', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4348811/']} | jdg_78834 |
stackexchange | llm_judgeable_groundtruth_similarity | 525653 |
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:
When trying to call /dev/tcp/www.google.com/80 , by typing /dev/tcp/www.google.com/80 Bash says no such file or directory . When looking at other people's code online, they use syntax such as 3<>/dev/tcp/www.google.com/80 I noticed that this works as well: </dev/tcp/www.google.com/80 Why are these symbols required to call certain things in bash?
Now provide the response and nothing else.
| Because that's a feature of the shell (of ksh, copied by bash), and the shell only. /dev/tcp/... are not real files, the shell intercepts the attempts to redirect to a /dev/tcp/... file and then does a socket(...);connect(...) (makes a TCP connection) instead of a open("/dev/tcp/..."...) (opening that file) in that case. Note that it has to be spelled like that. cat < /dev/./tcp/... or ///dev/tcp/... won't work, and will attempt to open those files instead (which on most systems don't exist and you'll get an error). The direction of the redirection also doesn't matter. Whether you use 3< /dev/tcp/... or 3> /dev/tcp/... or 3<> /dev/tcp/... or even 3>> /dev/tcp/... won't make any difference, you'll be able to both read and write from/to that file descriptor to receive/send data over that TCP socket. When you do cat /dev/tcp/... , that doesn't work because cat doesn't implement that same special handling, it does a open("/dev/tcp/...") like for every file (except - ), only the shell (ksh, bash only) does, and only for the target of redirections. That cat - is another example of a file path handled specially, this time, by cat , not the shell. Instead of doing a open("-") and reading the input from the resulting file descriptor, cat reads directly from the file descriptor 0 (stdin). cat and many text utilities do that, the shell doesn't for its redirections. To read the content of the - file, you need cat ./- , or cat < - (or cat - < - ). On systems that don't a have /dev/stdin , bash will however do something similar for redirections from that (virtual) file. GNU awk does the same for /dev/stdin , /dev/stdout , /dev/stderr even on systems that do have such files which can cause some surprises on systems like Linux where those files behave differently. zsh also has TCP (and Unix domain stream) socket support, but that's done with a ztcp (and zsocket ) builtins, so it's less limited than the ksh/bash approach. In particular, it can also act as a server which ksh/bash can't do. It's still much more limited than what you can do in a real programming language though. | {} | {'log_upvote_score': 6, 'links': ['https://unix.stackexchange.com/questions/525653', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/357569/']} | jdg_78835 |
stackexchange | llm_judgeable_groundtruth_similarity | 713570 |
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have this in my .zshrc file export MANLESS=""export LESS="--RAW-CONTROL-CHARS"export LESS_TERMCAP_mb=$(tput bold; tput setaf 5)export LESS_TERMCAP_md=$(tput bold; tput setaf 1)export LESS_TERMCAP_so=$(tput setaf 1; tput setab 3)export LESS_TERMCAP_se=$(tput rmso; tput sgr0)export LESS_TERMCAP_us=$(tput setaf 3)export LESS_TERMCAP_ue=$(tput sgr0) When I use man as: man zshexpn , I have nicely colored sections: When I use man as: man zshexpn | less '+/PROCESS SUBSTITUTION' , on same part of the manual page, it is no longer colored: How can I get colored output in second case, same as first case?
Now provide the response and nothing else.
| I’m assuming you’re using man on a mainstream Linux distribution. man there (and on other systems) defaults to removing formatting if its output isn’t a terminal; since you’re manually piping to less , that’s what’s happening here. You can override this by setting MAN_KEEP_FORMATTING to a non-empty value: MAN_KEEP_FORMATTING=1 man zshexpn | less '+/PROCESS SUBSTITUTION' If you want this behaviour to be the default, export MAN_KEEP_FORMATTING along with your other settings; bear in mind that this will affect all man invocations, which will have side-effects when the output doesn’t end up being processed by a terminal ( e.g. if you want to grep the output). | {} | {'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/713570', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/155832/']} | jdg_78836 |
stackexchange | llm_judgeable_groundtruth_similarity | 28994852 |
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 encountered a bug in my codebase, I've narrowed down to what caused this behavior. The first test case fails, whereas the last two succeed. @Testpublic void testBooleanNull1() { Boolean nullB = null; assertFalse(Boolean.valueOf(nullB));}@Testpublic void testBooleanNull2() { String nullS = null; assertFalse(Boolean.valueOf(nullS));}@Testpublic void testBooleanNull3() { assertFalse(Boolean.valueOf(null));} I know that Boolean.valueOf is an overloaded method with two variants one takes a String and the other takes a primitive of type boolean . I suspect that this is happening because of auto-boxing but I'm not sure if that is the case, furthermore I don't know why null is being converted to a Boolean as far as I know null is not a valid primitive type. I've moved on to using BooleanUtils from Apache Commons , I asked this here to better understand why the behavior is this way.
Now provide the response and nothing else.
| This Boolean.valueOf(nullB) is an invocation of Boolean#valueOf(boolean) . It fails because the unboxing of the Boolean value nullB fails with a NullPointerException . In other words, it becomes boolean val = nullB.booleanValue(); // at runtime nullB stores the value nullBoolean.valueOf(val) This process is described in the JLS here If r is a reference of type Boolean , then unboxing conversion converts r into r.booleanValue() This Boolean.valueOf(null) is invoking the overloaded version that accepts a String (since null is not a valid expression of type boolean ). Returns a Boolean with a value represented by the specified string. The Boolean returned represents a true value if the string argument is not null and is equal, ignoring case, to the string "true" . | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/28994852', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/632447/']} | jdg_78837 |
stackexchange | llm_judgeable_groundtruth_similarity | 6404992 |
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 b number of blocks and each block has t number of threads. I can use __syncthreads() to synchronize the threads that are in a particular block. for example __global__ void aFunction(){ for(i=0;i<10;i++) { //execute something __syncthreads(); }} But my problem is to synchronize all the threads in all the blocks. How can I do this?
Now provide the response and nothing else.
| In CUDA 9, NVIDIA is introducing the concept of cooperative groups , allowing you to synchronize all threads belonging to that group. Such a group can span over all threads in the grid. This way you will be able to synchronize all threads in all blocks: #include <cuda_runtime_api.h> #include <cuda.h> #include <cooperative_groups.h>cooperative_groups::grid_group g = cooperative_groups::this_grid(); g.sync(); You need a Pascal (compute capability 60) or a newer architecture to synchronize grids. In addition, there are more specific requirements. See: https://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#grid-synchronization-cg Basic functionality, such as synchronizing groups smaller than a thread block down to warp granularity, is supported on all architectures, while Pascal and Volta GPUs enable new grid-wide and multi-GPU synchronizing groups. Source: https://devblogs.nvidia.com/parallelforall/cuda-9-features-revealed/ Before CUDA 9, there was no native way to synchronise all threads from all blocks. In fact, the concept of blocks in CUDA is that some may be launched only after some other blocks already ended its work, for example, if the GPU it is running on is too weak to process them all in parallel. If you ensure that you don't spawn too many blocks, you can try to synchronise all blocks between themselves, e.g. by actively-waiting using atomic operations. This is however slow, eating up your GPU memory controller, is considered "a hack" and should be avoided. So, if you don't target Pascal (or newer) architecture, the best way that I can suggest is to simply terminate your kernel at the synchronisation point, and then launch a new kernel which would continue with your job. In most circumstances it will actually perform faster (or at least - with simmilar speeds) than using the mentioned hack. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/6404992', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/570593/']} | jdg_78838 |
stackexchange | llm_judgeable_groundtruth_similarity | 381901 |
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:
My text file looks like this: This is onesentence that is broken.However this is a good one.And thisone issomehow, broken intomany. I want to remove the trailing newline character for any line which is followed by a line starting with a lowercase letter. So this should be: This is one sentence that is broken.However this is a good one.And this one is somehow, broken into many. How can I do this? Edit: There are some really good answers here, but I chose to accept the first one that worked and was earliest. Thanks so much everyone!
Now provide the response and nothing else.
| try awk '$NF !~ /\.$/ { printf "%s ",$0 ; next ; } {print;}' file where $NF !~ /\.$/ match line where last element do not end with a dot, { printf "%s ",$0 print this line with a trailling space, and no line feed, next ; } fetch next line, {print;} and print it. I am sure there will be a sed option. Note: this will work with line ending in a dot, however condition in sentences beginning with upper case letter won't get merged. See Stéphane Chazelas's answer. | {} | {'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/381901', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/-1/']} | jdg_78839 |
stackexchange | llm_judgeable_groundtruth_similarity | 36932078 |
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 the regex with $in operator as mentioned in the docs but I am still unable to get the value. db.users.find({'profile.firstName':{$in:["/justin/i"]}}).count() = 0 but when I used like this db.users.find({'profile.firstName':{$in:["justin"]}}).count()=1 and db.users.find({'profile.firstName':{$in:["Justin"]}}).count()=2 Edited Question seems like I am not clear with the question I will add the code for easy understanding I am trying to get the list of documents from a query which is case insensitive.I think it better to explain my doubt with code. Meteor.users.find({'profile.firstName':{$in:[/justin/i,/helen/i]}}).count() will give documents whose profile.firstName is justin/Justin/JUSTIn/HElen/helen but my doubt how to give the variable x=["sai","test","jacob",---etc] in place of helen/justin
Now provide the response and nothing else.
| You need to wrap the elements in the array with the RegExp object i.e. regex = [new RegExp("sai", "i"), new RegExp("test", "i"),...] You can use the map() method to map the elements in the array with the RegExp wrappers to a new array that you can then use in the regex query with $in : var x = ["sai","test","jacob","justin"], regex = x.map(function (e) { return new RegExp(e, "i"); });db.users.find({"profile.firstName": { "$in": regex } }); Using $in can be fairly efficient with small arrays but not so well with huge lists since it will skip around in the index to find the matching documents, or walk through the whole collection if there isn't an index to use. Besides using the $in with the regular expression , you could use a pipe-delimited regex pattern with the keywords list like this: var x = ["sai","test","jacob","justin"], regex = x.join("|");db.users.find({ "profile.firstName": { "$regex": regex, "$options": "i" } }).count; | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/36932078', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4221420/']} | jdg_78840 |
Subsets and Splits