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
|
19492738
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Supposed execution of a Vagrantfile requires a specific Vagrant plugin to be installed. So, basically what you need to do is $ vagrant plugin install foobar-plugin$ vagrant up If you skip the first step, vagrant up fails. Is there an option in Vagrant to make it install the plugin automatically? In other words: Is it possible to specify within a Vagrantfile which plugins to install automatically before creating and booting up the machine?
Now provide the response and nothing else.
|
As I pointed out on my answer to your other question , you can use bindler for installing a set of plugins specific to a project using a single command. If bindler is installed and the required plugin is not, bindler will error out and will abort the process. There is also an open issue related to automatically installing plugins on vagrant up s but so far no one signed up for it yet. If you don't want to use bindler, you can make use of Vagrant.has_plugin? (available on 1.3.0+) at the top of your Vagrantfile and error out if the required plugin is not installed. Something like: unless Vagrant.has_plugin?("vagrant-some-plugin") raise 'some-plugin is not installed!'endVagrant.configure("2") do |config| config.vm.box = "box-name"end UPDATE : Bindler is no longer supported and no equivalent funcionality has been provided by Vagrant core as of May 11th, 2015
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/19492738', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1333873/']}
|
jdg_370641
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
6836603
|
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 attempting you the plugin found here (http://jquery-datatables-column-filter.googlecode.com/svn/trunk/default.html) on my datatables that are populated via AJAX, but when following the instructions in the example for adding the required footer to the table: <tfoot> <tr> <th>Rendering engine</th> <th>Browser</th> <th>Platform(s)</th> <th>Engine version</th> <th>CSS grade</th> </tr> </tfoot> I wind up simply with a footer row w/labels and not the text boxes as shown in the example. Any thoughts on what I need to do to correct this? Thanks!
Now provide the response and nothing else.
|
edit : it's currently 2016-09-24, and PHP 5.4 has been released 2012-03-01, and support has ended 2015-09-01. Still, this answer seems to gain upvotes. If you're still using PHP < 5.4, your are creating a security risk and endagering your project . If you have no compelling reasons to stay at <5.4, or even already use version >= 5.4, do not use this answer , and just use PHP>= 5.4 (or, you know, a recent one) and implement the JsonSerializable interface You would define a function, for instance named getJsonData(); , which would return either an array, stdClass object, or some other object with visible parameters rather then private/protected ones, and do a json_encode($data->getJsonData()); . In essence, implement the function from 5.4, but call it by hand. Something like this would work, as get_object_vars() is called from inside the class, having access to private/protected variables: function getJsonData(){ $var = get_object_vars($this); foreach ($var as &$value) { if (is_object($value) && method_exists($value,'getJsonData')) { $value = $value->getJsonData(); } } return $var;}
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/6836603', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/464180/']}
|
jdg_370642
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
314311
|
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
I am wondering if rebooting a server in a schedule would be good idea for performance. Let's say we want to reboot the server at 02:00 AM per 2 nights. The server here is Windows Server 2008 R2 . Mainly, SQL Server and IIS 7.5 (nearly 15 apps running) are running under this server. Server has 4GB memory.
Now provide the response and nothing else.
|
While I would agree that there is nothing wrong with rebooting the box, per se, based on your comment that the SQL Server Agent is stopping I would advise some additional root cause analysis. Services don't typically just stop, and the SQL Server Agent services hasn't acted that way in my experience, typically. I think you'd do well, aside from rebooting, to examine the event logs and run a long-term performance counter log that you can analyze with Performance Analysis of Logs (PAL) to see if it "sees" anything wrong. You should try, if nothing else, to correlate the events associated with the SQL Agent stopping with other factors.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://serverfault.com/questions/314311', 'https://serverfault.com', 'https://serverfault.com/users/77342/']}
|
jdg_370643
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
38857768
|
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 a situation where I want to build a code which gets $bindParam variable in this format: $bindParams = [$type1 => $param1, $type2 => $param2, ... ] I wanna build some code that dynamically adds that parameters to the prepared statement. This is the code which I built so far : $mysql = new mysqli("localhost", "root", "", "db1");$stmt = $mysql->prepare($sql);foreach($bindParams as $type => $data) { $stmt->bind_param($type, $data);}$stmt->execute();$result = $stmt->get_result();// and after perhaps twiddling with the result set, but this is not the case ..... For your instance $sql = "INSERT INTO table1 (name, age) VALUES (?,?);" and $bindParams = ["s" => "hello", "i" => 15] This does not always have this structure and it can change to for example $bindParams = ["s" => "hello", "i" => 15, "d" => 22.5] and so the $sql changes respectively. After the first time the compiler heads to $stmt->bind_param($type, $data); firefox flushes this error: Warning: mysqli_stmt::bind_param(): Number of variables doesn't match number of parameters in prepared statement in D:\PHP\tr.php on line 23 I know PDO support that as stated here at the end of the page. but perhaps as you might expect Im not a fan of PDO so ;) My other option is to use the eval() workarounds available in php but thats out of what I might think of. Is there another way to do this?
Now provide the response and nothing else.
|
Sadly mysqli doesn't support this. Calling the function over and over again overwrites the values, so you're only binding one param when you clearly have more. There's a couple of ways to get around this Switch to PDO. You can make one bind per function call with that Bind the params as one aggregate using call_user_func_array $sqltype = '';$sqldata = [];foreach($bindParams as $type => $data) { $sqltype .= $type; $sqldata[] = &$data; // MUST be a reference}array_unshift($sqldata, $sqltype); // prepend the typescall_user_func_array([$stmt, 'bind_param'], $sqldata);
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/38857768', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5252192/']}
|
jdg_370644
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
29334
|
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am a statistician searching for an efficient way to select rows or columns from a table of data in Mathematica . Let me pose the question in 2 parts with a SQL-style table of data: List[{"ID", "Variable 1", "Variable 2"}, {"Alpha", 1, 0}, {"Beta", 1, 1}, {"Alpha", 1, 0}]] Which, when formatted as a Grid looks roughly like this: ID Variable 1 Variable 2Alpha 1 0Beta 1 1Alpha 1 0 Part 1: How can the data in the header of the table, for example "ID", be set as the name of the list for that column? Ideally, the result would allow you to do the following: In[24]:= IDOut[24]= {"Alpha", "Beta", "Alpha"} Would one need to write a function to dissect the header row and then line up the header names as the name of a list that corresponds to the appropriate header? Although one might ask 'Why not refer to everything as a position and avoid the renaming headache entirely?' it is extremely cumbersome when working with tens or hundreds of columns/variables to use a meaningless position to reference a variable. Part 2: How can an individual row, or subset of rows, be returned from a table? Essentially I'm looking for the equivalent of the "WHERE" clause in SQL or the "subset" function in R. For example in the "ID" column I might want to retrieve all the rows where "ID" == "Alpha". Do I have to create a method that iterates over the "ID" list, stores the position in the list where the value of the element is equal to "Alpha", and then concatenate a list that contains the value in that position for all the other lists? I'm confident I could write the functions I mention, but it seems unconscionable that Mathematica would overlook such a rudimentary data manipulation task. I understand there's also the DataManipulation package that allows for SQL queries, but I have to believe (hope?) there's a way native to Mathematica that's quicker. Thank you for indulging me! And my apologies in advance to all the Mathematica aficionados who might see this as a corrupt question for trying to program in another language while in Mathematica!
Now provide the response and nothing else.
|
I think, your question has 3 levels: convenient syntax, data representation, and efficiency. I can offer a very lightweight solution which addresses all of these in the simplest way: syntax is resembling SQL but not exactly the same, data representation - just lists, as in your example (we do not make custom wrappers, objects of any kind, etc), and efficiency will be similar to the standard SQL select, in terms of asymptotic complexity of the query (but not in absolute timings of course): Clear[getIds];getIds[table : {colNames_List, rows__List}] := {rows}[[All, 1]];ClearAll[select, where];SetAttributes[where, HoldAll];select[table : {colNames_List, rows__List}, where[condition_]] := With[{selF = Apply[Function, Hold[condition] /. Dispatch[Thread[colNames -> Thread[Slot[Range[Length[colNames]]]]]]]}, Select[{rows}, selF @@ # &]]; Here is how you could use it: table = {{"ID", "Variable 1", "Variable 2"}, {"Alpha", 1, 0}, {"Beta", 1, 1}, {"Alpha", 1, 0}};getIds[table](* {"Alpha", "Beta", "Alpha"} *)select[table, where["ID" == "Alpha"]](* {{"Alpha", 1, 0}, {"Alpha", 1, 0}} *)select[table, where["Variable 1" == 1]](* {{"Alpha", 1, 0}, {"Beta", 1, 1}, {"Alpha", 1, 0}} *)select[table, where["Variable 2" == 1]](* {{"Beta", 1, 1}} *)
|
{}
|
{'log_upvote_score': 6, 'links': ['https://mathematica.stackexchange.com/questions/29334', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/-1/']}
|
jdg_370645
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
149559
|
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
Consider the measurable space $2^{\mathbb R}$, equipped with the tensor-product $\sigma$-algebra. Famously, this space has a measurable structure which is not generated by a topology (see this answer ). Can you provide an example of a non-trivial probability measure on $2^{\mathbb R}$?
Now provide the response and nothing else.
|
$2^{\mathbb{R}}$, being a product of compact Hausdorff groups, is a compact Hausdorff group, so it has a normalized Haar measure ("flipping uncountably many coins").
|
{}
|
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/149559', 'https://mathoverflow.net', 'https://mathoverflow.net/users/238/']}
|
jdg_370646
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3005606
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How do I parse this json with jQuery? DayEvents: [{ "0": "886", "event_id": "886", "1": "5029", "user_id": "5029", "2": "Professional", "user_type": "Professional", ...
Now provide the response and nothing else.
|
The term "parsing" is a bit misplaced since this is already in JSON format. You don't need to parse it, but just to access it. If it were a large String in JSON format then you indeed need to parse it into an useable JSON object first before accessing. This JSON contains one property, the DayEvents , which in turn contains an array [] . You can access properties using dot . operator. You can get an array item at the given index using [index] where zero 0 denotes the first item. var json = { DayEvents : [{"0":"886","event_id":"886","1":"5029","user_id":"5029","2":"Professional","user_type":"Professional" }]};var firstDayEvent = json.DayEvents[0]; The array in turn contains an object {} . Or maybe more than one? You can have more than one items in an array, you should then see [{}, {}, {}, ...] and you could then access each item in an loop like so: for (var i = 0; i < json.DayEvents.length; i++) { var dayEvent = json.DayEvents[i]; // ...} A single day event object has several properties: 0 , event_id , 1 , user_id , 2 , etc. You cannot access properties starting with a number using dot . operator, you would then like to use the brace notation: var zero = firstDayEvent['0'];var eventId = firstDayEvent.event_id;var one = firstDayEvent['1'];var userId = firstDayEvent.user_id;var two = firstDayEvent['2'];// ...alert(eventId); // 886alert(two); // Professional To learn more about JSON, check this tutorial .
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3005606', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/362387/']}
|
jdg_370647
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
36113347
|
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 getting this error testing in-app subscription products locally. authentication is required. you need to sign in to your google account I was able to check the the inventory for the product but shouldn't I also be able to purchase it? There are a number of posts about why this error might occur which I thought were addressed: the product is released in the beta channel with in-app billing enabled i am logged into Play Store with a test user licensed account on the device. Is the only way to test actual purchases via the beta/alpha channels - not straight from android studio. This post suggests it possible (see screen shot) http://developer.android.com/google/play/billing/billing_testing.html#billing-testing-test
Now provide the response and nothing else.
|
EDIT : This is now superseded by the newly accepted answer. In essence, in-app billing payments can only be tested with a release-signed apk (the one we upload to Google Play Console). Here are some steps that got me attached to a signed apk with Android Studio : I'm on Windows. It helps having adb.exe in the PATH, for me that's: C:\Users{your-username}\AppData\Local\Android\sdk\platform-tools In Google Play Console, ensure the app is published (< is a one-time manual step after its initially processed) in alpha or beta channel and you have a licensed test gmail account (from the Account Settings section) that is also in the list of alpha/beta testers and is not the owner of the app account. This account is the only account on the device. Release the apk and ensure it all works from an installed version from the Play Store. Have these settings:In AndroidManifest.xml under application node android:debuggable="true"tools:ignore="HardcodedDebugMode" Note:Propably, you need to add: xmlns:tools="http://schemas.android.com/tools" property to your manifest tag. It may look like: <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="your.package" xmlns:tools="http://schemas.android.com/tools"> And in your build.gradle file under android > buildTypes > release , add: debuggable true Generate a signed APK from Android Studio Attach your device for USB debugging. Remove current install: adb uninstall {yourdomain}.{yourpackagename} Install it (from the release path) adb install app-release.apk Open the app on the device. From Android Studio's Run menu, last option is "Attach debugger to Android Process" - select your device. You are now debugging. NB for in-app billing the build number needs to match the one currently published on Play Store
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/36113347', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/220005/']}
|
jdg_370648
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
19335722
|
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 base class bc and a number of subclasses based on bc . class bc(Object): def get_subclass_name(self): # Retrieve the name of the most derived subclass of this instance pass def somemethod(self): x = self.get_subclass_name()class sc1(bc): passclass sc2(bc) pass The idea is that when somemethod() is invoked on an instance of a subclass of bc , it will be able to use the name of the most derived subclass of that instance without needing to know in advance what potential subclasses may exist. I have put together a test case for this: class base_class(object): @classmethod def get_subclass_name(cls): return cls.__name__ def somemethod(self): print(base_class.get_subclass_name())class sub_class(base_class): passsub_class().somemethod() When this code is run it produces base_class rather than sub_class .
Now provide the response and nothing else.
|
Just as an alternative to @poorsod's solution, which works perfectly fine for me, here's another, perhaps simpler variant without class methods, using self.__class__ . Just as self always points to the current instance, self.__class__ always points to the actual class of that instance. class bc(object): def get_subclass_name(self): return self.__class__.__name__ Example, tested in Python 2.6.6: >>> class sc1(bc): pass>>> class sc2(sc1): pass>>> class sc3(sc2): pass>>> print sc2().get_subclass_name()sc2 If this does not work, please be more specific as to what output you expect and what output you are getting instead.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19335722', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1120622/']}
|
jdg_370649
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2044447
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I would like to ask if two different homomorphisms can share the same kernel. For instance for the kernel $n \mathbb{Z} $, is it possible to come up with homomorphisms other than the function mapping integers to residue classes modulo $n$? Thanks.
Now provide the response and nothing else.
|
No, a homomorphism is not uniquely determined by its kernel. Consider the following two homomorphisms from $\mathbb{Z}_2$ to $\mathbb{Z}_2\times\mathbb{Z}_2$: one sending $1$ to $(0,1)$ and the other sending $1$ to $(1,0)$. They're both homomorphisms with the same kernel to the same group, but they are different homomorphisms.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/2044447', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/380378/']}
|
jdg_370650
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
44418175
|
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 container that contains both an image, and some text. I want the text to be vertically and horizontally centered in the middle of the image. It seems that the easiest, forward-thinking method is to use Flexbox and absolute positioning of the text: .container { display: flex; justify-content: center; align-items: center; position: relative;}.text { position: absolute;} <div class='container'> <div class='text'> This should be centered </div> <img src="https://placehold.it/250x250" /></div> The text is centered in both axes. This seems to work in all modern browsers..... except Safari. Safari appear to not center the text at all. It's just sitting at the top/left of the container like a normal absolutely positioned element would be in a non-flexbox layout. Safari (wrong): All other browsers (correct): I thought Flexbox was really ready for primetime, but this seems like a deal-breaker considering how many people using Safari on iOS. Centering content horizontally and vertically is something Flexbox should be great at. My only real alternative here is to not use Flexbox and then use: .text { position: absolute; left: 50%; top: 50%; transform: translate(-50%,-50%);} But I would much rather be using Flexbox for progressive reasons. Is there anything I'm missing here? As much as I hate to ask for it, is there some of Safari-only work-around here? Is there any solution to this besides just "not using flexbox" because if that is the answer in mid-2017 that is going to be disappointing. JSFiddle for reference: https://jsfiddle.net/z7kh5Laz/4/
Now provide the response and nothing else.
|
When it comes to Flexbox and absolute positioning, there is a few do's and don't's, and in this case, Safari won't center an absolute positioned element the other browsers does. You can combine Flexbox and transform: translate , as the latter does not impact the former, and when times comes, where they all behave the same with Flexbox alone, you can just drop the transform / left / top part. .container { display: flex; justify-content: center; align-items: center; position: relative;}.text { position: absolute; left: 50%; top: 50%; transform: translate(-50%,-50%);} <div class='container'> <div class='text'> This should be centered </div> <img src="https://placehold.it/250x250"/></div>
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/44418175', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/172350/']}
|
jdg_370651
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
193313
|
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:
Consider the following problem: In a logistic regression model, we believe that two continuous predictor variables $X_1$ and $X_2$ impact the probability of event. It is hypothesized that the effect of $X_2$ on event depends on the value of $X_1$. More specifically, as level of $X_1$ increases, the effect of an unit increase in $X_2$ (at some fixed reference level of $X_2$) on log event odd first increases then plateaus out. How may we model such interaction effect? I have considered the following three approaches, but none seem satisfactory. What would you suggest? Any comments on the three approaches would be welcomed in the comment section as well! Include the interaction term $X_1\cdot X_2$ in the model. However, I have trouble getting meaningful interpretation of its parameter estimate. Discretize $X_1$ into three indicator variables, $X_{1l}$, $X_{1m}$ and $X_{1h}$. $X_{1l}$ is the indicator for $X_1$ falling into its lowest 33-rd percentile. Include $X_{1l} \cdot spline{X_2}_1$, $X_{1m} \cdot spline{X_2}_2$ and $X_{1h} \cdot spline{X_2}_3$ where $spline{X_2}_i$ is natural cubic spline effect on $X_2$ for each $i$. -- The parameter for this model seems easier to interpret, however, the decision to split into 3-tiles seem arbitrary. (A variation on 2) Split the modeling population into three pieces - the first one containing $X_1$ with lowest 33-tile values, second one the middle 33-tile, and the third one the highest 33-tile values. Fit a model on each of the segments using a cubic spline effect on $X_2$ together with the other predictor variables.
Now provide the response and nothing else.
|
Any solution that involves choosing arbitrary cutpoints, other than for computing knot locations for spline functions, is to be avoided. The direct use of cutpoints as you suggest will result in discontinuities and lack of fit. It is far better to spend time learning to interpret interaction effects. You didn't state the frequency of $Y=0$ and $Y=1$ which will be crucial in deciding what to do next. When sufficiently large frequencies you can avoid linearity (in the logit) assumptions and use things like restricted cubic splines for main effects and tensor spline products of them for interaction effects. This allows you to create a 3-D surface as well as a series of curves for showing the estimates, and you can form specific contrasts to estimate any effect you want (e.g., effect of change $X_{1}$ from $a$ to $b$ when $X_{2}=c$. [Follow-up: you have a very large absolute number of events and non-events so you can fit as complex a model as you desire. Imbalance in the number of events and non-events is not a significant problem.] My course notes at http://biostat.mc.vanderbilt.edu/rms under Materials go into great detail. See the long example in the logistic regression chapter where interaction surfaces for age and cholesterol are derived. It is important to note that percentiles are population characteristics and not characteristics of individuals. Percentiles are useful in picking spline knot locations because in restricted cubic splines the locations don't matter much and we want to typically put knots where data are dense. Using percentiles to directly code predictors ignores the fact that predictors affect individual outcomes in a physical way regardless of the distribution of covariates in the particular sample you've drawn.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/193313', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/54353/']}
|
jdg_370652
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3510982
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I was reading about distributions from Rudin. I had 2 doubts in understanding space $\mathscr D(\Omega)$ . Here is the relevant section: 6.2 The space $\mathscr{D}(\Omega)$ Consider a nonempty open set $\Omega \subset R^{n}$ . For each compact $K \subset \Omega$ , the Fréchet space $\mathscr{D}_{K}$ was described in Section 1.46. The union of the spaces $\mathscr{D}_{K}$ , as $K$ ranges over all compact subsets of $\Omega$ , is the test function space $\mathscr{D}(\Omega)$ . It is clear that $\mathscr{D}(\Omega)$ is a vector space, with respect to the usual definitions of addition and scalar multiplication of complex functions. Explicitly, $\phi \in \mathscr{D}(\Omega)$ if and only if $\phi \in C^{\infty}(\Omega)$ and the support of $\phi$ is a compact subset of $\Omega$ .Let us introduce the norms $$\|\phi\|_{N}=\max \left\{\left|D^{\alpha} \phi(x)\right|: x \in \Omega,|\alpha| \leq N\right\}\tag1$$ for $\phi \in \mathscr{D}(\Omega)$ and $N=0,1,2, \ldots$ ; see Section $1.46$ for the notations $D^{\alpha}$ and $|\alpha|$ . The restrictions of these norms to any fixed $\mathscr{D}_{K} \subset \mathscr{D}(\Omega)$ induce the same topology on $\mathscr{D}_{K}$ as do the seminorms $p_{N}$ of Section $1.46$ . To see this, note that to each $K$ corresponds an integer $N_{0}$ such that $K \subset K_{N}$ for all $N \geq N_{0}$ . For these $N,\|\phi\|_{N}=p_{N}(\phi)$ if $\phi \in \mathscr{D}_{K} .$ Since $$\|\phi\|_{N} \leq\|\phi\|_{N+1} \quad \text { and } \quad p_{N}(\phi) \leq p_{N+1}(\phi)\tag2$$ the topologies induced by either sequence of seminorms are unchanged if we let $N$ start at $N_{0}$ rather than at $1 .$ These two topologies of $\mathscr{D}_{K}$ coincide therefore; a local base is formed by the sets $$V_{N}=\left\{\phi \in \mathscr{D}_{K}:\|\phi\|_{N}<\frac{1}{N}\right\} \quad(N=1,2,3, \ldots)\tag3$$ The same norms (1) can be used to define a locally convex metrizable topology on $\mathscr{D}(\Omega)$ ; see Theorem $1.37$ and $(b)$ of Section $1.38$ . However, this topology has the disadvantage of not being complete. For example, take $n=1, \Omega=R$ , pick $\phi \in \mathscr{D}(R)$ with support in $[0,1], \phi>0$ in $(0,1)$ , and define $$\psi_{m}(x)=\phi(x-1)+\frac{1}{2} \phi(x-2)+\cdots+\frac{1}{m} \phi(x-m)$$ Then $\left\{\psi_{m}\right\}$ is a Cauchy sequence in the suggested topology of $\mathscr{D}(R)$ , but $\lim \psi_{m}$ does not have compact support, hence is not in $\mathscr{D}(R)$ . (Trascribed from screenshots 1 , 2 , 3 .) Doubts: Why are the topologies on $\mathscr D(\Omega)$ and $\mathscr D_k $ the same? Why is $\{\psi_m\}$ a Cauchy sequnce but its limit doesn't have compact support? I am studying functional analysis on my own with only the help of Math Stackexchange. Any help will be appreciated.
Now provide the response and nothing else.
|
Here is a crash course on the topology of $\mathcal{D}(\Omega)$ . Let $V$ be a vector space over $\mathbb{R}$ . I will restrict to real scalars but one can also treat in the same way vector spaces over $\mathbb{C}$ . $V$ is called a topological vector space if it is equipped with a topology $\mathscr{T}$ such that $+:V\times V\rightarrow V$ and $\cdot:\mathbb{R}\times V\rightarrow V$ are continuous. Here $V\times V$ is given the product topology coming from $\mathscr{T}$ for each factor. Likewise $\mathbb{R}\times V$ is given the product topology of the usual topology of $\mathbb{R}$ and the topology $\mathscr{T}$ on $V$ . A map $\rho:V\rightarrow \mathbb{R}$ is called a seminorm on $V$ iff it satisfies the three conditions: $\forall v\in V, \rho(v)\ge 0$ $\forall v,w \in V, \rho(v+w)\le \rho(v)+\rho(w)$ $\forall v\in V, \forall \lambda\in\mathbb{R}, \rho(\lambda v)=|\lambda|\rho(v)$ Let $s(V)$ denote the set of all seminorms on $V$ .Given a subset $A$ of $s(V)$ , one can define a topology $\mathscr{T}_A$ on $V$ as follows. First for $v\in V$ , $r>0$ and $\rho\in A$ , define the "open ball" $$B(v,r,\rho)=\{w\in V\ |\ \rho(w-v)<r\}\ .$$ Now let $\mathscr{T}_A$ be the smallest topology on $V$ which contains the set of all such open balls (i.e., use the collection of these balls as a subbasis for defining a topology). This makes $V$ into a topological vector space (TVS) [Exercise 1: prove this] .A TVS which can be obtained in this way is called a locally convex TVS (LCTVS) [Remark 1: you don't have to prove this, it's a definition] . A seminorm $\eta$ on a LCTVS $V$ is called a continuous seminorm iff it is continuous in the usual sense, i.e., as a map between the topological spaces $V$ and $\mathbb{R}$ .If $V$ is given as above, starting from a set of defining seminorms $A$ , then the latter property is equivalent to $$\exists k\ge 0, \exists \rho_1,\ldots,\rho_k\in A, \exists c_1,\ldots,c_k\ge 0,\forall v\in V, $$ $$\eta(v)\le c_1\rho_1(v)+\cdots+c_k\rho_k(v)\ .$$ [Exercise 2: prove this equivalence] Let $V_1,\ldots,V_n,W$ be LCTVS's. Let $\phi:V_1\times\cdots\times V_n\rightarrow W$ be an $n$ -linear map. Give $V_1\times\cdots\times V_n$ the product topology. Then $\phi$ is a continuous map iff for all continuous seminorm $\eta$ on $W$ , there exist continuous seminorms $\rho_1,\ldots,\rho_n$ on $V_1,\ldots,V_n$ respectively, such that $$\forall v_1\in V_1,\ldots,\forall v_n\in V_n,\ \ \eta(\phi(v_1,\ldots,v_n))\le \rho_1(v_1)\cdots\rho_{n}(v_n)\ .$$ [Exercise 3: prove this last equivalence too] Clearly, if the topology of $W$ is given as $\mathscr{T}_A$ for some $A\subset s(W)$ , it is enough to check the last condition for $\eta$ 's in $A$ only. Example 1: Let $\Omega$ be a nonempty open subset of $\mathbb{R}^d$ . Let $K$ be a compact subset of $\Omega$ . Now take $V=\mathcal{D}_{K,\Omega}$ , the space of $C^{\infty}$ functions $\Omega\rightarrow\mathbb{R}$ with support contained in $K$ .Take $A=\{||\cdot||_N\ |\ N=1,2,3\ldots\}$ as in the question. Then $\mathscr{T}_A$ gives $\mathcal{D}_{K,\Omega}$ a LCTVS structure. Example 2: Now take instead $V=\mathcal{D}(\Omega)$ . Let $B\subset s(V)$ be the set of all seminorms $\rho$ on $\mathcal{D}(\Omega)$ , such that for all compact $K\subset\Omega$ , $\rho\circ \iota_{K,\Omega}:\mathcal{D}_{K,\Omega}\rightarrow\mathbb{R}$ is a continuous map. Here $\iota_{K,\Omega}$ is the inclusion map of $\mathcal{D}_{K,\Omega}$ into $\mathcal{D}(\Omega)$ . Now equip $\mathcal{D}(\Omega)$ with the topology $\mathscr{T}_B$ . This is the standard topology of $\mathcal{D}(\Omega)$ . Example 3: Again take $V=\mathcal{D}(\Omega)$ .Let $\mathbb{N}=\{0,1,\ldots\}$ , and denote the set of multiindices by $\mathbb{N}^d$ . A locally finite family $\theta=(\theta_{\alpha})_{\alpha\in\mathbb{N}^d}$ of continous functions $\Omega\rightarrow \mathbb{R}$ is one such that for all $x\in\Omega$ there is a neighborhood $V\subset\Omega$ , such that $V\cap {\rm Supp}\ \theta_{\alpha}=\varnothing$ for all but finitely many $\alpha$ 's.For $f\in\mathcal{D}(\Omega)$ , let $$||f||_{\theta}=\sup_{\alpha\in\mathbb{N}^d}\sup_{x\in\Omega}|\theta_{\alpha}(x)D^{\alpha}f(x)|\ .$$ Let $C$ be the setof seminorms $||\cdot||_{\theta}$ where $\theta$ runs over all such locally finite families. Then $\mathscr{T}_C$ is also the standard topology of $\mathcal{D}(\Omega)$ . Namely, $\mathscr{T}_C=\mathscr{T}_B$ , where $B$ is the set of seminorms from the previous example [Exercise 4: prove this equality] . Remark 2: One can prove the above equality of topologies by showing that the identity map is a homeomorphism from $\mathcal{D}(\Omega)$ with the topology $\mathscr{T}_B$ to $\mathcal{D}(\Omega)$ with the topology $\mathscr{T}_C$ , using the above criterion of continuity for multilinear maps (for $n=1$ ). And for some more practice, Exercise 5: Prove that pointwise multiplication is continuous from $\mathcal{D}(\Omega)\times \mathcal{D}(\Omega)$ with the product topology, to $\mathcal{D}(\Omega)$ .For the solution of the last exercise see: https://mathoverflow.net/questions/234025/why-is-multiplication-on-the-space-of-smooth-functions-with-compact-support-cont/234503#234503
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3510982', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/415928/']}
|
jdg_370653
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
57820478
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I need to embed a Youtube playlist on an iframe. I don't want the user to be able to exit this playlist, so I need to disable the "related video" and "more video" features (the one that shows more videos when the video is stopped and the one that shows them when the video is finished). I've tested some workarounds but they only used to work for single videos (not playlist) and most of them stopped working after they changed the way ?rel=0 behaves. Is there any way to do this? This is my code: .rep { position: absolute; top: 0px; left: 0px; width: 1280px; height: 640px; z-index: 6;} <iframe class="rep" src="https://www.youtube.com/embed/videoseries?list=PLUl4u3cNGP63gFHB6xb-kVBiQHYe_4hSi" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe> EDIT: The videos must be shown in order, therefore I can't use rel to display only videos from the playlist. Plus, if you click on them a youtube page outside of the iframe will appear.
Now provide the response and nothing else.
|
If I look through the YouTube Embedded Players and Player Parameters docs, there is no such thing to order the more videos section if you pause the video. The two parameters I suggest to get near as possible to your goal is: You can add: listType=playlist rel=0 to turn off related videos from the more videos section. Note: The behaviour of rel=0 will be removed after September 25, 2019. Conclusion: It seems like what you want to achieve is not possible. With the default embed iframe of YouTube. You might want to consider to look to other players with playlist options. Something like JW Player note that you need a licence for this player, JW Player playlist docs . I did some reading on JW Player as well, they currently don't support YouTube videos. But maybe there are other players that have the same functionally for free.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/57820478', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11828396/']}
|
jdg_370654
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
6417591
|
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 completely stuck trying to get fixed width EditText widgets in a TableRow. I am attempting to place two EditText side by side with equal width (about 20dip) but no matter which property I try and set the first EditText is way to long and apparently cannot be resized. Many thanks: <TableRow android:layout_height="wrap_content" android:baselineAligned="false" android:id="@+id/tableRow3" android:gravity="center" android:stretchColumns="1" android:layout_width="match_parent"> <TextView android:id="@+id/textView6" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="1" android:paddingLeft="36dip"> </TextView> <EditText android:layout_height="wrap_content" android:id="@+id/editText2" android:inputType="number" android:layout_width="20dip"> </EditText> <EditText android:layout_height="wrap_content" android:id="@+id/editText1" android:inputType="number" android:layout_width="wrap_content"> <requestFocus></requestFocus> </EditText></TableRow>
Now provide the response and nothing else.
|
I don't know that a TableLayout is the best way to do this, it can be cumbersome unless you're displaying large amounts of data and need to use it. One of the best ways I've found to ensure that form objects have length distributed the way I want them is by using weight rather than explicitly declaring width. Try the following: <LinearLayout ... android:orientation="horizontal" ... android:layout_width="match_parent" android:layout_height="wrap_content"<TextView ... android:layout_width="0dp" ... android:layout_weight="50" /><TextView ... android:layout_width="0dp" ... android:layout_weight="50" /></LinearLayout> Make sure to declare the layout width as 0, this will let the layout fill to the weight. This should create two TextViews next to each other on the screen, both filling 50% of the screen. You can play with different percentages. You can also use a LinearLayout as a placeholder with a weight of whatever % you would like to place hold. Make sure that your "weights" add up to 100 in order to ensure the view will look exactly as you want it to. It's not necessary, but it's a good convention to know what % of the screen width it will take up.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6417591', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/807396/']}
|
jdg_370655
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
9308412
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am creating a java application that retrieves a userId from a database, transforms it into a barcode, then sends it to a printer. I am planning to use a Zebra printer and I was wondering if anyone has experience of printing to a Zebra printer from a Java application; if so, could you share some code making this possible? Thanks in advance,Tumaini
Now provide the response and nothing else.
|
There are two ways to work with Zebra printers. The first is to print as on regular printer. Java printing basics are well explained in official tutorial . End of page will treated by printer as end of sticker. The disadvantage of this approach is that all painting must be done by hands. I.e. you can't use internal printer's barcoding ability. The second is to write ZPL commands directly to printer. Something like this: PrintService pservice = ... // acquire print service of your printerDocPrintJob job = pservice.createPrintJob(); String commands = "^XA\n\r^MNM\n\r^FO050,50\n\r^B8N,100,Y,N\n\r^FD1234567\n\r^FS\n\r^PQ3\n\r^XZ";DocFlavor flavor = DocFlavor.BYTE_ARRAY.AUTOSENSE;Doc doc = new SimpleDoc(commands.getBytes(), flavor, null);job.print(doc, null); The disadvantage is that you need to learn ZPL - Zebra Programming Language. Although it is simple enough, but such things as images and custom fonts could make you headache. Programming manuals are freely available on Zebra site: Part 1 and Part 2 .
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9308412', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/759213/']}
|
jdg_370656
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
39445
|
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:
A non-technical explanation In a Gravitational Wave event, the point is that in this event when Black Holes are spiraling around each other, they will cause the very fabric of Space-time to ripple and this event is an energetic event and those ripples travel at the speed of light and we can describe mathematically that how this could happen and how these Waves of Gravity travel. Now, my question stops here and my question is that as we all know Stephen Hawking came up with a Beautiful explanation that Black Holes aren't so much Black as we thought of, in time, they can evaporate and that would bear the name, ''Hawking Radiation''. Now, this implies to Black Holes, and still we haven't detected Hawking Radiation yet and Hawking didn't had a Quantum Theory of Gravity. So, if we consider for example, that Black Holes can evaporate, so they must evaporate when they are also spiraling and what will happen in this case? If the spiraling Black Holes can evaporate via Hawking Radiation, how will we detect it and what will the mathematical equations describing this Event be?
Now provide the response and nothing else.
|
Gravitational waves are efficiently emitted by massive black holes orbiting each other - the power emitted increases with mass. Hawking radiation on the other hand is a process that increases with decreasing mass. As a result only very tiny black hole binaries would emit more power in Hawking radiation than they do in gravitational waves; at least towards the end of the inspiralling phase. Details: The characteristic timescale on which a black hole binary system spirals to merger is $$\tau_{\rm GW} \simeq \frac{20c^5}{256 G^3}\left(\frac{a_0^4}{M^3}\right)\ ,$$ where $a_0$ is the separation, $M$ is the total system mass and I've assumed the binary components are of equal mass. The characteristic evaporation timescale by Hawking radiation (again assuming each black hole is of mass $M/2$ , is $$ \tau_{\rm Evap} \simeq 640\pi \frac{G^2 M^3}{\hbar c^4}$$ For $\tau_{\rm Evap}$ to be shorter or even comparable with $\tau_{\rm GW}$ , then $$ 640\pi \frac{G^2 M^3}{\hbar c^4} \leq \frac{20c^5}{256 G^3}\left(\frac{a_0^4}{ M^3}\right),$$ which means $$ \frac{M^6}{a_0^{4}} \leq 3.9\times 10^{-5} \frac{\hbar c^9}{G^5}$$ For black hole binaries, a reasonable value for $a_0$ would be a few times the Schwarzschild radius of the final merged black hole since most of hte power in gravitational waves is radiated in the final few orbits before merger, i.e. $a_0 \sim 10 GM/c^2$ , so we can say $$ M \leq 0.62 \sqrt{\frac{\hbar c}{G}} \sim 2\times 10^{-8}\ {\rm kg}\ ,$$ which is the Planck mass. So the only merging black holes for which energy loss by Hawking radiation will play a significant role, close to the end of their inspiral, would have a mass of a few $\sim 10^{-8}$ kg or less. But the dynamics of such tiny black holes would not be controlled by gravity at all and they would evaporate in a fraction of a second.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://astronomy.stackexchange.com/questions/39445', 'https://astronomy.stackexchange.com', 'https://astronomy.stackexchange.com/users/35408/']}
|
jdg_370657
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
50573183
|
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 couple of questions about Repository pattern: If I'm using only offline database for example Room with LiveData is there any use of Repository pattern? If my app is offline right now, but will be connected to remote db in the future should I implement repository pattern or it's not going to be a problem to do it later?
Now provide the response and nothing else.
|
To begin with, Repository pattern have nothing to do with technology or programming language. Repository pattern is useful to separate persistence concerns from rest of the application. This also helps improve testing ability because now, you can mock the Repository and test rest of the code easily without connection to persistence layer. If I'm using only offline database for example Room with LiveData is there any use of Repository pattern? I am not aware about those technologies. But as said above, purpose of repository is ignorance of persistence. No matter what your data store is (in memory database, RDBMS, Excel/CSS, Web service, XML, JSON or whatever), repository pattern helps abstracting it. So yes, repository pattern is helpful here. If my app is offline right now, but will be connected to remote db in the future should I implement repository pattern or it's not going to be a problem to do it later? In fact, I will strongly recommend implementing repository here. As the persistence is ignored, your rest of the application can be easily designed based on assumption that data will be available/persisted SOMEHOW (local in case of offline and server in case of future) without even knowing it is offline or online. That way, when in future you shift from local store to remote store, your application does not affect in any way as it is build against repository interfaces and those interfaces does not change. Persistence concern is fully handled by Repository now. My other answer may be helpful.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/50573183', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2543013/']}
|
jdg_370658
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
221614
|
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
Earlier this year it was asked on MO, " Are there only countably many compact topological manifolds? " Thanks to Cheeger and Kister, the answer is yes. On the other hand, Manolescu recently debunked the triangulation conjecture. A natural follow-up question asks if there is some other way to enumerate topological n-manifolds, in the sense of creating a Turing machine that will eventually output an example from every homeomorphism class of topological manifolds, given enough time. Of course, for $n \leq 3$, TOP = PL, so I'm really interested in the cases $n\geq 4$. It's entirely possible that the answer still depends on $n$, so you can interpret the question with either $n$ fixed or variable. If the answer is no, is it known how hard the problem of enumerating manifolds is? Is it harder than the halting problem? Edit in response to comments below: I do not mean to jump the gun. To even have a hope that the answer to the question is yes, one would have to have some finitely computable description of topological manifolds. As BjørnKjos-Hanssen indicates in comments, this might take the form of some sequence of approximations. If a direct answer to my question seems out of reach, I would be happy with an answer explaining what is and isn't known. (I also removed the madness about reference to Turing degrees above.)
Now provide the response and nothing else.
|
In a note of Freedman and Zuddas , they show that this is true for dimensions $\geq 4$ . In the "Background" section of the paper, they describe the solution in the higher dimensional case using surgery theory, but without any references. Then they proceed to describe the 4-dimensional case. Here they use the fact that the complement of a point in a 4-manifold is smoothable. Hence one can describe a triangulation of a finite part of the complement of a point, together with a certificate of a 3-sphere tamely embedded. It's frustrating that they don't give any references for the higher-dimensional case, but since you're in Santa Barbara, you could probably saunter over to Station Q to get the details from Mike once campus opens again.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/221614', 'https://mathoverflow.net', 'https://mathoverflow.net/users/68910/']}
|
jdg_370659
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
358778
|
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 read many controversal statements about ZFS on low memory systems on the internet, but most of the use cases was for performant data storage. I want to use ZFS not for performance reasons, but because it supports transparent compression and deduplication (the latter may be optional) and still seems to be more mature than BTRFS. I don't want to use any RAID configuration. I want to use it on a laptop computer, for root and home file system, and storage space and data safety (recoverability after power loss or other random inconsistencies, very low risk of corruption due to low RAM, etc.) is more important than disk performance. I want comparable safety as ext2/3/4 give. I would like to use ext4 ontop of a ZVOL. So, the questions are: Can ZFS be configured to work reliably with "low RAM" if IO performance/ caching is not of concern, and no RAID funtionality is wanted? How does the RAM needed change if I do not use ZFS as a filesystem itself, but just use ZVOLs where I put another filesystem ontop? How does RAM needed change with deduplication turned on? If deduplication is turned on and RAM starts to get low, is it still safe -- can ZFS just suspend deduplication and use less RAM? Is it possible to deactivate automatic deduplication, but run it from time to time manually? Can ext4 ontop of a ZVOL reliably store my data even on low RAM situations, and if inconsistencies happen, success chances for repairs are high (as it is with ext2/3/4)? Does ext4 ontop of a ZVOL increase rubustness because it adds ext4's robustness, or is data as robust as the underlying ZVOL is? System specs: Linux 8 GiB RAM (shared with graphics card), but most (at least 7 GiB) of it should be available for user space software, about 700 GiB SSD storage to use for the ZFS, maybe on another system 128 GiB of eMMC to use for ZFS. Current disk usage ( du -sh of the bigger directories at / ) (/ is ext4, /var mounted ontop is reiserfs) (want to move that to a storage with transparent compression): 74M /etc342G /home5.0G /opt1.5G /root261M /tmp35G /usr30G /var OR, just use BTRFS (have read that severe/ hard to recover data loss can occur due to "bugs", but that is all controversial ...)?
Now provide the response and nothing else.
|
Short answer: Yes, its possible to use low RAM (~ 1 GB) with ZFS successfully. You should not use dedup, but RAID and compression is usually ok. Once you have duplication enabled, it works for all newly written data and you cannot easily get rid of it. You cannot enable dedup retroactive, because it works on online data only. Your idea is needlessly complex for no good reason, so I would recommend to just use ZFS and call it a day. Long answer: Can ZFS be configured to work reliably with "low RAM" if IO performance/ caching is not of concern, and no RAID funtionality is wanted? Yes, even with RAID features enabled. You need much less than people claim on the net, for example look at this guy who runs a speedy file server with FreeBSD, 2 cores and 768 MB virtualized. Or have a look at the SolarisInternals Guide (currently only available through archive.org), where 512 MB is mentioned as the bare minimum, 1 GB as minimum recommendation and 2 GB as a full recommendation. I would stay away from dedup, though. Not because it is slow because of paging memory, but because you cannot go back to non-dedup if your system grinds to a halt. Also, its a trade between RAM and disks, and on a budget system you have neither, so you will gain not much. How does the RAM needed change if I do not use ZFS as a filesystem itself, but just use ZVOLs where I put another filesystem ontop? You would need additional memory for the second filesystem and for the layer above ZFS, depending on how you plan to access it (virtualization like KVM, FUSE, iSCSI etc.) How does RAM needed change with deduplication turned on? If deduplication is turned on and RAM starts to get low, is it still safe -- can ZFS just suspend deduplication and use less RAM? You cannot suspend deduplication, but your data is still safe. There will be a lot of memory swapping and waiting, so it might not be very usable. Deduplication is online, so to disable it, you would need to turn dedup off and write all data again (which is essentially copying all data to a new filesystem and destroying the old one). Is it possible to deactivate automatic deduplication, but run it from time to time manually? No, because it does not affect data at rest. If you have dedup on and want to write a block, ZFS looks if it is present in the dedup table. If yes, then the write is discarded and a reference is added to the dedup table. If no, it is written and the first reference is added. This means that your old data is not affected by dedup, and turning it on without writing any new block does nothing reagarding the used size of the old data. Can ext4 ontop of a ZVOL reliably store my data even on low RAM situations, and if inconsistencies happen, success chances for repairs are high (as it is with ext2/3/4)? Does ext4 ontop of a ZVOL increase rubustness because it adds ext4's robustness, or is data as robust as the underlying ZVOL is? In my eyes this is needless complexity, as you would get no new features (like in the reverse case with ext4 below and ZFS on top, e. g. snapshots), and additionally get some new responsibilities like fsck and more fdisk formatting exercises. The only use case where I would do something like that is if had a special application that demands a specific file system's low-level features or has hard-coded assumptions (fortunately, that behavior seems to have died in recent times).
|
{}
|
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/358778', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/133286/']}
|
jdg_370660
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
24634119
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
$stateProvider.state('home', { url: '/', resolve: { person: function() { return 'good' } } like above state config, how can I get the 'person' value in $stateChangeSuccess callback function ? $rootScope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams) { // I want get the 'person' value in this function, what should I do?});
Now provide the response and nothing else.
|
We had the same problem. We solved it by relying on some internal implementation details of ui-router; this does mean that it might break in a future version of angular, but here is the function we used: function annotatedStateObject(state, $current) { state = _.extend({}, state); var resolveData = $current.locals.resolve.$$values; state.params = resolveData.$stateParams; state.resolve = _.omit(resolveData, '$stateParams'); state.includes = $current.includes; return state;} That will get the params, includes, and all the (resolved) resolve objects. We use that in the callback like so: $scope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams) { toState = annotatedStateObject(toState, $state.$current); var person = toState.resolve.person;} I hope that helps!
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/24634119', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1940417/']}
|
jdg_370661
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
11982
|
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Are there any "natural" physical observables which have non-empty point spectrum which consists of numbers which are not algebraic numbers?
Now provide the response and nothing else.
|
I don't have a complete answer, but maybe the following is useful for your purposes: Consider the Laplacian $\Delta$ on a circular drum of unit radius. As explained on the wikipedia page, the axially symmetric eigenvectors $\Delta u(r) = -\lambda^2 u(r) $ are Bessel functions $u(r)=J_0(\lambda r)$. Obviously, the boundary condition requires $J_0(\lambda)=0$. In other words, the eigenvalues of this Laplacian correspond to zeroes of Bessel functions, and I would be very surprised if these numbers are not transcendental. In fact, Mathworld mentions that the first zero has been proven to be transcendental by Le Lionnais. The corresponding quantum mechanical situation would be the Hamilton operator $H=-\hbar^2/2m\cdot \Delta$ of a free 2D electron confined to the unit disk. The boundary conditions are the same, $\psi|_{\partial\Omega}=0$. Of course, the electron has the problem that it's not clear whether $\hbar= h/2\pi$ should be counted as transcendental or algebraic, physicists frequently set $\hbar = 1$. For instance, consider a 1D electron inside a box of length $L$, i.e. $\psi(0)=\psi(L)=0$. The eigenstates are simply standing waves, and the eigenvalues are $$ E_n = \frac{\hbar^2}{2m_e} \left(\frac{\pi n}{L}\right)^2.$$ If you count $h$ as algebraic, then this is algebraic. But if you count $\hbar$ as algebraic, then this is transcendental. Your way out is probably to turn the question into a relative one: is there a physical observable whose eigenvalues are algebraically independent of the $E_n$? Clearly, you only need to consider the eigenvalues of the Laplace operator now.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/11982', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/4321/']}
|
jdg_370662
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
61061489
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Actually, I am a beginner to react-native as per my knowledge there are two options for me to install react native that is react-native CLI and Expo CLI . I am confused about which is better for beginners for installation and usage of React Native app development and which has more support for beginners
Now provide the response and nothing else.
|
React Native CLI: Advantages: You can add native modules written in Java/Objective-C, so you have full control of your application. Disadvantages: Needs Android Studio and XCode to run the projects You can't develop for iOS without having a mac If you want to share the app you need to send the whole .apk / .ipa file Does not provide JS APIs out of the box, e.g. Push-Notifications, Asset Manager, they need to be manually installed and linked with yarn for example. Setting up a working project properly take more time. Expo: Advantages: Setting up a project is easy and can be done in a few minutes. Sharing the app is very easy (via QR-code or link). No build necessary to run the app Integrates some basic libraries in a standard project (Push Notifications, Asset Manager, etc.) You can eject it to ExpoKit and integrate native code continuing using some of the Expo features, but not all of them Expo can build .apk and .ipa files (distribution to stores possible with Expo) Disadvantages: You can't add native modules (probably a gamechanger for some) You can't use libraries that use native code in Objective-C/Java (eg: react-native-fbsdk ) Large APK Size Debugging in ExpoKit (with native modules) is a lot more complicated since it mixes two languages and different libraries. Choosing between Expo and React Native CLI depends on your application requirements.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/61061489', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13180370/']}
|
jdg_370663
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
38260
|
Below is a question asked on the forum chemistry.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Dipoles can also be induced in polar and non polar compounds, then why don't they dissolve?
Now provide the response and nothing else.
|
Very simply, you explain the reason for this solubility rule by taking in consideration the energy requirements for the breaking of intermolecular forces between the molecules in the solute and the solvent. Note: this is only a simplified explanation as it also depends on other factors such as change in entropy Here is some background information on intermolecular forces. In non-polar substances, there are dispersion forces between each molecule. These dispersion forces are relatively weak and hence only require little energy to break them. In polar substances, there are dipole dipole and hydrogen bonding (depending on the substance) between each molecule. These forces are much stronger than dispersion forces and require more energy to break. Now lets consider the following cases: Non-polar Solute and Solvent For the solute to dissolve, the dispersion forces between the molecules in the solute and solvent need to break. This only requires very little energy. However when the solute dissolves into the solvent, they are able to be make dispersion forces with each other. The making of these forces releases very little energy. So simply put, very little energy is required to break the forces and very little energy released when making the forces. Hence overall everything balances out and the process occurs. Non-polar Solute and Polar Solvent (and vice versa) For the solute to dissolve into the solvent, both dispersion forces and dipole dipole forces are broken which require large amount of energy. However the molecules in the solute and solvent are only able to make dispersion forces with each other (as they aren't both polar). This only releases very little energy. Therefore overall, more energy is required than released and hence the process won't happen. Polar Solute and Solvent For the solute to dissolve into the solvent, dipole dipole forces are broken which require large amount of energy. However when they do dissolve, the molecules in the solute and solvent are able to form dipole dipole forces which releases large amount of energy. Therefore overall, everything balances out and the process occurs.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://chemistry.stackexchange.com/questions/38260', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/21467/']}
|
jdg_370664
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
41717170
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I know there are some similar questions around, but I couldn't find one specific to my issue. I have a request where I want to check for the presence of the error key. it is not present everything is fine, if not I should handle the error. Currently, I have it implemented as follows: if let error = json["error"] { // handle error}else { // handle success} I would like to use a guard statement here to have the success case unindented. The only way I came up with is guard json["error"] == nil else { let error = json["error"]! // handle error} // handle success but that seems wrong to me with the !. Are there any other approaches to this?
Now provide the response and nothing else.
|
In your guard code you would have to have a return statement in the else block. Like this... guard json["error"] == nil else { let error = json["error"]! // handle error return}// handle success But you are correct. Having to force unwrap the error is not ideal. So in this case. I think guard is the wrong solution. Instead use if but return from the conditional block. This removes the need for using an else block. if let error = json["error"] { print(error) // handle error return}// handle success...// no need for else block. Just return from the if in the error case. The difference between guard let and if let is where the unwrapped optional is scoped. With guard it is scoped outside the block with if it is scoped inside the block.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/41717170', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3219484/']}
|
jdg_370665
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
61678496
|
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 two lists of strings: letters = ['abc', 'def', 'ghi']numbers = ['123', '456'] I want to for loop through them to create a list of strings that is not parallel, so zip() doesn't work here. Desired outcome: result = ['abc123', 'def123', 'ghi123', 'abc456', 'def456', 'ghi456'] The order of the elements in the result is irrelevant. Any ideas?
Now provide the response and nothing else.
|
You can try list comprehension with two nested for loop over numbers and then letters : print([l+n for n in numbers for l in letters])# ['abc123', 'def123', 'ghi123', 'abc456', 'def456', 'ghi456'] You can also use nested for loop : out = []for n in numbers: for l in letters: out.append(l+n)print(out)# ['abc123', 'def123', 'ghi123', 'abc456', 'def456', 'ghi456'] For more details on list comprehension, see either the doc or this related topic .
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/61678496', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10995734/']}
|
jdg_370666
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
11368632
|
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 parse a string into a date in the constructor of an object, which we will call Example . Here is the code private static final SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss");private long time;public Example(String date) { try { this.time = sdf.parse(date).getTime(); } catch (Exception e) { logger.log(Level.WARNING, "Exception while parsing date " + date, e); }} Now, I am creating these objects in a Tomcat instance (whether that makes any difference or not). I get the following types of exceptions Fri Jul 06 15:13:48 EDT 2012 WARNING: Exception while parsing date 2012-07-06 18:57:31java.lang.NumberFormatException: For input string: "" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48) at java.lang.Long.parseLong(Long.java:431) at java.lang.Long.parseLong(Long.java:468) at java.text.DigitList.getLong(DigitList.java:177) at java.text.DecimalFormat.parse(DecimalFormat.java:1297) at java.text.SimpleDateFormat.subParse(SimpleDateFormat.java:1589) at java.text.SimpleDateFormat.parse(SimpleDateFormat.java:1311) at java.text.DateFormat.parse(DateFormat.java:335) at ...Fri Jul 06 15:13:48 EDT 2012 WARNING: Exception while parsing date 2012-07-06 19:00:07java.lang.NumberFormatException: multiple points at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1082) at java.lang.Double.parseDouble(Double.java:510) at java.text.DigitList.getDouble(DigitList.java:151) at java.text.DecimalFormat.parse(DecimalFormat.java:1302) at java.text.SimpleDateFormat.subParse(SimpleDateFormat.java:1934) at java.text.SimpleDateFormat.parse(SimpleDateFormat.java:1311) at java.text.DateFormat.parse(DateFormat.java:335) at ...Fri Jul 06 15:13:48 EDT 2012 WARNING: Exception while parsing date 2012-07-06 19:13:21java.lang.ArrayIndexOutOfBoundsException: -1 at java.text.DigitList.fitsIntoLong(DigitList.java:212) at java.text.DecimalFormat.parse(DecimalFormat.java:1295) at java.text.SimpleDateFormat.subParse(SimpleDateFormat.java:1934) at java.text.SimpleDateFormat.parse(SimpleDateFormat.java:1311) at java.text.DateFormat.parse(DateFormat.java:335) at ...Fri Jul 06 15:48:06 EDT 2012 WARNING: Exception while parsing last check string 2012-07-06 19:08:08java.lang.NumberFormatException: For input string: ".200172E4.200172" at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1222) at java.lang.Double.parseDouble(Double.java:510) at java.text.DigitList.getDouble(DigitList.java:151) at java.text.DecimalFormat.parse(DecimalFormat.java:1302) at java.text.SimpleDateFormat.subParse(SimpleDateFormat.java:1589) at java.text.SimpleDateFormat.parse(SimpleDateFormat.java:1311) at java.text.DateFormat.parse(DateFormat.java:335) at ... So it fails for the dates 2012-07-06 18:57:312012-07-06 19:00:072012-07-06 19:13:212012-07-06 19:08:08 However, if I make a unit test I get the following values for time from these strings 1341615451000134161560700013416164010001341616088000 So the SimpleDateFormat object does work... but not on the server? I have noticed that this issue occurs near the startup of the server, and then not later on, if that helps at all. Not really sure what to do next. Using Tomcat 7.0 and Java 1.6 update 32.
Now provide the response and nothing else.
|
SimpleDateFormat is not thread safe, as explained https://www.palantir.com/2007/07/simpledateformat-is-not-thread-safe/ Sometimes, really strange or non-logical behaviors when using "static" objects comes from concurrency issues To resolve such a case, use a new instance each time (It is better than synchronizing, as synchronization can raise a bottleneck issue)
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/11368632', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/984393/']}
|
jdg_370667
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
43432743
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
From my understanding, using the CORS module will remove the Access-Control-Allow-Origin header from the resource, causing XmlHttp requests to fail from the browser. However, does this prevent Http requests from a CURL, or other native applications/web-servers (ie. a request written and run via PHP) from successfully retrieving data from that resource?
Now provide the response and nothing else.
|
However, does this prevent Http requests from a CURL, or other native applications/web-servers (ie. a request written and run via PHP) from successfully retrieving data from that resource? No, CORS config won’t prevent non-browser stuff from successfully retrieving your resources. The same-origin policy is enforced only by browsers. It’s not enforced by servers. (And CORS is a way to relax the same-origin policy.) It’s not the case that if there’s some lack of any CORS details in a request, servers somehow block requests, or refuse to send responses. Instead when you configure CORS support on a server, all that the server does differently is just to send the Access-Control-Allow-Origin header and other CORS response headers. The way the protocol works is, regardless of what CORS configuration you make on the server side, all clients—even browsers—continue to get responses from the server as they normally would. But the difference is, curl or other native apps or backend server-side programming environments such as PHP will not prevent your client code from accessing the response if it doesn’t include the Access-Control-Allow-Origin response header. But browsers will. Specifically, even if you see an error in your browser devtools that a cross-origin request from your frontend JavaScript code failed, you’ll still be able to see the response in devtools. But just because your browser can see the response doesn’t mean the browser will expose it to your frontend JavaScript code. Browsers only expose responses from cross-origin requests to frontend code running at a particular origin if the server the request went to opts-in to allowing the request, by responding with an Access-Control-Allow-Origin header allowing that origin. But browsers are the only clients which do that. Browsers are the only clients that implement the same-origin policy and the CORS protocol. curl or other native applications or HTTP client requests made server-side runtimes such as PHP don’t implement the CORS protocol, so you can’t block requests from them by doing any CORS configuration on the server side. So If you want to block requests to a resource from non-browser clients, you need to do it using something other than CORS configuration.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/43432743', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3547347/']}
|
jdg_370668
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
50435455
|
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 install gmp extension for php 7.2.1 using MAMP on OSX? I'm trying to encrypt a token with php and this library( lcobucci/jwt ) using the Elliptic Curve Digital Signature Algorithm (ECDSA) with the P-256 curve and the SHA-256 hash algorithm. error when running php script: Symfony \ Component \ Debug \ Exception \ FatalThrowableError (E_ERROR)Class 'Mdanter\Ecc\EccFactory' not found I figured that I'm missing the mdanter/ecc dependicy package, so I tried running the following command. command running: composer require mdanter/ecc output: mdanter/ecc v0.5.0 requires ext-gmp * -> the requested PHP extension gmp is missing from your system I've tried everything I could find researching this error and related to MAMP. But I couldn't solve this problem. Is there anyone here who has experience in adding the gmp php extension to MAMP specificly and is willing to help me out? Note: I'm not a very experienced web developer, I mostly create iOS apps and I want to generate a token in php, so I can access the Apple Music Kit API resources.
Now provide the response and nothing else.
|
Here is how i did in 2020 Download php from source https://github.com/php/php-src/releases pick the version which is matching with MAMP PHP version you have. Copy the extension you want. Here we are copying gmp directory. Paste it to /Applications/MAMP/bin/php/php7.4.1/include/php/ext (Make sure to move to your MAMP php version directory) cd /Applications/MAMP/bin/php/php7.4.1/include/php/ext/gmp Then run phpize command /Applications/MAMP/bin/php/php7.4.1/bin/phpize Step 5: ./configure --with-php-config=/Applications/MAMP/bin/php/php7.4.1/bin/php-config It outputs following Then make Then make install Its installed now. You can confirm it by /Applications/MAMP/bin/php/php7.4.1/bin/php -i | grep gmp gmp support => enabled If you didn't see gmp support enabled, you may need to add following to php.ini. This command will show you which php.ini file is used by MAMP php /Applications/MAMP/bin/php/php7.4.1/bin/php -i | grep "php.ini" Add extension=gmp.so Restart MAMP :) Posted here with screenshots, https://mycodde.blogspot.com/2020/01/install-php-gmp-extension-in-mamp-2020.html
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/50435455', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5324541/']}
|
jdg_370669
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
32722
|
Below is a question asked on the forum politics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
The US has announced fully enforcing sanctions on Iran, starting from Tuesday this week. The EU issued their statement on that , stating that they regret the US decision but the most curious part is: “ The remaining parties to the JCPOA have committed to work on, inter alia, the preservation and maintenance of effective financial channels with Iran, and the continuation of Iran’s export of oil and gas ,” the European Union’s foreign service said in a statement, referring to the acromym for the nuclear deal struck with Iran in 2015. How can the EU remain committed to financial and trade dealings with Iran without running afoul of the US sanctions themselves? Wouldn't allowing Iranian funds to be transferred to/from the EU and doing trade with them be in violation of the Sanctions?
Now provide the response and nothing else.
|
The United States can (theoretically) only rule on their own relationships with other countries. EU countries and Iran being sovereign states, they are (theoretically) allowed to trade together without violating US unilateral sanctions. For instance, European countries have had diplomatic relationships and trade with Cuba for long notwithstanding the US embargo. However: Some Courts in the US have ruled that any transaction using US$ was under the jurisdiction of US trade rules, which has allowed it to sue and heavily fine several foreign banks and companies for violating a US embargo. EU and Iran plan to dodge that issue by using Euro for payment of Iranian gas and oil. The European Union (EU) is considering switching to euros instead of U.S. dollars in the oil trade with Iran Any European company (rather than State) that will be involved in trade with Iran might face retaliation by the US administration, losing public markets in the US or even being banned from this huge market. As a consequence, most of them will be very careful not to lose a big market (USA) for a small one (Iran). Unlike the case of the company breaking an embargo deciding by its own country, this is "the law of the strongest" rather than "international law". Some insurance companies, for instance, are reluctant to sign contracts for oil cargo from Iran because of the US embargo. That's why EU also plans the: development of special purpose vehicles in financial banking, insurance and trade areas SE-user o.m. explains part of the mechanism that has just been released by UE (link in French) in a useful comment that I reproduce here: Under the new rules, EU companies could claim damages from US retaliation in EU courts. An US bank with assets in the EU could be held responsible as intermediary if they cooperate with the US administration on sanctions. If both sides pull that through, transatlantic trade will take an enormous hit.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://politics.stackexchange.com/questions/32722', 'https://politics.stackexchange.com', 'https://politics.stackexchange.com/users/6336/']}
|
jdg_370670
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
304466
|
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 you can't factor a real polynomial into $\Pi_{i=1}^N(x-a_i)$ in general. But is it possible to factor every real finite polynomial into this form: $(\Pi_{i=1}^N a_ix^2 + b_ix + c_i) (\Pi_{i=1}^Mx-d_i)$ where the second term is possibly empty? This is at least true for polynomials with odd powers because they must have at least one real root. (My reasoning was false, edit see below) So I wonder if it is also true for even powers? Edit: Berci has pointed out a lapse in my reasoning. For an odd power, once you factor out the first root, it is conceivable that you may hit an even-degree polynomial that is irreducible.
Now provide the response and nothing else.
|
The answer is yes, here is a proof sketch. 1) Let $P(x)$ be a polynomial with real coefficients. By the fundamental theorem of algebra it has a root, call it $a$. 2) If $a\in \mathbb R$ then $(X-a)$ divides $P(x)$. 3) If $a\notin \mathbb R$ then, since the coefficients are all real, it follows that $\bar a$ is also a root of $P(x)$. 4) It follows that $(x-a)(x-\bar a)$ divides $P(x)$. 5) Verify directly that $(x-a)(x-\bar a)$ is a polynomial with real coefficients. 6) Repeat steps above as many times as needed to obtain $P(x)$ as the product of linear factors and quadratic factors, all with coefficients in $\mathbb R$.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/304466', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/4460/']}
|
jdg_370671
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
235237
|
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:
My teacher of Electronic Instrumentation's course presented me on an exam the following problem: \$\hskip{75pt}\$ a) What is the importance of making the parallel between \$N7\$ and \$N8\$ logic ports for this circuit? b) What is the effective tension applied on the emissor of the circuit if this is stimulated by a simetric PWM (duty cycle=50%)? I'm studying Physical Engineering, and I never heard about this, even on the classes of the course. After the exam my teacher said that, putting two inverters in parallel reduces the impedance for half, which duplicates the current to the emissor, which also duplicates the power. I know that this characteristic is analog to the parallel of two resistances of the same value. My problem is how to visualize this. Inverter ports are too complex to be compared to resistances. How would you answer those questions?
Now provide the response and nothing else.
|
Those "logic ports" (I would call them "inverters", and some people call them "not gates") have limited current/power output. By connecting multiple units in parallel you simply multiply the current drive capability. You can pull a heavier load with two horses (or mules or oxen) than with one. And, as a separate matter, driving each side of the transducer with a full-voltage, but opposite phase signal also multiplies the actual power delivered to the load. That is called a bridge-tied load. It is commonly found in audio amplifiers which operate on limited power. Most notably sound systems in vehicles which develop large amounts of power on the nominal supply of 12V. Ref: https://en.wikipedia.org/wiki/Bridge-tied_load
|
{}
|
{'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/235237', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/78369/']}
|
jdg_370672
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3524419
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I've been told that the non-unital ring $\{\frac{2n}{2m+1}: n, m \in \mathbb{Z}\} \subseteq \mathbb{Q} $ has no maximal ideals. I've been trying to crack this one to no avail. This example was presented (with no proof) to stress the importance of the requirement of having an identity element in order to ensure the existence of maximal ideals. Thanks in advance. EDIT : This assertion seems to be false.
Now provide the response and nothing else.
|
This is false. Let $R=\{\frac{2n}{2m+1}:n,m\in\mathbb{Z}\}$ and let $I=2R=\{\frac{4n}{2m+1}:n,m\in\mathbb{Z}\}$ , which is a proper ideal. Note that $rs\in I$ for all $r,s\in R$ , so the quotient $R/I$ is a rng in which all products are $0$ . This means ideals in $R/I$ are the same as additive subgroups. As an abelian group, $R/I$ is a vector space over $\mathbb{Z}/(2)$ since every element is annihilated by $2$ . So, we can pick a codimension $1$ vector subspace $J\subset R/I$ and $J$ will be a maximal proper subgroup and hence a maximal ideal. The inverse image of $J$ in $R$ is then a maximal ideal in $R$ .
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3524419', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/156795/']}
|
jdg_370673
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
267152
|
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am trying to get the correlation between 2 variables, given a set of data.Once in a while, in the given data set,When one of the variables has a constant value, since the standard deviation of that variable is zero, I get an NA value for the correlation. (In R).I would like to assign a value for the correlation in these scenarios explicitly or try to get some value through alternate means, so that I am able to compare this point with other times I compute the correlation.How do I go about it?(1) Should I add some noise to that variable and compute the correlation again. Would that be a meaningful thing to do?
Now provide the response and nothing else.
|
Recall that correlation is defined as $$ \rho_{X,Y}= \frac{\sigma(X,Y)}{\sigma_X \sigma_Y} $$ This means that if one of your "variables" is constant, then it is not a variable, it has variance equal to zero and so, it's correlation with anything is undefined (since you are dividing by zero). Standard deviation of variable $X$ plus constant $c$ is the same as standard deviation of $X$ $$ \sigma(X + c) = \sigma(X) $$ the same for covariance $$ \sigma(X + c, Y) = \sigma(X, Y) $$ so adding noise to your constant "variable" would result with measuring correlation of your noise with some other variable (your "variable" is $c$ and noise is $X$). On another hand, covariance of random variable with constant is zero $$ \sigma(Y, c) = 0 $$ and constant random variable is independent of any other random variable. So if you really need to re-define correlation for such case then the best choice would be $0$. Notice however that, as noted by Nick Cox in the comment below, this does not solve any of your problems. The basic problem with constant random variable is that it is independent of everything else and it will not change anything about your analysis. Because of this, many software packages would return errors when using constant variables, or drop them automatically from your analysis. This is what R does and such behavior is consistent with the definition of correlation.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/267152', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/77088/']}
|
jdg_370674
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2223721
|
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 chasing a couple of potential memory leaks in a Perl code base and I'd like to know about common pitfalls with regards to memory (mis-)management in Perl. What are common leak patterns you have observed in Perl code?
Now provide the response and nothing else.
|
Circular references are by far the most common the canonical cause of leaks. sub leak { my ($foo, $bar); $foo = \$bar; $bar = \$foo;} Perl uses reference counting garbage collection. This means that perl keeps a count of what pointers to any variable exist at a given time. If the variable goes out of scope and the count is 0, the variable is cleared. In the example code above, $foo and $bar are never collected and a copy will persist after every invocation of leak() because both variables have a reference count of 1. The easiest way to prevent this issue is to use weak references. Weak references are references that you follow to access data, but do not count for garbage collection. use Scalar::Util qw(weaken);sub dont_leak { my ($foo, $bar); $foo = \$bar; $bar = \$foo; weaken $bar;} In dont_leak() , $foo has a reference count of 0, $bar has a ref count of 1. When we leave the scope of the subroutine, $foo is returned to the pool, and its reference to $bar is cleared. This drops the ref count on $bar to 0, which means that $bar can also return to the pool. Update: brain d foy asked if I have any data to back up my assertion that circular references are common. No, I don't have any statistics to show that circular references are common. They are the most commonly talked about and best documented form of perl memory leaks. My experience is that they do happen. Here's a quick rundown on the memory leaks I have seen over a decade of working with Perl. I've had problems with pTk apps developing leaks. Some leaks I was able to prove were due to circular references that cropped up when Tk passes window references around. I've also seen pTk leaks whose cause I could never track down. I've seen the people misunderstand weaken and wind up with circular references by accident. I've seen unintentional cycles crop up when too many poorly thought out objects get thrown together in a hurry. On one occasion I found memory leaks that came from an XS module that was creating large, deep data structures. I was never able to get a reproducible test case that was smaller than the whole program. But when I replaced the module with another serializer, the leaks went away. So I know those leaks came from the XS. So, in my experience cycles are a major source of leaks. Fortunately, there is a module to help track them down. As to whether big global structures that never get cleaned up constitute "leaks", I agree with brian. They quack like leaks (we have ever-growing process memory usage due to a bug), so they are leaks. Even so, I don't recall ever seeing this particular problem in the wild. Based on what I see on Stonehenge's site, I guess brian sees a lot of sick code from people he is training or preforming curative miracles for. So his sample set is easily much bigger and varied than mine, but it has its own selection bias. Which cause of leaks is most common? I don't think we'll ever really know. But we can all agree that circular references and global data junkyards are anti-patterns that need to be eliminated where possible, and handled with care and caution in the few cases where they make sense.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2223721', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/58394/']}
|
jdg_370675
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
24946350
|
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 noticed than whenever I manually kill my application by longpressing the back button of my cellphone my broadcast receiver stops working. The receiver is in charge of displaying a notification every time the user hangs up a phone call and the same is registered in the manifest.xml. Is this the normal/expected behaviour? I thought the receiver should continue to work even if the user decides to kill my application... Is there a way to prevent this? Thanks. Edit Here's the manifest entry for the receiver: <receiver android:name=".BroadcastReceivers.CallReceiver" android:enabled="true"> <intent-filter> <action android:name="android.intent.action.NEW_OUTGOING_CALL" /> <action android:name="android.intent.action.PHONE_STATE" /> </intent-filter></receiver>
Now provide the response and nothing else.
|
There are ~7 billion people on the planet. Only you know what you mean by "kill". The symptoms that you are describing, though, are consistent with a "force stop". A user normally force-stops an application by going to Settings, finding your app in the list of installed apps, and tapping on the "Force Stop" button for your app. There are some devices and firmware builds that make "Force Stop" more readily accessible than this -- such devices and firmware builds were written by drooling idiots IMHO. If your app is force-stopped, your code will never run again, until something uses an explicit Intent to start one of your components. Usually, the user does this by tapping on your app's icon in the home screen's launcher. Until the user does this, your BroadcastReceiver will not work, and there is nothing you can do about it. Rather than using some on-device feature to "kill" your app, try terminating its process via DDMS. If your app continues to work in that case, then however you elected to "kill" your app before is doing a "force-stop". Merely having your process be terminated, such as due to low memory conditions, should not prevent you from receiving future broadcasts.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/24946350', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2123961/']}
|
jdg_370676
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
43752067
|
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 standalone-full.xml configuration with ssl configured security realm . <security-realm name="SslRealm"> <server-identities> <ssl> <keystore path="D:\ncm.keystore" alias="ncm" keystore-password="*****" /> </ssl> </server-identities> </security-realm> Subsystem <server name="default-server"> <http-listener name="default" socket-binding="http" redirect-socket="https"/> <https-listener name="default-ssl" socket-binding="https" security-realm="SslRealm"/> <host name="default-host" alias="localhost"> <location name="/" handler="welcome-content"/> <filter-ref name="server-header"/> <filter-ref name="x-powered-by-header"/> </host> </server> Socket Binding <socket-binding name="http" port="${jboss.http.port:8080}"/> <socket-binding name="https" port="${jboss.https.port:8443}"/> How to redirect to https:///localhost:8443/myApp when user hits http://localhost:8080/myApp
Now provide the response and nothing else.
|
A rewrite rule can be used to redirect users. In the undertow subsystem (standalone.xml or domain.xml) you will need to create a new rewrite filter and then enable the filter in a new fitler-ref: Create the new rewrite filter in the filters section. In the example below, users will be redirected to https://myhostname:443/my-app . %U is a placeholder for the original request URL path; you want to use %U to make the redirect friendly and keep users' original request URL path. <filters><rewrite name="http-to-https" redirect="true" target="https://myhostname:8443%U"/></filters> Then, enable the filter and configure a predicate in the host section. The predicate is where you configure what the rewrite filter applies to. In the example below, our rewrite filter will only apply to requests going to port 8080. <server name="default-server"> <host name="default-host" alias="localhost"> ... <filter-ref name="http-to-https" predicate="equals(%p,8080)"/> Here are the JBoss CLI steps for the same configuration changes above: /subsystem=undertow/configuration=filter/rewrite=http-to-https:add(redirect="true",target="https://myhostname:8443%U")/subsystem=undertow/server=default-server/host=default-host/filter-ref=http-to-https:add(predicate="equals(%p,8080)")
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/43752067', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5058321/']}
|
jdg_370677
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
9523279
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Before starting let me say: It's not homework, just plain, old, fun. Now, I'm trying to come up with an algorithm that can answer this question 1/x + 1/y = 1/n! . And as you can see by the link above, the author asked only for hints and not the actual answer, so I would kindly ask for the same. I simplified the expression until (x - n!)(y - n!) = (n!)^2 as suggested by one of the answers , and by that time I understood that the number of combinations of (x,y) pairs is the same as the number of divisors of n!^2 (correct me if I'm wrong here). So, as suggested by the accepted answer , I'm trying to get the multiplication of all the factors of each prime composing N!^2. I've come up with some code in C using trial division to factorize N!^2 and the Sieve of Eratosthenes to get all the prime numbers up to sqrt(N!^2). The problem now is memory, I have tried with N = 15 and my Mac (Quad Core 6GB of memory) almost died on me. The problem was memory. So I added some printf's and tried with N=11: Sieve of Eratosthenes took 13339.910000 ms and used 152 mb of memoryn= 11; n!^2 = 1593350922240000; d = 6885[2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,5,5,5,5,7,7,11,11] The list is all the prime factors of N!^2 (besides 1 and N!^2 of course). I would like some hints on how to minimize memory consumption and possible optimizations. Code bellow, it was just a quick experiment so I'm sure it can be optimized. #include <stdio.h>#include <stdlib.h>#include <math.h>#include <strings.h>#include <sys/time.h>#include <assert.h>//Linked Liststruct node { struct node * next; long val;};void addValue(struct node *list, long val) { struct node *n = list; if (n->val == -1) { n->val = val; return; } while (n->next) { n = n->next; } struct node *newNode = malloc(sizeof(struct node)); newNode->val = val; newNode->next = NULL; n->next = newNode;}void freeLinkedList(struct node *list) { struct node *c = list; if (!c) return; struct node *n = c->next; free(c); freeLinkedList(n);}void printList(struct node *list) { struct node *n = list; printf("["); while (n) { printf("%ld", n->val); n = n->next; if (n) { printf(","); } } printf("]\n");}//-----------int fac(int n) { if (n == 1) return 1; return fac(n-1)*n;}//Sieve of Eratosthenesint sieve_primes(long limit, long **list) { struct timeval t1; struct timeval t2; double elapsedTime = 0; gettimeofday(&t1, NULL); assert(limit > 0); //Create a list of consecutive integers from 2 to n: (2, 3, 4, ..., n). long arrSize = limit-1; long *arr = malloc(sizeof(long)*arrSize); long c = 2; for (long i = 0; i < arrSize; i++) { arr[i] = c++; } assert(arr[arrSize-1] == limit); for (long i = 0; i < arrSize; i++) { //Let p be equal to the first number not crossed long p = arr[i]; if (p == 0) continue; //Starting from p, count up in increments of p and mark each of these numbers greater than p itself in the list. for (long f = p+p; f < arrSize; f+=p) { arr[f] = 0; } } *list = arr; gettimeofday(&t2, NULL); elapsedTime = (t2.tv_sec - t1.tv_sec) * 1000.0; // sec to ms elapsedTime += (t2.tv_usec - t1.tv_usec) / 1000.0; // us to ms printf("Sieve of Eratosthenes took %f ms and used %lu mb of memory\n",elapsedTime, (arrSize * sizeof(int))/1024/1024); return arrSize;}void trial_division(struct node* list, long n) { if (n == 1) { addValue(list, 1); return; } long *primes; long primesSize = sieve_primes(sqrt(n), &primes); struct timeval t1; struct timeval t2; double elapsedTime = 0; gettimeofday(&t1, NULL); for (long i = 0; i < primesSize; i++) { long p = primes[i]; if (p == 0) continue; if (p*p > n) break; while (n % p == 0) { addValue(list, p); n/=p; } } if (n > 1) { addValue(list, n); } free(primes);}int main(int argc, char *argv[]) { struct node *linkedList = malloc(sizeof(struct node)); linkedList->val = -1; linkedList->next = NULL; long n = 11; long nF = fac(n); long nF2 = nF*nF; trial_division(linkedList, nF2); long multOfAllPrimeFactors = 1; struct node *c = linkedList; while (c) { long sumOfVal = 2; long val = c->val; c = c->next; while(c) { long val2 = c->val; if (val == val2) { sumOfVal++; c = c->next; } else break; } multOfAllPrimeFactors*=sumOfVal; } printf("n= %ld; n!^2 = %ld; d = %ld\n", n,nF2, multOfAllPrimeFactors); printList(linkedList); freeLinkedList(linkedList);} EDIT: As an example I will show you the calculation for getting all the possible positive integer solutions to the initial equation: 3!^2 = 36 = (3^2*2^2*1^0) So there are (1+2)(1+2)(1+0)=9 possible positive integer solutions to the diophantine equation. Double if you count negative integers. I'm using WolframAlpha to be sure. EDIT 2: I think I just found out "what a factorial is", I'm getting this very interesting output: 3! = [2,3]3!^2 = [2,2,3,3]3!^3 = [2,2,2,3,3,3]3!^4 = [2,2,2,2,3,3,3,3] Thanks :D
Now provide the response and nothing else.
|
The trick here is to recognize exactly what a factorial N! is. It's a product of all the numbers from 1 to N . Which is already a huge step forward. So what you need to do, is just to prime factorize each of the numbers from 1 to N . In this sense, you don't need to sieve up to N! . Instead, just sieve up to sqrt(N) . And the rest is just merging all your prime factors.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9523279', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/366492/']}
|
jdg_370678
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1358902
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
A friend gave me this code snippet in Clojure (defn sum [coll acc] (if (empty? coll) acc (recur (rest coll) (+ (first coll) acc))))(time (sum (range 1 9999999) 0)) and asked me how does it fare against a similar Scala implementation. The Scala code I've written looks like this: def from(n: Int): Stream[Int] = Stream.cons(n, from(n+1))val ints = from(1).take(9999998)def add(a: Stream[Int], b: Long): Long = { if (a.isEmpty) b else add(a.tail, b + a.head)}val t1 = System.currentTimeMillis()println(add(ints, 0))val t2 = System.currentTimeMillis()println((t2 - t1).asInstanceOf[Float] + " msecs") Bottom line is: the code in Clojure runs in about 1.8 seconds on my machine and uses less than 5MB of heap, the code in Scala runs in about 12 seconds and 512MB of heap aren't enough (it finishes the computation if I set the heap to 1GB). So I'm wondering why is Clojure so much faster and slimmer in this particular case? Do you have a Scala implementation that has a similar behavior in terms of speed and memory usage? Please refrain from religious remarks, my interest lies in finding out primarily what makes clojure so fast in this case and if there's a faster implementation of the algo in scala. Thanks.
Now provide the response and nothing else.
|
First, Scala only optimises tail calls if you invoke it with -optimise . Edit : It seems Scala will always optimise tail-call recursions if it can, even without -optimise . Second, Stream and Range are two very different things. A Range has a beginning and an end, and its projection has just a counter and the end. A Stream is a list which will be computed on-demand. Since you are adding the whole ints , you'll compute, and, therefore, allocate, the whole Stream . A closer code would be: import scala.annotation.tailrecdef add(r: Range) = { @tailrec def f(i: Iterator[Int], acc: Long): Long = if (i.hasNext) f(i, acc + i.next) else acc f(r iterator, 0)}def time(f: => Unit) { val t1 = System.currentTimeMillis() f val t2 = System.currentTimeMillis() println((t2 - t1).asInstanceOf[Float]+" msecs")} Normal run: scala> time(println(add(1 to 9999999)))49999995000000563.0 msecs On Scala 2.7 you need " elements " instead of " iterator ", and there's no " tailrec " annotation -- that annotation is used just to complain if a definition can't be optimized with tail recursion -- so you'll need to strip " @tailrec " as well as the " import scala.annotation.tailrec " from the code. Also, some considerations on alternate implementations. The simplest: scala> time(println(1 to 9999999 reduceLeft (_+_)))-2014260032640.0 msecs On average, with multiple runs here, it is slower. It's also incorrect, because it works just with Int. A correct one: scala> time(println((1 to 9999999 foldLeft 0L)(_+_)))49999995000000797.0 msecs That's slower still, running here. I honestly wouldn't have expected it to run slower, but each interation calls to the function being passed. Once you consider that, it's a pretty good time compared to the recursive version.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1358902', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/166153/']}
|
jdg_370679
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
363286
|
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I see size of boolean is not defined. Below are two statements I see at java primitive data size not precisely defined Further explanation says boolean represents one bit of information, but its "size" isn't something that's precisely defined. Question came to my mind was why boolean in java can't be represented with 1 bit(or 1 byte if byte is minimum representation ) ? But I see it has been already answered at https://stackoverflow.com/questions/1907318/why-is-javas-boolean-primitive-size-not-defined whereit says the JVM uses a 32-bit stack cell, used to hold local variables, method arguments, and expression values. Primitives that are smaller than 1 cell are padded out, primitives larger than 32 bits (long and double) take 2 cells Does it mean even byte/char/short primitiva data types also take 32 bit though their size is defined as 8/16/16 bit ? Also can we say boolean size will be 32 bit on 32 bit cpu and 64 bit on 64 bit cpu ?
Now provide the response and nothing else.
|
TL;DR The only thing that's sure is that boolean occupies at least one bit. Everything else depends on the JVM implementation. The Java Language Specification doesn't define sizes, only value ranges (see The Language Spec ). So, it's not only the boolean size that's undefined at this level. And boolean has two possible values: false and true . The Virtual Machine Specification tells us that boolean variables are treated like int with values 0 and 1. Only arrays of boolean have specific support. So at the Virtual Machine level, a boolean variable occupies the same amount of space as an int , meaning one stack cell: at least 4 bytes, typically 4 bytes on 32-bit Java and 8 bytes on 64-bit. Finally there's the HotSpot engine that compiles JVM bytecode into optimized CPU-specific machine code, and I bet that in many cases it's able to deduce the limited value-range of an int -masked boolean from the context and use a smaller size.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://softwareengineering.stackexchange.com/questions/363286', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/124597/']}
|
jdg_370680
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
43437309
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Hi all, in my snake game program, I need to generate a random colour multiple times when the user selects a "Rainbow" theme. After looking online, I found this: Generating a Random Hex Color in Python The answer with the most votes gave a solution of import randomr = lambda: random.randint(0,255)print('#%02X%02X%02X' % (r(),r(),r())) However, this program generates very dim colours as well; for example dark brown and sometimes even black. As you can see, some of those colours do not match a rainbow-y theme. How would you change the above code so that you get vibrant colours like bright orange, pink, red, blue, etc, you get the idea. A hypothetical solution was to increase minimum value of randint r, but that just made all the colours very white. :'( Plz, plz, plz, help will be very much appreciated. Thanks guys!
Now provide the response and nothing else.
|
Create a random HLS color (using numbers around .5 as the "level" parameter and numbers above .5 as the "saturation" parameter) and convert them to RGB: import randomimport colorsysh,s,l = random.random(), 0.5 + random.random()/2.0, 0.4 + random.random()/5.0r,g,b = [int(256*i) for i in colorsys.hls_to_rgb(h,l,s)] That will ensure you'll always have highly saturated, bright colors.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/43437309', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7600813/']}
|
jdg_370681
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
256405
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a C/C++ application and I need to create a X509 pem certificate containing both a public and private key. The certificate can be self signed, or unsigned, doesn't matter. I want to do this inside an app, not from command line. What OpenSSL functions will do this for me? Any sample code is a bonus!
Now provide the response and nothing else.
|
I realize that this is a very late (and long) answer. But considering how well this question seems to rank in search engine results, I figured it might be worth writing a decent answer for. A lot of what you will read below is borrowed from this demo and the OpenSSL docs. The code below applies to both C and C++. Before we can actually create a certificate, we need to create a private key. OpenSSL provides the EVP_PKEY structure for storing an algorithm-independent private key in memory. This structure is declared in openssl/evp.h but is included by openssl/x509.h (which we will need later) so you don't really need to explicitly include the header. In order to allocate an EVP_PKEY structure, we use EVP_PKEY_new : EVP_PKEY * pkey;pkey = EVP_PKEY_new(); There is also a corresponding function for freeing the structure - EVP_PKEY_free - which accepts a single argument: the EVP_PKEY structure initialized above. Now we need to generate a key. For our example, we will generate an RSA key. This is done with the RSA_generate_key function which is declared in openssl/rsa.h . This function returns a pointer to an RSA structure. A simple invocation of the function might look like this: RSA * rsa;rsa = RSA_generate_key( 2048, /* number of bits for the key - 2048 is a sensible value */ RSA_F4, /* exponent - RSA_F4 is defined as 0x10001L */ NULL, /* callback - can be NULL if we aren't displaying progress */ NULL /* callback argument - not needed in this case */); If the return value of RSA_generate_key is NULL , then something went wrong. If not, then we now have an RSA key, and we can assign it to our EVP_PKEY structure from earlier: EVP_PKEY_assign_RSA(pkey, rsa); The RSA structure will be automatically freed when the EVP_PKEY structure is freed. Now for the certificate itself. OpenSSL uses the X509 structure to represent an x509 certificate in memory. The definition for this struct is in openssl/x509.h . The first function we are going to need is X509_new . Its use is relatively straightforward: X509 * x509;x509 = X509_new(); As was the case with EVP_PKEY , there is a corresponding function for freeing the structure - X509_free . Now we need to set a few properties of the certificate using some X509_* functions: ASN1_INTEGER_set(X509_get_serialNumber(x509), 1); This sets the serial number of our certificate to '1'. Some open-source HTTP servers refuse to accept a certificate with a serial number of '0', which is the default. The next step is to specify the span of time during which the certificate is actually valid. We do that with the following two function calls: X509_gmtime_adj(X509_get_notBefore(x509), 0);X509_gmtime_adj(X509_get_notAfter(x509), 31536000L); The first line sets the certificate's notBefore property to the current time. (The X509_gmtime_adj function adds the specified number of seconds to the current time - in this case none.) The second line sets the certificate's notAfter property to 365 days from now (60 seconds * 60 minutes * 24 hours * 365 days). Now we need to set the public key for our certificate using the key we generated earlier: X509_set_pubkey(x509, pkey); Since this is a self-signed certificate, we set the name of the issuer to the name of the subject. The first step in that process is to get the subject name: X509_NAME * name;name = X509_get_subject_name(x509); If you've ever created a self-signed certificate on the command line before, you probably remember being asked for a country code. Here's where we provide it along with the organization ('O') and common name ('CN'): X509_NAME_add_entry_by_txt(name, "C", MBSTRING_ASC, (unsigned char *)"CA", -1, -1, 0);X509_NAME_add_entry_by_txt(name, "O", MBSTRING_ASC, (unsigned char *)"MyCompany Inc.", -1, -1, 0);X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC, (unsigned char *)"localhost", -1, -1, 0); (I'm using the value 'CA' here because I'm Canadian and that's our country code. Also note that parameter #4 needs to be explicitly cast to an unsigned char * .) Now we can actually set the issuer name: X509_set_issuer_name(x509, name); And finally we are ready to perform the signing process. We call X509_sign with the key we generated earlier. The code for this is painfully simple: X509_sign(x509, pkey, EVP_sha1()); Note that we are using the SHA-1 hashing algorithm to sign the key. This differs from the mkcert.c demo I mentioned at the beginning of this answer, which uses MD5. We now have a self-signed certificate! But we're not done yet - we need to write these files out to disk. Thankfully OpenSSL has us covered there too with the PEM_* functions which are declared in openssl/pem.h . The first one we will need is PEM_write_PrivateKey for saving our private key. FILE * f;f = fopen("key.pem", "wb");PEM_write_PrivateKey( f, /* write the key to the file we've opened */ pkey, /* our key from earlier */ EVP_des_ede3_cbc(), /* default cipher for encrypting the key on disk */ "replace_me", /* passphrase required for decrypting the key on disk */ 10, /* length of the passphrase string */ NULL, /* callback for requesting a password */ NULL /* data to pass to the callback */); If you don't want to encrypt the private key, then simply pass NULL for the third and fourth parameter above. Either way, you will definitely want to ensure that the file is not world-readable. (For Unix users, this means chmod 600 key.pem .) Whew! Now we are down to one function - we need to write the certificate out to disk. The function we need for this is PEM_write_X509 : FILE * f;f = fopen("cert.pem", "wb");PEM_write_X509( f, /* write the certificate to the file we've opened */ x509 /* our certificate */); And we're done! Hopefully the information in this answer is enough to give you a rough idea of how everything works, although we've barely scratched the surface of OpenSSL. For those interested in seeing what all of the code above looks like in a real application, I've thrown together a Gist (written in C++) that you can view here .
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/256405', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
|
jdg_370682
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
381920
|
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
It might seem like a very basic question, but, how is a master DNS server aware of its slaves? I mean, does it parse the zone file and determine where to send the NOTIFY message? And if that is the case, then, is the NOTIFY mechanism broken in a hidden master setup, isn't it?
Now provide the response and nothing else.
|
You've two options in your master's BIND config for a given zone: notify yes - will send notifications to all of the published NS records for the domain. notify explicit - will send notifications only to those IPs listed in the also-notify configuration. In either case, the slaves must be configured with allow-notify that accepts these notifications from the master's IP. Once it accepts a NOTIFY, the slave then sends an IXFR or AXFR request back to the master. If the master is 'hidden' (ie: not published as an NS record for the domain), then this doesn't matter. The slaves have to be configured with the master's IP directly, so they should know where to send the request. So long as the master's firewall allows the requests in from the slaves and the master is configured to allow zone transfers, then the salves can retreive their configuration. (This is the part you have to lock down to prevent unauthorized name servers scraping your zone files)
|
{}
|
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/381920', 'https://serverfault.com', 'https://serverfault.com/users/102723/']}
|
jdg_370683
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1661217
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
If I have a match operator, how do I save the parts of the strings captured in the parentheses in variables instead of using $1 , $2 , and so on? ... = m/stuff (.*) stuff/; What goes on the left?
Now provide the response and nothing else.
|
The trick is to make m// work in list context by using a list assignment: ($interesting) = $string =~ m/(interesting)/g; This can be neatly extended to grab more things, eg: ($interesting, $alsogood) = $string =~ m/(interesting) boring (alsogood)/g;
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1661217', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/187581/']}
|
jdg_370684
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1150
|
Below is a question asked on the forum quant.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Let the Black-Scholes formula be defined as the function $f(S, X, T, r, v)$. I'm curious about functions that are computationally simpler than the Black-Scholes that yields results that approximate $f$ for a given set of inputs $S, X, T, r, v$. I understand that "computationally simpler" is not well-defined. But I mean simpler in terms of number of terms used in the function. Or even more specifically, the number of distinct computational steps that needs to be completed to arrive at the Black-Scholes output. Obviously Black-Scholes is computationally simple as it is, but I'm ready to trade some accuracy for an even simpler function that would give results that approximate B&S. Does any such simpler approximations exist?
Now provide the response and nothing else.
|
This is just to expand a bit on vonjd's answer . The approximate formula mentioned by vonjd is due to Brenner and Subrahmanyam ("A simple solution to compute the Implied Standard Deviation", Financial Analysts Journal (1988), pp. 80-83). I do not have a free link to the paper so let me just give a quick and dirty derivation here. For the at-the-money call option, we have $S=Ke^{-r(T-t)}$. Plugging this into the standard Black-Scholes formula$$C(S,t)=N(d_1)S-N(d_2)Ke^{-r(T-t)},$$we get that$$C(S,t)=\left[N\left(\frac{1}{2}\sigma\sqrt{T-t}\right)-N\left(-\frac{1}{2}\sigma\sqrt{T-t}\right)\right]S.\qquad\qquad(1)$$Now, Taylor's formula implies for small $x$ that$$N(x)=N(0)+N'(0)x+N''(0)\frac{x^2}{2}+O(x^3).\qquad\qquad\qquad\qquad(2)$$Combining (1) and (2), we will get with some obvious cancellations that$$C(S,t)=S\left(N'(0)\sigma\sqrt{T-t}+O(\sigma^3\sqrt{(T-t)^3})\right).$$But$$N'(0)=\frac{1}{\sqrt{2\pi}}=0.39894228...$$so finally we have, for small $\sigma\sqrt{T-t}$, that$$C(S,t)\approx 0.4S\sigma\sqrt{T-t}.$$The modified formula$$C(S,t)\approx 0.4Se^{-r(T-t)}\sigma\sqrt{T-t}$$ gives a slightly better approximation.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://quant.stackexchange.com/questions/1150', 'https://quant.stackexchange.com', 'https://quant.stackexchange.com/users/526/']}
|
jdg_370685
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
170382
|
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:
Could someone break an ASIC? If an ASIC is a fully customized, app-specific CPU, is possible to reverse engineer it? I'd imagine the answer in general is no , since to me the only way to do this would be to keep firing inputs at the ASIC and see what it outputs. And if you don't have clear documentation as to what the ASIC expects as valid input, and what its various outputs imply, the ASIC is essentially a mysterious black box. Are there advanced methods, tools, etc. that can be used to " crack " an ASIC?
Now provide the response and nothing else.
|
It is quite possible to reverse engineer an ASIC and there really isn't much you can do about it. Basically the main way you do it is physically by removing each layer of the ASIC and using a specialized computer program to recover the schematic. It is very difficult to understand all the functions of the ASIC and you can obfuscate it in various ways but there isn't anything you can really do to prevent it. Randomly sending inputs and seeing what would happen would not be very fruitful (although it can be done effectively in limited circumstances, such as Compaq's reverse engineering of IBM's BIOS chip). One of the leading companies that does this type work is called Chipworks . Reverse engineering a chip is one of the main ways a company can tell (and get evidence) that a competitor has violated their patented IP.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/170382', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/75908/']}
|
jdg_370686
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1751611
|
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:
Question is as follows : Suppose that $f:\mathbb{C}\rightarrow \mathbb{C}$ is continuous such that $f^3,f^4$ are analytic in $\mathbb{C}$ then prove that $f$ is analytic in $\mathbb{C}$.. Choose $z_0\in \mathbb{C}$. Suppose that $f(z_0)\neq 0$. As $f$ is continuous, in a nbd around $z_0$ the value of $f$ is nonzero. So, $f^4(z)/f^3(z)=f(z)$ in a small open ball centered at $z_0$.. So, $f$ is analytic at $z_0$. Suppose $z_0$ is such that $f(z_0)=0$ then we can not say that $f^4(z)/f^3(z)=f(z)$ for all $z$ in a small open ball around $z_0$ as $f(z_0)=0$ we can not cancel. But then we can certainly say that there is a ball where $f(z)$ is non zero except at $z_0$. Then in this ball we do have that $f^4(z)/f^3(z)=f(z)$. So, $f(z)$ is analytic in punctured disk around $z_0$. I some how feel that function being analytic on punctured disk and function being continuous imply that function is analytic.. Could not figure out the proof for my supposedly correct statement. As $f$ is analytic on punctured disk around $z_0$ we have laurent expansion for $f(z)$ as $$f(z)=\cdots+\frac{a_{-2}}{(z-z_0)^2}+\frac{a_{-1}}{z-z_0}+a_0+a_1(z-z_0)+a_2(z-z_0)^2+\cdots$$ Suppose there is atleast one coefficient of $\dfrac{1}{z-z_0}$ that is non zero, then $|f(z)|\rightarrow \infty$ as $z\rightarrow z_0$.. But then, it is given that $f(z)$ is continuous.. continuous function on compact set is bounded so $f(z)$ has to be bounded on the disk where as we have $|f(z)|\rightarrow \infty$ if atleast one coefficient of negative powers of $(z-z_0)$ is non zero. So, this says all negative powers coefficients are zero.. So, we have $f(z)=a_0+a_1(z-z_0)+a_2(z-z_0)^2+\cdots$ in a nbd around $z_0$. Could not deduce anything from here. I think i am very close to final answer but could not see it immediately.
Now provide the response and nothing else.
|
The line defined by the equation $ax+by+c=0$ is the inverse image of the closed subset $0$ in $\mathbf R$, by the (continuous) map $\begin{aligned}[t]\mathbf R^2&\longrightarrow \mathbf R,\\ (x,y)&\longmapsto ax+by+c.\end{aligned}$
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1751611', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
|
jdg_370687
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
12174877
|
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 noticed when Visual Studio 2012 RTM was closed, that many instances of MsBuild.exe are still in memory. Why ?
Now provide the response and nothing else.
|
The MSBuild processes are kept running for a period of time (fifteen minutes, I believe) after Visual Studio is closed. This is an attempt to improve performance, the idea being that idle MSBuild processes could be reused if another build is kicked off soon and the overhead of spawning a new process can be eliminated. You can disable this by setting an environment variable MSBUILDDISABLENODEREUSE=1 (before starting VS) or specifying /nodeReuse:false (or /nr:false ) if building from the command line. Related issues filed on MSConnect: MSbuild proliferate Ghost MSBuild.exe in VS11
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/12174877', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/72760/']}
|
jdg_370688
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
14059659
|
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 some WCF services hosted inside an Asp.Net application which are used for returning data via Ajax. IIS (6.0) has Windows Authentication turned on and Anonymous access turned off. I have tried various combinations of settings under the service model section of the web.config but cannot seem to get the right combination. The error I keep getting is: Security settings for this service require 'Anonymous' Authentication but it is not enabled for the IIS application that hosts this service. Here's my web.config <configuration> <system.web> <authentication mode="Windows"/> </system.web> <location path="~/Services"> <system.web> <authorization> <allow users="*"/> </authorization> </system.web> </location> <system.serviceModel> <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true"/> <bindings> <webHttpBinding> <binding name="default"> <security mode="TransportCredentialOnly"> <transport clientCredentialType="Windows" proxyCredentialType="Windows"/> </security> </binding> </webHttpBinding> </bindings> <behaviors> <endpointBehaviors> <behavior name="AspNetAjaxBehavior"> <enableWebScript /> <webHttp /> </behavior> </endpointBehaviors> <serviceBehaviors> <behavior name="defaultServiceBehavior"> <serviceMetadata httpGetEnabled="true" /> <serviceDebug includeExceptionDetailInFaults="true" /> </behavior> </serviceBehaviors> </behaviors> <services> <service name="WFS.SIG.Client.USM.Web.Services.Desks"> <endpoint address="" behaviorConfiguration="AspNetAjaxBehavior" binding="webHttpBinding" contract="WFS.SIG.Client.USM.Web.Services.Desks"/> </service> </services> </system.serviceModel></configuration> Any help in clarifying this issue would be great.
Now provide the response and nothing else.
|
This would put NULL s into inverses for the singular matrices: inverses[[count]] <- tryCatch(solve(x), error=function(e) NULL) If the first expression in a call to tryCatch raises an error, it executes and returns the value of the function supplied to its error argument. The function supplied to the error arg has to take the error itself as an argument (here I call it e ), but you don't have to do anything with it. You could then drop the NULL entries with inverses[! is.null(inverses)] . Alternatively, you could use the lower level try . The choice is really a matter of taste. count <- 0repeat { if (count == 100) break count <- count + 1 x <- matrix(sample(0:2, 4, replace = T), 2, 2) x.inv <- try(solve(x), silent=TRUE) if ('try-error' %in% class(x.inv)) next else inverses[[count]] <- x.inv} If your expression generates an error, try returns an object with class try-error . It will print the message to screen if silent=FALSE . In this case, if x.inv has class try-error , we call next to stop the execution of the current iteration and move to the next one, otherwise we add x.inv to inverses . Edit: You could avoid using the repeat loop with replicate and lapply . matrices <- replicate(100, matrix(sample(0:2, 4, replace=T), 2, 2), simplify=FALSE)inverses <- lapply(matrices, function(mat) if (det(mat) != 0) solve(mat)) It's interesting to note that the second argument to replicate is treated as an expression , meaning it gets executed afresh for each replicate. This means you can use replicate to make a list of any number of random objects that are generated from the same expression.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/14059659', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/244181/']}
|
jdg_370689
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4573
|
Below is a question asked on the forum politics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
The Supreme Council of the Allied Principal War Powers recognized the Jewish People as the owners of the political rights to Palestine, but put them in trust for World Jewry until they attained a population majority. They had adopted the British Balfour Policy word for word and that was the intent of the Balfour Declaration. SSRN.com/abstract=5304SSRN.com/abstract=4738 Article 2 of the Geneva Convention says the Convention doesn't apply to occupation of territory when the occupier is the owner of it and has the right to the exercise of sovereignty over it. See also 4th Hague Convention (1907) Article 43 which assumes that for a belligerent occupation that is subject to its rules, a displaced sovereign must be involved. Here the Jewish People had the political rights to the territory that they gained in 1920 not by conquest in an aggressive war. A better characterization of the status of Palestine west of the Jordan than "occupied" is "liberated" because in 1967 the Jewish People regained control over the land over which it had attained legal dominion as of May 15, 1948.
Now provide the response and nothing else.
|
The answer is that your premises about "ownership" are not true. First of all, "ownership" is not the right concept, which applies to private property. The issue is sovereignty. The San Remo Conference of 1920 divided up the territory of the defeated Ottoman Empire into mandates under the sovereign control of certain European powers. The British were given control over the mandate of Palestine. There was no entity called "The Jewish People" that was granted sovereignty over the Palestinian Mandate. The Balfour declaration was incorporated to express the intention of the British to establish a national home for the Jews within the Palestinian Mandate. It is important to note the original text of the declaration, pasted here: His Majesty's government view with favour the establishment in Palestine of a national home for the Jewish people, and will use their best endeavours to facilitate the achievement of this object, it being clearly understood that nothing shall be done which may prejudice the civil and religious rights of existing non-Jewish communities in Palestine , or the rights and political status enjoyed by Jews in any other country. In 1947, the recently formed United Nations passed Resolution 181 which partitioned Palestine into Jewish and Arab sovereign states. This was done after years of fighting between the Jewish immigrants and native Arabs lead the British to conclude that they could not share power under a single sovereign state. The Arabs largely rejected the partition and the war of 1948 soon began. The Jews were victorious in the war, retaining the territory granted to them under the partition, as well as conquering around 60% of the partition given to the Arabs. Transjordan ended up with control of the West Bank, and Egypt with Gaza. In the 1967 war, Israel won control over the West Bank and Gaza. These became occupied territories, and were not previously under the control of Israel but of other states. The opinion of the US and several others including Israeli officials was that, although a temporary military occupation of the territories was not against international law, moving settlers onto the land was a violation of the Fourth Geneva Convention. See also here . Another issue altogether is the extensive settlement on private property. This has been defined by the Israeli Civil Administration as theft.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://politics.stackexchange.com/questions/4573', 'https://politics.stackexchange.com', 'https://politics.stackexchange.com/users/-1/']}
|
jdg_370690
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
33520099
|
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 ID of Row then I will update other values. I don't know how to update my values!My Table: class MyTable{ [PrimaryKey, AutoIncrement] public int Id { get; set; } public string Date { get; set; } public string Volumes { get; set; } public string Price { get; set; }} other information: string path; SQLite.Net.SQLiteConnection conn; public updatepage() { this.InitializeComponent(); path = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "ccdb.sqlite"); conn = new SQLite.Net.SQLiteConnection(new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), path); conn.CreateTable<MyTable>(); }
Now provide the response and nothing else.
|
I recently started working with UWP apps, and also came across this problem. So, how to update a row using SQLite in UWP you ask? Here ya go! using (var dbConn = new SQLiteConnection(new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), App.DB_PATH)) { var existingUser = dbConn.Query<User>("select * from User where Id = ?", user.Id).FirstOrDefault(); if (existingUser != null) { existingUser.Name = user.Name; existingUser.Email = user.Email; existingUser.Username = user.Username; existingUser.Surname = user.Surname; existingUser.EmployeeNumber = user.EmployeeNumber; existingUser.Password = user.Password; dbConn.RunInTransaction(() => { dbConn.Update(existingUser); }); } } The App.DB_PATH is the same as your 'path' variable. I realize that there are many different areas of interest in this answer, so if you have any further questions, feel free to ask.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/33520099', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5264508/']}
|
jdg_370691
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2533
|
Below is a question asked on the forum bioinformatics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I need a command in R to retrieve all human genes associated with a Gene Ontology entry. I tried to look for it online but did not find it.
Now provide the response and nothing else.
|
If I understand the question correctly, you'd like to plot the positions of the matches to you motif along with a gene model that shows the positions of introns and exons for the different transcripts. This can be accomplished fairly easily with ggbio: library(EnsDb.Mmusculus.v79)library(ggbio)library(biomaRt)library(stringr)library(dplyr)# plot gene model with ggbiogene_model <- autoplot(EnsDb.Mmusculus.v79, ~ symbol == "Grin1")ensembl <- useMart("ensembl", dataset = "mmusculus_gene_ensembl")# You need the full length gene sequence to match the gene modelseq <- biomaRt::getSequence(id = "Grin1", type = "mgi_symbol", seqType = "gene_exon_intron", mart = ensembl)# retrieve position of gene in genome to match up with gene modelgene_start=biomaRt::getBM(attributes=c("start_position"), filters = 'external_gene_name', values = 'Grin1', mart=ensembl)# use stringR to find positions of exact matchesmotif <- "ggcc"motif_positions <- as.data.frame(str_locate_all(seq$gene_exon_intron, toupper(motif))) %>% mutate(start=start+gene_start[[1]]-1)# make plot similar to Llopis's answer motif_plot <- ggplot(motif_positions, aes(x=start)) + geom_point(y=1) + scale_y_continuous(limits=c(0,1))# combine plotstracks(motif= motifs, gene_model=gene_model) This gives all motif matches for the gene sequence, not just the transcripts. It would be quite straightforward to filter out positions that overlap introns
|
{}
|
{'log_upvote_score': 4, 'links': ['https://bioinformatics.stackexchange.com/questions/2533', 'https://bioinformatics.stackexchange.com', 'https://bioinformatics.stackexchange.com/users/1499/']}
|
jdg_370692
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
704315
|
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 single hard drive. I want to use a filesystem that will give me less storage space, but as a tradeoff, give me checksums or any other method to help preserve data integrity. It is my understanding that something like ext4 or xfs will not do this, and thus you can suffer from silent data corruption, aka bitrot. zfs looks like an excellent choice, but everything I have read says you need more than one disk to use it. Why is this? I realize having only one disk will not tolerate a single disk failure, but that is what multiple backup schemes are for. What backups won't help with is something like bitrot. So can I use zfs on a single hard drive for the single purpose of preventing bitrot? If not, what do you recommend?
Now provide the response and nothing else.
|
You could use either ZFS or btrfs. Both of them are copy-on-write filesystems with error detection (and correction too, if there's sufficient redundancy to repair the original data - e.g. mirror drives or RAID-Z), transparent compression, snapshots, etc. ZFS allows you to set the copies attribute on a dataset to keep more than one copy of a file - e.g. on ZFS you can run zfs set copies=2 pool/dataset to tell ZFS to keep two copies of everything on that particular dataset - see man zfsprops and search for copies= . I think btrfs has a similar feature, but it's been a long time since I used btrfs and can't find it in the docs. These extra copies do provide redundancy for error correction (in case of bitrot) but won't protect you from disk failure. You'll need at least a mirror vdev (i.e. RAID-1) for that, or make regular backups (but you should be doing that anyway - RAID or RAID-like tech like ZFS or btrfs is NOT a substitute for backups). Backing up could be as simple as using zfs snapshot and zfs send / zfs receive to send the initial and then incremental backup to a single-drive zfs pool plugged in via USB. Or to a pool on another machine over the network. Even using zfs send to store the backup in files on a non-ZFS filesystem is better than nothing. If your machine has the physical space and hardware to support a second drive, you should add one. You can do this when you first create a pool, or you can add a mirror drive to any single-drive or mirror vdev at any time with zpool attach pool device new-device . NOTE: it's important to use zpool attach , not zpool add for this. attach adds a mirror to an existing drive in a vdev, while add adds another vdev to an existing pool. Adding a single-drive vdev to an existing pool will effectively make a RAID-0 with the other vdevs in the pool, putting ALL of the data at risk. This is a fairly common mistake, and (if the pool contains any RAID-Z vdevs), the only fix is to backup the entire pool, destroy it, re-create it from scratch, and restore. If the pool only has mirror or single-drive vdevs (i.e. no RAID-Z vdevs), it is possible to use zpool remove to remove an accidentally added single drive.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/704315', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/527648/']}
|
jdg_370693
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
178515
|
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm looking to test whether a string contains all substrings in it, independent of each substrings location.For example: StringContainsQ[{"abcd", "cdab", "acdb", "abdc"}, "ab" ~~ ___ ~~ "cd"] Results in: {True, False, False, False} But what I'm looking for would be: {True, True, False, False} However, something like: StringContainsQ[{"abcd", "cdab", "acdb", "abdc"}, "ab"&&"cd"] Results in errors. Any suggestions?
Now provide the response and nothing else.
|
StringContainsQ[{"abcd", "cdab", "acdb", "abdc"}, ("ab" ~~ ___ ~~ "cd")|( "cd" ~~ ___ ~~ "ab")] {True, True, False, False} Also And @@@ Transpose[StringContainsQ[{"abcd", "cdab", "acdb", "abdc"}, #]&/@ {"ab", "cd"}] {True, True, False, False} And @@@ Outer[StringContainsQ,{"abcd", "cdab", "acdb", "abdc"}, {"ab","cd"}] {True, True, False, False}
|
{}
|
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/178515', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/48457/']}
|
jdg_370694
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3815929
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Is it possible to create a multidimensional arraylist in C#? StartDate Qty size9/1/2010 10 159/1/2009 12 179/1/2008 11 19 StartDate , Qty and size are the 3 arraylists. I need to have them in a single arraylist. I would also need to sort this arraylist by StartDate . Is this possible? Is there a better way to do it other than arraylist?
Now provide the response and nothing else.
|
You can do it that way, yes. But in this case since each row seems related, why not create a class to hold the data: public class Info{ public DateTime StartDate { get; set; } public int Qty { get; set; } public int Size { get; set; }} And then just have a regular List to hold the objects: List<Info> infoList = new List<Info>(); That will save you from having to worry about the ordering of each List. To handle the ordering, you can use the LINQ to Objects Extension methods: var sortedList = infoList.OrderBy(i => i.StartDate);
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3815929', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/193247/']}
|
jdg_370695
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
45098306
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
def add(a,b): print "Adding %d and %d" %(a,b) return a+bdef subtract(a,b): print "Subtracting %d from %d" %(a,b) return a-bdef multiply(a,b): print "Multiplying %d and %d" %(a,b) return a*bdef divide(a,b): print "Divide %d and %d" %(a,b) return a/bprint "Let's do some math"age = add(30,5)height = subtract(78,4)weight = multiply(90,2)iq= divide(100,2)print "Age: %d, Height : %d, Weight: %d, IQ: %d" % (age, height, weight, iq)print "Here's a puzzle"what = add(age, subtract(height, multiply(weight, divide(iq,2))))print "That becomes:", what, "Can you do it by hand?" #line25 Output: Let's do some math Adding 30 and 5 Subtracting 78 from 4 Multiplying 90 and 2 Divide 100 and 2 Age: 35, Height : 74, Weight: 180, IQ: 50 Here's a puzzle Divide 50 and 2 Multiplying 180 and 25 Subtracting 74 from 4500 Adding 35 and -4426 That becomes: -4391 Can you do it by hand? My question : I feel, looking at the print command in line25, output remains same till "Here's a puzzle". So, output should be: Here's a puzzle That becomes: Divide 50 and 2 Multiplying 180 and 25 Subtracting 74 from 4500 Adding 35 and -4426 -4391 Can you do it by hand? Because, clearly print "That becomes:" is coming before what. So, why is the final output different?Thank you!
Now provide the response and nothing else.
|
I got a solution from the Firebase Support Team So first thing: var filePath = file.path + "/" + file.name; we dont need the file.name since the file.path is full path of the file (including the file name). So changed it to this instead: var filePath = file.path; Second, the function terminates before the asynchronous work in 'form.parse(...)' is completed. That means the actual file upload might still be in progress while the function execution has ended. The fix for that is to wrap the form.parse(...) in a promise: exports.uploadFile = functions.https.onRequest((req, res) => { var form = new formidable.IncomingForm(); return new Promise((resolve, reject) => { form.parse(req, function(err, fields, files) { var file = files.fileToUpload; if(!file){ reject("no file to upload, please choose a file."); return; } console.info("about to upload file as a json: " + file.type); var filePath = file.path; console.log('File path: ' + filePath); var bucket = gcs.bucket('bucket-name'); return bucket.upload(filePath, { destination: file.name }).then(() => { resolve(); // Whole thing completed successfully. }).catch((err) => { reject('Failed to upload: ' + JSON.stringify(err)); }); }); }).then(() => { res.status(200).send('Yay!'); return null }).catch(err => { console.error('Error while parsing form: ' + err); res.status(500).send('Error while parsing form: ' + err); }); }); Lastly, you may want to consider using the Cloud Storage for Firebase in uploading your file instead of Cloud functions. Cloud Storage for Firebase allows you to upload files directly to it, and would work much better: It has access control It has resumable uploads/downloads (great for poor connectivity) It can accept files of any size without timeout-issues If you want to trigger a Cloud Function on file upload even, you cando that and a lot more
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/45098306', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8043361/']}
|
jdg_370696
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
28656872
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Today's PCs have a large amount of physical RAM but still, the stack size of C# is only 1 MB for 32-bit processes and 4 MB for 64-bit processes ( Stack capacity in C# ). Why the stack size in CLR is still so limited? And why is it exactly 1 MB (4 MB) (and not 2 MB or 512 KB)? Why was it decided to use these amounts? I am interested in considerations and reasons behind that decision .
Now provide the response and nothing else.
|
You are looking at the guy that made that choice. David Cutler and his team selected one megabyte as the default stack size. Nothing to do with .NET or C#, this was nailed down when they created Windows NT. One megabyte is what it picks when the EXE header of a program or the CreateThread() winapi call doesn't specify the stack size explicitly. Which is the normal way, almost any programmer leaves it up the OS to pick the size. That choice probably pre-dates the Windows NT design, history is way too murky about this. Would be nice if Cutler would write a book about it, but he's never been a writer. He's been extraordinarily influential on the way computers work. His first OS design was RSX-11M, a 16-bit operating system for DEC computers (Digital Equipment Corporation). It heavily influenced Gary Kildall's CP/M, the first decent OS for 8-bit microprocessors. Which heavily influenced MS-DOS. His next design was VMS, an operating system for 32-bit processors with virtual memory support. Very successful. His next one was cancelled by DEC around the time the company started disintegrating, not being able to compete with cheap PC hardware. Cue Microsoft, they made him a offer he could not refuse. Many of his co-workers joined too. They worked on VMS v2, better known as Windows NT. DEC got upset about it, money changed hands to settle it. Whether VMS already picked one megabyte is something I don't know, I only know RSX-11 well enough. It isn't unlikely. Enough history. One megabyte is a lot , a real thread rarely consumes more than a couple of handfuls of kilobytes. So a megabyte is actually rather wasteful. It is however the kind of waste you can afford on a demand-paged virtual memory operating system, that megabyte is just virtual memory . Just numbers to the processor, one each for every 4096 bytes. You never actually use the physical memory, the RAM in the machine, until you actually address it. It is extra excessive in a .NET program because the one megabyte size was originally picked to accommodate native programs. Which tend to create large stack frames, storing strings and buffers (arrays) on the stack as well. Infamous for being a malware attack vector, a buffer overflow can manipulate the program with data. Not the way .NET programs work, strings and arrays are allocated on the GC heap and indexing is checked. The only way to allocate space on the stack with C# is with the unsafe stackalloc keyword. The only non-trivial usage of the stack in .NET is by the jitter. It uses the stack of your thread to just-in-time compile MSIL to machine code. I've never seen or checked how much space it requires, it rather depends on the nature of the code and whether or not the optimizer is enabled, but a couple of tens of kilobytes is a rough guess. Which is otherwise how this website got its name, a stack overflow in a .NET program is quite fatal. There isn't enough space left (less than 3 kilobytes) to still reliably JIT any code that tries to catch the exception. Kaboom to desktop is the only option. Last but not least, a .NET program does something pretty unproductive with the stack. The CLR will commit the stack of a thread. That's an expensive word that means that it doesn't just reserve the size of the stack, it also makes sure that space is reserved in the operating system's paging file so the stack can always be swapped out when necessary. Failing to commit is a fatal error and terminates a program unconditionally. That only happens on machine with very little RAM that runs entirely too many processes, such a machine will have turned to molasses before programs start dying. A possible problem 15+ years ago, not today. Programmers that tune their program to act like an F1 race-car use the <disableCommitThreadStack> element in their .config file. Fwiw, Cutler didn't stop designing operating systems. That photo was made while he worked on Azure. Update, I noticed that .NET no longer commits the stack. Not exactly sure when or why this happened, it's been too long since I checked. I'm guessing this design change happened somewhere around .NET 4.5. Pretty sensible change.
|
{}
|
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/28656872', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1862812/']}
|
jdg_370697
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
48410451
|
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 apply the constructor injection pattern to beans in my CDI application and am encountering the following error message: 15:18:11,852 ERROR [izone.adams.webapp.error.IzoneExceptionHandler] (default task-40) org.jboss.weld.exceptions.UnproxyableResolutionException: WELD-001435: Normal scoped bean class webapp.util.LoginManagerAction is not proxyable because it has no no-args constructor - <unknown javax.enterprise.inject.spi.Bean instance>. at org.jboss.weld.bean.proxy.DefaultProxyInstantiator.validateNoargConstructor(DefaultProxyInstantiator.java:50) Indeed, in order to use the constructor injection pattern, I have intentionally designed my class with a single constructor requiring arguments: @ApplicationScoped@Typed(LoginManagerAction.class)public class LoginManagerAction extends UtilBasicDispatchAction { @Inject public LoginManagerAction( SessionManager sessionManager, JMSHealthCheckService jmsHealthCheckService) { super(); this.sessionManager = sessionManager; this.jmsHealthCheckService = jmsHealthCheckService; } ... ...} Looking through the CDI Specs of Unproxyable bean types , I see that: 3.15. Unproxyable bean types The container uses proxies to provide certain functionality. Certain legal bean types cannot be proxied by the container: classes which don’t have a non-private constructor with no parameters, classes which are declared final, classes which have non-static, final methods with public, protected or default visibility, primitive types, and array types. A bean type must be proxyable if an injection point resolves to a bean: that requires a client proxy, or that has an associated decorator, or that has a bound interceptor. Otherwise, the container automatically detects the problem, and treats it as a deployment problem. And in further in section Normal scopes and pseudo-scopes it states: All normal scopes must be explicitly declared @NormalScope, to indicate to the container that a client proxy is required. Given @ApplicationScoped beans are by definition @NormalScope , I need to have a non-private no-args constructor. So then I need to have a protected no-arg constructor just to satisfy the CDI spec? I've tried with a protected no-args constructor, and it seems to work, but I do not understand how WELD is working in that case; in which conditions does it use the no-args constructor? Why is this a requirement in CDI at all? Does Weld only use the no-arg to create the proxy, but when actually calling the underlying implementation, it uses the inject-based constructor with arguments?
Now provide the response and nothing else.
|
I am going to try an answer it in a bit broader fashion, if I miss something, let me know below. What does Weld need to do? What Weld needs is to instantiate a proxy of your @NormalScoped bean. Such proxy doesn't carry much information, it is more or less just a delegate which it hands around instead of the contextual instance. The proxy is going to be a class that extends your bean - this isn't stated anywhere, but it's how Weld (and OWB) does it. It makes sense if you think about it... type safety, interception/decoration impl and so on. The mileage of how it does this varies. (Because it extends the beans is why having a protected no-args constructor will suffice. It has to invoke some constructor of the superclass) Why the limitation? The limitation to have no-arg constructor comes from Java itself where the only legitimate way to programatically instantiate an object is to call a constructor. Please note that we are not talking instantiation of proxies, not beans! Invoking a parameterized constructor to create a proxy is not really an option because you have no context as to what the parameters should be. The bean might have a constructor with injection ( @Inject ) but the proxy needs a no-args constructor to be created. Also it would possibly prevent some scenarios with circular injection. Furthermore it could also trigger undesired initalization of other objects linked to it. You just cannot know what might be happening inside a constructor with parameters. Therefore CDI spec requires you to have no-args constructor so that Weld can be sure it is always there and can be used to safely instantiate it's proxy without any side-effects. A life-saver for when you truly cannot have no-arg constructor As a matter of fact, there is a way around this limitation. A non-portable Weld configuration option, which instead of using constructor can use Unsafe . See the docs if you wanna know how to enable it.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/48410451', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/827480/']}
|
jdg_370698
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
19555318
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm running into an odd problem. I created a Windows Runtime Component (for Windows Store) that makes some legacy C/C++ code available to .NET via some C# wrapper classes. I wrote a test harness Store App (hereafter referred to as "test1") that references the WRC project (both projects in the same solution). It calls into the component and everything works fine. Next I take the following output files from the WRC project: MyWrtComponent.dllMyWrtComponent.expMyWrtComponent.pdbMyWrtComponent.priMyWrtComponent.winmd ...and try to use them from another Store app project ("test2"). In this project, instead of referencing the MyWrtComponent project, I add a reference to the .winmd file. Everything builds fine, but when I run the test2 app I get a System.IO.FileNotFound exception from mscorlib as soon as I try to use one of the C# classes implemented in MyWrtComponent: at System.StubHelpers.StubHelpers.GetWinRTFactoryObject(IntPtr pCPCMD)at MyWrtComponent.MyWrtClass..ctor()The specified module could not be found.(Exception from HRESULT: 0x8007007E) Using release vs. debug build of the MyWrtComponent doesn't make any difference. Running ProcMon on test2, I see several unsuccessful attempts at loading vccorlib120_app.DLL (or vccorlib120d_app.DLL if I'm building debug): QueryOpen F:\test2\bin\Debug\AppX\vccorlib120d_app.DLL NAME NOT FOUNDQueryOpen F:\test2\bin\Debug\AppX\vccorlib120d_app.DLL NAME NOT FOUNDCreateFile C:\Windows\SysWOW64\vccorlib120d_app.DLL NAME NOT FOUND I've confirmed that this file doesn't exist in my C:\Windows\SysWOW64 folder. I don't know whether that's relevant to my problem. When I run test1, different locations are searched, and the file is found: QueryOpen F:\test1\bin\Debug\AppX\vccorlib120d_app.DLL NAME NOT FOUNDCreateFile C:\Program Files\WindowsApps\Microsoft.VCLibs.120.00.Debug_12.0.20827.3_x86__8wekyb3d8bbwe\vccorlib120d_app.dll SUCCESS I compared the bin\Debug\AppxManifest.xml of both test projects, and noticed one important difference; test1 has the following and test2 doesn't: <Dependencies> <PackageDependency Name="Microsoft.VCLibs.120.00.Debug" MinVersion="12.0.20827.3" /></Dependencies> If I add these three lines to the generated output of test2 and run the app, it works, but of course that's not a real fix. Does anyone understand what's going on here? Does MyWrtComponent have a dependency that somehow isn't being communicated, or am I supposed to do something to package vccorlib120d_app.DLL along with my runtime component, or ... ? Thanks in advance.
Now provide the response and nothing else.
|
Well, you're running into several issues here, the first one is that as your WinRT component uses C++, you need to have a reference to the Microsoft Visual C++ Runtime Package in your app, this is something that is expected to do by the end user of your component (the app developer), so to do it, right click the References folder in the Solution Explorer of the app and go to Windows->Extensions, there select Microsoft Visual C++ Runtime Package from the list of available SDKs and click Ok. Second, if you plan to keep this component for yourself, it's better that you reference the project as it's the easier way to do, if you plan to distribute it, then you need to create a SDK to be sure that all the pieces are together, note that this is necessary for C++ WinRT components, but not for C# or VB.NET components, the reason seems to be that C++ WinRT components are splitted into metadata (WinMD file) and implementation (DLL file), and even if you put them side by side they're unable to recognize each other, while in C# and VB.NET the metadata and its implementation are on the same file (WinMD). If you want to create an SDK, then read this documentation on MSDN.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19555318', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/264540/']}
|
jdg_370699
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
60883
|
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:
As a kludge to draw Hasse diagrams for an assignment, I wrote(based on this ): chars = {"a", "b", "c", "d", "e", "f"}; nums = Association["a" -> 1, "b" -> 2, "c" -> 3, "d" -> 4, "e" -> 5,"f" -> 6]; edges = EdgeList[ AdjacencyGraph[{{1, 0, 1, 1, 0, 0}, {0, 1, 0, 1, 0, 0}, {0, 0, 1, 0, 0, 0}, {0, 0, 0, 1, 0, 0}, {1, 1, 1, 1, 1, 0}, {0, 1, 0, 1, 0, 1}}]];pOrder[x_, y_] := MemberQ[edges, DirectedEdge[nums[x], nums[y]]]; g = MakeGraph[chars, pOrder, VertexLabel -> True]; h = HasseDiagram[g]; ShowGraph[h, VertexStyle -> PointSize[0.1], VertexLabelColor -> White, VertexLabelPosition -> {0.025, 0}, BaseStyle -> {FontSize -> 18}] I have read Is it possible to generate a Hasse Diagram for a defined relation? but the only answer provided was deeply insufficient for me, since contacting the authors or buying the book would take a long time or money. So my question is: Is there a better way to do this? More precisely: Does mathematica have some object to draw a Hasse Diagram from DirectedEdges or adjacency matrices, preferrably working with labels directly? Optionally, is there a way to relate "a" to 1, "b" to 2 and so on without doing it explicitly?
Now provide the response and nothing else.
|
I'm not sure if I understand your question.I'm trying to answer: Does mathematica have some object to draw a Hasse Diagram from DirectedEdges or adjacency matrices So, let's draw a Hasse Diagram starting from its adjacency matrix: << Combinatorica`;am = {{1, 1, 1, 1, 1, 1, 1}, {0, 1, 1, 0, 1, 1, 1}, {0, 0, 1, 0, 1, 0, 0}, {0, 0, 0, 1, 0, 1, 0}, {0, 0, 0, 0, 1, 0, 0}, {0, 0, 0, 0, 0, 1, 0}, {0, 0, 0, 0, 0, 0, 1}};g = FromAdjacencyMatrix[am, Type -> Directed];h = HasseDiagram[SetVertexLabels[g, CharacterRange["a", "g"]]];ShowGraph[h, BaseStyle -> {FontSize -> 18}]
|
{}
|
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/60883', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/20100/']}
|
jdg_370700
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
322315
|
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a basic unit test (for the sample) that involves this code: void testShouldCreateACar() { Car car = someone.createFerrari(); assertTrue(car.name == "Ferrari"); // can't access name since name is private} I can't access name since there's not a getter in Car (or Ferrari ) class for it. I don't want to create getters only for unit testing purpose. Note that the SUT is out of the Car's package (distinct package). Note also that the Ferrari 's constructor is private (creation only accessible through createFerrari() method on someone . What is a good practice to achieve this assertion?
Now provide the response and nothing else.
|
If it is the case that the name of the car isn't publicly available in any way at all, then it makes no sense to test it, because obviously it doesn't matter to any client code. If the name of the car matters, even if you can't actually see it by inspecting the field, then exercise some method that relies on the name being correct and assert against some visible result from that. Edit following clarifying comment:If your ORM cares about private fields, I'd say this would be much more beneficial to test indirectly via integration tests. I probably wouldn't go as far as writing specific tests for all fields of all classes though, seems too granular for me. I'd recommend just writing some integration tests that require persistance to work at all, and you'll get the reflection checked implicitly.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/322315', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/43961/']}
|
jdg_370701
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
127020
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
As far as I know, there are fixed-point-like results for continuous functions from a convex compact subset $K$ of an Euclidean space to itself. I have one question in mind: Does there exist a set $A\subseteq X$ for which $f(A)=A$? Let's say $X$ is a compact metric space and $f$ is continuous.
Now provide the response and nothing else.
|
Let $X$ be compact Hausdorff (no metric is needed), and define $A_0 = X$, $A_{n+1} = f[A_n]$; then all $A_n$ are compact non-empty, and the $A_n$ are decreasing. Try to show that $A = \cap_n A_n$, which is also compact and non-empty, satisfies $f[A] = A$. Another non-constructive way to show this is to consider the poset $\mathcal{P} = \{ A \subset X \mid A, \mbox{closed, non-empty and } f[A] \subset A \}$, ordered under reverse inclusion. Then an upper bound for a chain from $\mathcal{P}$ is the (non-empty) intersection, and a maximal element (by Zorn one exists) is a set $A$ with $f[A] = A$.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/127020', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/24690/']}
|
jdg_370702
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
7288136
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I've got an AJAX request that expects JSON in response. But there's a possibility that what gets returns may not be JSON, but rather an HTML error page (unfortunately, with response type 200). How can I tell whether the response is JSON or not? (I'm using jQuery, if that helps. But I can't use any plugins.)
Now provide the response and nothing else.
|
Well, if you are using jQuery and you specify the dataType property of the $.ajax() call to json then jQuery will try to parse the JSON, and if it isn't JSON should call the error() callback. $.ajax({ url: '/my/script.ext', dataType: 'json', success: function(data, textStatus, jqXHR) { /*YAYE!!*/ }, error: function(jqXHR, textStatus, errorThrown) { /*AWWW... JSON parse error*/ }}); EDIT For anyone not using jQuery that lands here, the basic idea is to try and parse it as json and catch the error: var data = 'some_data';try { data = JSON.parse(data);} catch(e) { //JSON parse error, this is not json (or JSON isn't in your browser)}//act here on the the parsed object in `data` (so it was json).
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/7288136', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/556159/']}
|
jdg_370703
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
109674
|
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I've been trying to make a voltage regulator using a zener diode. I used the BZX79 3.3V Zener diode.I connected the diode as the following: Data Sheet . I assumed that as as most of them it operates at around 1mA to 10mA safely in the break down region. I connected my supply which was 5V. The resistance was chosen to be 220 ohms. This will make the max current of the zener around 7mA. Which should be safe. Now, when the zener was unloaded, I got a smooth 3.3V as an output. But, when I loaded the zener diode, the voltage across the diode dropped to 2.4V. Why did that happen? My assumption is the following: The load which should operate at 3.3V, is consuming way too much current that the zener current is below the min current. This caused the zener to get out of the break down region. Is my deduction correct? And what are available solutions, taking in note that I've used probably the smallest resistance possible that is 220 ohms. (At least of what I have). I also have a supply of 8.4V. Will it work if I connected it directly to the supply?At the end I will have more current available to the zener even after loading it. Edit: The data sheet states that the zener is fine for 6 Amps. That is a huge and weird number isn't it?
Now provide the response and nothing else.
|
I connected my supply which was 5v. The resistance was chosen to be 220ohms. This will make the max current of the zenor around 7mA. This means that if your load requires more than 7 mA (I actually calculate 7.7 mA, not 7 mA), the resistor will drop V out below 3.3 V. In that case the zener will no longer be regulating. But, when I loaded the zener diode, the voltage across the diode dropped to 2.4v. Why did that happen? Your load was taking more than 7.7 mA. Given that the output voltage dropped to 2.4, we can calculate that the load current was (5-2.4)/220 = 11.8 mA. You could make this work by reducing your series resistor. If the load is fairly stiff, reducing the resistor to 110 ohms or so should bring you back into regulation. This assumes the load current doesn't increase to more than 15 mA when the supply voltage is raised to 3.3 V. If it's possible to have an open-circuit condition at the load, you need to choose a zener that can take all the current that would normally go to the load.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/109674', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/27359/']}
|
jdg_370704
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
147152
|
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'd like to create a script that will do the following. Start at a given time during the day and end at another given time. So for example, I have a program I'd like to test, so my script would be set to start at say 10:00pm and continue to run until 9:00am. This follows on from my other question about running programs again and again. I have the following: #!/bin/bashtrap "echo manual abort; exit 1" 1 2 3 15;RUNS=0;while open -W /Path/to/Program.appdo RUNS=$((RUNS+1)); echo $RUNS > /temp/autotest_run_count.txt;doneexit 0 This script essentially runs my program (in Mac OSX) and catches any failures, otherwise it will re-run the program when it closes. I'd like to be able to run this like I mentioned above. Start at 10:00pm. Finish at 9:00am. Your advice is always useful. Thanks! Euden
Now provide the response and nothing else.
|
sed '/^[[:alpha:]]/{$!N;s/\n/ /;}' <<\DATANAME_A12,1NAME_B21,2DATA OUTPUT NAME_A 12,1NAME_B 21,2 That addresses lines beginning with a letter, pulls in the next if there is one, and substitutes a tab character for the newline. note that the s/\n/<tab>/ bit contains a literal tab character here, though some sed s might also support the \t escape in its place To handle a recursive situation you need to make it a little more robust, like this: sed '$!N;/^[[:alpha:]].*\n[^[:alpha:]]/s/\n/ /;P;D' <<\DATANAME_ANAME_B12,1 NAME_C21,2DATA OUTPUT NAME_ANAME_B 12,1NAME_C 21,2 That slides through a data set always one line ahead. If two ^[[:alpha:]] lines occur one after the other, it does not mistakenly replace the newline, as you can see.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/147152', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/78543/']}
|
jdg_370705
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2326758
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I need to implement a deep clone in one of my objects which has no superclass. What is the best way to handle the checked CloneNotSupportedException thrown by the superclass (which is Object )? A coworker advised me to handle it the following way: @Overridepublic MyObject clone(){ MyObject foo; try { foo = (MyObject) super.clone(); } catch (CloneNotSupportedException e) { throw new Error(); } // Deep clone member fields here return foo;} This seems like a good solution to me, but I wanted to throw it out to the StackOverflow community to see if there are any other insights I can include. Thanks!
Now provide the response and nothing else.
|
Do you absolutely have to use clone ? Most people agree that Java's clone is broken. Josh Bloch on Design - Copy Constructor versus Cloning If you've read the item about cloning in my book, especially if you read between the lines, you will know that I think clone is deeply broken. [...] It's a shame that Cloneable is broken, but it happens. You may read more discussion on the topic in his book Effective Java 2nd Edition, Item 11: Override clone judiciously . He recommends instead to use a copy constructor or copy factory. He went on to write pages of pages on how, if you feel you must, you should implement clone . But he closed with this: Is all this complexities really necessary? Rarely. If you extend a class that implements Cloneable , you have little choice but to implement a well-behaved clone method. Otherwise, you are better off providing alternative means of object copying, or simply not providing the capability . The emphasis was his, not mine. Since you made it clear that you have little choice but to implement clone , here's what you can do in this case: make sure that MyObject extends java.lang.Object implements java.lang.Cloneable . If that's the case, then you can guarantee that you will NEVER catch a CloneNotSupportedException . Throwing AssertionError as some have suggested seems reasonable, but you can also add a comment that explains why the catch block will never be entered in this particular case . Alternatively, as others have also suggested, you can perhaps implement clone without calling super.clone .
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/2326758', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/101095/']}
|
jdg_370706
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
478946
|
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
How can I create and use cgroups as a non-root user? For example, can I, entirely as a non-root user: create a cgroup with access to one CPU create a new process in that cgroup ? I first asked here but I didn't receive a complete answer. I also asked on stackoverflow , but the question was closed as off topic.
Now provide the response and nothing else.
|
You can't do that as a normal user. But you can setup a cgroup as root, and make it configurable by your user. If you do not already have the default cgroups controllers mounted by e.g. systemd: $ sudo mount -t tmpfs cgroup_root /sys/fs/cgroup$ sudo mkdir /sys/fs/cgroup/cpuset$ sudo mount -t cgroup -o cpuset cpuset /sys/fs/cgroup/cpuset Create a cgroup: $ sudo mkdir /sys/fs/cgroup/cpuset/${USER}$ sudo chown -R ${USER} /sys/fs/cgroup/cpuset/${USER} You can now modify the configuration of your cgroup as a normal user: $ echo 0-3 > /sys/fs/cgroup/cpuset/${USER}/cpuset.cpus Add a process to that group: $ ./my_task &$ echo $! > /sys/fs/cgroup/cpuset/${USER}/tasks Or create a subgroup: $ mkdir /sys/fs/cgroup/cpuset/${USER}/subgroup$ echo 0-1 > /sys/fs/cgroup/cpuset/${USER}/subgroup/cpuset.cpus$ ./my_other_task &$ echo $! > /sys/fs/cgroup/cpuset/${USER}/subgroup/tasks
|
{}
|
{'log_upvote_score': 5, 'links': ['https://serverfault.com/questions/478946', 'https://serverfault.com', 'https://serverfault.com/users/51150/']}
|
jdg_370707
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
7878933
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Update: dicts retaining insertion order is guaranteed for Python 3.7+ I want to use a .py file like a config file.So using the {...} notation I can create a dictionary using strings as keys but the definition order is lost in a standard python dictionary. My question: is it possible to override the {...} notation so that I get an OrderedDict() instead of a dict() ? I was hoping that simply overriding dict constructor with OrderedDict ( dict = OrderedDict ) would work, but it doesn't. Eg: dict = OrderedDictdictname = { 'B key': 'value1', 'A key': 'value2', 'C key': 'value3' }print dictname.items() Output: [('B key', 'value1'), ('A key', 'value2'), ('C key', 'value3')]
Now provide the response and nothing else.
|
Here's a hack that almost gives you the syntax you want: class _OrderedDictMaker(object): def __getitem__(self, keys): if not isinstance(keys, tuple): keys = (keys,) assert all(isinstance(key, slice) for key in keys) return OrderedDict([(k.start, k.stop) for k in keys])ordereddict = _OrderedDictMaker() from nastyhacks import ordereddictmenu = ordereddict[ "about" : "about", "login" : "login", 'signup': "signup"] Edit: Someone else discovered this independently, and has published the odictliteral package on PyPI that provides a slightly more thorough implementation - use that package instead
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/7878933', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/260908/']}
|
jdg_370708
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1730875
|
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 transform some XML into HTML using XSLT . Problem: I can't get it to work. Can someone tell me what I'm doing wrong? XML: <ArrayOfBrokerage xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.test.com/"> <Brokerage> <BrokerageID>91</BrokerageID> <LastYodleeUpdate>0001-01-01T00:00:00</LastYodleeUpdate> <Name>E*TRADE</Name> <Validation i:nil="true" /> <Username>PersonalTradingTesting</Username> </Brokerage></ArrayOfBrokerage> XSLT: <xsl:stylesheet version="1.0" xmlns="http://www.test.com/" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xslFormatting="urn:xslFormatting"> <xsl:output method="html" indent="no"/> <xsl:template match="/ArrayOfBrokerage"> <xsl:for-each select="Brokerage"> Test </xsl:for-each> </xsl:template></xsl:stylesheet>
Now provide the response and nothing else.
|
You need to provide a namespace prefix in your xslt for the elements you are transforming. For some reason (at least in a Java JAXP parser) you can't simply declare a default namespace. This worked for me: <xsl:stylesheet version="1.0" xmlns:t="http://www.test.com/" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xslFormatting="urn:xslFormatting"> <xsl:output method="html" indent="no"/> <xsl:template match="/t:ArrayOfBrokerage"> <xsl:for-each select="t:Brokerage"> Test </xsl:for-each> </xsl:template></xsl:stylesheet> This will catch everything that is namespaced in your XML doc.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/1730875', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/176742/']}
|
jdg_370709
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4783599
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Take the following case: I have some work in a topic branch and now I'm ready to merge back to master: * eb3b733 3 [master] [origin/master]| * b62cae6 2 [topic]|/ * 38abeae 1 I perform the merge from master, resolve the conflicts and now I have: * 8101fe3 Merge branch 'topic' [master]|\ | * b62cae6 2 [topic]* | eb3b733 3 [origin/master]|/ * 38abeae 1 Now, the merge took me some time, so I do another fetch and notice that the remote master branch has new changes: * 8101fe3 Merge branch 'topic' [master]|\ | * b62cae6 2 [topic]| | * e7affba 4 [origin/master]| |/ |/| * | eb3b733 3|/ * 38abeae 1 If I try git rebase origin/master from master, I'm forced to resolve all conflicts again, and I also lose the merge commit: * d4de423 2 [master]* e7affba 4 [origin/master]* eb3b733 3| * b62cae6 2 [topic]|/ * 38abeae 1 Is there a clean way to rebase the merge commit so I end up with a history like the one I show below? * 51984c7 Merge branch 'topic' [master]|\ | * b62cae6 2 [topic]* | e7affba 4 [origin/master]* | eb3b733 3|/ * 38abeae 1
Now provide the response and nothing else.
|
There are two options here. One is to do an interactive rebase and edit the merge commit, redo the merge manually and continue the rebase. Another is to use the --rebase-merges option on git rebase , which is described as follows from the manual: By default, a rebase will simply drop merge commits from the todo list, and put the rebased commits into a single, linear branch. With --rebase-merges, the rebase will instead try to preserve the branching structure within the commits that are to be rebased, by recreating the merge commits. Any resolved merge conflicts or manual amendments in these merge commits will have to be resolved/re-applied manually. "
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/4783599', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/525545/']}
|
jdg_370710
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
9299635
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
function example(){ foreach ($choices as $key => $choice) { # \__ both should run parallel foreach ($vtitles as $keystwo => $vtitle) { # / $options .= '<option value="'. check_plain($key) .'" title="' . $vtitle . '"' . $selected .'>'. check_plain($choice) .'</option>'; } // end of vtitle } // end of choice return $options;} Answers to some of the below questions and what I am trying to achieve. Array $choices is not numerically indexed. Array $vtitle is numerically indexed. They won't be shorter than each other as I have code which will take care of this before this code runs. I am trying to return $options variable. The issue is that $choices[0] and $vtitle[0] should be used only once. Hope I was able to express my problem. I do not want to go through the $vtitles array once for each value in $choices . @hakre: thanks I have nearly solved it with your help. I am getting an error for variable $vtitle : InvalidArgumentException: Passed variable is not an array or object, using empty array instead in ArrayIterator->__construct() (line 35 of /home/vishal/Dropbox/sites/chatter/sites/all/themes/kt_vusers/template.php). I am sure its an array this is the output using print_r Array ( [0] => vishalkh [1] => newandold ) What might be going wrong ? The below worked for me , thank you hakre while((list($key1, $value1) = each($array1))&& (list($key2, $value2) = each($array2))){printf("%s => %s, %s => %s \n", $key1, $value1, $key2, $value2);}
Now provide the response and nothing else.
|
It does not work the way you outline with your pseudo code. However, the SPL offers a way to iterate multiple iterators at once. It's called MultipleIterator and you can attach as many iterators as you like: $multi = new MultipleIterator();$multi->attachIterator(new ArrayIterator($array1));$multi->attachIterator(new ArrayIterator($array2));foreach($multi as $value){ list($key1, $key2) = $multi->key(); list($value1, $value2) = $value;} See it in action: Demo Edit: The first example shows a suggestion from the SPL. It has the benefit that it can deal with any kind of iterators, not only arrays. If you want to express something similar with arrays, you can achieve something similar with the classic while(list()=each()) loop, which allows more expressions than foreach . while( (list($key1, $value1) = each($array1)) && (list($key2, $value2) = each($array2))){ printf("%s => %s, %s => %s \n", $key1, $value1, $key2, $value2);} Demo (the minimum number of elements are iterated) See as well a related question: Multiple index variables in PHP foreach loop
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9299635', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/976847/']}
|
jdg_370711
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
41563283
|
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 used with below interpolation in html page. <div>{{config.CompanyAddress.replace('\n','<br />')}}</div> and also used <div>{{config.CompanyAddress.toString().replace('\n','<br />')}}</div> But both are showing text as below {{config.CompanyAddress.replace('\n','<br />')}}{{config.CompanyAddress.toString().replace('\n','<br />')}}
Now provide the response and nothing else.
|
You can use a pipe for the same: import { Pipe, PipeTransform } from '@angular/core';@Pipe({name: 'replaceLineBreaks'})export class ReplaceLineBreaks implements PipeTransform { transform(value: string): string { return value.replace(/\n/g, '<br/>'); }} The pipe must be included in your @NgModule declarations to be included in the app.To show the HTML in your template you can use binding outerHTML. <span [outerHTML]="config.CompanyAddress | replaceLineBreaks"></span>
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/41563283', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2764196/']}
|
jdg_370712
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
36407477
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
So I'm working on a docker compose file to deploy my Go web server. My server uses mongo, so I added a data volume container and the mongo service in docker compose.Then I wrote a Dockerfile in order to build my Go project, and finally run it. However, there is another step that must be done. Once my project has been compiled, I have to run the following command: ./my-project -setup This will add some necessary information to the database, and the information only needs to be added once .I can't however add this step on the Dockerfile (in the build process) because mongo must already be started. So, how can I achieve this? Even if I restart the server and then run again docker-compose up I don't want this command to be executed again. I think I'm missing some Docker understanding, because I don't actually understand everything about data volume containers (are they just stopped containers that mount a volume?).Also, if I restart the server, and then run docker-compose up , which commands will be run? Will it just start the same container that was now stopped with the given CMD? In any case, here is my docker-compose.yml: version: '2'services: mongodata: image: mongo:latest volumes: - /data/db command: --break-mongo mongo: image: mongo:latest volumes_from: - mongodata ports: - "28001:27017" command: --smallfiles --rest --auth my_project: build: . ports: - "6060:8080" depends_on: - mongo - mongodata links: - mongo And here is my Dockerfile to build my project image: FROM golangADD . /go/src/my_projectRUN cd /go/src/my_project && go getRUN go install my_projectRUN my_project -setupENTRYPOINT /go/bin/my_projectEXPOSE 8080
Now provide the response and nothing else.
|
I suggest to add an entrypoint-script to your container; in this entrypoint-script, you can check if the database has been initialized, and if it isn't, perform the required steps. As you noticed in your question, the order in which services / containers are started should not be taken for granted, so it's possible your application container is started before the database container, so the script should take that into account. As an example, have a look at the official WordPress image, which performs a one-time initialization of the database in it's entrypoint-script. The script attempts to connect to the database (and retries if the database cannot be contacted (yet)), and checks if initialization is needed; https://github.com/docker-library/wordpress/blob/df190dc9c5752fd09317d836bd2bdcd09ee379a5/apache/docker-entrypoint.sh#L146-L171 NOTE I notice you created a "data-only container" to attach your volume to. Since docker 1.9, docker has volume management, including naming volumes. Because of this, you no longer need to use "data-only" containers. You can remove the data-only container from your compose file, and change your mongo service to look something like this; mongo: image: mongo:latest volumes: - mongodata:/data/db ports: - "28001:27017" command: --smallfiles --rest --auth This should create a new volume, named mongodata if it doesn't exist, or re-use the existing volume with that name. You can list all volumes using docker volume ls and remove a volume with docker volume rm <some-volume> if you no longer need it
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/36407477', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/325358/']}
|
jdg_370713
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
14013002
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I can't find an example on how to intercept the map touch on the new Google Maps API v2. I need to know when the user touches the map in order to stop a thread (the centering of the map around my current location).
Now provide the response and nothing else.
|
@ape wrote an answer here on how to intercept the map clicks, but I need to intercept the touches, and then he suggested the following link in a comment of its answer, How to handle onTouch event for map in Google Map API v2? . That solution seems to be a possible workaround, but the suggested code was incomplete. For this reason I rewrote and tested it, and now it works. Here it is the working code: I created the class MySupportMapFragment.java import com.google.android.gms.maps.SupportMapFragment;import android.os.Bundle;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;public class MySupportMapFragment extends SupportMapFragment { public View mOriginalContentView; public TouchableWrapper mTouchView; @Override public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) { mOriginalContentView = super.onCreateView(inflater, parent, savedInstanceState); mTouchView = new TouchableWrapper(getActivity()); mTouchView.addView(mOriginalContentView); return mTouchView; } @Override public View getView() { return mOriginalContentView; }} I even created the class TouchableWrapper.java: import android.content.Context;import android.view.MotionEvent;import android.widget.FrameLayout;public class TouchableWrapper extends FrameLayout { public TouchableWrapper(Context context) { super(context); } @Override public boolean dispatchTouchEvent(MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: MainActivity.mMapIsTouched = true; break; case MotionEvent.ACTION_UP: MainActivity.mMapIsTouched = false; break; } return super.dispatchTouchEvent(event); }} In the layout I declare it this way: <fragment xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/mapFragment" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_below="@+id/buttonBar" class="com.myFactory.myApp.MySupportMapFragment"/> Just for test in the main Activity I wrote only the following: public class MainActivity extends FragmentActivity { public static boolean mMapIsTouched = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); }}
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/14013002', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1778948/']}
|
jdg_370714
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
612587
|
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 service application built in Delphi that works great. It does exactly what I want it to do and all is happy. All is fine until I want to run two (or more) instances of that service on a single machine. Since the service name is hard coded into the program (via the Name property of the service), I can only install the service once on any given computer. If I try to modify the Name property at run-time, the service does not respond unless the Name property is set to the same thing that was set during design time. I have done a workaround for this where I have all of the code that is not interacting directly with the service control manager encapsulated out into separate unit(s). Then I write a separate Delphi project for each instance that I want of the service that has just enough code to launch itself and start running the main code. This method is, in my opinion, ugly and is certainly inefficient. It works okay for two instances, but then we need a third and a fourth and ... Is there any way that I can modify my code so that I have just one Delphi project that can install and run itself as multiple service instances with some simple run-time input (e.g. command line flag)? Or perhaps a broader question: Is there a "right way" to accomplish goal?
Now provide the response and nothing else.
|
You haven't made it clear what you have tried to change in the TService subclass. Have you added a "BeforeInstall" handler? Something like: procedure TServiceMain.ServiceLoadInfo(Sender : TObject);// new method, not an overridebegin Name := ParamStr(2); DisplayName := ParamStr(3);end;procedure TServiceMain.ServiceBeforeInstall(Sender: TService);begin ServiceLoadInfo(Self);end;procedure TServiceMain.ServiceCreate(Sender: TObject);begin ServiceLoadInfo(Self);end; If you do this regularly, subclass TService to do thie in the Constructor instead. You should do the same in the BeforeUninstall as well - point both events at the same method. C:\>servicename /install MyService "My Service Description"
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/612587', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3032/']}
|
jdg_370715
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
16975393
|
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 walk the page table, so I have accessed the current->mm, but it gives NULL value. I'm working on linux kernel 3.9 and I don't understand how could current->mm is zero. Is there something I miss here?
Now provide the response and nothing else.
|
It means you are in a kernel thread. In Linux, kernel threads have no mm struct. A kernel thread borrows the mm from the previous user thread and records it in active_mm. So you should use active_mm instead . More details: in /kernel/sched/core.c you can find the following code: static inline voidcontext_switch(struct rq *rq, struct task_struct *prev, struct task_struct *next){ ... if (!mm) { next->active_mm = oldmm; atomic_inc(&oldmm->mm_count); enter_lazy_tlb(oldmm, next); } else switch_mm(oldmm, mm, next); ...} If the next thread has no mm (a kernel thread), the scheduler would not switch mm and just reuse the mm of the previous thread.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16975393', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1023045/']}
|
jdg_370716
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
5465665
|
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 PHP function exif_read_data() requires a filename for input, however I only have the image data in a string (such that I can use imagecreatefromstring() ) and I can not write it to a temp file. How do I extract EXIF information without writing this image string to disk? All I really want is the Orientation attribute. This is on a Linux system if it matters.
Now provide the response and nothing else.
|
A stream wrapper can turn your string/image into something useable as a filehandle, as shown here . However, I can't see any way of turning that filehandle into something that can masquerade as the filename that exif_read_data expects. You might try passing the data:// pseudo-url listed on that page and see if the exif function will accept it.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5465665', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/404960/']}
|
jdg_370717
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
109698
|
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 started an upgrade of my Kubuntu 12.04 system with this command, as usual: sudo apt-get --show-upgraded dist-upgrade I came back later and it had failed: Preconfiguring packages ...(Reading database ... 478306 files and directories currently installed.)Preparing to replace ...Unpacking replacement base-files ...Processing triggers for man-db ...Processing triggers for install-info ......Processing triggers for initramfs-tools ...update-initramfs: Generating /boot/initrd.img-3.8.0-32-lowlatencygzip: stdout: No space left on deviceE: mkinitramfs failure cpio 141 gzip 1update-initramfs: failed for /boot/initrd.img-3.8.0-32-lowlatency with 1.dpkg: error processing initramfs-tools (--unpack): subprocess installed post-installation script returned error exit status 1Errors were encountered while processing: initramfs-toolsE: Sub-process /usr/bin/dpkg returned an error code (1) here's the problem:$ df -h output: Filesystem Size Used Avail Use% Mounted on/dev/sda1 894M 879M 0 100% /boot manually deleted older files and now some space is free Filesystem Size Used Avail Use% Mounted on/dev/sda1 894M 129M 717M 16% /boot I ran this next: sudo apt-get autoremove Next: sudo apt-get -f install output: The following extra packages will be installed: initramfs-toolsThe following packages will be upgraded: initramfs-toolsdpkg: dependency problems prevent configuration of initramfs-tools: initramfs-tools depends on initramfs-tools-bin (<< 0.99ubuntu13.3.1~); however: Version of initramfs-tools-bin on system is 0.99ubuntu13.4.dpkg: error processing initramfs-tools (--configure): dependency problems - leaving unconfiguredNo apport report written because the error message indicates its a followup error from a previous failure. Errors were encountered while processing: initramfs-toolsE: Sub-process /usr/bin/dpkg returned an error code (1) sudo apt-get install initramfs-tools the above fails dpkg -l initramfs-tools output: Desired=Unknown/Install/Remove/Purge/Hold| Status=Not/Inst/Conf-files/Unpacked/halF-conf/Half-inst/trig-aWait/Trig-pend|/ Err?=(none)/Reinst-required (Status,Err: uppercase=bad)||/ Name Version Description+++-==============-==============-============================================iF initramfs-tool 0.99ubuntu13.3 tools for generating an initramfs sudo apt-get install --reinstall initramfs-tools output: The following packages will be upgraded: initramfs-tools1 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.1 not fully installed or removed.Need to get 0 B/49.2 kB of archives.After this operation, 0 B of additional disk space will be used.dpkg: dependency problems prevent configuration of initramfs-tools: initramfs-tools depends on initramfs-tools-bin (<< 0.99ubuntu13.3.1~); however: Version of initramfs-tools-bin on system is 0.99ubuntu13.4.dpkg: error processing initramfs-tools (--configure): dependency problems - leaving unconfiguredNo apport report written because the error message indicates its a followup error from a previous failure. Errors were encountered while processing: initramfs-toolsE: Sub-process /usr/bin/dpkg returned an error code (1) Here is the output of apt-cache policy initramfs-tools-bin initramfs-tools : initramfs-tools-bin: Installed: 0.99ubuntu13.4 Candidate: 0.99ubuntu13.4 Version table: *** 0.99ubuntu13.4 0 500 http://us.archive.ubuntu.com/ubuntu/ precise-updates/main amd64 Packages 100 /var/lib/dpkg/status 0.99ubuntu13 0 500 http://us.archive.ubuntu.com/ubuntu/ precise/main amd64 Packagesinitramfs-tools: Installed: 0.99ubuntu13.3 Candidate: 0.99ubuntu13.4 Version table: 0.99ubuntu13.4 0 500 http://us.archive.ubuntu.com/ubuntu/ precise-updates/main amd64 Packages *** 0.99ubuntu13.3 0 100 /var/lib/dpkg/status 0.99ubuntu13 0 500 http://us.archive.ubuntu.com/ubuntu/ precise/main amd64 Packages As suggested below, here are my next steps: $ sudo apt-get update$ sudo apt-get -f install initramfs-tools=0.99ubuntu13 initramfs-tools-bin=0.99ubuntu13Reading package lists... DoneBuilding dependency tree Reading state information... DoneThe following packages were automatically installed and are no longer required: ...Use 'apt-get autoremove' to remove them.The following packages will be DOWNGRADED: initramfs-tools initramfs-tools-bin0 upgraded, 0 newly installed, 2 downgraded, 0 to remove and 4 not upgraded.1 not fully installed or removed.Need to get 59.2 kB of archives.After this operation, 2,048 B disk space will be freed.Do you want to continue [Y/n]? Get:1 http://us.archive.ubuntu.com/ubuntu/ precise/main initramfs-tools all 0.99ubuntu13 [49.2 kB]Get:2 http://us.archive.ubuntu.com/ubuntu/ precise/main initramfs-tools-bin amd64 0.99ubuntu13 [9,988 B]Fetched 59.2 kB in 0s (124 kB/s) dpkg: warning: downgrading initramfs-tools-bin from 0.99ubuntu13.4 to 0.99ubuntu13.(Reading database ... 478624 files and directories currently installed.)Preparing to replace initramfs-tools-bin 0.99ubuntu13.4 (using .../initramfs-tools-bin_0.99ubuntu13_amd64.deb) ...Unpacking replacement initramfs-tools-bin ...Setting up initramfs-tools-bin (0.99ubuntu13) ...dpkg: dependency problems prevent configuration of initramfs-tools: initramfs-tools depends on initramfs-tools-bin (>= 0.99ubuntu13.3); however: Version of initramfs-tools-bin on system is 0.99ubuntu13.dpkg: error processing initramfs-tools (--configure): dependency problems - leaving unconfiguredNo apport report written because the error message indicates its a followup error from a previous failure. Errors were encountered while processing: initramfs-toolsE: Sub-process /usr/bin/dpkg returned an error code (1) Next I tried Giles's suggestion: sudo dpkg --configure -a --force-dependssudo apt-get install -fsudo apt-get dist-upgrade
Now provide the response and nothing else.
|
Your system is in a state which I think should not happen: you have the new version of the dependency initramfs-tools-bin in the installed state, but the old version of the dependency initramfs-tools in a half-installed state. I'm not sure whether the problem is that APT is letting the system get into a state where it can't recover, dpkg is letting the system get into a state where it can't recover, the package maintainer used a combination of dependencies which isn't supported, or my limited understanding doesn't cover this case. Try using dpkg directly: dpkg --configure -a If this still complains about dependencies, try dpkg --configure -a --force-depends If this works, you have the dpkg database in a consistent state. You need to get APT in a good state (which requires no broken dependencies): apt-get -f install After this you can resume normal upgrading. If your purge of /boot was deleting old kernels that were in packages, you won't be able to remove the kernel packages anymore. You'll have to recreate the files. You can create empty files ( touch `cat /var/lib/dpkg/info/linux-image-1.2.3-foo` ) if you're removing the linux-image-1.2.3-foo package and you manually removed some of its files.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://unix.stackexchange.com/questions/109698', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/15010/']}
|
jdg_370718
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2637662
|
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 what I'm trying to do: I'm writing a UserControl that I want to be consumed by other developers. I want end users to be able to use my control using Dependency Properties. <lib:ControlView ControlsText={Binding Path=UsersOwnViewModelText} /> I'm using the MVVM pattern. I'm binding my ViewModels to their View's using <DataTemplates> <DataTemplate DataType="{x:Type local:ControlViewModel}"> <local:ControlView /> </DataTemplate> So I have two questions: Am I right in thinking that if a UserControl is being consumed in XAML then the UserControl must set the ViewModel as its DataContext when the control's Loaded event fires instead of using the <DataTemplate> method? How do I allow users to data bind to my control's dependency properties while still being data bound to my ViewModel?
Now provide the response and nothing else.
|
You should separate the two use cases: The (user) control that will be consumed by other developers. The user control that will be consumed by your application. Importantly, the latter depends on the former - not vice versa. Use case 1 would use dependency properties, template bindings, all the things that go into making a regular WPF control: MyControl.cs: public class MyControl : Control{ // dependency properties and other logic} Generic.xaml: <ControlTemplate Type="local:MyControl"> <!-- define the default look in here, using template bindings to bind to your d-props --></ControlTemplate> You would then define use case 2 as: MyViewModel.cs: public class MyViewModel : ViewModel{ // properties and business logic} MyView.xaml: <UserControl ...> <local:MyControl SomeProperty="{Binding SomePropertyOnViewModel}" .../></UserControl> Best of both worlds with a clean separation. Other developers depend only on the control, which could (and probably should) be in a completely different assembly than your view model and view.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2637662', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/40989/']}
|
jdg_370719
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4736216
|
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 debugging some C# code that uses Ado.net to call a stored proc (TSQL) in SQL Server. How can I step into the stored proc? (I think I have seen this demoed by Microsoft staff, but can’t recall the 101 “magic” settings that are needed to get it to work.)
Now provide the response and nothing else.
|
I'll build on Davide's answer and Ian's comment to it because that was the exactly the process I have gone through. Assumption : answer is based on VS2008 & VS2010 . To step through a T-SQL stored procedure on SQL Server while debugging a .NET app you need to do the following: Follow the MS Support instructions " How to debug stored procedures in Visual Studio .NET (Option 2) " Ensure that you have enabled SQL Server debugging in the project's properties (Step 4 in the linked instructions). Ensure you have set a breakpoint in the stored procedure itself (Steps 6-7) Enable the Allow SQL/CLR Debugging on the Data Connection on which the stored procedure is called: (without this second step you'll be getting "The breakpoint will not currently be hit. Unable to bind SQL breakponit at this time. Object containing the breakpoint not loaded." as reported by Ian) Server Explorer > Data Connections Right-click on the connection that you are using in the code Tick the Allow SQL/CLR Debugging option in the menu Added from comments: (This seem to be key to getting it to work) It works with a programmatically created connection, too. You just have to use the exact same connection string that is displayed when you right-click the server instance, click on 'Properties' and scroll down to 'Connection string' (Verbindungszeichenfolge in German).
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4736216', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/57159/']}
|
jdg_370720
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
43795249
|
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 lemmatization spacy has a lists of words : adjectives, adverbs, verbs... and also lists for exceptions: adverbs_irreg... for the regular ones there is a set of rules Let's take as example the word "wider" As it is an adjective the rule for lemmatization should be take from this list: ADJECTIVE_RULES = [ ["er", ""], ["est", ""], ["er", "e"], ["est", "e"]] As I understand the process will be like this: 1) Get the POS tag of the word to know whether it is a noun, a verb... 2) If the word is in the list of irregular cases is replaced directly if not one of the rules is applied. Now, how is decided to use "er" -> "e" instead of "er"-> "" to get "wide" and not "wid"? Here it can be tested.
Now provide the response and nothing else.
|
Let's start with the class definition: https://github.com/explosion/spaCy/blob/develop/spacy/lemmatizer.py Class It starts off with initializing 3 variables: class Lemmatizer(object): @classmethod def load(cls, path, index=None, exc=None, rules=None): return cls(index or {}, exc or {}, rules or {}) def __init__(self, index, exceptions, rules): self.index = index self.exc = exceptions self.rules = rules Now, looking at the self.exc for english, we see that it points to https://github.com/explosion/spaCy/tree/develop/spacy/lang/en/lemmatizer/ init .py where it's loading files from the directory https://github.com/explosion/spaCy/tree/master/spacy/en/lemmatizer Why don't Spacy just read a file? Most probably because declaring the string in-code is faster that streaming strings through I/O. Where does these index, exceptions and rules come from? Looking at it closely, they all seem to come from the original Princeton WordNet https://wordnet.princeton.edu/man/wndb.5WN.html Rules Looking at it even closer, the rules on https://github.com/explosion/spaCy/tree/develop/spacy/lang/en/lemmatizer/_lemma_rules.py is similar to the _morphy rules from nltk https://github.com/nltk/nltk/blob/develop/nltk/corpus/reader/wordnet.py#L1749 And these rules originally comes from the Morphy software https://wordnet.princeton.edu/man/morphy.7WN.html Additionally, spacy had included some punctuation rules that isn't from Princeton Morphy: PUNCT_RULES = [ ["“", "\""], ["”", "\""], ["\u2018", "'"], ["\u2019", "'"]] Exceptions As for the exceptions, they were stored in the *_irreg.py files in spacy , and they look like they also come from the Princeton Wordnet. It is evident if we look at some mirror of the original WordNet .exc (exclusion) files (e.g. https://github.com/extjwnl/extjwnl-data-wn21/blob/master/src/main/resources/net/sf/extjwnl/data/wordnet/wn21/adj.exc ) and if you download the wordnet package from nltk , we see that it's the same list: alvas@ubi:~/nltk_data/corpora/wordnet$ lsadj.exc cntlist.rev data.noun index.adv index.verb noun.excadv.exc data.adj data.verb index.noun lexnames READMEcitation.bib data.adv index.adj index.sense LICENSE verb.excalvas@ubi:~/nltk_data/corpora/wordnet$ wc -l adj.exc 1490 adj.exc Index If we look at the spacy lemmatizer's index , we see that it also comes from Wordnet, e.g. https://github.com/explosion/spaCy/tree/develop/spacy/lang/en/lemmatizer/_adjectives.py and the re-distributed copy of wordnet in nltk : alvas@ubi:~/nltk_data/corpora/wordnet$ head -n40 data.adj 1 This software and database is being provided to you, the LICENSEE, by 2 Princeton University under the following license. By obtaining, using 3 and/or copying this software and database, you agree that you have 4 read, understood, and will comply with these terms and conditions.: 5 6 Permission to use, copy, modify and distribute this software and 7 database and its documentation for any purpose and without fee or 8 royalty is hereby granted, provided that you agree to comply with 9 the following copyright notice and statements, including the disclaimer, 10 and that the same appear on ALL copies of the software, database and 11 documentation, including modifications that you make for internal 12 use or for distribution. 13 14 WordNet 3.0 Copyright 2006 by Princeton University. All rights reserved. 15 16 THIS SOFTWARE AND DATABASE IS PROVIDED "AS IS" AND PRINCETON 17 UNIVERSITY MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR 18 IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PRINCETON 19 UNIVERSITY MAKES NO REPRESENTATIONS OR WARRANTIES OF MERCHANT- 20 ABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE 21 OF THE LICENSED SOFTWARE, DATABASE OR DOCUMENTATION WILL NOT 22 INFRINGE ANY THIRD PARTY PATENTS, COPYRIGHTS, TRADEMARKS OR 23 OTHER RIGHTS. 24 25 The name of Princeton University or Princeton may not be used in 26 advertising or publicity pertaining to distribution of the software 27 and/or database. Title to copyright in this software, database and 28 any associated documentation shall at all times remain with 29 Princeton University and LICENSEE agrees to preserve same. 00001740 00 a 01 able 0 005 = 05200169 n 0000 = 05616246 n 0000 + 05616246 n 0101 + 05200169 n 0101 ! 00002098 a 0101 | (usually followed by `to') having the necessary means or skill or know-how or authority to do something; "able to swim"; "she was able to program her computer"; "we were at last able to buy a car"; "able to get a grant for the project" 00002098 00 a 01 unable 0 002 = 05200169 n 0000 ! 00001740 a 0101 | (usually followed by `to') not having the necessary means or skill or know-how; "unable to get to town without a car"; "unable to obtain funds" 00002312 00 a 02 abaxial 0 dorsal 4 002 ;c 06037666 n 0000 ! 00002527 a 0101 | facing away from the axis of an organ or organism; "the abaxial surface of a leaf is the underside or side facing away from the stem" 00002527 00 a 02 adaxial 0 ventral 4 002 ;c 06037666 n 0000 ! 00002312 a 0101 | nearest to or facing toward the axis of an organ or organism; "the upper side of a leaf is known as the adaxial surface" 00002730 00 a 01 acroscopic 0 002 ;c 06066555 n 0000 ! 00002843 a 0101 | facing or on the side toward the apex 00002843 00 a 01 basiscopic 0 002 ;c 06066555 n 0000 ! 00002730 a 0101 | facing or on the side toward the base 00002956 00 a 02 abducent 0 abducting 0 002 ;c 06080522 n 0000 ! 00003131 a 0101 | especially of muscles; drawing away from the midline of the body or from an adjacent part 00003131 00 a 03 adducent 0 adductive 0 adducting 0 003 ;c 06080522 n 0000 + 01449236 v 0201 ! 00002956 a 0101 | especially of muscles; bringing together or drawing toward the midline of the body or toward an adjacent part 00003356 00 a 01 nascent 0 005 + 07320302 n 0103 ! 00003939 a 0101 & 00003553 a 0000 & 00003700 a 0000 & 00003829 a 0000 | being born or beginning; "the nascent chicks"; "a nascent insurgency" 00003553 00 s 02 emergent 0 emerging 0 003 & 00003356 a 0000 + 02625016 v 0102 + 00050693 n 0101 | coming into existence; "an emergent republic" 00003700 00 s 01 dissilient 0 002 & 00003356 a 0000 + 07434782 n 0101 | bursting open with force, as do some ripe seed vessels On the basis that the dictionary, exceptions and rules that spacy lemmatizer uses is largely from Princeton WordNet and their Morphy software, we can move on to see the actual implementation of how spacy applies the rules using the index and exceptions. We go back to the https://github.com/explosion/spaCy/blob/develop/spacy/lemmatizer.py The main action comes from the function rather than the Lemmatizer class: def lemmatize(string, index, exceptions, rules): string = string.lower() forms = [] # TODO: Is this correct? See discussion in Issue #435. #if string in index: # forms.append(string) forms.extend(exceptions.get(string, [])) oov_forms = [] for old, new in rules: if string.endswith(old): form = string[:len(string) - len(old)] + new if not form: pass elif form in index or not form.isalpha(): forms.append(form) else: oov_forms.append(form) if not forms: forms.extend(oov_forms) if not forms: forms.append(string) return set(forms) Why is the lemmatize method outside of the Lemmatizer class? That I'm not exactly sure but perhaps, it's to ensure that the lemmatization function can be called outside of a class instance but given that @staticmethod and @classmethod exist perhaps there are other considerations as to why the function and class has been decoupled Morphy vs Spacy Comparing spacy lemmatize() function against the morphy() function in nltk (which originally comes from http://blog.osteele.com/2004/04/pywordnet-20/ created more than a decade ago), morphy() , the main processes in Oliver Steele's Python port of the WordNet morphy are: Check the exception lists Apply rules once to the input to get y1, y2, y3, etc. Return all that are in the database (and check the original too) If there are no matches, keep applying rules until we find a match Return an empty list if we can't find anything For spacy , possibly, it's still under development, given the TODO at line https://github.com/explosion/spaCy/blob/develop/spacy/lemmatizer.py#L76 But the general process seems to be: Look for the exceptions, get them if the lemma from the exception list if the word is in it. Apply the rules Save the ones that are in the index lists If there are no lemma from step 1-3, then just keep track of the Out-of-vocabulary words (OOV) and also append the original string to the lemma forms Return the lemma forms In terms of OOV handling, spacy returns the original string if no lemmatized form is found, in that respect, the nltk implementation of morphy does the same,e.g. >>> from nltk.stem import WordNetLemmatizer>>> wnl = WordNetLemmatizer()>>> wnl.lemmatize('alvations')'alvations' Checking for infinitive before lemmatization Possibly another point of difference is how morphy and spacy decides what POS to assign to the word. In that respect, spacy puts some linguistics rule in the Lemmatizer() to decide whether a word is the base form and skips the lemmatization entirely if the word is already in the infinitive form (is_base_form()) , this will save quite a bit if lemmatization was to be done for all words in the corpus and quite a chunk of it are infinitives (already the lemma form). But that's possible in spacy because it allowed the lemmatizer to access the POS that's tied closely to some morphological rules. While for morphy although it's possible to figure out some morphology using the fine-grained PTB POS tags, it still takes some effort to sort them out to know which forms are infinitive. Generalment, the 3 primary signals of morphology features needs to be teased out in the POS tag: person number gender Updated SpaCy did make changes to their lemmatizer after the initial answer (12 May 17). I think the purpose was to make the lemmatization faster without look-ups and rules processing. So they pre-lemmatize words and leave them in a lookup hash-table to make the retrieval O(1) for words that they have pre-lemmatized https://github.com/explosion/spaCy/blob/master/spacy/lang/en/lemmatizer/lookup.py Also, in efforts to unify the lemmatizers across languages, the lemmatizer is now located at https://github.com/explosion/spaCy/blob/develop/spacy/lemmatizer.py#L92 But the underlying lemmatization steps discussed above is still relevant to the current spacy version ( 4d2d7d586608ddc0bcb2857fb3c2d0d4c151ebfc ) Epilogue I guess now that we know it works with linguistics rules and all, the other question is "are there any non rule-based methods for lemmatization?" But before even answering the question before, "What exactly is a lemma?" might the better question to ask.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/43795249', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4544413/']}
|
jdg_370721
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
14410275
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Of course I realize all types do have a common ancestor, but what I mean is this: In dynamically-typed languages, it is a common practice to have 'mixed' return types. A common case is a function which attempts to retrieve data from a database, then returns either an object (initialized with the found data) or FALSE (in the event no data was found). A little pseudocode to demonstrate just such an anti-pattern: function getObjectFromDatabase(object_id) { if(result = db_fetch_object("SELECT * FROM objects WHERE id = %d", object_id) { return result } else { return FALSE }} If data is found for my object id, I get a DB record back as an object. If not, I get a boolean value. Then, of course, it is on me, the client, to handle multiple possible return types. Is the only way to accomplish this in Scala to find a common ancestor for all possible return types and declare that as the return type in the signature? // Like so:def getObjectFromDatabase(objectId: Int): Any = { val result = dbFetchObject("SELECT * FROM objects WHERE id = %d", object_id) if(result) { return result } else { return false }} Or is it possible to annotate multiple possible return types? (Note that I do not hope it is possible to do this, as I would prefer it to be enforced that function return types are as unambiguous as possible. It would come as a relief to me to learn that the language forbids ambiguous return types, which is more the reason I am asking.)
Now provide the response and nothing else.
|
Yes, use Either : def getObjectFromDatabase(objectId: Int): Either[Boolean, DbResult] = { val result = dbFetchObject("SELECT * FROM objects WHERE id = %d", object_id) if (result) Right(result) else Left(false)}getObjectFromDatabase(id) match { case Right(result) => // do something with result case Left(bool) => // do something with bool} Or, if the no results case doesn't need a specific value, use Option : def getObjectFromDatabase(objectId: Int): Option[DbResult] = { val result = dbFetchObject("SELECT * FROM objects WHERE id = %d", object_id) if (result) Some(result) else None}getObjectFromDatabase(id) match { case Some(result) => // do something with result case None => // do something about no results} See Tony Morris' Option Cheat Sheet for a list of the most common methods you can call on Option and how they translate to pattern matching. Two other alternatives are Validation from scalaz and Try , new in Scala 2.10. For Validation there are some really good answers on StackOverflow, for example: Method parameters validation in Scala, with for comprehension and monads . For Try see this blog post: The Neophyte's Guide to Scala Part 6: Error Handling With Try . The same author has good posts on Option and Either .
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14410275', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1461460/']}
|
jdg_370722
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2006458
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Let $G$ be a group of order $12$. Does $\mathrm{Aut}(G)$ contain an element of order $5$? I have tried using Sylow Theorems to obtain (G has only one Sylow 2-subgroup (order 4) or G has only one Sylow 3-subgroup (order 3)), G is not simple. And I was trying to construct some group actions, but these seem to lead me to nowhere.
Now provide the response and nothing else.
|
Here is an argument that works for all groups of order $12$. Suppose that $\alpha \in {\rm Aut}(G)$ of order $5$ with $|G|=12$. Since the elements in $G$ that are fixed by $\alpha$ form a subgroup, $\alpha$ must act on the elements of $G$ with two orbits of length $5$ and fixed subgroup of order $2$. The elements in the same orbit have the same order, and there exist elements of order $3$. The total number of elements of order $3$ is even, so there must be $10$ such, but that would give $5$ Sylow $3$-subgroups, contradicting Sylow's theorem.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2006458', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/387597/']}
|
jdg_370723
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
36697
|
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 $R$ be the ring which is generated by homeomorphism classes $[M]$ of compact closed manifolds (of arbitrary dimension) subject to the relations that$$[F]\cdot [B] = [E]$$if there exists a fibre bundle $F \to E \to B$, and$$[M] + [N] = [M \cup N]$$if $M$ and $N$ are of the same dimension. Clearly, $[pt]$ behaves as a unit and we can write $[pt]=1$. Moreover, since $[F] \cdot [B] = [F \times B] = [B \times F] = [B] \cdot [F]$, we see that $R$ is a commutative ring. It is clear that the Euler characteristic defines a homomorphism $\chi : R \to {\mathbb Z}$. What else can we say about the ring $R$ ? What can we say if everything is required to be oriented and/or smooth etc.? Is the ring $R$ finitely generated? Example: Since $S^1$ is a double cover of itself, we get$[S^0] \cdot [S^1] = [S^1]$, but $[S^0] = 2$ and hence $[S^1]=0$. In particular, the classes of all mapping tori of homeomorphisms vanish in $R$ since they are fiber bundles over $S^1$.
Now provide the response and nothing else.
|
Consider the variation where we ask for smooth manifolds and smooth fiber bundles. Then I claim that $R$ is not finitely generated. The starting observation is that if $F \to E \xrightarrow{p} B$ is a smooth fiber bundle then $$0 \to \text{ker}(p) \to T(E) \to p^{\ast}(T(B)) \to 0$$ gives a splitting of the tangent bundle of $E$. There are cohomological obstructions to such splittings existing in general, which we can compute. The upshot is that if $E$ is a simply connected (so it has no nontrivial covers) closed smooth manifold whose tangent bundle has no nontrivial subbundles, then $[E]$ does not participate in any of the interesting relations defining $R$, and in particular cannot lie in the subring of $R$ generated by manifolds of dimension smaller than $\dim E$. Hence to show that $R$ is not finitely generated it suffices to write down a sequence of such $E$ of arbitrarily large dimension. But this is standard: we can take the even-dimensional spheres $S^{2n}$. First, observe that because $S^{2n}$ is simply connected, it has no nontrivial covering spaces, and in addition every real vector bundle over $S^{2n}$ is orientable, hence has well-defined Euler classes (after picking an orientation). Second, the Euler class $e(T)$ of the tangent bundle is $2$ times a generator of $H^{2n}(S^{2n})$, and in particular does not vanish. Since the Euler class is multiplicative with respect to direct sum, if $T = T_1 \oplus T_2$ is a nontrivial splitting of the tangent bundle then $e(T) = e(T_1) e(T_2)$. But the cohomology groups that $e(T_1)$ and $e(T_2)$ live in both vanish for $S^{2n}$; contradiction. Hence the tangent bundle of $S^{2n}$ admits no nontrivial splittings, and so $S^{2n}$ is not the total space of any nontrivial smooth fiber bundle of closed smooth manifolds. (Maybe this argument can be rescued in the topological setting using tangent microbundles?) (Strictly speaking this argument's not quite complete: we also need to show that there aren't any interesting bundles with total space the disjoint union of $S^{2n}$ with something else. But fiber bundle maps $p : E \to B$ are open, so the image of $S^{2n}$ under such a map is a connected component of the base, and we can restrict our attention to this connected component without loss of generality. Then $E$ breaks up, as a fiber bundle, as a disjoint union of $S^{2n}$ and whatever else, and we can restrict our attention to $S^{2n}$ again without loss of generality. In other words, in the defining relations we can assume that $E$ and $B$ are both connected without loss of generality.)
|
{}
|
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/36697', 'https://mathoverflow.net', 'https://mathoverflow.net/users/8176/']}
|
jdg_370724
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3366348
|
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 curious to know what the best way to generate a random integer R that is not in a provided set of integers (R∉N). I can think of several ways of doing this but I'm wondering what you all think.
Now provide the response and nothing else.
|
Let N be the size of the overall set, and let K be the size of the excluded set. I depends on the size of the set you are sampling from. If the excluded set is much smaller than the overall range, just choose a random number, and if it is in the excluded set, choose again. If we keep the excluded set in a hash table each try can be done in O(1) time. If the excluded set is large, choose a random number R in a set of size (N - K) and output the choice as the member of the non excluded elements. If we store just the holes in a hash table keyed with the value of the random number we can generate this in one sample in time O(1). The cutoff point will depend on the size of (N - K)/N, but I suspect that unless this is greater than .5 or so, or you sets are very small, just sampling until you get a hit will be faster in practice.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3366348', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/380213/']}
|
jdg_370725
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
15927583
|
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 some PowerPC assembly code translated with a gcc cross compiler with this function: uint32_t fill_cache(void){ __asm__ ("addi 3, 0, 0\n"); /* R3 = 0 */ /* More asm here modifying R3 and filling the cache lines. */} which, under the PowerPC EABI, returns the value computed in R3. When compiling I get foo.c:105: warning: control reaches end of non-void function Is there a way to teach gcc that a value is actually returned? Or is there a way to suppress the warning (without removing -Wall or adding -Wno-*)? I would like to very selectively suppress this warning for only this function in order to leave the general warning level as high as possible. It is not an option to make this function return void since the value computed is required by the caller.
Now provide the response and nothing else.
|
Solution 1 : with diagnostic pragmas you can locally suppress certain diagnostic checks. The specific option (which also is implied by -Wall ) that complains for no return in a non-void function is -Wreturn-type . So the specific code to suppress the warning is: #pragma GCC diagnostic push#pragma GCC diagnostic ignored "-Wreturn-type"/* Your code here */#pragma GCC diagnostic pop You can find out which option is causing the warning by compiling with -fdiagnostics-show-option . It will simply append the option to the warning message. Solution 2: define a register variable and put it in the desired register. Refer to the variable in an inline assembler template , with the resulting code: uint32_t fill_cache(void){ register uint32_t cacheVal __asm__ ("r3"); __asm__ __volatile__ ("addi %0, 0, 0" : "=r" (cacheVal)); /* More code here */ return cacheVal;} The volatile modifier is to ensure that the instruction is not removed or in some other way affected undesirably by the optimization strategy. Solution 2 is preferred for at least two reasons: The value of a no returning non-void function is undefined as far as the standard is concerned. There's no risk of suppressing (new) diagnostic warnings there was no intention to suppress in the first place.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15927583', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/648658/']}
|
jdg_370726
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
18260103
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have to transpose a 3d list the following way: Input: matrix7 = [[['A ', 'E ', 'C#'], ['B ', 'E ', 'C#'], ['C ', 'E ', 'C#']], [[' ', 'F#', 'D '], [' ', 'F#', 'D '], [' ', 'F#', 'D ']], [[' ', 'E ', 'B '], [' ', 'E ', 'B '], [' ', 'E ', 'B ']], [[' ', 'E ', 'C#'], [' ', 'E ', 'C#'], [' ', 'E ', 'C#']], [[' ', 'F#', 'D '], [' ', 'F#', 'D '], [' ', 'F#', 'D ']], [[' ', 'E ', 'B '], [' ', 'E ', 'B '], [' ', 'E ', 'B ']], [[' ', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' ']], [[' ', 'E ', 'C#'], [' ', 'E ', 'C#'], [' ', 'E ', 'C#']]] desired output: [[['A ', 'E ', 'C#'], [' ', 'F#', 'D '], [' ', 'E ', 'B '], [' ', 'E ', 'C#'], [' ', 'F#', 'D '], [' ', 'E ', 'B '], [' ', ' ', ' '], [' ', 'E ', 'C#']], [['B ', 'E ', 'C#'], [' ', 'F#', 'D '], [' ', 'E ', 'B '], [' ', 'E ', 'C#'], [' ', 'F#', 'D '], [' ', 'E ', 'B '], [' ', ' ', ' '], [' ', 'E ', 'C#']], [['C ', 'E ', 'C#'], [' ', 'F#', 'D '], [' ', 'E ', 'B '], [' ', 'E ', 'C#'], [' ', 'F#', 'D '], [' ', 'E ', 'B '], [' ', ' ', ' '], [' ', 'E ', 'C#']]] I have the following program: matrix8 = []for index in matrix7: matrix8 = numpy.array(matrix7).transpose() matrix9 = matrix8.tolist()print matrix9 which is giving me the wrong output: [[['A ', 'E ', 'C#'], ['B ', 'E ', 'C#'], ['C ', 'E ', 'C#']], [[' ', 'F#', 'D '], [' ', 'F#', 'D '], [' ', 'F#', 'D ']], [[' ', 'E ', 'B '], [' ', 'E ', 'B '], [' ', 'E ', 'B ']], [[' ', 'E ', 'C#'], [' ', 'E ', 'C#'], [' ', 'E ', 'C#']], [[' ', 'F#', 'D '], [' ', 'F#', 'D '], [' ', 'F#', 'D ']], [[' ', 'E ', 'B '], [' ', 'E ', 'B '], [' ', 'E ', 'B ']], [[' ', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' ']], [[' ', 'E ', 'C#'], [' ', 'E ', 'C#'], [' ', 'E ', 'C#']]] Can anyone help me with this?
Now provide the response and nothing else.
|
I think this is what you want: numpy.transpose(matrix7, axes=(1, 0, 2)).tolist() # The 'axes' attribute tells transpose to swaps axes 0 and 1, leaving the last one alone. OUTPUT: [[['A ', 'E ', 'C#'], [' ', 'F#', 'D '], [' ', 'E ', 'B '], [' ', 'E ', 'C#'], [' ', 'F#', 'D '], [' ', 'E ', 'B '], [' ', ' ', ' '], [' ', 'E ', 'C#']],[['B ', 'E ', 'C#'], [' ', 'F#', 'D '], [' ', 'E ', 'B '], [' ', 'E ', 'C#'], [' ', 'F#', 'D '], [' ', 'E ', 'B '], [' ', ' ', ' '], [' ', 'E ', 'C#']],[['C ', 'E ', 'C#'], [' ', 'F#', 'D '], [' ', 'E ', 'B '], [' ', 'E ', 'C#'], [' ', 'F#', 'D '], [' ', 'E ', 'B '], [' ', ' ', ' '], [' ', 'E ', 'C#']]]
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18260103', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1189952/']}
|
jdg_370727
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
11380717
|
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 use Minitest for an existing Rails app (3.2), but not having any luck running routing tests. I've tried rspec syntax (should route_to) and TestUnit syntax (assert_routing) but no luck. Any advice on getting this to work? Specific modules I need to include, etc? thanks
Now provide the response and nothing else.
|
If you are using minitest-rails you can create route tests by placing the following in test/routes/homepage_test.rb : require "minitest_helper"class HomepageRouteTest < ActionDispatch::IntegrationTest def test_homepage assert_routing "/", :controller => "home", :action => "index" endend Alternatively, you can use the Minitest Spec DSL: require "minitest_helper"describe "Homepage Route Acceptance Test" do it "resolves the homepage" do assert_routing "/", :controller => "home", :action => "index" endend You can run these tests with the following rake task: rake minitest:routes
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11380717', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/839190/']}
|
jdg_370728
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4386130
|
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 Spring and Hibernate, I want to write to one MySQL master database, and read from one more more replicated slaves in cloud-based Java webapp. I can't find a solution that is transparent to the application code. I don't really want to have to change my DAOs to manage different SessionFactories, as that seems really messy and couples the code with a specific server architecture. Is there any way of telling Hibernate to automatically route CREATE/UPDATE queries to one datasource, and SELECT to another? I don't want to do any sharding or anything based on object type - just route different types of queries to different datasources.
Now provide the response and nothing else.
|
An example can be found here: https://github.com/afedulov/routing-data-source . Spring provides a variation of DataSource, called AbstractRoutingDatasource . It can be used in place of standard DataSource implementations and enables a mechanism to determine which concrete DataSource to use for each operation at runtime. All you need to do is to extend it and to provide an implementation of an abstract determineCurrentLookupKey method. This is the place to implement your custom logic to determine the concrete DataSource. Returned Object serves as a lookup key. It is typically a String or en Enum, used as a qualifier in Spring configuration (details will follow). package website.fedulov.routing.RoutingDataSourceimport org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;public class RoutingDataSource extends AbstractRoutingDataSource { @Override protected Object determineCurrentLookupKey() { return DbContextHolder.getDbType(); }} You might be wondering what is that DbContextHolder object and how does it know which DataSource identifier to return? Keep in mind that determineCurrentLookupKey method will be called whenever TransactionsManager requests a connection. It is important to remember that each transaction is "associated" with a separate thread. More precisely, TransactionsManager binds Connection to the current thread. Therefore in order to dispatch different transactions to different target DataSources we have to make sure that every thread can reliably identify which DataSource is destined for it to be used. This makes it natural to utilize ThreadLocal variables for binding specific DataSource to a Thread and hence to a Transaction. This is how it is done: public enum DbType { MASTER, REPLICA1,}public class DbContextHolder { private static final ThreadLocal<DbType> contextHolder = new ThreadLocal<DbType>(); public static void setDbType(DbType dbType) { if(dbType == null){ throw new NullPointerException(); } contextHolder.set(dbType); } public static DbType getDbType() { return (DbType) contextHolder.get(); } public static void clearDbType() { contextHolder.remove(); }} As you see, you can also use an enum as the key and Spring will take care of resolving it correctly based on the name. Associated DataSource configuration and keys might look like this: ....<bean id="dataSource" class="website.fedulov.routing.RoutingDataSource"> <property name="targetDataSources"> <map key-type="com.sabienzia.routing.DbType"> <entry key="MASTER" value-ref="dataSourceMaster"/> <entry key="REPLICA1" value-ref="dataSourceReplica"/> </map> </property> <property name="defaultTargetDataSource" ref="dataSourceMaster"/></bean><bean id="dataSourceMaster" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="${db.master.url}"/> <property name="username" value="${db.username}"/> <property name="password" value="${db.password}"/></bean><bean id="dataSourceReplica" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="${db.replica.url}"/> <property name="username" value="${db.username}"/> <property name="password" value="${db.password}"/></bean> At this point you might find yourself doing something like this: @Servicepublic class BookService { private final BookRepository bookRepository; private final Mapper mapper; @Inject public BookService(BookRepository bookRepository, Mapper mapper) { this.bookRepository = bookRepository; this.mapper = mapper; } @Transactional(readOnly = true) public Page<BookDTO> getBooks(Pageable p) { DbContextHolder.setDbType(DbType.REPLICA1); // <----- set ThreadLocal DataSource lookup key // all connection from here will go to REPLICA1 Page<Book> booksPage = callActionRepo.findAll(p); List<BookDTO> pContent = CollectionMapper.map(mapper, callActionsPage.getContent(), BookDTO.class); DbContextHolder.clearDbType(); // <----- clear ThreadLocal setting return new PageImpl<BookDTO>(pContent, p, callActionsPage.getTotalElements()); } ...//other methods Now we can control which DataSource will be used and forward requests as we please. Looks good! ...Or does it? First of all, those static method calls to a magical DbContextHolder really stick out. They look like they do not belong the business logic. And they don't. Not only do they not communicate the purpose, but they seem fragile and error-prone (how about forgetting to clean the dbType). And what if an exception is thrown between the setDbType and cleanDbType? We cannot just ignore it. We need to be absolutely sure that we reset the dbType, otherwise Thread returned to the ThreadPool might be in a "broken" state, trying to write to a replica in the next call. So we need this: @Transactional(readOnly = true) public Page<BookDTO> getBooks(Pageable p) { try{ DbContextHolder.setDbType(DbType.REPLICA1); // <----- set ThreadLocal DataSource lookup key // all connection from here will go to REPLICA1 Page<Book> booksPage = callActionRepo.findAll(p); List<BookDTO> pContent = CollectionMapper.map(mapper, callActionsPage.getContent(), BookDTO.class); DbContextHolder.clearDbType(); // <----- clear ThreadLocal setting } catch (Exception e){ throw new RuntimeException(e); } finally { DbContextHolder.clearDbType(); // <----- make sure ThreadLocal setting is cleared } return new PageImpl<BookDTO>(pContent, p, callActionsPage.getTotalElements()); } Yikes >_< ! This definitely does not look like something I would like to put into every read only method. Can we do better? Of course! This pattern of "do something at the beginning of a method, then do something at the end" should ring a bell. Aspects to the rescue! Unfortunately this post has already gotten too long to cover the topic of custom aspects. You can follow up on the details of using aspects using this link .
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4386130', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/534804/']}
|
jdg_370729
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
30355241
|
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 managed to find the length of the paths in svg, but now i want to find the length for the line, rect, polygon and circle tags from SVG, I am really lost right now, and clues ? or are there already some functions like there is for path?
Now provide the response and nothing else.
|
In case anyone else wants to find the length of these tags I made some functions for each of them, tested them and I say they work pretty ok, this was what i needed. var tools = { /** * * Used to get the length of a rect * * @param el is the rect element ex $('.rect') * @return the length of the rect in px */ getRectLength:function(el){ var w = el.attr('width'); var h = el.attr('height'); return (w*2)+(h*2); }, /** * * Used to get the length of a Polygon * * @param el is the Polygon element ex $('.polygon') * @return the length of the Polygon in px */ getPolygonLength:function(el){ var points = el.attr('points'); points = points.split(" "); var x1 = null, x2, y1 = null, y2 , lineLength = 0, x3, y3; for(var i = 0; i < points.length; i++){ var coords = points[i].split(","); if(x1 == null && y1 == null){ if(/(\r\n|\n|\r)/gm.test(coords[0])){ coords[0] = coords[0].replace(/(\r\n|\n|\r)/gm,""); coords[0] = coords[0].replace(/\s+/g,""); } if(/(\r\n|\n|\r)/gm.test(coords[1])){ coords[0] = coords[1].replace(/(\r\n|\n|\r)/gm,""); coords[0] = coords[1].replace(/\s+/g,""); } x1 = coords[0]; y1 = coords[1]; x3 = coords[0]; y3 = coords[1]; }else{ if(coords[0] != "" && coords[1] != ""){ if(/(\r\n|\n|\r)/gm.test(coords[0])){ coords[0] = coords[0].replace(/(\r\n|\n|\r)/gm,""); coords[0] = coords[0].replace(/\s+/g,""); } if(/(\r\n|\n|\r)/gm.test(coords[1])){ coords[0] = coords[1].replace(/(\r\n|\n|\r)/gm,""); coords[0] = coords[1].replace(/\s+/g,""); } x2 = coords[0]; y2 = coords[1]; lineLength += Math.sqrt(Math.pow((x2-x1), 2)+Math.pow((y2-y1),2)); x1 = x2; y1 = y2; if(i == points.length-2){ lineLength += Math.sqrt(Math.pow((x3-x1), 2)+Math.pow((y3-y1),2)); } } } } return lineLength; }, /** * * Used to get the length of a line * * @param el is the line element ex $('.line') * @return the length of the line in px */ getLineLength:function(el){ var x1 = el.attr('x1'); var x2 = el.attr('x2'); var y1 = el.attr('y1'); var y2 = el.attr('y2'); var lineLength = Math.sqrt(Math.pow((x2-x1), 2)+Math.pow((y2-y1),2)); return lineLength; }, /** * * Used to get the length of a circle * * @param el is the circle element * @return the length of the circle in px */ getCircleLength:function(el){ var r = el.attr('r'); var circleLength = 2 * Math.PI * r; return circleLength; }, /** * * Used to get the length of the path * * @param el is the path element * @return the length of the path in px */ getPathLength:function(el){ var pathCoords = el.get(0); var pathLength = pathCoords.getTotalLength(); return pathLength; } }
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/30355241', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3189314/']}
|
jdg_370730
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
400648
|
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am getting confused on how exactly should I be using exception handling inside a class that respects S-Principle. For example consider this code in C#: public class BcryptDecrypt { private string _password; private string _hash; public BcryptDecrypt(string password, string hash) { this._password = password; this._hash = hash; } public bool Verify() { return BCrypt.Net.BCrypt.Verify(this._password, this._hash); } } Clearly it states that it decrypts a bcrypt hash. But you can see in the Verify method there is no try-catch block to handle an exception. If we add a try-catch to handle exception then we cannot follow S-Principle. So how do software engineers solve this issue? // After adding try-catchpublic class BcryptDecrypt { private string _password; private string _hash; public BcryptDecrypt(string password, string hash) { this._password = password; this._hash = hash; } public bool Verify() { try { return BCrypt.Net.BCrypt.Verify(this._toDecrypt, this._hash); } catch (System.Exception SomeException) { // Handle exception as you like and break S-Principle } } } One way I thought of is to make a separate class to handle each method or class exception or make a universal class to handle it. I saw similar question on Stack Overflow , but the only given answer said to re-throw the exception to let the controller handle it. This doesn't sound like a solution to me considering the controller itself would be following the S-Principle.
Now provide the response and nothing else.
|
Single responsibility ? There is a fundamental misunderstanding about SRP here: The single responsibility does not mean that a class should do only one thing, but that it should have only one reason to change. In other words, it's not the single responsibility OF the class, but the single responsibility FOR the class to change. So it's about decision making. Here an enlightening article from Uncle Bob , who invented SOLID, and explains it better than I with all his authority on the subject. In consequence, you may very well do exception handling in that class without any design concern. You could even have a single Cypher class for encrypting, decrypting and autochecking itself, if you'd really want it. Do one thing ? In Clean Code, Uncle Bob also promotes the Do-one-thing-and-do-it-well , for functions. This could be questioned for exception handling: Do one thing is not the same as do half of the thing If something bad happens when you do the thing, and if you would not handle it as you should, then you would not do the thing well. So exception handling does not infringe do-one-thing. Your option 2 is therefore acceptable. Anything about try/catch ? The only remaining principle to consider for your function is Single Level of Abstraction Principle ( SLAP ) : if you try on some high level function, you should catch and do some high level function. It would not be sound to have a catch clause that would be very low level and detailed, like two page of code for the catch vs 1 line for the try. If exception handling gets too complex, here a nice pragmatic advice : It is better to extract the bodies of the try and catch blocks out into functions of their own.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://softwareengineering.stackexchange.com/questions/400648', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/312994/']}
|
jdg_370731
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2405070
|
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:
Saw how it was simplified and I was wondering what allows you to rewrite this as $3^2 = 9$?
Now provide the response and nothing else.
|
$\frac{1}{3^{-2}}=\frac{1}{3^{-2}}\cdot 1 = \frac{1}{3^{-2}}\cdot\frac{3^2}{3^2}=\frac{1\cdot 3^2}{3^{-2}\cdot 3^2}=\frac{3^2}{3^{-2+2}}=\frac{3^2}{3^0}=\frac{3^2}{1}=3^2$ In general, you can skip many of these steps and use the result $x^n=\frac{1}{x^{-n}}$ for any nonzero $x$.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2405070', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/472288/']}
|
jdg_370732
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
18383205
|
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 set up a variant fetch method on my backbone model that will fetch the current model for a given user. This is available from the API on /api/mealplans/owner/{username}/current . I have written the following model. I commented out the URL Root, as the prototype fetch call was simply using the urlRoot and I wanted to see if that was overriding the url parameter I passed in portions somehow. var mealPlan = Backbone.Model.extend({ name: 'Meal Plan', //urlRoot: '/api/mealplans', defaults: {}, fetchCurrent: function (username, attributes, options) { attributes = attributes || {}; options = options || {}; if (options.url === undefined) { options.url = "/api/mealplans/owner/" + username + "/current"; } return Backbone.Model.prototype.fetch.call(this, attributes, options); }, validate: function (attributes) { // To be done return null; }}); I've seen this done, in some variations in other places, such as at backbone.js use different urls for model save and fetch - In that case the code is slightly different (I started with that and broke it down to make it easier for me to read.) The options object has the url parameter in it fine when I pass it to fetch, but then it seems to ignore it!
Now provide the response and nothing else.
|
I was assuming the same parameters to fetch as to save - This is not the case. The method signature for fetch ONLY takes 'options' and not 'attributes', hence the url parameter wasn't found. The model code should look a bit more like this.. var mealPlan = Ministry.Model.extend({ name: 'Meal Plan', urlRoot: '/api/mealplans', defaults: { }, fetchCurrent: function (username, options) { options = options || {}; if (options.url === undefined) { options.url = this.urlRoot + "/owner/" + username + "/current"; } return Backbone.Model.prototype.fetch.call(this, options); }, validate: function (attributes) { // To be done return null; } });
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18383205', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2579219/']}
|
jdg_370733
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
22259272
|
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 that I have a text field in which a user can submit code snippets. I want to detect when a specific word occurs in the string and then do something with the words/characters that come after that word. Let's say we have a string and that after the word pyjamas I want to start the rest of the code on a new line without an indent. (Very similar to how code beautifiers work.) The output will be rendered inside pre , so I don't want any <br> tags or other HTML tags. There are some catches though. Everything following a word ( pyjamas ) has to start on a new line on the same "level" (equally amount of tab indents) as the line before. Commas should always start on a new line and reverse indented with a tab When there is another character, let's say an exclamation mark ! , the code following has to start on a new line with a tab as an indent. Example: Input : Bananas! Apples and pears walk down pyjamas the street! and they say pyjamas hi to eachother, pyjamas But then! some one else comes pyjamas along pyjamas Who is he?, pyjamas I don't know who! he is pyjamas whatever,, Output : Bananas! Apples and pears walk down pyjamas the street! and they say pyjamas hi to eachother , pyjamas But then! some one else comes pyjamas along pyjamas Who is he? , pyjamas I don't know who! he is pyjamas whatever ,, I am working with jQuery, so you can use it if you want. Here is a fiddle with the code above, so you can test it out. My result thus far is not great at all. (Type something in the textarea, the output will change.) As I'm currently only barely knowledgeable with regex, I am in need of some help. What I have so far: var a = $("textarea").val(), b = a.split('!').join("!\n "), c = b.split('pyjamas').join("pyjamas \n");$("textarea").keyup(function() { $("#output>pre").html(c);});
Now provide the response and nothing else.
|
Here is a simple approach that doesn't require recursive functions and could even be done without regular expressions (but I find them convenient here). function indent(str){ var tabs = function(n) { return new Array(n+1).join('\t'); } var tokens = str.match(/!|,|pyjamas|(?:(?!pyjamas)[^!,])+/g); var depth = 0; var result = ''; for (var i = 0; i < tokens.length; ++i) { var token = tokens[i]; switch(token) { case '!': ++depth; result += token + '\n' + tabs(depth); break; case ',': --depth; result += '\n' + tabs(depth) + token; break; case 'pyjamas': result += token + '\n' + tabs(depth); break; default: result += token; break; } } return result;} First, we define a function that returns a string of n tabs (for convenience). Then we split up the process into two steps. First we tokenise the string - that is we split it into ! , , , pyjamas and anything else. (There's an explanation of the regex at the end, but you could do the tokenisation some other way as well.) Then we simply walk the tokens one by one keeping the current indentation level in depth . If it's an ! we increment the depth, print the ! , a line break and the tabs. If it's a , we decrement the depth, print a line break, the tabs and then the , . If it's pyjamas , we simply print that and a line break and the tabs. If it's anything else we just print that token. That's it. You might want to add some sanity check that depth doesn't go negative (i.e. you have more , than ! ) - currently that would simply be rendered without any tabs, but you'd need to write extra ! after that to get the depth back up to 1 . This is quite easy to deal with, but I don't know what your assumptions or requirements about that are. It also doesn't take care of additional spaces after line breaks yet (see the edit at the end). Working demo. Now for the regex: / ! # Match a literal !| # OR , # Match a literal ,| # OR pyjamas # Match pyjamas| # OR (?: # open a non-capturing group (?!pyjamas) # make sure that the next character is not the 'p' of 'pyjamas' [^!,] # match a non-!, non-, character )+ # end of group, repeat once or more (as often as possible)/g The g to find all matches (as opposed to just the first one). ECMAScript 6 will come with a y modifier , which will make tokenisation even easier - but annoyingly this y modifier is ECMAScript's own invention, whereas every other flavour that provides this feature uses a \G anchor within the pattern. If some of the more advanced concepts in the regex are not familiar to you, I refer you to this great tutorial: negated character classes non-capturing groups lookaheads EDIT: Here is an updated version that fixes the above caveat I mentioned regarding spaces after line breaks. At the end of the processing we simply remove all spaces after tabs with: result = result.replace(/^(\t*)[ ]+/gm, '$1'); The regex matches the beginning of a line and then captures zero or more tabs, and then as many spaces as possible. The square brackets around the space are not necessary but improve readability. The modifier g is again to find all such matches and m makes ^ match at the beginning of a line (as opposed to just the beginning of the string). In the replacement string $1 refers to what we captured in the parentheses - i.e. all those tabs. So write back the tabs but swallow the spaces. Working demo.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/22259272', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1150683/']}
|
jdg_370734
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
15195750
|
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 PHP can you compress/minify CSS with regex (PCRE)? (As a theoretical in regex. I'm sure there are libraries out there that do this well.) Background note: After spending hours writing an answer to a deleted (half crap) question , I thought I'd post a part of the underlying question and answer it my self. Hope it's ok.
Now provide the response and nothing else.
|
Simple regex CSS minifier/compressor (Ok, it may not be overly simple, but pretty straight forward.) Requirements This answer assumes that the requirements are: Remove comments Replace whitespace combinations longer than 1 space with a single space Remove all whitespace around the meta characters: { , } , ; , , , > , ~ , + , - Remove spaces around !important Remove spaces around : , except in selectors (where you have to keep a space before it) Remove spaces around operators like $= Remove all spaces right of ( / [ and left of ) / ] Remove all spaces at the beginning and end of string Remove the last ; in a block Don't change anything in strings Doesn't have to work on invalid CSS Note that the requirements here do not include converting CSS properties to shorter versions (like using shorthand properties instead of several full length properties, removing quotes where not required).This is something that regex would not be able to solve in general. Solution It's easier to solve this in two passes: first remove the comments, then everything else. It should be possible to do in a single pass, but then you have to replace all \s with an expression that matches both spaces and comments (among some other modifications). The first pass expression to remove comments: (?xs) # quotes ( "(?:[^"\\]++|\\.)*+" | '(?:[^'\\]++|\\.)*+' )| # comments /\* (?> .*? \*/ ) Replace with $1 . And to remove everything else you can use: (?six) # quotes ( "(?:[^"\\]++|\\.)*+" | '(?:[^'\\]++|\\.)*+' )| # ; before } (and the spaces after it while we're here) \s*+ ; \s*+ ( } ) \s*+| # all spaces around meta chars/operators \s*+ ( [*$~^|]?+= | [{};,>~+-] | !important\b ) \s*+| # spaces right of ( [ : ( [[(:] ) \s++| # spaces left of ) ] \s++ ( [])] )| # spaces left (and right) of : \s++ ( : ) \s*+ # but not in selectors: not followed by a { (?! (?> [^{}"']++ | "(?:[^"\\]++|\\.)*+" | '(?:[^'\\]++|\\.)*+' )*+ { )| # spaces at beginning/end of string ^ \s++ | \s++ \z| # double spaces to single (\s)\s+ Replaced with $1$2$3$4$5$6$7 . The selector check for removing spaces before : (the negative lookahead) can slow this down compared to proper parsers.Parsers already know if they are in a selector or not, and don't have to do extra searches to check that. Example implementation in PHP function minify_css($str){ # remove comments first (simplifies the other regex) $re1 = <<<'EOS'(?sx) # quotes ( "(?:[^"\\]++|\\.)*+" | '(?:[^'\\]++|\\.)*+' )| # comments /\* (?> .*? \*/ )EOS; $re2 = <<<'EOS'(?six) # quotes ( "(?:[^"\\]++|\\.)*+" | '(?:[^'\\]++|\\.)*+' )| # ; before } (and the spaces after it while we're here) \s*+ ; \s*+ ( } ) \s*+| # all spaces around meta chars/operators \s*+ ( [*$~^|]?+= | [{};,>~+-] | !important\b ) \s*+| # spaces right of ( [ : ( [[(:] ) \s++| # spaces left of ) ] \s++ ( [])] )| # spaces left (and right) of : \s++ ( : ) \s*+ # but not in selectors: not followed by a { (?! (?> [^{}"']++ | "(?:[^"\\]++|\\.)*+" | '(?:[^'\\]++|\\.)*+' )*+ { )| # spaces at beginning/end of string ^ \s++ | \s++ \z| # double spaces to single (\s)\s+EOS; $str = preg_replace("%$re1%", '$1', $str); return preg_replace("%$re2%", '$1$2$3$4$5$6$7', $str);} Quick test Can be found at ideone.com : $in = <<<'EOS'p * i , html /* remove spaces *//* " comments have no escapes \*/body/* keep */ /* space */p,p [ remove ~= " spaces " ] :nth-child( 3 + 2n ) > b span i , div::after{ /* comment */ background : url( " /* string */ " ) blue !important ; content : " escapes \" allowed \\" ; width: calc( 100% - 3em + 5px ) ; margin-top : 0; margin-bottom : 0; margin-left : 10px; margin-right : 10px;}EOS;$out = minify_css($in);echo "input:\n";var_dump($in);echo "\n\n";echo "output:\n";var_dump($out); Output: input:string(435) "p * i , html /* remove spaces *//* " comments have no escapes \*/body/* keep */ /* space */p,p [ remove ~= " spaces " ] :nth-child( 3 + 2n ) > b span i , div::after{ /* comment */ background : url( " /* string */ " ) blue !important ; content : " escapes \" allowed \\" ; width: calc( 100% - 3em + 5px ) ; margin-top : 0; margin-bottom : 0; margin-left : 10px; margin-right : 10px;}"output:string(251) "p * i,html body p,p [remove~=" spaces "] :nth-child(3+2n)>b span i,div::after{background:url(" /* string */ ") blue!important;content:" escapes \" allowed \\";width:calc(100%-3em+5px);margin-top:0;margin-bottom:0;margin-left:10px;margin-right:10px}" Compared cssminifier.com Results of cssminifier.com for the same input as the test above: p * i,html /*\*/body/**/p,p [remove ~= " spaces "] :nth-child(3+2n)>b span i,div::after{background:url(" /* string */ ") blue;content:" escapes \" allowed \\";width:calc(100% - 3em+5px);margin-top:0;margin-bottom:0;margin-left:10px;margin-right:10px} Length 263 byte. 12 byte longer than the output of the regex minifier above. cssminifier.com has some disadvantages compared to this regex minifier: It leaves parts of comments. (There may be a reason for this. Maybe some CSS hacks.) It doesn't remove spaces around operators in some expressions CSSTidy Output of CSSTidy 1.3 (via codebeautifier.com ) at highest compression level preset: p * i,html /* remove spaces *//* " comments have no escapes \*/body/* keep */ /* space */p,p [ remove ~= " spaces " ] :nth-child( 3 + 2n ) > b span i,div::after{background:url(" /* string */ ") blue!important;content:" escapes \" allowed \\";width:calc(100%-3em+5px);margin:0 10px;} Length 286 byte. 35 byte longer than the output of the regex minifier. CSSTidy doesn't remove comments or spaces in some selectors. But it does minify to shorthand properties. The latter should probably help compress normal CSS a lot more. Side by side comparison Minified output from the different minifiers for the same input as in the above example.(Leftover line breaks replaced with spaces.) this answern (251): p * i,html body p,p [remove~=" spaces "] :nth-child(3+2n)>b span i,div::after{background:url(" /* string */ ") blue!important;content:" escapes \" allowed \\";width:calc(100%-3em+5px);margin-top:0;margin-bottom:0;margin-left:10px;margin-right:10px}cssminifier.com (263): p * i,html /*\*/body/**/p,p [remove ~= " spaces "] :nth-child(3+2n)>b span i,div::after{background:url(" /* string */ ") blue!important;content:" escapes \" allowed \\";width:calc(100% - 3em+5px);margin-top:0;margin-bottom:0;margin-left:10px;margin-right:10px}CSSTidy 1.3 (286): p * i,html /* remove spaces */ /* " comments have no escapes \*/ body/* keep */ /* space */p,p [ remove ~= " spaces " ] :nth-child( 3 + 2n ) > b span i,div::after{background:url(" /* string */ ") blue!important;content:" escapes \" allowed \\";width:calc(100%-3em+5px);margin:0 10px;} For normal CSS CSSTidy is probably best as it converts to shorthand properties. I assume there are other minifiers (like the YUI compressor) that should be better at this, and give shorter result than this regex minifier.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/15195750', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/107152/']}
|
jdg_370735
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1796949
|
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:
Problem : Suppose that $f$ is continuous on $\mathbb{R}$. Show that $f$ and $\hat f$ cannot both be compactly supported unless $f=0$. Hint : Assume $f$ is supported in [0,1/2]. Expand $f$ in a Fourier series in the interval [-,1], and note that as a result, f is a trigonometric polynomial. I proved that f is trigonometric polynomial by using hint.But, I don't know how to prove function's fourier transform cannot compactly supported function. Can I get some hints?
Now provide the response and nothing else.
|
Suppose the support of $f$ is contained in $[-1,1],$ and $\hat f (y) = 0$ for $|y|>N \in \mathbb N.$ Applying a standard Fourier series argument on $[-\pi,\pi]$ then shows $$f(x) = \sum_{-N}^{N}\hat f (n) e^{inx}, x \in [-\pi,\pi].$$ Thus $f$ is a trigonometric polynomial that vanishes on $[1,\pi].$ But a trigonometric polynomial on $[-\pi,\pi]$ that vanishes at an infinite number of points must vanish identically. Thus $f\equiv 0.$
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1796949', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/329818/']}
|
jdg_370736
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
138581
|
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
Fresh out of the arXiv press is the remarkable result of Manjul Bhargava saying that most hyperelliptic curves over $\mathbf{Q}$ have no rational points. Don Zagier suggests the paraphrase : Most hyperelliptic curves are pointless . Crucial to the precise mathematical formulation of the statement is a kind of canonical equation for hyperelliptic curves (of a fixed genus) permitting one to define the density of those which have no rational points. What is the corresponding statement for all curves over $\mathbf{Q}$ ? Addendum (2013/09/28) A very nice introduction to the work of Bhargava can be found in How many rational points does a random curve have? by Wei Ho.
Now provide the response and nothing else.
|
My paper with Bjorn Poonen (which is referenced and discussed in Bjorn's answer to this MO question: Are most cubic plane curves over the rationals elliptic? ) has a precise statement for plane curves. You can follow Mike's suggestion in his comment to make a statement for all curves, but this has a problem. Namely, the moduli space of curves of genus $g$ is of general type for $g>22$ (or something like that) so, if you believe Lang's conjecture (or some weakening of it) then there no (or very few) "general" curves of genus $g$ defined over $\mathbb{Q}$, so one expects that most curves of genus $g$ defined over $\mathbb{Q}$ are restricted to rational subvarieties of the moduli space and the biggest one is the hyperelliptic locus, so maybe in some weird sense "most" curves over $\mathbb{Q}$ are hyperelliptic.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/138581', 'https://mathoverflow.net', 'https://mathoverflow.net/users/2821/']}
|
jdg_370737
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
8525
|
Below is a question asked on the forum quant.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am reading the book An Introduction to Financial Option Valuation . The following on page 58 makes me confused: For the formula: $\exp \left\{ -1.96\sigma \sqrt{t}+(\mu-0.5 \sigma^2)t \right\}$, if $t$ is small, then it is approximately equal to $\exp \left (-1.96 \sigma \sqrt{t} \right )$. Moreover, the second formula approximagely equals $1 - 1.96 \sigma \sqrt{t}$. I don't understand how can we get the second and the third expression. If $t$ is very small, then $\sqrt{t}$ should be infinitesimal. Then, why has $(\mu-0.5 \sigma^2)t$ disappeared in the second formula, but not $-1.96 \sigma \sqrt{t}$?
Now provide the response and nothing else.
|
To simplify notations, let $a:= -1.96\sigma$ and $b := \mu - 0.5\sigma^2$. The development in the book could be justified if both $a\sqrt{t}$ and $bt$ are small (close to zero), and if we have that $|a\sqrt{t}| > |bt|$. Recall that $\exp (x+y)= \exp(x)\exp(y)$, $\exp(x)\approx 1 + x,\quad \text{if } x\approx 0$. Then, using these properties we have\begin{align}\exp (a\sqrt{t} + bt) &= \exp (a\sqrt{t}) \exp (bt)\\ &\approx \exp (a\sqrt{t}) (1 + bt) \\ &\approx \exp (a\sqrt{t}),\tag{1} \\ &\approx 1 + a\sqrt{t},\end{align}where the approximation in (1) follows from the fact that $bt$ is (very) close to zero. The fact that $bt$ dissapeared but not $a\sqrt{t}$ comes from the fact that they probably assume that $|a\sqrt{t}| > |bt|$. This assumption should be explicitly stated or obvious from the context (given the typical values for $\sigma$ and $\mu$).
|
{}
|
{'log_upvote_score': 4, 'links': ['https://quant.stackexchange.com/questions/8525', 'https://quant.stackexchange.com', 'https://quant.stackexchange.com/users/5744/']}
|
jdg_370738
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
107767
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm trying to understand the following claim: If $z_1,z_2,z_3,z_4$ are points (as complex numbers) on a circle, then $z_1,z_3,z_4$ and $z_2,z_3,z_4$ determine the same orientation iff $CR(z_1,z_2,z_3,z_4)>0$. Why is this? This was the explanation I tried to explain to myself, but I don't know if it's fully correct, since I make a lot of assumptions to simplify the work. Since the cross ratio is invariant under transformation, we can assume that $z_1,z_2,z_3,z_4$ lie on the real axis. Moreover, we can use a transformation to assume that $z_2=0$, $z_3=1$, and $z_4=2$. Now $$(z_1,z_2,z_3,z_4)=\frac{2(z_1-z_3)}{z_1-z_4}$$and so $(z_1,z_2,z_3,z_4)>0$ if any only if $\frac{z_1-z_3}{z_1-z_4}>0$. Now note that for any $z$,$$(z,z_1,z_3,z_4)=\frac{(z_1-z_4)z-(z_1-z_4)}{(z_1-z_3)z-2(z_1-z_3)}$$and$$(z,z_2,z_3,z_4)=\frac{2z-2}{z-2}.$$So the determinant of the first transformation is $-(z_1-z_3)(z_1-z_4)$, and that of the latter is $-2$. But $\frac{z_1-1}{z_1-2}>0$ when numerator and denominator have the same sign, that is, either when $z_1>z_3$ and $z_1>z_4$, or when $z_1<z_3$ or $z_1<z_4$, and in either case the determinant is negative. It follows that $\Im(z,z_1,z_3,z_4)$ and $\Im(z,z_2,z_3,z_4)$ always have the same sign, and thus determine the same orientation. Thanks.
Now provide the response and nothing else.
|
Then, there's brute force: 303,916,253,?96 ~= 30.3 e+10 ~= (5.5 e+5) squared ~= (n cubed) squared.So, 80 < n < 90 since 80 cubed = 512,000 and 90 cubed = 729,000.Since 303,916,253,?96 ends with 6, the number that is squared must end with 4 or 6. Hence, none of n, n+1, and n+2 can have 0 or 5 in the one's digit.This limits possible choices to 81*82*83 or 82*83*84 or 86*87*88 or 87*88*89. As it turns out, with n=81, 81*82*83 = 551,286, which when squared = 303,916,253,796.The missing digit (?) is 7.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/107767', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/24734/']}
|
jdg_370739
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2446098
|
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 a little confused how jQuery stores data with .data() functions. Is this something called expando ?Or is this using HTML5 Web Storage although I think this is very unlikely? The documentation says: The .data() method allows us to attach data of any type to DOM elements in a way that is safe from circular references and therefore from memory leaks. As I read about expando, it seems to have a risk of memory leak. Unfortunately my skills are not enough to read and understand jQuery code itself, but I want to know how jQuery stores such data by using data() . http://api.jquery.com/data/
Now provide the response and nothing else.
|
Basically jQuery holds the information you store/retrieve with data(name, value)/data(name) and remove with removeData(name) in an internal javascript object named cache . The rest is just a bit of javascript magic to make it work and keep all the associations right. Oh and to answer the first part of your question. Neither is it expando nor HTML5 WebStorage. To correct myself I think jQuery does use expando in one occasion. It sets one attribute on those elements you used data() on to store information to them. The attribute name looks like this "jQuery" + now() //e.g. jQuery1268647073375 btw. now() is an internal function which returns (new Date).getTime() and the value is an UUID generated by jQuery. This way jQuery later on can retrieve the correct associated data from it's internal cache. So if you are concerned about expando in IE, where I recall you can't delete them, then the leak should be minimal as jQuery only uses 1 expando per element you store data on. Unless you call data() on literally 1000s of elements I see no memory problems
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2446098', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/227171/']}
|
jdg_370740
|
Subsets and Splits
SQL Console for PrimeIntellect/stackexchange-question-answering
Retrieves samples with 'mathoverflow.net' in the prompt, providing a basic subset for inspection but with limited analytical value.
SQL Console for PrimeIntellect/stackexchange-question-answering
Retrieves 10 samples where the prompt mentions Mathematica Stack Exchange, offering basic filtering to locate specific content.
SQL Console for PrimeIntellect/stackexchange-question-answering
This query retrieves a limited number of rows where the prompt contains a specific URL, providing basic filtering that offers minimal insight into the broader dataset patterns.
SQL Console for PrimeIntellect/stackexchange-question-answering
This query retrieves 10 samples from the dataset where the prompt contains 'dsp.stackexchange.com', offering a basic filtering of data points related to that specific domain.
SQL Console for PrimeIntellect/stackexchange-question-answering
Retrieves a sample of rows where the prompt contains 'cs.stackexchange.com', providing a basic filter without extensive insight.
Electronics Q&A Subset
Retrieves a limited number of samples that contain a specific URL, providing only raw data filtered by that URL.
StackExchange Stats Questions
Retrieves 100 entries containing 'stats.stackexchange.com' in the prompt, which is useful for finding specific content but lacks broader analytical value.
Math StackExchange Questions
Retrieves 100 records from the train dataset where the prompt contains 'math.stackexchange.com', providing a basic filtered overview of specific entries.
Physics SE Questions
Retrieves 100 samples containing the word 'physics.stackexchange.com' in the prompt, offering basic filtering without deep analysis.